Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions backend/ai_system/agent/projection.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Public tool details. Never persist raw tool requests or model results as Items."""
from pathlib import Path
import json
import re
from services.file_services.workspace_layout import workspace_path
RESEARCH_SOURCE_REFS = {'research:feedback', 'research:consistency'}
Expand All @@ -21,7 +22,7 @@ def safe_file(root, value, *, nonempty=False):



def safe_diagnostic(root, value, limit=400):
def safe_diagnostic(root, value, limit=400, *, json_pointer=False):
"""Bound existing error_detail output; remove secrets, prompt dumps and paths.

Tool exceptions use review_cache.error_detail (validation errors
Expand All @@ -42,13 +43,31 @@ def safe_diagnostic(root, value, limit=400):
text = re.sub(r'(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+', r'\1[已隐藏]', text)
text = re.sub(r"(?i)((?:api[_-]?key|access[_-]?token|authorization|sa[_-]?token|password|secret|credential)[\"']?\s*[:=]\s*)(?:\"[^\"]*\"|'[^']*'|[^\s,;]+)", r'\1[已隐藏]', text)
text = re.sub(r'\bsk-[A-Za-z0-9_-]{8,}', '[已隐藏]', text)
if root is not None:text = text.replace(str(Path(root).resolve()) + '/', '')
text = re.sub(r'(?<![\w.])(?:[A-Za-z]:[\\/]|/)[^\s<>\"\']+', '[工作区外路径]', text)
text = re.sub(r'\.system/[^\s<>\"\']+', '[内部记录]', text)
# Only explicitly typed JSON field coordinates skip filesystem redaction.
# Credential/URL/prompt filtering still applies to those field names.
if not json_pointer:
if root is not None:text = text.replace(str(Path(root).resolve()) + '/', '')
text = re.sub(r'(?<![\w.])(?:[A-Za-z]:[\\/]|/)[^\s<>\"\']+', '[工作区外路径]', text)
text = re.sub(r'\.system/[^\s<>\"\']+', '[内部记录]', text)
text = re.sub(r'(?i)(?:system[_ -]?prompt|prompt|messages)\s*[:=].*', '[内部请求已隐藏]', text)
return text[:limit]


def json_pointer_diagnostic(root, diagnostic):
def field(value):
return safe_diagnostic(root, json.dumps(value, ensure_ascii=False), limit=160, json_pointer=True)
text = (f"JSON 路径 {field(diagnostic['pointer'])} 不存在;当前节点 "
+ (field(diagnostic['current']) if diagnostic['current'] else '根节点'))
if diagnostic['type'] == 'object':
text += ';可用字段:' + '、'.join(field(key) for key in diagnostic.get('keys', [])[:20])
elif diagnostic['type'] == 'array':
size = diagnostic['size']
text += f';数组长度:{size},可用下标:' + (f'0–{size-1}' if size else '无')
else:
text += ';节点类型:' + diagnostic['type']
return text[:400]


def page_range(pages):
if not isinstance(pages, list):return ''
numbers = sorted({p for p in pages if type(p) is int and p > 0})[:4]
Expand Down Expand Up @@ -142,7 +161,9 @@ def tool_projection(root, research_id, item, *, fs=None):
if output.get('compiled'): row['label'] = '编译并预览论文 PDF'
row['warnings'] = [safe_diagnostic(root, warning) for warning in output.get('warnings', [])[:20] if isinstance(warning, str)]
if item.get('error_type') or row['status'] in {'failed','error'}:
reason = safe_diagnostic(root, item.get('message')) if item.get('error_type') else ''
diagnostic = item.get('json_pointer_error')
reason = (json_pointer_diagnostic(root, diagnostic) if diagnostic is not None else
safe_diagnostic(root, item.get('message')) if item.get('error_type') else '')
row['message'] = reason or '未记录具体错误;已有产物保留,可查看执行输出。'
elif item.get('message'):
row['message'] = safe_diagnostic(root, item['message'])
Expand Down
3 changes: 3 additions & 0 deletions backend/ai_system/agent/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,10 @@ async def dispatch(ctx, invocation, handler):
return result
except BaseException as exc:
from ai_system.research.review_cache import error_detail
from ai_system.research.json_views import JsonPointerLookupError
operation.metadata.update(error_type=type(exc).__name__, message=error_detail(exc))
if isinstance(exc, JsonPointerLookupError):
operation.metadata['json_pointer_error'] = exc.diagnostic
if operation.item['type']=='plan':operation.item['explanation']=safe_diagnostic(turn.store.root,error_detail(exc))
operation.finish('interrupted' if isinstance(exc, asyncio.CancelledError) else 'failed')
raise
Expand Down
32 changes: 23 additions & 9 deletions backend/ai_system/modules/writing/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,37 @@
import json
from pathlib import Path

from pydantic import Field
from pydantic import Field, field_validator
from ..registry import Inputs, CapabilityProduct
from services.chat_services import paper_project as project
from services.file_services.workspace_layout import workspace_path
from services.file_services.workspace_lock import edit_lock
from ai_system.sandbox.content_store import ContentStore

ASSETS = '.system/paper-project/assets.json'
ASSET_DIRECTORIES = ('figures', 'tables', 'paper-assets')
ASSET_SUFFIXES = project.ASSET_SUFFIXES | {'.csv', '.json', '.py', '.tex'}
ASSET_DESTINATION_RULE = ('目标只能位于 ' + '、'.join(name+'/' for name in ASSET_DIRECTORIES)
+ ';支持扩展名:' + '、'.join(sorted(ASSET_SUFFIXES))
+ '。不用于向 data/ 或 attachment/ 整理复现资料;不得覆盖已有不同文件。')


def asset_destination(name):
from services.file_services.workspace_layout import relative_parts
parts = relative_parts(name)
if parts[0] not in ASSET_DIRECTORIES or len(parts) < 2 or Path(name).suffix.lower() not in ASSET_SUFFIXES:
raise ValueError(ASSET_DESTINATION_RULE)
return name


class AssetInput(Inputs):
source: str = Field(description='research_list_files返回的实际结果路径。')
destination: str = Field(description='论文内使用的新路径,如figures/forecast.png;不得覆盖已有不同文件。')
source: str = Field(description='research_list_files返回的工作区材料或结果文件路径。')
destination: str = Field(description='论文依赖的相对路径,如 figures/forecast.png。'+ASSET_DESTINATION_RULE)

@field_validator('destination')
@classmethod
def validate_destination(cls, name):
return asset_destination(name)


class ReferenceEdit(Inputs):
Expand Down Expand Up @@ -56,12 +74,8 @@ async def use_asset(ctx, inputs):
from ai_system.research.files import resolve
from services.file_services.workspace_layout import safe_join
source=resolve(ctx,inputs['source'])
name=inputs['destination']
name=asset_destination(inputs['destination'])
target=safe_join(ctx.workspace,name)
if Path(name).parts[0] not in {'figures','tables','paper-assets'}:
raise ValueError('论文依赖请放入figures/、tables/或paper-assets/')
if Path(name).suffix.lower() not in project.ASSET_SUFFIXES | {'.csv','.json','.py','.tex'}:
raise ValueError('不支持此类论文依赖')
store=ContentStore(ctx.workspace,20_000_000)
version=await asyncio.to_thread(store.put,source)
with edit_lock(ctx.workspace):
Expand Down Expand Up @@ -113,6 +127,6 @@ def register(registry):
registry.register('writing','writing.propose_edits','paper',propose_edits,ReferenceEdits,model_callable=True,
purpose='用户要求修改本轮论文引用时,按reference编号提出版本化修改集,等待用户接受。无确认源码范围时不能猜测位置。')
registry.register('writing','writing.use_asset','paper',use_asset,AssetInput,model_callable=True,
purpose='把选定结果复制为固定版本的论文图片、表格或代码依赖,返回实际引用路径;保留来源,不覆盖旧版本。')
purpose='把选定结果复制为固定版本的论文图片、表格、代码或字体依赖,返回实际引用路径;保留来源。'+ASSET_DESTINATION_RULE)
registry.register('writing','writing.preview','paper',preview,PreviewInput,model_callable=True,
purpose='编译或复用当前TeX项目的PDF,查看实际页面、文本和排版警告;修改正文后重新预览。')
13 changes: 11 additions & 2 deletions backend/ai_system/research/json_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ def shape(value, pointer, depth=1):
return result


class JsonPointerLookupError(ValueError):
"""Keep field coordinates typed across the tool/public-diagnostic boundary."""
def __init__(self, pointer, current, value):
node = shape(value, current)
self.diagnostic = {'pointer': pointer, 'current': current,
**{key: node[key] for key in ('type', 'size', 'keys') if key in node}}
super().__init__(f'JSON 路径 {pointer!r} 不存在;当前节点 {current!r}:'
+ json.dumps(node, ensure_ascii=False)[:2000])


def select(value, pointer):
if pointer and not pointer.startswith('/'):
raise ValueError('json_pointer 使用 /字段/数组下标,例如 /q2/0/optimum;空字符串表示根节点')
Expand All @@ -36,8 +46,7 @@ def select(value, pointer):
elif isinstance(value, list) and re.fullmatch(r'0|[1-9][0-9]*', key) and int(key) < len(value):
value = value[int(key)]
else:
available = json.dumps(shape(value, current), ensure_ascii=False)
raise ValueError(f'JSON 路径 {pointer!r} 不存在;当前节点 {current!r}:{available[:2000]}')
raise JsonPointerLookupError(pointer, current, value)
current = child_pointer(current, key)
return value

Expand Down
32 changes: 32 additions & 0 deletions backend/tests/test_result_reading_and_drafting.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,38 @@ async def run():
asyncio.run(run())


def test_json_lookup_errors_keep_field_paths_in_public_tool_items(tmp_path):
from ai_system.agent.projection import safe_diagnostic
from ai_system.agent.store import AgentStore
from ai_system.research.json_views import JsonPointerLookupError
ctx = session_context(tmp_path)
ctx.fs.write_text('outputs/answer.json', json.dumps({
'Q4': {'monthly': [], 'repeated_vs_unique': {}, 'sk-private-test-secret': None},
'a/b': {'~key': [0]}, 'file': '/home/owner/private.json',
}), kind='data')

async def run():
for pointer, current in [('/Q4/repeat_groups', '/Q4'), ('/a~1b/~0key/2', '/a~1b/~0key'), ('/file/missing', '/file')]:
with pytest.raises(JsonPointerLookupError, match='不存在'):
await invoke(ctx, 'research.read_artifact', path='outputs/answer.json', json_pointer=pointer)
failed = [item for item in AgentStore(tmp_path).items() if item.get('status') == 'failed'][-1]
message = failed['message']
assert pointer in message and current in message
assert '[工作区外路径]' not in message
assert '/home/owner' not in message and 'sk-private-test-secret' not in message
if pointer.startswith('/Q4'):
assert 'monthly' in message and 'repeated_vs_unique' in message
elif pointer.startswith('/a~1b'):
assert '数组长度:1' in message
else:
assert '节点类型:string' in message
# A JSON-looking string alone must not exempt a real filesystem path.
message = safe_diagnostic(tmp_path, "JSON 路径 '/home/owner/private.json' 不存在;api_key='owner-secret'")
assert '/home/owner' not in message and 'owner-secret' not in message

asyncio.run(run())


@pytest.mark.parametrize('mode',['markdown','latex'])
def test_chapter_drafts_survive_interruption_and_keep_edit_conflicts(tmp_path,mode):
main='paper.tex' if mode=='latex' else 'paper.md'
Expand Down
24 changes: 24 additions & 0 deletions backend/tests/test_runtime_architecture.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,30 @@ async def run():
asyncio.run(run())


def test_asset_tool_description_and_validation_share_destination_rules(tmp_path):
from ai_system.modules.registry import capabilities, invoke
from ai_system.modules.writing.document import ASSET_DIRECTORIES, ASSET_SUFFIXES
ctx = context(tmp_path)
ctx.fs.write_text('outputs/example.png', 'source')
ctx.fs.register_file('outputs/example.png', kind='data', visibility='user')
capability = capabilities().get('writing.use_asset')
description = capability.inputs.model_json_schema()['properties']['destination']['description']
for name in ASSET_DIRECTORIES:
assert name+'/' in description and name+'/' in capability.purpose
for suffix in ASSET_SUFFIXES:
assert suffix in description and suffix in capability.purpose

async def run():
for destination in ('data/example.png', 'attachment/example.png', 'figures/example.exe', 'figures/../data/example.png'):
with pytest.raises(ValueError):
await invoke(ctx, 'writing.use_asset', source='outputs/example.png', destination=destination)
for destination in ('figures/example.png', 'tables/example.csv', 'paper-assets/example.py'):
result = await invoke(ctx, 'writing.use_asset', source='outputs/example.png', destination=destination)
assert result['path'] == destination and (tmp_path/destination).read_text() == 'source'
assert not (tmp_path/'data/example.png').exists() and not (tmp_path/'attachment/example.png').exists()
asyncio.run(run())


def test_actual_pdf_pages_and_model_images_use_current_pdf(tmp_path):
import pypdfium2 as pdfium
from ai_system.modules.writing.document import PreviewInput,render_pages,tool_content
Expand Down
Loading