diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index b311d8f03..1e237d666 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -20,6 +20,16 @@ from opendirector.agent.catalog import model_choices from opendirector.agent.context import RunContext, RuntimeId +from opendirector.agent.decisions import ( + ASK_SUPPORTED_RUNTIMES, + DecisionAnswerSubmit, + DecisionStore, + InteractionMode, + PlanAdjustInput, + PlanConfirmInput, + build_continuation_prompt_block, + build_execution_prompt_block, +) from opendirector.agent.citations import referenced_sources, with_trace_sources from opendirector.agent.runtime import AgentRuntimes, runtime_available, configured_runtimes, runtime_spec, runtime_catalog, runtime_status from opendirector.agent.skills import skills @@ -73,6 +83,8 @@ class Turn(BaseModel): thinking: Literal['auto', 'low', 'medium', 'high'] = 'auto' modelSelections: dict[str, str | None] = Field(default_factory=dict) skills: list[str] = Field(default_factory=list, max_length=1) + mode: InteractionMode = 'auto' + planOnly: bool = False def draft_content_is_empty(content): @@ -160,7 +172,8 @@ def path(self, project_id: UUID, session: str | None = None) -> Path: return directory def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | None = None, - begin: dict | None = None, finish: dict | None = None, conversation_id: UUID | None = None, + begin: dict | None = None, begin_segment: dict | None = None, + finish: dict | None = None, conversation_id: UUID | None = None, before_begin=None, agent_session: str | None = None) -> dict: finish_mono, finish_at = (_monotonic(), _utc_now()) if finish is not None else (None, None) with self.projects.local.transaction() as db: @@ -174,10 +187,11 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant')) supplied = draft.conversationId if draft is not None else conversation_id - if (draft is not None or begin is not None or finish is not None) and str(supplied) != value['conversationId'] and (supplied is not None or value.get('archivedConversations')): + if (draft is not None or begin is not None or begin_segment is not None or finish is not None) and str(supplied) != value['conversationId'] and (supplied is not None or value.get('archivedConversations')): raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409) changed = False started = None + started_reply_id = None if draft is not None: value.update(draft.model_dump(mode="json", exclude={"conversationId"})) changed = True @@ -189,17 +203,41 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | if agent_session is not None: self.projects.local.start_agent_session(db, project_id, directory, agent_session) value['messages'].append(begin) - reply_id = str(uuid5(UUID(begin['id']), 'assistant')) - value['messages'].append({'id': reply_id, - 'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(), + started_reply_id = str(uuid5(UUID(begin['id']), 'assistant')) + value['messages'].append({'id': started_reply_id, + 'role': 'assistant', 'text': '', 'status': 'streaming', 'turnId': begin['id'], + 'startedAt': _utc_now(), **{key: begin[key] for key in ('model', 'modelIsCliDefault', 'runtime') if key in begin}}) value.update(draft='', draftContent=None, assets=[], skills=[]) changed = True + if begin_segment is not None: + if before_begin is not None: + before_begin() + if agent_session is not None: + self.projects.local.start_agent_session(db, project_id, directory, agent_session) + started_reply_id = str(uuid5(UUID(begin_segment['turnId']), 'assistant')) + segment_msg = { + 'id': started_reply_id, + 'role': 'assistant', + 'text': '', + 'status': 'streaming', + 'startedAt': _utc_now(), + 'turnId': begin_segment['turnId'], + 'taskId': begin_segment['taskId'], + 'segmentKind': begin_segment['segmentKind'], + **({'parentRequestId': begin_segment['parentRequestId']} if begin_segment.get('parentRequestId') else {}), + **{key: begin_segment[key] for key in ('model', 'modelIsCliDefault', 'runtime') if key in begin_segment}, + } + if any(message['id'] == started_reply_id for message in value['messages']): + value['messages'] = [segment_msg if message['id'] == started_reply_id else message for message in value['messages']] + else: + value['messages'].append(segment_msg) + changed = True if finish is not None: with self._started_lock: started = self._started.pop(finish['id'], None) def stamped(message): - result = dict(finish) + result = {**message, **finish} if message.get('startedAt'): result['startedAt'] = message['startedAt'] if finish.get('status') in TIMED_STATUSES and started is not None: @@ -218,11 +256,11 @@ def stamped(message): with self._started_lock: self._started.setdefault(finish['id'], started) raise - if begin is not None: + if started_reply_id is not None: # The turn counts as accepted only now. The clock starts after the begin write succeeded, # still inside the transaction, so no finish for this reply can run before it is set. with self._started_lock: - self._started[reply_id] = _monotonic() + self._started[started_reply_id] = _monotonic() result = public_conversation(value) return with_trace_sources(result, directory) @@ -265,25 +303,27 @@ def dispatch(self, project_id: UUID, session: str | None = None, with self.projects.local.transaction() as db: self.projects._recover() directory, _, _ = self.projects._load(db, project_id) - if session: - self.projects._lease(db, project_id, directory, session) - if agent_session is not None: - self.projects.local.start_agent_session(db, project_id, directory, agent_session) folder = child(directory, 'agent-runs') - folder.mkdir(exist_ok=True) file = child(folder, 'conversation.json') - value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + if not file.exists(): + return None + value = read_json(file) value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant')) pending = next((item for item in value['messages'] if item.get('status') == 'queued'), None) if pending is None: return None + if session: + self.projects._lease(db, project_id, directory, session) + if agent_session is not None: + self.projects.local.start_agent_session(db, project_id, directory, agent_session) index = value['messages'].index(pending) pending['status'] = 'complete' reply_id = str(uuid5(UUID(pending['id']), 'assistant')) value['messages'].insert(index + 1, { 'id': reply_id, - 'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(), - **{key: pending[key] for key in ('model', 'runtime') if key in pending}}) + 'role': 'assistant', 'text': '', 'status': 'streaming', 'turnId': pending['id'], + 'startedAt': _utc_now(), + **{key: pending[key] for key in ('model', 'modelIsCliDefault', 'runtime') if key in pending}}) value.update(draft='', draftContent=None, assets=[], skills=[]) durable_json(file, value) # Same boundary as update(begin): the clock starts once the write succeeded, inside the transaction. @@ -329,9 +369,8 @@ def list(self, project_id: UUID) -> dict: def trace(self, project_id: UUID, conversation_id: UUID, running: UUID | None = None) -> dict: """Executed turns of one conversation, read-only: no lease, no activation, no log bodies. - A turn is a user message together with the assistant message whose id is derived from - it (``uuid5(user id, 'assistant')``), which is how a turn is persisted when it is accepted. - A user message without that assistant record was never executed and is not a turn. + A user turn requires the assistant record identified by ``uuid5(user id, 'assistant')``. + Continuations and confirmed executions have their own assistant record and turn ID. """ directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') @@ -347,19 +386,30 @@ def trace(self, project_id: UUID, conversation_id: UUID, running: UUID | None = if message.get('role') == 'assistant'} turns = [] for message in found.get('messages', []): - if message.get('role') != 'user': - continue - try: - reply = replies.get(str(uuid5(UUID(message['id']), 'assistant'))) - except (KeyError, ValueError, TypeError): - reply = None - if reply is None: + if message.get('role') == 'user': + try: + reply = replies.get(str(uuid5(UUID(message['id']), 'assistant'))) + except (KeyError, ValueError, TypeError): + reply = None + if reply is None: + continue + turn_id_str = message['id'] + summary_text = (message.get('text') or '')[:200] + elif ( + message.get('role') == 'assistant' + and message.get('segmentKind') in ('continuation', 'execution') + and message.get('turnId') + ): + reply = message + turn_id_str = str(message['turnId']) + summary_text = (message.get('text') or message.get('segmentKind') or '')[:200] + else: continue status = reply.get('status') or 'complete' - if status == 'streaming' and (found is not current or running != UUID(message['id'])): + if status == 'streaming' and (found is not current or running != UUID(turn_id_str)): status = 'interrupted' - turns.append({'id': message['id'], 'number': len(turns) + 1, - 'text': (message.get('text') or '')[:200], + turns.append({'id': turn_id_str, 'number': len(turns) + 1, + 'text': summary_text, 'runtime': reply.get('runtime') or message.get('runtime') or 'default', 'model': reply.get('model') or message.get('model'), 'status': status, @@ -381,6 +431,9 @@ def conversation_of(self, project_id: UUID, turn_id: UUID) -> str: if (any(m.get('role') == 'user' and m.get('id') == str(turn_id) for m in messages) and any(m.get('role') == 'assistant' and m.get('id') == reply for m in messages)): return item['conversationId'] + if any(m.get('role') == 'assistant' and m.get('segmentKind') in ('continuation', 'execution') + and m.get('turnId') == str(turn_id) for m in messages): + return item['conversationId'] raise ProjectError('该轮用户消息不存在。', 404) def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, create=False) -> dict: @@ -484,10 +537,135 @@ class Chain: last: dict | None = None +def _build_context_messages( + directory: Path, + messages: list[dict], + assets: dict, + preferences: dict, + decisions_by_id: dict[str, dict], + tasks_by_id: dict[str, dict], + *, + current_segment: dict | None = None, +) -> list[dict]: + """Reconstruct alternating user/assistant context for initial, continuation and execution segments.""" + context: list[dict] = [] + current_request_id = ( + current_segment['decision']['requestId'] + if current_segment is not None and current_segment['kind'] == 'continuation' else None + ) + decision_turn_id = ( + current_segment['decision'].get('turnId') + if current_segment is not None and current_segment['kind'] == 'continuation' else None + ) + original_request = None + refinement_request = None + for message in messages: + if message['role'] == 'user': + content = message['text'] or '(empty reply)' + references = [] + for attachment in message.get('assets', []): + asset = assets.get(attachment['id']) + if asset is not None: + references.append({ + 'id': str(asset.id), + 'name': attachment['name'], + 'kind': asset.kind, + 'path': str((directory / asset.path).resolve()), + 'metadata': asset.metadata.model_dump(mode='json', exclude_none=True), + }) + if references: + content += '\nReferenced project assets: ' + json.dumps(references, ensure_ascii=False) + content += '\nThese are asset references, not visual observations. Inspect media with available tools before describing its contents.' + context.append({'role': 'user', 'content': content}) + if current_segment is not None and message['id'] == current_segment['task']['taskId']: + original_request = content + if ( + current_segment is not None + and decision_turn_id + and decision_turn_id != current_segment['task']['taskId'] + and message['id'] == decision_turn_id + ): + refinement_request = content + elif message['role'] == 'assistant': + content = message.get('text') or '(empty reply)' + req_id = message.get('decisionRequestId') + decision = decisions_by_id.get(req_id) if req_id else None + if decision is not None: + content += '\nAsked user decision (' + decision['requestId'] + '): ' + json.dumps( + decision.get('questions', []), ensure_ascii=False + ) + context.append({'role': 'assistant', 'content': content}) + if decision is not None and decision.get('answers') is not None and req_id != current_request_id: + task = tasks_by_id.get(decision['taskId'], {'taskId': decision['taskId']}) + context.append({'role': 'user', 'content': build_continuation_prompt_block(task, decision)}) + + if current_segment is not None: + task = current_segment['task'] + block = ( + build_continuation_prompt_block(task, current_segment['decision']) + if current_segment['kind'] == 'continuation' else build_execution_prompt_block(task) + ) + if original_request: + block += '\n\nOriginal request for this task:\n' + original_request + if refinement_request: + block += '\n\nLatest user refinement request for this decision:\n' + refinement_request + context.append({'role': 'user', 'content': block}) + + if preferences and context and context[-1]['role'] == 'user': + context[-1]['content'] += '\nUser model preferences for this turn: ' + json.dumps(preferences, ensure_ascii=False) + context[-1]['content'] += ( + '\nUse these models for new generation unless the user explicitly requests another. ' + 'If unavailable or unsuitable, explain and ask before substituting. ' + 'Keep existing nodes on their configured models unless the user requests a change.' + ) + return context + + +def _enrich_conversation( + project_id: UUID, + value: dict, + decisions: DecisionStore, + active_turn_id: UUID | None = None, + *, + state: dict | None = None, +) -> dict: + cid = value.get('conversationId') + if not cid: + return value + if state is None: + state = decisions.public_state(project_id, cid, active_turn_id) + live_reply = str(uuid5(active_turn_id, 'assistant')) if active_turn_id is not None else None + value = { + **value, + 'messages': [ + {**message, 'status': 'interrupted'} + if message.get('status') == 'streaming' and message.get('id') != live_reply else message + for message in value['messages'] + ], + } + interactive_tasks = [ + task for task in state['tasks'] + if task.get('mode') == 'ask' + or task.get('planOnly') + or int(task.get('planRevision', 0)) > 0 + or task.get('activeDecisionId') + or len(task.get('segmentTurnIds', [])) > 1 + or task.get('stage') not in {'running', 'completed'} + ] + if not state['decisions'] and not interactive_tasks: + return value + return { + **value, + 'decisions': state['decisions'], + 'tasks': interactive_tasks, + } + + def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter: router = APIRouter(prefix='/api/creation/projects/{project_id}/assistant') conversations = Conversations(projects) runtimes = AgentRuntimes(projects, generation, configs, provider) + decisions = runtimes.business.decisions def running_turn(project_id: UUID) -> UUID | None: running = active.get(project_id) @@ -510,6 +688,8 @@ def trace_input(project_id: UUID, turn_id: UUID): for message in item.get('messages', []): if message['role'] == 'user' and message['id'] == str(turn_id): return {'text': message['text']} + if message['role'] == 'assistant' and message.get('turnId') == str(turn_id): + return {'text': message.get('text') or message.get('segmentKind') or ''} raise ProjectError('该轮用户消息不存在。', 404) @router.get('/traces/{turn_id}/{source}') @@ -566,18 +746,30 @@ def turn_jobs(project_id: UUID, turn_id: UUID): if active is None: active = {} + launching: dict[UUID, UUID] = {} admission: dict[UUID, asyncio.Lock] = {} - @router.get('') - async def conversation(project_id: UUID): - value = await asyncio.to_thread(conversations.update, project_id) + def _live_turn_id(project_id: UUID) -> UUID | None: running = active.get(project_id) + if running is not None and running.task is not None and not running.task.done(): + return running.turn + return launching.get(project_id) + + async def _read_enriched_conversation(project_id: UUID, *, include_launching=True) -> dict: + value = await asyncio.to_thread(conversations.update, project_id) + live = _live_turn_id(project_id) if include_launching else None + value = await asyncio.to_thread(_enrich_conversation, project_id, value, decisions, live) # A streaming message without a chain was interrupted (for example by a # restart); with one, the client can attach to the turn it is running. - if running is not None: - value = {**value, 'activeTurnId': str(running.turn)} + if live is not None: + value = {**value, 'activeTurnId': str(live)} return value + @router.get('') + async def conversation(project_id: UUID): + async with admission.setdefault(project_id, asyncio.Lock()): + return await _read_enriched_conversation(project_id) + @router.get('/conversations') async def list_conversations(project_id: UUID): return await asyncio.to_thread(conversations.list, project_id) @@ -586,7 +778,8 @@ async def change_conversation(project_id: UUID, conversation_id: UUID, session: async with admission.setdefault(project_id, asyncio.Lock()): if project_id in active: raise ProjectError('请先停止或等待当前回复结束,再切换对话。', 409) - return await asyncio.to_thread(conversations.activate, project_id, conversation_id, str(session), create=create) + result = await asyncio.to_thread(conversations.activate, project_id, conversation_id, str(session), create=create) + return await asyncio.to_thread(_enrich_conversation, project_id, result, decisions, None) @router.post('/conversations') async def new_conversation(project_id: UUID, value: ConversationCreate, x_opendirector_session: UUID = Header()): @@ -598,7 +791,31 @@ async def activate_conversation(project_id: UUID, conversation_id: UUID, x_opend @router.put('/draft') async def draft(project_id: UUID, value: Draft, x_opendirector_session: UUID = Header()): - return await asyncio.to_thread(conversations.update, project_id, str(x_opendirector_session), draft=value) + result = await asyncio.to_thread(conversations.update, project_id, str(x_opendirector_session), draft=value) + return await asyncio.to_thread(_enrich_conversation, project_id, result, decisions, _live_turn_id(project_id)) + + @router.post('/decisions/{request_id}/answers') + async def submit_decision_answer( + project_id: UUID, + request_id: UUID, + value: DecisionAnswerSubmit, + x_opendirector_session: UUID = Header(), + ): + session = str(x_opendirector_session) + result = await asyncio.to_thread(decisions.submit_answer, project_id, session, request_id, value) + return {**result, 'busy': _live_turn_id(project_id) is not None} + + @router.post('/tasks/{task_id}/adjust-plan') + async def adjust_task_plan( + project_id: UUID, + task_id: UUID, + value: PlanAdjustInput, + x_opendirector_session: UUID = Header(), + ): + session = str(x_opendirector_session) + async with runtimes.business.write_lock(project_id): + task = await asyncio.to_thread(decisions.adjust_plan, project_id, session, task_id, value) + return {'task': task} @router.get('/runtimes') async def available_runtimes(project_id: UUID, probe: bool = True): @@ -648,55 +865,118 @@ def check() -> None: generation.availability.require(current, _assistant_request(current), prepared) return check - async def prepare(project_id: UUID, value: Turn, session: str, accept_language: str | None) -> dict: - """Validate a submitted turn and resolve everything it needs to run. - - Validation happens while the user is still at the keyboard: a message - that could never run must fail now, not after the active turn, when the - user has already moved on. - """ + async def _prepare_runtime_and_assets( + project_id: UUID, + session: str, + accept_language: str | None, + *, + runtime_name: Runtime, + runtime_model: str | None, + model_id: UUID | str | None, + thinking: Literal['auto', 'low', 'medium', 'high'], + model_selections: dict[str, str | None], + selected_skills: list[str], + mode: InteractionMode, + referenced_asset_ids: list[str], + ) -> dict: directory = await asyncio.to_thread(conversations.path, project_id, session) - if not runtime_available(value.runtime): - raise ProjectError(f'{value.runtime} 未安装,请安装 CLI 并登录。', 503) - spec = runtime_spec(value.runtime) - if not spec.supportsSkills and value.skills: + if mode == 'ask' and runtime_name not in ASK_SUPPORTED_RUNTIMES: + raise ProjectError('当前 Agent 运行时暂不支持询问模式。', 409, code='ask_mode_runtime_unsupported') + if not runtime_available(runtime_name): + raise ProjectError(f'{runtime_name} 未安装,请安装 CLI 并登录。', 503) + spec = runtime_spec(runtime_name) + if not spec.supportsSkills and selected_skills: raise ProjectError(f'{spec.label} 不支持技能,请移除技能后发送。', 409) - if value.runtime == 'jiuwenswarm' and value.thinking != 'auto': + if runtime_name == 'jiuwenswarm' and thinking != 'auto': raise ProjectError('JiuwenSwarm 当前使用原生默认推理强度。', 409) - config = await asyncio.to_thread(configs.resolve, str(value.modelId), 'agent') if spec.modelSource == 'settings' else None + resolved_model_id = str(model_id) if model_id is not None else model_selections.get('agent') + config = await asyncio.to_thread(configs.resolve, str(resolved_model_id), 'agent') if spec.modelSource == 'settings' else None prepared = None if config is not None: prepared = await asyncio.to_thread(generation.availability.prepare, config) - current = await asyncio.to_thread(configs.resolve, str(value.modelId), 'agent') + current = await asyncio.to_thread(configs.resolve, str(resolved_model_id), 'agent') generation.availability.require(current, _assistant_request(current), prepared) config = current available = await skills(projects.local.repository, directory) if spec.supportsSkills else [] - if set(value.skills) - {item['name'] for item in available}: + if set(selected_skills) - {item['name'] for item in available}: raise ProjectError('技能已失效,请重新选择。', 409) snapshot = await asyncio.to_thread(projects.snapshot, project_id) assets = {str(asset.id): asset for asset in snapshot.assets} - for asset_id in value.assets: + for asset_id in referenced_asset_ids: if str(asset_id) not in assets: raise ProjectError('引用素材不属于当前工程。', 409) - model = config['modelId'] if config else value.runtimeModel + model = config['modelId'] if config else runtime_model model_is_cli_default = spec.modelSource == 'cli' and not model - model_selections = dict(value.modelSelections) - return {'session': session, 'directory': directory, 'config': config, 'prepared': prepared, - 'config_id': str(value.modelId) if value.modelId else None, - 'available': available, - 'model': model, 'model_is_cli_default': model_is_cli_default, - 'model_selections': model_selections, - 'preferences': preferences_for(model_selections), 'thinking': value.thinking, - 'accept_language': accept_language, - 'message': {'id': str(value.id), 'role': 'user', 'text': value.text, 'content': value.content, - 'assets': [{'id': str(asset.id), 'name': asset.name, 'type': asset.metadata.mimeType, - 'size': asset.metadata.size, 'fingerprint': asset.fingerprint} - for asset in (assets[str(key)] for key in value.assets)], - 'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel, - 'modelSelections': dict(value.modelSelections), 'model': model, - 'modelIsCliDefault': model_is_cli_default, - 'thinking': value.thinking, 'status': 'complete', - **({'modelConfigId': str(value.modelId)} if value.modelId else {})}} + return { + 'session': session, + 'directory': directory, + 'config': config, + 'prepared': prepared, + 'config_id': str(resolved_model_id) if resolved_model_id is not None else None, + 'available': available, + 'model': model, + 'model_is_cli_default': model_is_cli_default, + 'model_selections': dict(model_selections), + 'preferences': preferences_for(model_selections), + 'thinking': thinking, + 'accept_language': accept_language, + 'assets': assets, + } + + async def prepare(project_id: UUID, value: Turn, session: str, accept_language: str | None) -> dict: + """Validate a submitted turn and resolve everything it needs to run. + + Validation happens while the user is still at the keyboard: a message + that could never run must fail now, not after the active turn, when the + user has already moved on. + """ + base = await _prepare_runtime_and_assets( + project_id, + session, + accept_language, + runtime_name=value.runtime, + runtime_model=value.runtimeModel, + model_id=value.modelId, + thinking=value.thinking, + model_selections=dict(value.modelSelections), + selected_skills=value.skills, + mode=value.mode, + referenced_asset_ids=[str(key) for key in value.assets], + ) + assets = base.pop('assets') + config = base['config'] + model_cfg_id = str(config['id']) if config is not None else (str(value.modelId) if value.modelId else None) + return { + **base, + 'message': { + 'id': str(value.id), + 'role': 'user', + 'text': value.text, + 'content': value.content, + 'assets': [ + { + 'id': str(asset.id), + 'name': asset.name, + 'type': asset.metadata.mimeType, + 'size': asset.metadata.size, + 'fingerprint': asset.fingerprint, + } + for asset in (assets[str(key)] for key in value.assets) + ], + 'skills': value.skills, + 'runtime': value.runtime, + 'runtimeModel': value.runtimeModel, + 'modelSelections': dict(value.modelSelections), + 'model': base['model'], + 'modelId': str(config['id']) if config is not None else None, + 'modelIsCliDefault': base['model_is_cli_default'], + 'thinking': value.thinking, + 'status': 'complete', + **({'mode': value.mode} if value.mode != 'auto' else {}), + **({'planOnly': True} if value.planOnly else {}), + **({'modelConfigId': model_cfg_id} if model_cfg_id else {}), + }, + } async def plan_for(project_id: UUID, message: dict, session: str, accept_language: str | None) -> dict: """Settings for a message that was accepted earlier and is due now. @@ -708,9 +988,10 @@ async def plan_for(project_id: UUID, message: dict, session: str, accept_languag directory = await asyncio.to_thread(conversations.path, project_id, session) spec = runtime_spec(message['runtime']) config = None - if spec.modelSource == 'settings' and message.get('modelConfigId'): + config_id = message.get('modelConfigId') or message.get('modelId') + if spec.modelSource == 'settings' and config_id: try: - config = await asyncio.to_thread(configs.resolve, message['modelConfigId'], 'agent') + config = await asyncio.to_thread(configs.resolve, config_id, 'agent') except Exception: logger.warning('agent.queue.model_missing project_id=%s message_id=%s', project_id, message.get('id')) @@ -724,10 +1005,14 @@ async def plan_for(project_id: UUID, message: dict, session: str, accept_languag 'thinking': message.get('thinking') or 'auto', 'message': message} async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None, str]: - """Run one turn and persist its reply; the caller decides what runs next.""" + """Run one turn or task segment and persist its reply; the caller decides what runs next.""" project_id = chain.project_id message = plan['message'] turn_id = UUID(message['id']) + segment_meta = plan.get('segment_meta') + segment_claimed = segment_meta is not None + effective_task_id = plan.get('task_id') or turn_id + current_plan = (segment_meta or {}).get('task', {}).get('plan') text, status, error = '', 'complete', None activities: list[dict] = [] sources: dict = {} @@ -740,6 +1025,11 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None async def renew_session() -> None: """Keep the project writable while a turn outlives the lease it started under.""" + try: + if not await asyncio.to_thread(projects.local.renew_agent_session, run_session): + return + except Exception: + logger.exception(f'agent.session.renew.failed project_id={project_id}') while True: await asyncio.sleep(projects.local.LEASE_SECONDS / 3) try: @@ -751,36 +1041,103 @@ async def renew_session() -> None: try: saved = plan['start'] chain.conversation_id = UUID(saved['conversationId']) - chain.events.put({'type': 'start', 'conversation': saved}) renewal = asyncio.create_task(renew_session()) - previous_sources = {source['id']: source for reply in saved['messages'][:-2] - for source in reply.get('sources', [])} + if segment_meta is None: + mode: InteractionMode = message.get('mode') or 'auto' + plan_only = bool(message.get('planOnly')) + if mode == 'ask' or plan_only: + task_record = await asyncio.to_thread( + decisions.begin_task, + project_id, + chain.conversation_id, + turn_id, + mode=mode, + runtime=message['runtime'], + referenced_asset_ids=[item['id'] for item in (message.get('assets') or [])], + plan_only=plan_only, + continue_existing=mode == 'ask', + ) + segment_claimed = True + effective_task_id = UUID(task_record['taskId']) + current_plan = task_record.get('plan') + effective_stage = task_record['stage'] + else: + effective_stage = 'running' + else: + mode = plan['mode'] + effective_stage = plan['task_stage'] + + raw_state = await asyncio.to_thread( + decisions.public_state, project_id, saved['conversationId'], turn_id + ) + enriched_start = _enrich_conversation(project_id, saved, decisions, turn_id, state=raw_state) + chain.events.put({'type': 'start', 'turnId': str(turn_id), 'conversation': enriched_start}) + reply_id = str(uuid5(turn_id, 'assistant')) + non_queued = [ + item for item in saved['messages'] + if item.get('status') not in {'queued', 'cancelled'} + ] + if segment_meta is None: + reply_index = next( + (idx for idx, item in enumerate(non_queued) if item['id'] == reply_id), + len(non_queued), + ) + history = non_queued[:reply_index] + else: + # A retry reuses its earlier reply slot, even after newer turns have completed. + history = [item for item in non_queued if item['id'] != reply_id] + previous_sources = { + source['id']: source + for item in history + for source in item.get('sources', []) + } snapshot = await asyncio.to_thread(projects.snapshot, project_id) assets = {str(asset.id): asset for asset in snapshot.assets} - context = [] - for reply in saved['messages'][:-1]: - content = reply['text'] or '(empty reply)' - references = [] - for attachment in reply.get('assets', []): - asset = assets.get(attachment['id']) - if asset is not None: - references.append({'id': str(asset.id), 'name': attachment['name'], - 'kind': asset.kind, 'path': str((plan['directory'] / asset.path).resolve()), - 'metadata': asset.metadata.model_dump(mode='json', exclude_none=True)}) - if references: - content += '\nReferenced project assets: ' + json.dumps(references, ensure_ascii=False) - content += '\nThese are asset references, not visual observations. Inspect media with available tools before describing its contents.' - context.append({'role': reply['role'], 'content': content}) - if plan['preferences']: - context[-1]['content'] += '\nUser model preferences for this turn: ' + json.dumps(plan['preferences'], ensure_ascii=False) - context[-1]['content'] += '\nUse these models for new generation unless the user explicitly requests another. If unavailable or unsuitable, explain and ask before substituting. Keep existing nodes on their configured models unless the user requests a change.' - run = RunContext(runtime=message['runtime'], project_id=project_id, turn_id=turn_id, - session=run_session, directory=plan['directory'], config=plan['config'], messages=context, - selected_skills=message.get('skills') or [], thinking=plan['thinking'], - model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'), - skills=plan['available'], conversation_id=chain.conversation_id) + decisions_by_id = {d['requestId']: d for d in raw_state['decisions']} + tasks_by_id = {t['taskId']: t for t in raw_state['tasks']} + context = _build_context_messages( + plan['directory'], + history, + assets, + plan['preferences'], + decisions_by_id, + tasks_by_id, + current_segment=segment_meta, + ) + dispatched_marked = False + + async def mark_dispatched() -> None: + nonlocal dispatched_marked + if dispatched_marked or segment_meta is None: + return + await asyncio.to_thread(decisions.mark_model_dispatched, project_id, effective_task_id, turn_id) + dispatched_marked = True + + run = RunContext( + runtime=message['runtime'], + project_id=project_id, + turn_id=turn_id, + session=run_session, + directory=plan['directory'], + config=plan['config'], + messages=context, + selected_skills=message.get('skills') or [], + thinking=plan['thinking'], + model_selections=plan['model_selections'], + runtime_model=message.get('runtimeModel'), + skills=plan['available'], + conversation_id=chain.conversation_id, + mode=mode, + task_id=effective_task_id, + task_stage=effective_stage, + current_plan=current_plan, + rebuild_native_context=bool(non_queued and non_queued[-1]['id'] != reply_id), + on_dispatched=mark_dispatched if segment_meta is not None else None, + ) async with aclosing(runtimes.stream(run)) as stream: async for event in stream: + if message['runtime'] != 'deepseek': + await mark_dispatched() if event['type'] == 'delta': text += event['text'] inherited = ([source for source in referenced_sources(text, previous_sources) @@ -829,12 +1186,30 @@ async def renew_session() -> None: if activity['status'] == 'running': activity['status'] = 'interrupted' try: + if segment_claimed or (plan['directory'] / 'agent-runs' / 'decisions.json').is_file(): + await asyncio.to_thread( + decisions.finalize_segment, + project_id, + turn_id, + reply_text=text, + segment_status=status, + error=error, + ) saved = await asyncio.to_thread(conversations.update, project_id, finish={ - 'id': str(uuid5(turn_id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status, - 'model': plan['model'], 'modelIsCliDefault': plan.get('model_is_cli_default', False), - 'runtime': message['runtime'], 'thinking': plan['thinking'], 'tools': activities, + 'id': str(uuid5(turn_id, 'assistant')), + 'role': 'assistant', + 'turnId': str(turn_id), + 'taskId': str(effective_task_id), + 'text': text, + 'status': status, + 'model': plan['model'], + 'modelIsCliDefault': plan.get('model_is_cli_default', False), + 'runtime': message['runtime'], + 'thinking': plan['thinking'], + 'tools': activities, 'sources': list(sources.values()), **({'plan': steps} if steps is not None else {})}, conversation_id=chain.conversation_id) + saved = await asyncio.to_thread(_enrich_conversation, project_id, saved, decisions, None) except Exception: logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}') saved = None @@ -878,8 +1253,11 @@ async def run_chain(chain: Chain, plan: dict) -> None: if dispatched is None: break chain.turn = UUID(dispatched['message']['id']) + enriched_dispatched = await asyncio.to_thread( + _enrich_conversation, project_id, dispatched['conversation'], decisions, chain.turn + ) chain.events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': str(chain.turn), - 'conversation': dispatched['conversation'], 'error': None}) + 'conversation': enriched_dispatched, 'error': None}) plan = await plan_for(project_id, dispatched['message'], chain.session, None) plan['start'] = dispatched['conversation'] plan['run_session'] = run_session @@ -955,6 +1333,288 @@ async def turn_events(project_id: UUID, turn_id: UUID, after: int = 0): raise ProjectError('这轮回复已结束,请重新读取对话。', 404) return StreamingResponse(chain.events.follow(after), media_type='text/event-stream') + def _resolve_task_turn_parameters(current_conv: dict, task: dict) -> dict: + preferred_id = task.get('latestTurnId') or task['taskId'] + initial_user = next( + (m for m in current_conv.get('messages', []) if m.get('role') == 'user' and m.get('id') == preferred_id), + None, + ) or next( + (m for m in current_conv.get('messages', []) if m.get('role') == 'user' and m.get('id') == task['taskId']), + None, + ) + if initial_user is None: + raise ProjectError('找不到原任务的消息和模型配置。', 409, code='task_model_unavailable') + runtime_name = initial_user.get('runtime') or task.get('runtime') or current_conv.get('runtime') or 'default' + runtime_model = initial_user.get('runtimeModel') + if runtime_model is None: + if current_conv.get('runtime') == runtime_name: + runtime_model = current_conv.get('runtimeModel') + if runtime_model is None: + runtime_model = (current_conv.get('harnessModels') or {}).get(runtime_name) + model_selections = { + **dict(initial_user.get('modelSelections') or {}), + **dict(current_conv.get('modelSelections') or {}), + } + thinking = ( + initial_user.get('thinking') + or (current_conv.get('thinking') if current_conv.get('runtime') == runtime_name else None) + or 'auto' + ) + selected_skills = list(initial_user.get('skills') or []) + draft_agent_id = (current_conv.get('modelSelections') or {}).get('agent') + initial_agent_id = ( + initial_user.get('modelId') + or initial_user.get('modelConfigId') + or (initial_user.get('modelSelections') or {}).get('agent') + ) + model_id = initial_agent_id or draft_agent_id + if runtime_spec(runtime_name).modelSource == 'settings': + resolved_id = None + candidates = [draft_agent_id, initial_agent_id] if draft_agent_id else [initial_agent_id] + for candidate_id in candidates: + if not candidate_id: + continue + try: + resolved = configs.resolve(str(candidate_id), 'agent') + resolved_id = str(resolved['id']) + break + except ProjectError: + continue + if resolved_id is not None: + model_id = resolved_id + else: + agent_configs = [row for row in configs.list() if row.get('kind') == 'agent' and row['modelId'] == initial_user.get('model')] + if len(agent_configs) == 1: + model_id = str(agent_configs[0]['id']) + else: + raise ProjectError('无法确认原任务的 Agent 模型配置。', 409, code='task_model_unavailable') + return { + 'runtime': runtime_name, + 'runtimeModel': runtime_model, + 'modelSelections': model_selections, + 'thinking': thinking, + 'skills': selected_skills, + 'modelId': model_id, + } + + def _completed_sse(turn_id: UUID, saved_conv: dict) -> StreamingResponse: + events = RunEvents() + events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': None, 'conversation': saved_conv, 'error': None}) + return StreamingResponse(events.follow(), media_type='text/event-stream') + + async def _launch_task_segment( + project_id: UUID, + session: str, + accept_language: str | None, + *, + segment_turn_id: UUID, + task: dict, + task_stage: str, + segment_begin: dict, + current_segment_meta: dict, + claim_execution=None, + ) -> StreamingResponse: + if project_id in active: + raise ProjectError('当前工程已有回复正在执行。', 409, code='project_assistant_busy') + current_conv = await asyncio.to_thread(conversations.update, project_id, session) + params = _resolve_task_turn_parameters(current_conv, task) + mode: InteractionMode = task.get('mode', 'ask') + plan = await _prepare_runtime_and_assets( + project_id, + session, + accept_language, + runtime_name=params['runtime'], + runtime_model=params['runtimeModel'], + model_id=params['modelId'], + thinking=params['thinking'], + model_selections=params['modelSelections'], + selected_skills=params['skills'], + mode=mode, + referenced_asset_ids=[], + ) + plan.pop('assets', None) + check = revalidate(plan) + if claim_execution is not None: + if check is not None: + await asyncio.to_thread(check) + claimed = await asyncio.to_thread(claim_execution) + if claimed['state'] != 'claimed': + raise ProjectError('计划执行已受理,请查询原执行片段。', 409, code='project_assistant_busy') + current_segment_meta = {**current_segment_meta, 'task': claimed['task']} + run_session = str(uuid4()) + seg = { + **segment_begin, + 'model': plan['model'], + 'modelIsCliDefault': plan['model_is_cli_default'], + 'runtime': params['runtime'], + } + plan['start'] = await asyncio.to_thread( + conversations.update, + project_id, + session, + begin_segment=seg, + conversation_id=UUID(task['conversationId']), + before_begin=check, + agent_session=run_session, + ) + plan['run_session'] = run_session + plan['task_id'] = UUID(task['taskId']) + plan['task_stage'] = task_stage + plan['mode'] = mode + plan['segment_meta'] = current_segment_meta + plan['message'] = { + 'id': str(segment_turn_id), + 'runtime': params['runtime'], + 'runtimeModel': params['runtimeModel'], + 'skills': params['skills'], + 'mode': mode, + 'planOnly': False, + 'assets': [], + } + return launch(project_id, plan, UUID(plan['start']['conversationId'])) + + @router.post('/continuations/{continuation_id}') + async def continue_decision( + project_id: UUID, + continuation_id: UUID, + x_opendirector_session: UUID = Header(), + accept_language: str | None = Header(default=None, alias='Accept-Language'), + ): + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + running = active.get(project_id) + if running is not None and running.task is not None and not running.task.done(): + if running.turn == continuation_id: + return StreamingResponse(running.events.follow(), media_type='text/event-stream') + raise ProjectError('当前工程已有回复正在执行。', 409, code='project_assistant_busy') + + await asyncio.to_thread(decisions.reconcile_interrupted, project_id) + launching[project_id] = continuation_id + try: + claimed = await asyncio.to_thread(decisions.claim_continuation, project_id, session, continuation_id) + if claimed['state'] == 'already_completed': + return _completed_sse(continuation_id, await _read_enriched_conversation(project_id, include_launching=False)) + if claimed['state'] == 'already_resuming': + await asyncio.to_thread(decisions.reconcile_interrupted, project_id, None) + current = await _read_enriched_conversation(project_id, include_launching=False) + dec = next((d for d in current.get('decisions', []) if d.get('continuationId') == str(continuation_id)), None) + if dec and dec.get('status') == 'completed': + return _completed_sse(continuation_id, current) + raise ProjectError( + '上一次接续执行状态待核对,为避免重复付费调用,未自动重发。', + 409, + code='continuation_status_unknown', + ) + + task, decision = claimed['task'], claimed['decision'] + try: + return await _launch_task_segment( + project_id, + session, + accept_language, + segment_turn_id=continuation_id, + task=task, + task_stage='resuming', + segment_begin={ + 'turnId': str(continuation_id), + 'taskId': task['taskId'], + 'segmentKind': 'continuation', + 'parentRequestId': decision['requestId'], + }, + current_segment_meta={'kind': 'continuation', 'task': task, 'decision': decision}, + ) + except Exception as failure: + await asyncio.to_thread( + decisions.finalize_segment, + project_id, + continuation_id, + reply_text='', + segment_status='interrupted', + error=str(failure), + before_model=True, + ) + raise + finally: + launching.pop(project_id, None) + + @router.post('/tasks/{task_id}/confirm-plan') + async def confirm_task_plan( + project_id: UUID, + task_id: UUID, + value: PlanConfirmInput, + x_opendirector_session: UUID = Header(), + accept_language: str | None = Header(default=None, alias='Accept-Language'), + ): + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + tentative_exec_cid = uuid5(task_id, f'execute:{value.planRevision}') + launching[project_id] = tentative_exec_cid + try: + running = active.get(project_id) + is_live = running is not None and running.task is not None and not running.task.done() + if is_live and running.turn != tentative_exec_cid: + raise ProjectError('当前工程已有回复正在执行。', 409, code='project_assistant_busy') + if not is_live: + await asyncio.to_thread(decisions.reconcile_interrupted, project_id) + claimed = await asyncio.to_thread( + decisions.claim_plan_execution, project_id, session, task_id, value, inspect_only=True + ) + exec_cid = UUID(claimed['continuationId']) + launching[project_id] = exec_cid + running = active.get(project_id) + is_live = running is not None and running.task is not None and not running.task.done() + if claimed['state'] == 'already_completed': + return _completed_sse(exec_cid, await _read_enriched_conversation(project_id, include_launching=False)) + if claimed['state'] == 'already_executing': + if is_live and running.turn == exec_cid: + return StreamingResponse(running.events.follow(), media_type='text/event-stream') + await asyncio.to_thread(decisions.reconcile_interrupted, project_id, None) + reconciled_task = await asyncio.to_thread(decisions.get_task, project_id, task_id) + if reconciled_task and reconciled_task.get('stage') in {'completed', 'waiting_jobs', 'execution_failed'}: + return _completed_sse(exec_cid, await _read_enriched_conversation(project_id, include_launching=False)) + raise ProjectError( + '当前任务执行状态待核对,请先核对已生成产物或回执。', + 409, + code='continuation_status_unknown', + ) + if is_live: + raise ProjectError('当前工程已有回复正在执行。', 409, code='project_assistant_busy') + + execution_claimed = False + + def _claim_execution(): + nonlocal execution_claimed + result = decisions.claim_plan_execution(project_id, session, task_id, value) + execution_claimed = result.get('state') == 'claimed' + return result + + try: + return await _launch_task_segment( + project_id, + session, + accept_language, + segment_turn_id=exec_cid, + task=claimed['task'], + task_stage='executing', + segment_begin={'turnId': str(exec_cid), 'taskId': str(task_id), 'segmentKind': 'execution'}, + current_segment_meta={'kind': 'execution', 'task': claimed['task']}, + claim_execution=_claim_execution, + ) + except Exception as failure: + if execution_claimed: + await asyncio.to_thread( + decisions.finalize_segment, + project_id, + exec_cid, + reply_text='', + segment_status='interrupted', + error=str(failure), + before_model=True, + ) + raise + finally: + launching.pop(project_id, None) + @router.post('/turns') async def turn(project_id: UUID, value: Turn, x_opendirector_session: UUID = Header(), accept_language: str | None = Header(default=None, alias='Accept-Language')): @@ -962,19 +1622,23 @@ async def turn(project_id: UUID, value: Turn, x_opendirector_session: UUID = Hea async with admission.setdefault(project_id, asyncio.Lock()): if project_id in active: raise ProjectError('当前工程已有回复正在执行。', 409) - plan = await prepare(project_id, value, session, accept_language) - run_session = str(uuid4()) + launching[project_id] = value.id try: - plan['start'] = await asyncio.to_thread(conversations.update, project_id, session, - begin=plan['message'], conversation_id=value.conversationId, - before_begin=revalidate(plan), agent_session=run_session) - except ProjectError as failure: - # The message points at a thread that is no longer the active one. - # Clients of this endpoint read that from the stream, so report it - # where they already look instead of as a bare status code. - return rejected(UUID(plan['message']['id']), failure, accept_language) - plan['run_session'] = run_session - return launch(project_id, plan, UUID(plan['start']['conversationId'])) + plan = await prepare(project_id, value, session, accept_language) + run_session = str(uuid4()) + try: + plan['start'] = await asyncio.to_thread(conversations.update, project_id, session, + begin=plan['message'], conversation_id=value.conversationId, + before_begin=revalidate(plan), agent_session=run_session) + except ProjectError as failure: + # The message points at a thread that is no longer the active one. + # Clients of this endpoint read that from the stream, so report it + # where they already look instead of as a bare status code. + return rejected(UUID(plan['message']['id']), failure, accept_language) + plan['run_session'] = run_session + return launch(project_id, plan, UUID(plan['start']['conversationId'])) + finally: + launching.pop(project_id, None) @router.post('/messages') async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = Header(), @@ -998,17 +1662,21 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = chain.events.put({'type': 'queued', 'message': queued}) return JSONResponse({'queued': queued, 'chainId': str(chain.id), 'turnId': str(chain.turn)}, status_code=202) - check = revalidate(plan) - if check is not None: - await asyncio.to_thread(check) - await asyncio.to_thread(conversations.queue, project_id, session, plan['message'], value.conversationId) - start_session = str(uuid4()) - dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session, start_session) - if dispatched is None: - raise ProjectError('这条消息未能开始执行,请重新发送。', 409) - started = await plan_for(project_id, dispatched['message'], session, accept_language) - started['start'] = dispatched['conversation'] - started['run_session'] = start_session - return launch(project_id, started, UUID(dispatched['conversation']['conversationId'])) + launching[project_id] = value.id + try: + check = revalidate(plan) + if check is not None: + await asyncio.to_thread(check) + await asyncio.to_thread(conversations.queue, project_id, session, plan['message'], value.conversationId) + start_session = str(uuid4()) + dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session, start_session) + if dispatched is None: + raise ProjectError('这条消息未能开始执行,请重新发送。', 409) + started = await plan_for(project_id, dispatched['message'], session, accept_language) + started['start'] = dispatched['conversation'] + started['run_session'] = start_session + return launch(project_id, started, UUID(dispatched['conversation']['conversationId'])) + finally: + launching.pop(project_id, None) return router diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index cf7a982f5..d0ea5c9d4 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -144,6 +144,21 @@ "local_only": "Only this computer can access the project service.", "cross_origin": "File access from another site is not allowed.", "invalid_local_request": "This is not a valid local app request.", + "ask_mode_runtime_unsupported": "Ask mode is available for Default, OpenCode, Claude Code, Codex, DeepSeek Harness, and Pi only.", + "task_waiting_input": "This task is waiting for the user to answer the current question. Subsequent operations are paused.", + "plan_confirmation_required": "This task is in the interactive planning stage. Confirm the current plan before modifying the project or starting generation.", + "decision_answer_invalid": "Check the answers for each question and try again.", + "decision_answer_conflict": "A different answer was already submitted for this question in another tab. Showing the saved answer.", + "decision_version_invalidated": "Related assets or the plan version changed. This question is no longer valid and will not overwrite newer content.", + "decision_not_answered": "Save an answer to this question before continuing the task.", + "continuation_resume_failed": "Could not start the continuation. Check the Agent configuration and try again.", + "continuation_status_unknown": "The previous execution status needs verification. To avoid duplicate paid calls, it was not resent automatically.", + "plan_missing": "This task does not have a confirmable plan revision yet.", + "plan_revision_stale": "The plan version changed and the previous confirmation is no longer valid. Confirm the latest plan version.", + "plan_step_kind_mismatch": "Only inspection steps can record an inspection result.", + "task_conversation_changed": "Return to the task's original conversation to continue.", + "task_model_unavailable": "The original Agent model configuration could not be resolved.", + "project_assistant_busy": "Another reply is currently running in this project. Wait for it to finish and then continue.", } ENGLISH_BY_STATUS = { diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 1d38e48f7..d77bbace3 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -112,11 +112,33 @@ On Windows, Codex explicitly sets `windows.sandbox="elevated"` so ignoring user CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不使用连接令牌或凭据文件。网关继续校验工程范围、轮次生命周期及业务输入。 +## 交互式规划与恢复 / Interactive planning and recovery + +右侧助手默认使用自动模式。Default、OpenCode、Claude Code、Codex 和 DeepSeek Harness 可选择询问模式。其他运行时在界面禁用询问入口,API 收到显式 `mode: ask` 时返回 `409 ask_mode_runtime_unsupported`。由 `mode: ask` 或显式 `planOnly: true` 进入规划阶段。规划与接续阶段允许查询和规划工具,工程写入和生成提交须经当前计划版本授权。 + +`agent-runs/decisions.json` 随工程保存任务、题组、答案、计划版本、已确认版本和执行回执。任务及其申请、回答、接续与执行标识关联原会话。`ask_user` 使当前片段进入等待回答,释放工程的运行名额。答案保存后,接续使用固定的续跑 ID,并按该任务最新要求保存计划。确认以计划版本为准,改版后旧确认失效。 + +提交答案返回任务和决策回执,调整计划返回更新后的任务。回执中的 `task.conversationId` 标识所属会话。完整会话通过助手会话接口或流事件读取。 + +计划步骤保存为 `write`、`read` 或 `inspection`,文本步骤采用 `write`。写入步骤凭业务回执完成。只读步骤凭使用对应操作 ID 的查询结果完成,原生检查步骤通过 `plan complete-step` 登记结果。CLI 的 `asset write-text --file` 接受命令 JSON,`--text-file` 接受字面文本,两者均可用 `-` 读取标准输入。文本大小限制按解码后的内容计算。 + +执行前记录操作 ID、输入指纹及 `pendingWrites`。确认发生在业务提交前的文件读取和本地校验失败会清除待处理记录,并保留按原操作 ID 和输入重试的能力。DeepSeek 完成 ACP 初始化和模型配置后,在发送 `session/prompt` 前记录模型派发。重启时根据新版计划的接续 ID 和已提交业务回执恢复状态,时间线导入也核对最终批次回执。读取失败和状态未明的远端提交保留待核对记录。 + +English summary: the right-hand assistant defaults to Auto. Default, OpenCode, Claude Code, Codex, and DeepSeek Harness support Ask mode. The UI disables Ask on other runtimes, and an explicit unsupported `mode: ask` request receives `409 ask_mode_runtime_unsupported`. Ask or explicit `planOnly: true` enters planning. Planning and continuation permit read and planning tools. Project writes and generation submissions require authorization for the current plan revision. + +The project stores tasks, question groups, answers, plan revisions, confirmations, and execution receipts in `agent-runs/decisions.json`. Questions, answers, continuations, and execution segments belong to the original conversation. `ask_user` pauses the segment and releases the project's run slot. A saved answer has a stable continuation ID. A revised plan supersedes authorization for the previous revision. + +Submitting answers returns the task and decision receipt. Adjusting a plan returns the updated task. Both identify the owning conversation through `task.conversationId`. Read the full conversation through the assistant conversation endpoint or stream. + +Plan step kinds are `write`, `read`, and `inspection`. A plain text step defaults to `write`. Write steps require business receipts, read steps record queries under the matching operation ID, and native inspection steps record their findings via `plan complete-step`. The CLI accepts command JSON via `asset write-text --file` and literal content via `--text-file`. Either option accepts `-` for standard input. The asset size limit applies to the decoded text. + +Before dispatch, the service records the operation ID, input fingerprint, and `pendingWrites` entry. Confirmed preflight failures clear the pending write and allow retry with the same ID and input. DeepSeek records model dispatch after ACP setup and immediately before sending `session/prompt`. Restart recovery uses the saved plan's continuation ID and authoritative business receipts, including the final batch receipt for timeline imports. Unreadable records and uncertain remote submissions remain pending verification. + ## 对话轨迹页 / Conversation trace page -轨迹页 `/?traceProject=…&conversation=…&turn=…` 在一页内按顺序列出一个对话的全部已执行轮次,每轮可独立展开,展开时才读取该轮日志与关联 Job;“下载原始轨迹”是用户显式触发的例外,见下。轮次索引来自只读接口 `GET .../assistant/conversations/{conversation_id}/trace`,它解析当前对话、已归档对话和 `reusedCreateIds` 别名,只返回轮次元数据(序号、用户输入摘要、运行时、状态),不读取日志正文,不激活对话,不获取编辑租约。轮次由持久化的身份关系确定:用户消息与 id 为 `uuid5(用户消息 id, 'assistant')` 的助手消息成对才算已执行的一轮;没有该助手记录的用户消息(例如排队中、未执行)不出现。每轮使用自己记录的运行时选择日志源和解析器,仅 Default(opencode)显示模型原始请求。`GET .../traces/{turn_id}/conversation` 供旧的单轮链接查找所属对话;找不到时保持原单轮页面。 +轨迹页 `/?traceProject=…&conversation=…&turn=…` 在一页内按顺序列出一个对话的全部已执行轮次和独立分段,每项可独立展开,展开时才读取其日志与关联 Job;“下载原始轨迹”是用户显式触发的例外,见下。轮次索引来自只读接口 `GET .../assistant/conversations/{conversation_id}/trace`,它解析当前对话、已归档对话和 `reusedCreateIds` 别名,只返回序号、摘要、运行时、状态等元数据,不读取日志正文,不激活对话,不获取编辑租约。普通轮次由持久化的身份关系确定:用户消息与 id 为 `uuid5(用户消息 id, 'assistant')` 的助手消息成对才算已执行的一轮,只计一次;没有该助手记录的用户消息(例如排队中、未执行)不出现。`segmentKind` 为 `continuation` 或 `execution` 的独立助手消息按自己的 `turnId` 入列。每项使用自己记录的运行时选择日志源和解析器,仅 Default(opencode)显示模型原始请求。`GET .../traces/{turn_id}/conversation` 供旧的单轮链接查找所属对话;找不到时保持原单轮页面。 -English summary: the trace page lists every executed turn of a conversation, expanded one at a time, and reads a turn's logs and linked Jobs only when it is opened; the user-triggered original trace download is the one exception (below). The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, input summary, runtime, status). It never reads log bodies, activates a conversation or takes a lease. A turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, so queued or never executed user messages are not listed. Each turn uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains. +English summary: the trace page lists every executed turn and standalone segment of a conversation, expanded one at a time, and reads a row's logs and linked Jobs only when it is opened; the user-triggered original trace download is the one exception (below). The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, summary, runtime, status). It never reads log bodies, activates a conversation or takes an editing lease. An ordinary turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, appearing once, so queued or never executed user messages are not listed. Standalone assistant records with `segmentKind` of `continuation` or `execution` appear under their own `turnId`. Each row uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains. 轨迹浏览使用 `GET .../traces/{turn_id}/{source}?cursor=…` 按字节读取追加日志。空游标从头开始,之后使用响应返回的游标;每个响应最多读取 512 KiB。浏览器跨响应保留未完成的 UTF-8 和 JSONL 记录,并增量合并同一消息或工具调用。回合结束后,浏览器读完剩余字节即停止轮询。无游标的同一路径继续提供原始文件。 diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 20e3ea60f..5e453fa85 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -118,6 +118,8 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Lesson:** A timer may run after the editor's saving flag clears but before React installs the new document. Comparing that old closure against the new baseline can turn a view-only save into a business rollback, invalidating a previously captured publication version. - **Check:** Invalidate scheduled automatic callbacks when the editor transaction starts, drain queued saves and explicitly persist the current draft before the edit. Preserve publication CAS checks. Exercise the real due callback at the acknowledgment boundary; isolate projection-test gates by snapshot identity, assert release/restoration and always clean up. Distinguish a forced reproduction from proof of the exact CI schedule. - **Queued-edit follow-up:** The H3 browser regression in [PR #266](https://github.com/ThinkFlowLab/OpenDirector/pull/266) holds the first import's background hydration until the second import queues an edit. A ref updated during render can still describe the old document; a late refresh then replaces both nodes with one. Track requested and rendered history writes, defer refreshes while they differ, and recheck when hydration finishes. Resume after a no-op write too. Verify both saved nodes, their bytes, and subsequent edits after reopening. / **排队编辑补充:** React 尚未显示的编辑也需要保护;后台刷新必须检查已经请求的修改,并在页面更新后继续。回归检查两张图片的保存内容及重开后的编辑,不能把人工控制的执行顺序当作原 CI 顺序的证明。 +- **Remote-refresh follow-up:** Investigating [PR #546's undo failure](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/46012590478/job/140551857483) reproduced a due autosave publishing `canvas.show` after a remote hide installed its baseline, causing undo to reject the changed field. Invalidate preceding callbacks before installing changed background content; retain pending view saves when the content is unchanged. Exercise the real due callback at that boundary, inspect persisted visibility and revision, and verify undo/redo and view persistence. The controlled reproduction does not establish the exact original CI schedule. / **后台刷新补充:** 新内容成为保存基线前,应使旧自动保存回调失效;内容未变化时保留待保存的视图。用真实到期回调验证隐藏状态、版本、撤销重做及视图持久化,不能将人工复现顺序当作原 CI 顺序的证明。 +- **Gesture setup follow-up:** [The next PR #546 run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/46024450895/job/140592409452) timed out waiting for that callback. Local inspection reproduced a fixed-coordinate drag hitting the selected node's prompt editor without moving the viewport. Hit-test exposed canvas and assert the viewport changes before waiting for its autosave; unrelated pending timers can otherwise mask a broken setup. / **手势准备补充:** 固定坐标拖动可能落在所选节点的提示词编辑器,未移动画布却等待保存。应先命中无遮挡画布并验证视图变化,避免其他待保存定时器掩盖准备步骤失败。 - **Preset editor follow-up:** Selecting an image preset used to queue a settings edit and a prompt-chip edit that still held the old settings. Render the chip from the saved preset and publish preset changes caused by prompt editing in the same command as the prompt. Check the saved parameters after autosave and reopening. Chrome can move the caret past a wrapped hint through native mouse-down selection. Verify the caret's rendered position after the chip with a visible multiline hint before releasing the button. Check that typing replaces the hint, retains the first character and saves only the user's text. - **Preset submission follow-up:** Treat the selected preset as a prompt in both the button preflight and the generation service. Freeze its instructions in the accepted job, since updating only the draft's plain prompt can be ignored by structured references and can duplicate instructions on a second run. Check preset-only submission, the structured provider prompt, and adoption without modifying the draft. - **Image preset prompt variants:** Use the resolved image inputs to choose between image-guided and text-guided instructions. Publish both variants so the preview can make the same choice from usable references. Check that enabling face emphasis and adding or removing the last image change both the preview and the submitted prompt. Keep the ordered steps of multi-shot presets in both variants. diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index e65932e51..d6c604b01 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -154,6 +154,8 @@ Click a source number to view its full URL in a bordered information card, then Click **Chat with AI** at the bottom right, select a chat model, and describe what you want to create. You can upload, drag and drop, or paste assets, or type `@` to reference canvas content. The assistant can save text as requested and call configured generation models to create assets. +With Default, OpenCode, Claude Code, Codex, or DeepSeek Harness, choose **Ask** beside the composer to plan interactively. You can select a numbered option on the question card or type your own answer directly in the chat box below. When the assistant is waiting for an answer, you can switch conversations. Refreshing the page or returning to a conversation with an unfinished Ask plan restores **Ask**. Review the current plan and select **Confirm and execute** when you want the assistant to act. Steps that submit generation jobs show progress until their jobs finish. If a step is rejected, adjust and confirm a new revision. If execution status needs verification after an interruption, check the saved results before retrying. + When the latest reply offers next steps, three to five suggested replies appear beneath it and stay visible as you type. Select one to fill the composer or replace the text you have already written. Attachments, references and skills stay in your draft. You can edit the text or undo the replacement. Press **Send** or `Enter` when you are ready. Use **New conversation** at the top of the panel to start a separate chat. **Conversation history** lets you search and switch between this canvas's conversations. Switching saves your draft and restores the selected conversation's messages, reference attachments, and model choices; the active conversation also survives a page reload. Wait for uploads or replies to finish, or stop the reply, before switching. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index f6dc6a095..789d2e523 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -154,6 +154,8 @@ Codex 网页检索引用在具有匹配来源时显示为编号链接;复制 点击右下角“与 AI 对话”,选择对话模型后输入创作要求。可上传、拖放、粘贴素材,或输入 `@` 引用画布中的内容。助手可按要求保存文本,并调用已配置的生成模型制作素材。 +使用 Default、OpenCode、Claude Code、Codex 或 DeepSeek Harness 时,可在输入区选择「询问」来交互式规划。问题卡片弹出后可直接点选编号选项,也可以直接在下方聊天输入框填写其他回答并发送。助手等待回答时可以切换会话。刷新页面或回到还有未完成询问计划的会话时,输入区会恢复「询问」。审阅当前计划后,选择「确认并执行」开始交付。提交生成任务的步骤会显示进度,直到任务完成。若某一步明确被拒绝,可以调整并确认新版计划。若中断后显示「执行状态待核对」,请先检查已保存的产物再决定是否重试。 + 当助手在最新回复中给出后续建议时,回复下方会显示 3~5 个建议回复按钮,输入时仍可参考。点选一条即可填入输入框,替换已有文字,保留附件、引用和技能。你可以继续编辑或撤销替换,准备好后点击「发送」或按 `Enter`。 点击对话框顶部“新建”开始独立会话;点击“历史会话”可搜索并切换当前画布的旧会话。切换前会保存草稿,切回后恢复消息、参考附件和模型选择,刷新页面仍保留当前会话。回复或参考上传进行中,请先等待完成或停止回复后再切换。 diff --git a/packages/core/src/opendirector/agent/cli_transport.py b/packages/core/src/opendirector/agent/cli_transport.py index 9e5e2f003..889257c5c 100644 --- a/packages/core/src/opendirector/agent/cli_transport.py +++ b/packages/core/src/opendirector/agent/cli_transport.py @@ -73,6 +73,18 @@ async def connection(reader, writer): 'arguments': arguments, 'result': detail[:65536], 'resultTruncated': len(detail) > 65536, 'timing': {'spawn': spawn, 'work': round(time.monotonic() - received, 3)}}) + if not outcome.error and isinstance(outcome.value, dict): + if name == 'ask_user' and outcome.value.get('decision'): + await queue.put({ + 'type': 'decision', + 'decision': outcome.value['decision'], + 'task': outcome.value.get('task'), + }) + elif name == 'update_plan' and outcome.value.get('task'): + await queue.put({ + 'type': 'task', + 'task': outcome.value['task'], + }) except (ProjectError, ValueError, KeyError, OSError, TimeoutError) as failure: response = {'error': str(failure)} writer.write(json.dumps(response, ensure_ascii=False).encode() + b'\n') @@ -83,6 +95,15 @@ async def connection(reader, writer): pending.discard(task) if hasattr(asyncio, 'start_unix_server'): + if sys.platform == 'linux' and len(os.fsencode(endpoint)) >= 104: + path = Path(endpoint) + descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + return await asyncio.start_unix_server( + connection, f'/proc/self/fd/{descriptor}/{path.name}', limit=4 * 1024 * 1024, + ), None + finally: + os.close(descriptor) return await asyncio.start_unix_server(connection, endpoint, limit=4 * 1024 * 1024), None server = await asyncio.start_server(connection, '127.0.0.1', 0, limit=4 * 1024 * 1024) host, port = server.sockets[0].getsockname()[:2] diff --git a/packages/core/src/opendirector/agent/context.py b/packages/core/src/opendirector/agent/context.py index e8708c474..e2dcd10f8 100644 --- a/packages/core/src/opendirector/agent/context.py +++ b/packages/core/src/opendirector/agent/context.py @@ -1,7 +1,9 @@ """Shared input contract for SDK, CLI and service-backed runtimes.""" import json +from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from pathlib import Path +from typing import Literal from uuid import UUID from pydantic import JsonValue @@ -27,6 +29,12 @@ class RunContext: thinking: str = 'auto' runtime_model: str | None = None skills: list[dict[str, str]] = field(default_factory=list) + mode: Literal['auto', 'ask'] = 'auto' + task_id: UUID | None = None + task_stage: str = 'running' + current_plan: dict[str, JsonValue] | None = None + rebuild_native_context: bool = False + on_dispatched: Callable[[], Awaitable[None]] | None = field(default=None, repr=False, compare=False) def native_session_path(self) -> Path | None: if self.conversation_id is None: @@ -34,6 +42,8 @@ def native_session_path(self) -> Path | None: return self.directory / 'agent-runs' / f'{self.runtime}-sessions' / str(self.conversation_id) def native_session(self, selection: dict) -> dict | None: + if self.rebuild_native_context: + return None directory = self.native_session_path() if directory is None or not (directory / 'session.json').is_file(): return None diff --git a/packages/core/src/opendirector/agent/decisions.py b/packages/core/src/opendirector/agent/decisions.py new file mode 100644 index 000000000..b84af7997 --- /dev/null +++ b/packages/core/src/opendirector/agent/decisions.py @@ -0,0 +1,1518 @@ +"""Authoritative decision records, versioned plan snapshots and continuation recovery.""" +from __future__ import annotations + +from contextlib import contextmanager +import hashlib +import json +import re +from pathlib import Path +from typing import Annotated, Literal +from uuid import UUID, uuid5 + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from opendirector.application.creation_timeline_packages import CreationTimelinePackages +from opendirector.domain.creation.base import agent_command_id +from opendirector.domain.creation.timeline_packages import TimelinePackageImportFile +from opendirector.domain.projects import ProjectError +from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH +from opendirector.infrastructure.creation_projects import durable_json +from opendirector.infrastructure.local_projects import child, read_json + +InteractionMode = Literal['auto', 'ask'] +ASK_SUPPORTED_RUNTIMES = frozenset({'default', 'opencode', 'claude', 'codex', 'deepseek', 'pi'}) + +TaskStage = Literal[ + 'running', + 'planning', + 'waiting_input', + 'answer_saved', + 'resuming', + 'waiting_confirmation', + 'executing', + 'waiting_jobs', + 'execution_failed', + 'completed', + 'interrupted', + 'status_unknown', +] + +DecisionStatus = Literal[ + 'waiting_input', + 'answer_saved', + 'resuming', + 'completed', + 'invalidated', + 'resume_failed', + 'status_unknown', +] + +_RECOMMENDED_SUFFIX = re.compile( + r'(?:\s*(?:(推荐)|\(推荐\)|\(Recommended\)|\[Recommended\]|【推荐】))+\s*$', + re.IGNORECASE, +) + + +def strip_recommended_marker(label: str) -> str: + cleaned = _RECOMMENDED_SUFFIX.sub('', label.strip()).strip() + return cleaned or label.strip() + + +def _require_non_blank(value: str) -> str: + trimmed = value.strip() + if not trimmed: + raise ValueError('Field must not be blank.') + return trimmed + + +class QuestionOptionModel(BaseModel): + model_config = ConfigDict(extra='forbid') + id: str = Field(min_length=1, max_length=120, description='Stable option identifier within the question.') + label: str = Field(min_length=1, max_length=200, description='Short option label without hardcoded recommendation badges.') + impact: str = Field(min_length=1, max_length=500, description='One-sentence explanation of what changes if this option is chosen.') + + _non_blank = field_validator('id', 'impact')(_require_non_blank) + + @field_validator('label') + @classmethod + def _clean_label(cls, value: str) -> str: + cleaned = strip_recommended_marker(value) + if not cleaned: + raise ValueError('Option label must not be blank.') + return cleaned + + +class QuestionItemModel(BaseModel): + model_config = ConfigDict(extra='forbid') + id: str = Field(min_length=1, max_length=120, description='Stable question identifier within the request.') + question: str = Field(min_length=1, max_length=500, description='Question prompt shown to the user.') + multiSelect: bool = Field(default=False, description='Whether the user may select multiple preset options.') + required: bool = Field(default=True, description='Whether this question requires an answer before submission.') + defaultOptionIds: list[str] = Field(default_factory=list, max_length=8, description='Explicit default option IDs for optional questions.') + defaultText: str | None = Field(default=None, max_length=500, description='Explicit default custom answer for optional questions.') + options: list[QuestionOptionModel] = Field(min_length=1, max_length=8, description='Options ordered from highest recommendation to lowest.') + + _non_blank = field_validator('id', 'question')(_require_non_blank) + + @model_validator(mode='after') + def _validate_options(self) -> QuestionItemModel: + option_ids = [option.id for option in self.options] + if len(option_ids) != len(set(option_ids)): + raise ValueError(f'Duplicate option IDs in question {self.id!r}.') + if self.defaultOptionIds: + if self.required: + raise ValueError(f'Required question {self.id!r} cannot declare defaultOptionIds.') + unknown = set(self.defaultOptionIds) - set(option_ids) + if unknown: + raise ValueError(f'Unknown defaultOptionIds in question {self.id!r}: {sorted(unknown)}.') + if not self.multiSelect and len(self.defaultOptionIds) > 1: + raise ValueError(f'Single-select question {self.id!r} cannot have multiple defaultOptionIds.') + if self.defaultText is not None: + if self.required: + raise ValueError(f'Required question {self.id!r} cannot declare defaultText.') + if not self.defaultText.strip(): + raise ValueError(f'defaultText in question {self.id!r} must not be blank.') + return self + + +class PlanStepInput(BaseModel): + model_config = ConfigDict(extra='forbid') + content: str = Field(min_length=1, max_length=1000) + kind: Literal['write', 'read', 'inspection'] + + +PlanStep = PlanStepInput | Annotated[str, Field(min_length=1, max_length=1000)] + + +class PlanDraftInput(BaseModel): + model_config = ConfigDict(extra='forbid') + summary: str = Field(min_length=1, max_length=PROMPT_MAX_LENGTH, description='Versioned plan summary or Markdown content.') + steps: list[PlanStep] = Field( + default_factory=list, max_length=50, description='Ordered steps. A string denotes a write step.' + ) + + +class AskUserInput(BaseModel): + model_config = ConfigDict(extra='forbid') + questions: list[QuestionItemModel] = Field(min_length=1, max_length=4, description='1 to 4 questions in this decision group.') + stage: str = Field(default='planning', min_length=1, max_length=80, description='Logical task stage.') + plan: PlanDraftInput | str | None = Field(default=None, description='Optional current plan summary or structured plan draft.') + + @model_validator(mode='after') + def _unique_question_ids(self) -> AskUserInput: + ids = [item.id for item in self.questions] + if len(ids) != len(set(ids)): + raise ValueError('Question IDs in ask_user must be unique.') + return self + + +class UpdatePlanInput(BaseModel): + model_config = ConfigDict(extra='forbid') + summary: str = Field(min_length=1, max_length=PROMPT_MAX_LENGTH, description='Complete updated plan summary or Markdown body.') + steps: list[PlanStep] = Field( + default_factory=list, max_length=50, description='Ordered steps. A string denotes a write step.' + ) + planOnly: bool | None = Field(default=None, description='Whether the user requested planning only without execution.') + + +class CompleteStepInput(BaseModel): + model_config = ConfigDict(extra='forbid') + stepId: str = Field(min_length=1, max_length=120, description='Plan step ID such as step-1.') + summary: str = Field(min_length=1, max_length=2000, description='Concise verified outcome of this read or inspection step.') + + +class AnswerItemInput(BaseModel): + model_config = ConfigDict(extra='forbid') + questionId: str = Field(min_length=1, max_length=120) + source: Literal['options', 'custom', 'default'] + selectedOptionIds: list[str] = Field(default_factory=list, max_length=8) + customText: str | None = Field(default=None, max_length=PROMPT_MAX_LENGTH) + + +class DecisionAnswerSubmit(BaseModel): + model_config = ConfigDict(extra='forbid') + answers: list[AnswerItemInput] = Field(min_length=1, max_length=4) + + +class PlanConfirmInput(BaseModel): + model_config = ConfigDict(extra='forbid') + planRevision: int = Field(ge=1) + + +class PlanAdjustInput(BaseModel): + model_config = ConfigDict(extra='forbid') + planRevision: int = Field(ge=1) + prompt: str | None = Field(default=None, max_length=PROMPT_MAX_LENGTH) + + +def extract_plan_steps(text: str) -> list[str]: + steps: list[str] = [] + for raw_line in text.splitlines(): + line = raw_line.strip() + if not line or line == '[opendirector-replies]: #': + continue + match = re.match(r'^(?:[-*+]|\d+[.)、])\s+(.+)$', line) + if match: + step = match.group(1).strip() + if step and len(step) <= 500: + steps.append(step) + if len(steps) >= 20: + break + if not steps and text.strip(): + first_line = text.strip().splitlines()[0].strip() + if first_line: + steps.append(first_line[:500]) + return steps + + +def _build_default_answer(question: dict, options_by_id: dict[str, dict]) -> dict: + default_ids = question.get('defaultOptionIds') or [] + default_text = question.get('defaultText') + labels = [options_by_id[opt_id]['label'] for opt_id in default_ids if opt_id in options_by_id] + return { + 'questionId': question['id'], + 'source': 'default', + 'selectedOptionIds': list(default_ids), + 'selectedLabels': labels, + 'customText': default_text, + 'displayText': default_text if default_text else '、'.join(labels), + } + + +def normalize_answers(questions: list[dict], submitted: list[AnswerItemInput]) -> tuple[list[dict], str]: + by_id = {q['id']: q for q in questions} + seen: set[str] = set() + normalized_by_id: dict[str, dict] = {} + + for item in submitted: + if item.questionId in seen: + raise ProjectError('同一题目不能重复提交多份答案。', 422, code='decision_answer_invalid') + seen.add(item.questionId) + question = by_id.get(item.questionId) + if question is None: + raise ProjectError(f'未知题目标识:{item.questionId}。', 422, code='decision_answer_invalid') + options_by_id = {opt['id']: opt for opt in question['options']} + if item.source == 'custom': + custom = (item.customText or '').strip() + if not custom: + raise ProjectError('自定义回答不能为空。', 422, code='decision_answer_invalid') + if item.selectedOptionIds: + raise ProjectError('输入自定义回答后不能同时提交预设选项。', 422, code='decision_answer_invalid') + normalized_by_id[item.questionId] = { + 'questionId': item.questionId, + 'source': 'custom', + 'selectedOptionIds': [], + 'selectedLabels': [], + 'customText': custom, + 'displayText': custom, + } + elif item.source == 'options': + if item.customText is not None and item.customText.strip(): + raise ProjectError('选择预设选项时不能同时混入自定义文本。', 422, code='decision_answer_invalid') + if not item.selectedOptionIds: + raise ProjectError('请至少选择一个选项,或直接输入自定义内容。', 422, code='decision_answer_invalid') + if not question.get('multiSelect', False) and len(item.selectedOptionIds) > 1: + raise ProjectError('单选题只能选择一个预设选项。', 422, code='decision_answer_invalid') + ordered_ids: list[str] = [] + for opt_id in item.selectedOptionIds: + if opt_id not in options_by_id: + raise ProjectError(f'选项标识无效:{opt_id}。', 422, code='decision_answer_invalid') + if opt_id not in ordered_ids: + ordered_ids.append(opt_id) + labels = [options_by_id[opt_id]['label'] for opt_id in ordered_ids] + normalized_by_id[item.questionId] = { + 'questionId': item.questionId, + 'source': 'options', + 'selectedOptionIds': ordered_ids, + 'selectedLabels': labels, + 'customText': None, + 'displayText': '、'.join(labels), + } + elif item.source == 'default': + if question.get('required', True): + raise ProjectError('必答题不能使用默认值跳过。', 422, code='decision_answer_invalid') + if not (question.get('defaultOptionIds') or question.get('defaultText')): + raise ProjectError('该题目没有设置默认值,不能使用默认值跳过。', 422, code='decision_answer_invalid') + normalized_by_id[item.questionId] = _build_default_answer(question, options_by_id) + + ordered_answers: list[dict] = [] + for q in questions: + qid = q['id'] + if qid in normalized_by_id: + ordered_answers.append(normalized_by_id[qid]) + elif not q.get('required', True) and (q.get('defaultOptionIds') or q.get('defaultText')): + ordered_answers.append(_build_default_answer(q, {opt['id']: opt for opt in q['options']})) + else: + raise ProjectError(f'请先回答题目:{q["question"]}', 422, code='decision_answer_invalid') + + canonical = [ + { + 'questionId': ans['questionId'], + 'source': ans['source'], + 'selectedOptionIds': ans['selectedOptionIds'], + 'customText': ans['customText'], + } + for ans in ordered_answers + ] + encoded = json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') + return ordered_answers, 'sha256:' + hashlib.sha256(encoded).hexdigest() + + +def capture_related_versions(snapshot_dict: dict, task: dict) -> list[dict]: + """Capture explicit plan and referenced-asset versions without binding unrelated canvas moves.""" + versions: list[dict] = [{ + 'objectType': 'plan', + 'id': str(task['taskId']), + 'revision': int(task.get('planRevision', 0)), + 'fingerprint': None, + }] + assets_by_id = {str(item['id']): item for item in snapshot_dict.get('assets', [])} + seen_assets: set[str] = set() + for asset_id in task.get('referencedAssetIds', []): + aid = str(asset_id) + asset = assets_by_id.get(aid) + if asset is not None and aid not in seen_assets: + seen_assets.add(aid) + versions.append({ + 'objectType': 'asset', + 'id': aid, + 'revision': int(asset['revision']), + 'fingerprint': asset.get('fingerprint'), + }) + return versions + + +def related_versions_valid(snapshot_dict: dict, task: dict | None, decision: dict) -> bool: + """Verify explicit dependency versions. Unrelated canvas dragging never invalidates a question.""" + if task is None: + return False + assets_by_id = { + str(item['id']): item + for item in snapshot_dict.get('assets', []) + if not item.get('trashedAt') + } + for entry in decision.get('relatedVersions', []): + kind = entry['objectType'] + expected_rev = entry.get('revision') + if kind == 'plan': + if int(task.get('planRevision', 0)) != int(expected_rev or 0): + return False + elif kind == 'asset': + target = assets_by_id.get(str(entry['id'])) + if target is None: + return False + if expected_rev is not None and int(target['revision']) != int(expected_rev): + return False + if entry.get('fingerprint') and target.get('fingerprint') != entry['fingerprint']: + return False + return True + + +def build_continuation_prompt_block(task: dict, decision: dict) -> str: + """Build the authoritative latest context block when resuming after user answers ask_user.""" + question_map = {q['id']: q for q in decision.get('questions', [])} + formatted_answers = [] + for ans in decision.get('answers') or []: + q = question_map.get(ans['questionId'], {}) + options_map = {opt['id']: opt for opt in q.get('options', [])} + chosen_impacts = [ + options_map[oid]['impact'] + for oid in ans.get('selectedOptionIds', []) + if oid in options_map + ] + formatted_answers.append({ + 'questionId': ans['questionId'], + 'question': q.get('question', ans['questionId']), + 'answerSource': ans['source'], + 'selectedOptionIds': ans.get('selectedOptionIds', []), + 'selectedLabels': ans.get('selectedLabels', []), + 'selectedImpacts': chosen_impacts, + 'customText': ans.get('customText'), + 'effectiveAnswer': ans.get('customText') if ans['source'] == 'custom' else ans.get('displayText'), + }) + + payload = { + 'type': 'ask_user_answer_continuation', + 'taskId': task['taskId'], + 'requestId': decision['requestId'], + 'continuationId': decision['continuationId'], + 'mode': task.get('mode', 'ask'), + 'currentPlanRevision': task.get('planRevision', 0), + 'currentPlan': task.get('plan'), + 'acceptedReceipts': task.get('acceptedReceipts', []), + 'answers': formatted_answers, + } + return ( + 'OpenDirector user decision response (authoritative checkpoint):\n' + + json.dumps(payload, ensure_ascii=False, indent=2) + + '\n\nInstructions for this continuation segment:\n' + '1. You MUST incorporate every `effectiveAnswer` above into the updated plan. ' + 'When `answerSource` is `"custom"`, `customText` is a first-class requirement: adopt its exact values and instructions verbatim ' + '(for example, exact duration such as 12 秒 and shot instructions such as 最后留 3 秒空镜) and NEVER map or round it to a preset option.\n' + '2. Do NOT repeat any operation with an applied, accepted, or noop receipt.\n' + '3. This segment is in the planning stage (`waiting_confirmation`). Save the updated plan by running ' + '`opendirector plan save --summary "" --step "" --step ""` ' + 'or use `opendirector plan save --file updated_plan.json` for steps with explicit kinds. ' + 'In JSON, each step can be {"content": "...", "kind": "write|read|inspection"}. ' + 'Use write for project changes or generation, read for OpenDirector queries, and inspection for native file/media checks. ' + 'A plain string denotes a write step. Because the UI renders the saved plan card (summary and steps) directly below your reply, ' + 'reply with only 1 to 3 brief sentences on key creative choices or trade-offs without repeating the numbered step list in Markdown, ' + 'and END THIS TURN IMMEDIATELY to wait for the user to confirm execution. ' + 'Do NOT execute project mutation commands (`canvas`, `asset`, `video`, `generation`) in this segment.' + ) + + +def build_execution_prompt_block(task: dict) -> str: + """Build the authoritative context block when executing a confirmed plan revision.""" + plan = task.get('plan') or {} + payload = { + 'type': 'plan_execution_confirmation', + 'taskId': task['taskId'], + 'confirmedPlanRevision': task.get('confirmedPlanRevision'), + 'executionContinuationId': task.get('executionContinuationId'), + 'stepOperationIds': { + step['id']: str(step_operation_id(task, step)) + for step in plan.get('steps', []) + }, + 'plan': plan, + 'acceptedReceipts': task.get('acceptedReceipts', []), + } + return ( + 'OpenDirector confirmed plan execution (authoritative checkpoint):\n' + + json.dumps(payload, ensure_ascii=False, indent=2) + + '\n\nInstructions for this execution segment:\n' + '1. The user has explicitly confirmed Plan Revision ' + f"{task.get('confirmedPlanRevision')}. Project write operations are now unlocked.\n" + '2. Inspect `acceptedReceipts` and step status first. Skip completed steps and do not repeat an operation with an applied, accepted, noop, or verified receipt.\n' + '3. Execute the confirmed plan faithfully, including every custom answer in `plan.summary`. ' + 'Use the corresponding `stepOperationIds` value as the global `--operation-id` for each step’s final OpenDirector command ' + '(including read/query commands such as `project show` or `query`). ' + 'For an inspection step that uses native file/media tools, record its outcome with ' + '`opendirector --operation-id plan complete-step --step --summary ""`. ' + 'Every other independent write needs its own operation ID. Reuse an ID only to retry the same write with the same input. ' + 'Report any incomplete steps and summarize the actual results.' + ) + + +def step_operation_id(task: dict, step: dict) -> UUID: + if step.get('operationId'): + return UUID(step['operationId']) + return uuid5(UUID(task['taskId']), f"plan:{task['planRevision']}:{step['id']}") + + +def write_allowed(task: dict, turn_id: UUID | str) -> bool: + if task['stage'] == 'running': + return str(turn_id) == task['taskId'] + return ( + task['stage'] == 'executing' + and task.get('executionContinuationId') == str(turn_id) + and task.get('confirmedPlanRevision') == task.get('planRevision') + and task.get('confirmedPlanRevision') is not None + ) + + +def receipt_outcome(receipt: dict, jobs: dict) -> str: + status = receipt.get('status') + if status in {'applied', 'noop', 'verified'}: + return 'completed' + if status == 'rejected': + return 'failed' + if status == 'accepted' and receipt.get('jobIds'): + linked = [jobs.get(str(job_id)) for job_id in receipt['jobIds']] + if all(linked): + if all(job.status == 'succeeded' for job in linked): + return 'completed' + if any(job.status in {'queued', 'running'} for job in linked): + return 'in_progress' + if all(job.status in {'succeeded', 'failed', 'cancelled'} and + getattr(job.errorDetails, 'category', None) != 'submission_unknown' for job in linked): + return 'failed' + return 'pending' + + +def execution_outcome(task: dict, jobs: dict) -> str: + steps = (task.get('plan') or {}).get('steps', []) + step_calls = {f"cli:{step_operation_id(task, step)}": step for step in steps} + relevant = {} + for receipt in task.get('acceptedReceipts', []): + call_id = receipt['callId'] + step = step_calls.get(call_id) + if receipt.get('receipt', {}).get('stepId'): + kind = 'inspection' if receipt['type'] == 'complete_step' else 'read' + if step is None or step.get('kind', 'write') != kind: + continue + elif step is None and receipt.get('turnId') != task.get('executionContinuationId'): + continue + relevant[call_id] = receipt_outcome(receipt, jobs) + for call_id, step in step_calls.items(): + step['status'] = relevant.get(call_id, 'pending') + if task.get('pendingWrites') or 'pending' in relevant.values(): + return 'status_unknown' + if 'in_progress' in relevant.values(): + return 'waiting_jobs' + if 'failed' in relevant.values(): + return 'execution_failed' + if steps and all(step['status'] == 'completed' for step in steps): + return 'completed' + return 'status_unknown' + + +class DecisionStore: + """Project-scoped durable persistence for logical tasks, decisions and versioned plans.""" + + def __init__(self, projects): + self.projects = projects + + def _file(self, directory: Path) -> Path: + return child(child(directory, 'agent-runs'), 'decisions.json') + + def _read_raw(self, directory: Path) -> dict: + file = self._file(directory) + if not file.is_file(): + return {'tasks': {}, 'decisions': {}} + data = read_json(file) + return {'tasks': dict(data.get('tasks') or {}), 'decisions': dict(data.get('decisions') or {})} + + def _write_raw(self, directory: Path, data: dict) -> None: + file = self._file(directory) + file.parent.mkdir(exist_ok=True) + durable_json(file, data) + + @contextmanager + def _open_store(self, project_id: UUID, *, session: str | None = None, open_project: bool = False): + with self.projects.local.transaction() as db: + self.projects._recover() + directory, _, records = self.projects._load(db, project_id) + if session is not None: + self.projects._lease(db, project_id, directory, session, browser_only=open_project) + if open_project: + self.projects.local.acquire_edit_lease(db, {'id': str(project_id), 'path': str(directory)}, session) + yield db, directory, records, self._read_raw(directory) + + @contextmanager + def _open_existing_store(self, project_id: UUID): + with self.projects.local.transaction() as db: + directory, _ = self.projects._find(db, project_id) + if not self._file(directory).is_file(): + yield db, directory, None + return + self.projects._recover() + directory, _, _ = self.projects._load(db, project_id) + yield db, directory, self._read_raw(directory) + + @staticmethod + def _lazy_auto_task(directory: Path, data: dict, project_id: UUID, turn_id: UUID) -> dict | None: + conv_file = child(child(directory, 'agent-runs'), 'conversation.json') + if not conv_file.is_file(): + return None + conv = read_json(conv_file) + tid = str(turn_id) + user_msg = next((m for m in conv.get('messages', []) if m.get('role') == 'user' and m.get('id') == tid), None) + if user_msg is None: + return None + cid = conv.get('conversationId') or str(uuid5(project_id, 'assistant')) + task = { + 'taskId': tid, + 'conversationId': cid, + 'mode': user_msg.get('mode') or 'auto', + 'runtime': user_msg.get('runtime') or conv.get('runtime') or 'default', + 'planOnly': bool(user_msg.get('planOnly')), + 'stage': 'running', + 'latestTurnId': tid, + 'referencedAssetIds': [str(item['id']) for item in (user_msg.get('assets') or []) if isinstance(item, dict) and 'id' in item], + 'planRevision': 0, + 'plan': None, + 'confirmedPlanRevision': None, + 'executionContinuationId': None, + 'activeDecisionId': None, + 'pendingContinuationId': None, + 'segmentTurnIds': [tid], + 'acceptedReceipts': [], + 'pendingWrites': [], + 'error': None, + 'errorCode': None, + } + data['tasks'][tid] = task + return task + + @staticmethod + def _find_task(data: dict, turn_id: UUID | str) -> dict | None: + tid = str(turn_id) + return data['tasks'].get(tid) or next( + (item for item in data['tasks'].values() if tid in item.get('segmentTurnIds', [])), + None, + ) + + @staticmethod + def _receipt_entry( + command_id: str, + call_id: str, + turn_id: UUID | str, + kind: str, + receipt: dict, + *, + input_fingerprint: str | None = None, + retryable: bool = False, + ) -> dict: + entry = { + 'commandId': command_id, + 'callId': call_id, + 'turnId': str(turn_id), + 'type': kind, + 'status': receipt.get('status'), + 'inputFingerprint': input_fingerprint, + 'changed': receipt.get('changed', []), + 'jobIds': receipt.get('jobIds', []), + 'receipt': receipt, + } + if retryable: + entry['retryable'] = True + return entry + + @staticmethod + def _store_committed_receipt(task: dict, entry: dict) -> None: + cid = entry['commandId'] + task['acceptedReceipts'] = [ + r for r in task.get('acceptedReceipts', []) if not (r.get('commandId') == cid and r.get('retryable')) + ] + if not any(r.get('commandId') == cid for r in task['acceptedReceipts']): + task['acceptedReceipts'].append(entry) + + @classmethod + def _retryable_rejection( + cls, command_id: str, call_id: str, turn_id: UUID | str, kind: str, message: str, + *, code: str | None = None, input_fingerprint: str | None = None, + ) -> dict: + receipt = { + 'status': 'rejected', + 'retryable': True, + 'issues': [{'code': code or 'operation_rejected', 'message': message}], + } + return cls._receipt_entry( + command_id, call_id, turn_id, kind, receipt, input_fingerprint=input_fingerprint, retryable=True, + ) + + @staticmethod + def _require_current_conversation(directory: Path, task: dict, project_id: UUID) -> None: + file = child(child(directory, 'agent-runs'), 'conversation.json') + current = read_json(file).get('conversationId') if file.is_file() else None + if task['conversationId'] != (current or str(uuid5(project_id, 'assistant'))): + raise ProjectError('请切回任务所属对话后再继续。', 409, code='task_conversation_changed') + + def begin_task( + self, + project_id: UUID, + conversation_id: UUID, + turn_id: UUID, + *, + mode: InteractionMode, + runtime: str, + referenced_asset_ids: list[str], + plan_only: bool = False, + continue_existing: bool = False, + ) -> dict: + if mode == 'ask' and runtime not in ASK_SUPPORTED_RUNTIMES: + raise ProjectError('当前 Agent 运行时暂不支持询问模式。', 409, code='ask_mode_runtime_unsupported') + initial_stage: TaskStage = 'planning' if (mode == 'ask' or plan_only) else 'running' + with self._open_store(project_id) as (_, directory, _, data): + tid, cid = str(turn_id), str(conversation_id) + if continue_existing and mode == 'ask': + reusable = None + for candidate in data['tasks'].values(): + if candidate.get('conversationId') != cid: + continue + is_planned_mode = candidate.get('mode') == 'ask' or bool(candidate.get('planOnly')) + if candidate.get('pendingWrites'): + if is_planned_mode: + reusable = None + continue + stage = candidate.get('stage') + if stage == 'waiting_input': + active_id = candidate.get('activeDecisionId') + if active_id and active_id in data['decisions']: + old_dec = data['decisions'][active_id] + if old_dec.get('status') == 'waiting_input': + old_dec['status'] = 'invalidated' + candidate['activeDecisionId'] = None + if candidate.get('plan') is not None: + reusable = candidate + else: + candidate['stage'] = 'interrupted' + reusable = None + elif ( + candidate.get('plan') is not None + and stage in {'planning', 'waiting_confirmation', 'execution_failed', 'interrupted'} + ): + reusable = candidate + elif is_planned_mode: + reusable = None + if reusable is not None: + reusable.update( + mode=mode, + runtime=runtime, + planOnly=plan_only, + stage='planning', + latestTurnId=tid, + confirmedPlanRevision=None, + error=None, + errorCode=None, + ) + existing_refs = list(reusable.get('referencedAssetIds') or []) + for aid in referenced_asset_ids: + if str(aid) not in existing_refs: + existing_refs.append(str(aid)) + reusable['referencedAssetIds'] = existing_refs + if tid not in reusable.setdefault('segmentTurnIds', []): + reusable['segmentTurnIds'].append(tid) + self._write_raw(directory, data) + return reusable + task = { + 'taskId': tid, + 'conversationId': cid, + 'mode': mode, + 'runtime': runtime, + 'planOnly': plan_only, + 'stage': initial_stage, + 'latestTurnId': tid, + 'referencedAssetIds': [str(aid) for aid in referenced_asset_ids], + 'planRevision': 0, + 'plan': None, + 'confirmedPlanRevision': None, + 'executionContinuationId': None, + 'activeDecisionId': None, + 'pendingContinuationId': None, + 'segmentTurnIds': [tid], + 'acceptedReceipts': [], + 'pendingWrites': [], + 'error': None, + 'errorCode': None, + } + data['tasks'][tid] = task + self._write_raw(directory, data) + return task + + def get_task(self, project_id: UUID, task_id: UUID | str) -> dict | None: + with self._open_store(project_id) as (_, _, _, data): + return data['tasks'].get(str(task_id)) + + def task_for_turn(self, project_id: UUID, turn_id: UUID | str) -> dict | None: + try: + with self._open_existing_store(project_id) as (_, _, data): + return self._find_task(data, turn_id) if data is not None else None + except ProjectError: + return None + + def record_question(self, project_id: UUID, turn_id: UUID, call_id: str, payload: AskUserInput) -> dict: + snapshot = self.projects.snapshot(project_id).model_dump(mode='json') + request_id = str(uuid5(turn_id, f'ask_user:{call_id}')) + with self._open_store(project_id) as (_, directory, _, data): + task = self._find_task(data, turn_id) or self._lazy_auto_task(directory, data, project_id, turn_id) + if task is None: + raise ProjectError('找不到当前对话任务上下文。', 404, code='missing_object') + + existing = data['decisions'].get(request_id) + if existing is not None: + return {'decision': existing, 'task': task} + + if task.get('activeDecisionId'): + active_dec = data['decisions'].get(task['activeDecisionId']) + if active_dec and active_dec.get('status') == 'waiting_input': + raise ProjectError('当前任务已有待回答的问题,请等待用户回答后再继续。', 409, code='task_waiting_input') + + requires_new_confirmation = write_allowed(task, turn_id) and task['stage'] == 'executing' + if payload.plan is not None: + summary = payload.plan if isinstance(payload.plan, str) else payload.plan.summary + steps = ( + extract_plan_steps(payload.plan) + if isinstance(payload.plan, str) + else (payload.plan.steps or extract_plan_steps(payload.plan.summary)) + ) + self._apply_plan_update_locked(task, summary, steps, str(turn_id), force_revision=requires_new_confirmation) + elif requires_new_confirmation: + plan = task['plan'] + self._apply_plan_update_locked( + task, plan['summary'], self._plan_step_inputs(plan), str(turn_id), force_revision=True, + ) + + assistant_message_id = str(uuid5(turn_id, 'assistant')) + decision = { + 'requestId': request_id, + 'taskId': task['taskId'], + 'conversationId': task['conversationId'], + 'turnId': str(turn_id), + 'messageId': assistant_message_id, + 'callId': call_id, + 'stage': payload.stage, + 'planRevision': int(task.get('planRevision', 0)), + 'relatedVersions': capture_related_versions(snapshot, task), + 'questions': [q.model_dump(mode='json') for q in payload.questions], + 'status': 'waiting_input', + 'answers': None, + 'answerFingerprint': None, + 'continuationId': None, + 'error': None, + 'errorCode': None, + } + data['decisions'][request_id] = decision + task['stage'] = 'waiting_input' + task['activeDecisionId'] = request_id + self._write_raw(directory, data) + + conv_file = child(child(directory, 'agent-runs'), 'conversation.json') + if conv_file.is_file(): + conv = read_json(conv_file) + for msg in conv.get('messages', []): + if msg.get('id') == assistant_message_id: + msg['decisionRequestId'] = request_id + msg['taskId'] = task['taskId'] + durable_json(conv_file, conv) + + return {'decision': decision, 'task': task} + + @staticmethod + def _plan_step_inputs(plan: dict) -> list[PlanStepInput]: + return [PlanStepInput(content=step['content'], kind=step.get('kind', 'write')) for step in plan['steps']] + + @staticmethod + def _apply_plan_update_locked(task: dict, summary: str, steps: list[PlanStep], turn_id: str, *, force_revision=False) -> dict: + cleaned_summary = summary.strip() + if not cleaned_summary: + return task.get('plan') or {} + current_plan = task.get('plan') + steps = [ + PlanStepInput(content=step, kind='write') if isinstance(step, str) else step + for step in steps or extract_plan_steps(cleaned_summary) + ] + unchanged = bool( + current_plan + and current_plan['summary'] == cleaned_summary + and DecisionStore._plan_step_inputs(current_plan) == steps + ) + if unchanged and not force_revision: + return current_plan + next_revision = int(task.get('planRevision', 0)) + 1 + plan_steps = [] + for index, step in enumerate(steps, start=1): + step_id = f'step-{index}' + previous = current_plan['steps'][index - 1] if unchanged else None + if previous is not None and previous['status'] == 'failed': + previous = None + operation_id = ( + step_operation_id(task, previous) if previous is not None + else uuid5(UUID(task['taskId']), f'plan:{next_revision}:{step_id}') + ) + plan_steps.append({ + 'id': step_id, **step.model_dump(), 'status': previous['status'] if previous else 'pending', + 'operationId': str(operation_id), + }) + plan_obj = { + 'revision': next_revision, + 'summary': cleaned_summary, + 'steps': plan_steps, + 'updatedAtTurnId': str(turn_id), + } + task['planRevision'] = next_revision + task['plan'] = plan_obj + if task.get('confirmedPlanRevision') is not None and task['confirmedPlanRevision'] < next_revision: + task['confirmedPlanRevision'] = None + return plan_obj + + def save_plan(self, project_id: UUID, turn_id: UUID, payload: UpdatePlanInput) -> dict: + with self._open_store(project_id) as (_, directory, _, data): + task = self._find_task(data, turn_id) or self._lazy_auto_task(directory, data, project_id, turn_id) + if task is None: + raise ProjectError('找不到当前对话任务上下文。', 404, code='missing_object') + if payload.planOnly is not None: + task['planOnly'] = payload.planOnly + previous_revision = task['planRevision'] + stage = task['stage'] + plan = task.get('plan') or {} + # Saving an identical draft in a refinement still requires a new confirmation. + force_revision = stage == 'resuming' or ( + stage == 'planning' and bool(plan) and plan.get('updatedAtTurnId') != str(turn_id) + ) + steps = payload.steps or extract_plan_steps(payload.summary) + plan_obj = self._apply_plan_update_locked( + task, payload.summary, steps, str(turn_id), force_revision=force_revision, + ) + if stage != 'waiting_input' and plan_obj.get('updatedAtTurnId') == str(turn_id) and ( + stage != 'executing' or task['planRevision'] != previous_revision + ): + task['stage'] = 'waiting_confirmation' + self._write_raw(directory, data) + return {'plan': plan_obj, 'task': task} + + def finalize_segment( + self, + project_id: UUID, + turn_id: UUID, + *, + reply_text: str, + segment_status: str, + error: str | None = None, + before_model: bool = False, + ) -> dict | None: + """Update task and decision state when a turn or continuation segment ends.""" + with self._open_store(project_id) as (_, directory, records, data): + task = self._find_task(data, turn_id) + if task is None: + return None + if task.get('pendingModelTurnId') == str(turn_id): + before_model = True + task.pop('pendingModelTurnId') + + decision = next( + (d for d in data['decisions'].values() if d.get('continuationId') == str(turn_id)), + None, + ) + if task['stage'] == 'waiting_input': + if decision is not None and decision['status'] == 'resuming': + decision['status'] = 'completed' + task['pendingContinuationId'] = None + self._write_raw(directory, data) + return task + + saved_continuation_plan = decision is not None and self._has_continuation_plan(task, decision) + if segment_status in {'interrupted', 'stopped'} and not saved_continuation_plan: + if decision is not None and decision['status'] == 'resuming': + decision['status'] = 'resume_failed' if before_model else 'status_unknown' + decision['error'] = error + decision['errorCode'] = 'continuation_resume_failed' if before_model else 'continuation_status_unknown' + task['stage'] = 'answer_saved' if before_model else 'status_unknown' + task['error'] = decision['error'] + elif task.get('executionContinuationId') == str(turn_id): + if write_allowed(task, turn_id) and before_model: + task['stage'] = 'waiting_confirmation' + task['confirmedPlanRevision'] = None + task['error'] = error + else: + task['stage'] = 'interrupted' + task['error'] = error + self._write_raw(directory, data) + return task + + if decision is not None and not saved_continuation_plan: + decision['status'] = 'resume_failed' + decision['errorCode'] = 'continuation_plan_missing' + task['stage'] = 'answer_saved' + self._write_raw(directory, data) + return task + + if decision is not None and decision['status'] in {'resuming', 'status_unknown', 'answer_saved'}: + self._complete_continuation(task, decision) + if task['stage'] == 'status_unknown': + task['stage'] = 'resuming' + + if task.get('executionContinuationId') == str(turn_id): + if write_allowed(task, turn_id): + jobs = {str(job.id): job for job in records[0].snapshot.jobs} + task['stage'] = execution_outcome(task, jobs) + elif task['stage'] in {'planning', 'resuming', 'waiting_confirmation', 'running'}: + plan_updated_in_turn = ( + task['stage'] != 'running' + and task.get('plan') is not None + and task['plan'].get('updatedAtTurnId') == str(turn_id) + ) + if plan_updated_in_turn: + task['stage'] = 'waiting_confirmation' + elif task['stage'] != 'running' and task.get('plan') is not None: + task['stage'] = 'planning' + elif task.get('planOnly') and reply_text.strip(): + self._apply_plan_update_locked(task, reply_text.strip(), extract_plan_steps(reply_text), str(turn_id)) + task['stage'] = 'waiting_confirmation' + else: + task['stage'] = 'completed' + + self._write_raw(directory, data) + return task + + def submit_answer( + self, + project_id: UUID, + session: str, + request_id: UUID | str, + submission: DecisionAnswerSubmit, + ) -> dict: + snapshot = self.projects.snapshot(project_id).model_dump(mode='json') + req_id = str(request_id) + with self._open_store(project_id, session=session, open_project=True) as (_, directory, _, data): + decision = data['decisions'].get(req_id) + if decision is None: + raise ProjectError('待回答的问题不存在。', 404, code='missing_object') + task = data['tasks'].get(decision['taskId']) + if task is None: + raise ProjectError('所属对话任务不存在。', 404, code='missing_object') + + self._require_current_conversation(directory, task, project_id) + normalized, fingerprint = normalize_answers(decision['questions'], submission.answers) + + if decision.get('answers') is not None and decision['status'] != 'invalidated': + if decision.get('answerFingerprint') == fingerprint: + return { + 'replayed': True, + 'requestId': req_id, + 'status': decision['status'], + 'continuationId': decision['continuationId'], + 'decision': decision, + 'task': task, + } + raise ProjectError('该问题已在其他页面提交了不同答案,已展示当前保存的结果。', 409, code='decision_answer_conflict') + + if decision['status'] == 'invalidated' or not related_versions_valid(snapshot, task, decision): + decision['status'] = 'invalidated' + if task.get('activeDecisionId') == req_id: + task['activeDecisionId'] = None + self._write_raw(directory, data) + raise ProjectError('相关素材或计划版本已变更,旧问题已失效,不会覆盖新内容。', 409, code='decision_version_invalidated') + + continuation_id = str(uuid5(UUID(req_id), 'continuation')) + decision.update( + answers=normalized, + answerFingerprint=fingerprint, + continuationId=continuation_id, + status='answer_saved', + error=None, + errorCode=None, + ) + task['stage'] = 'answer_saved' + task['pendingContinuationId'] = continuation_id + if continuation_id not in task['segmentTurnIds']: + task['segmentTurnIds'].append(continuation_id) + + self._write_raw(directory, data) + return { + 'replayed': False, + 'requestId': req_id, + 'status': 'answer_saved', + 'continuationId': continuation_id, + 'decision': decision, + 'task': task, + } + + def claim_continuation(self, project_id: UUID, session: str, continuation_id: UUID | str) -> dict: + """Atomically transition a continuation from answer_saved (or resume_failed) to resuming.""" + snapshot = self.projects.snapshot(project_id).model_dump(mode='json') + cid = str(continuation_id) + with self._open_store(project_id, session=session, open_project=True) as (_, directory, _, data): + decision = next((d for d in data['decisions'].values() if d.get('continuationId') == cid), None) + if decision is None: + raise ProjectError('接续记录不存在。', 404, code='missing_object') + task = data['tasks'].get(decision['taskId']) + if task is None: + raise ProjectError('所属对话任务不存在。', 404, code='missing_object') + + self._require_current_conversation(directory, task, project_id) + if decision['status'] == 'completed': + return {'state': 'already_completed', 'decision': decision, 'task': task} + if decision['status'] == 'status_unknown': + raise ProjectError('上一次接续执行状态待核对,为避免重复付费调用,未自动重发。', 409, code='continuation_status_unknown') + if decision['status'] == 'resuming': + return {'state': 'already_resuming', 'decision': decision, 'task': task} + if decision['status'] == 'invalidated' or not related_versions_valid(snapshot, task, decision): + decision['status'] = 'invalidated' + self._write_raw(directory, data) + raise ProjectError('相关素材或计划版本已变更,旧问题已失效,不会覆盖新内容。', 409, code='decision_version_invalidated') + if decision['status'] not in {'answer_saved', 'resume_failed'}: + raise ProjectError('当前问题尚未保存答案,无法接续。', 409, code='decision_not_answered') + + decision.update(status='resuming', error=None, errorCode=None) + task['stage'] = 'resuming' + task['pendingModelTurnId'] = cid + if cid not in task['segmentTurnIds']: + task['segmentTurnIds'].append(cid) + self._write_raw(directory, data) + return {'state': 'claimed', 'decision': decision, 'task': task} + + def claim_plan_execution( + self, + project_id: UUID, + session: str, + task_id: UUID | str, + payload: PlanConfirmInput, + *, + inspect_only: bool = False, + ) -> dict: + tid = str(task_id) + with self._open_store(project_id, session=session, open_project=True) as (_, directory, _, data): + task = data['tasks'].get(tid) + if task is None: + raise ProjectError('对话任务不存在。', 404, code='missing_object') + self._require_current_conversation(directory, task, project_id) + if task.get('planOnly'): + raise ProjectError('此任务只要求规划。', 409, code='plan_confirmation_required') + if not task.get('plan') or int(task.get('planRevision', 0)) < 1: + raise ProjectError('当前任务尚无可确认的计划版本。', 409, code='plan_missing') + if int(payload.planRevision) != int(task['planRevision']): + raise ProjectError('计划版本已变更,旧确认已失效,请确认最新计划版本。', 409, code='plan_revision_stale') + if task.get('stage') == 'waiting_input': + raise ProjectError('请先回答待决问题后再确认执行计划。', 409, code='task_waiting_input') + if task.get('stage') == 'status_unknown': + raise ProjectError('当前任务执行状态待核对,请先核对已生成产物或回执。', 409, code='continuation_status_unknown') + + exec_cid = str(uuid5(UUID(tid), f'execute:{payload.planRevision}')) + if ( + task.get('confirmedPlanRevision') == payload.planRevision + and task.get('executionContinuationId') == exec_cid + ): + if task['stage'] == 'completed': + return {'state': 'already_completed', 'continuationId': exec_cid, 'task': task} + if ( + task['stage'] in {'executing', 'interrupted'} + or any(r.get('turnId') == exec_cid for r in task.get('acceptedReceipts', [])) + or any(p.get('turnId') == exec_cid for p in task.get('pendingWrites', [])) + ): + return {'state': 'already_executing', 'continuationId': exec_cid, 'task': task} + + if task['stage'] != 'waiting_confirmation': + raise ProjectError('当前计划尚未准备好确认。', 409, code='plan_confirmation_required') + if task.get('pendingWrites'): + raise ProjectError('原操作状态待核对,暂不能执行新版计划。', 409, code='continuation_status_unknown') + if inspect_only: + return {'state': 'ready', 'continuationId': exec_cid, 'task': task} + task['confirmedPlanRevision'] = payload.planRevision + task['executionContinuationId'] = exec_cid + task['stage'] = 'executing' + task['pendingModelTurnId'] = exec_cid + if exec_cid not in task['segmentTurnIds']: + task['segmentTurnIds'].append(exec_cid) + self._write_raw(directory, data) + return {'state': 'claimed', 'continuationId': exec_cid, 'task': task} + + def mark_model_dispatched(self, project_id: UUID, task_id: UUID, turn_id: UUID) -> None: + with self._open_store(project_id) as (_, directory, _, data): + task = data['tasks'].get(str(task_id)) + if ( + task is None or task.get('pendingModelTurnId') != str(turn_id) + or task['stage'] not in {'resuming', 'executing'} + ): + raise ProjectError('此执行片段的启动许可已失效。', 409, code='plan_revision_stale') + task.pop('pendingModelTurnId') + self._write_raw(directory, data) + + def adjust_plan(self, project_id: UUID, session: str, task_id: UUID | str, payload: PlanAdjustInput) -> dict: + tid = str(task_id) + with self._open_store(project_id, session=session, open_project=True) as (_, directory, records, data): + task = data['tasks'].get(tid) + if task is None: + raise ProjectError('对话任务不存在。', 404, code='missing_object') + self._require_current_conversation(directory, task, project_id) + if payload.planRevision != task['planRevision']: + raise ProjectError('计划版本已变更,请按最新版本调整。', 409, code='plan_revision_stale') + if task['stage'] not in {'executing', 'waiting_confirmation', 'status_unknown', 'execution_failed'} or not task.get('plan'): + raise ProjectError('当前计划不能调整。', 409, code='plan_confirmation_required') + plan = task['plan'] + if task.get('executionContinuationId'): + execution_outcome(task, {str(job.id): job for job in records[0].snapshot.jobs}) + if task['stage'] == 'status_unknown' and ( + task.get('pendingWrites') or not any(step['status'] == 'completed' for step in plan['steps']) + ): + raise ProjectError('原操作状态待核对,暂不能执行新版计划。', 409, code='continuation_status_unknown') + task['confirmedPlanRevision'] = None + summary = payload.prompt.strip() if payload.prompt else '' + steps = extract_plan_steps(summary) if summary else self._plan_step_inputs(plan) + self._apply_plan_update_locked(task, summary or plan['summary'], steps, plan['updatedAtTurnId'], force_revision=True) + task['stage'] = 'waiting_confirmation' + task.pop('pendingModelTurnId', None) + self._write_raw(directory, data) + return task + + def record_pending_write( + self, + project_id: UUID, + turn_id: UUID, + call_id: str, + command_dict: dict, + input_fingerprint: str, + *, + session: str | None = None, + ) -> dict | None: + """Fix operation identity before dispatch, or return an already-accepted receipt.""" + command_id = str(command_dict['commandId']) + try: + with self._open_existing_store(project_id) as (db, directory, data): + if data is None: + return None + task = self._find_task(data, turn_id) + if task is None: + return None + if session is not None: + self.projects._lease(db, project_id, directory, session) + if not write_allowed(task, turn_id): + raise ProjectError('当前计划尚未确认,不能派发写入。', 409, code='plan_confirmation_required') + if task['stage'] == 'running': + return None + for existing in task.get('acceptedReceipts', []): + if existing.get('commandId') == command_id and not existing.get('receipt', {}).get('stepId'): + if existing.get('inputFingerprint') and existing['inputFingerprint'] != input_fingerprint: + raise ProjectError('工具调用标识被用于不同输入。', 409) + if not existing.get('retryable') and existing.get('receipt'): + return existing['receipt'] + + pending = task.setdefault('pendingWrites', []) + existing = next((item for item in pending if item.get('commandId') == command_id), None) + if existing is not None: + if existing['inputFingerprint'] != input_fingerprint: + raise ProjectError('工具调用标识被用于不同输入。', 409) + raise ProjectError('原操作状态待核对,未重新派发。', 409, code='continuation_status_unknown') + pending.append({ + 'commandId': command_id, + 'callId': call_id, + 'turnId': str(turn_id), + 'type': command_dict['type'], + 'inputFingerprint': input_fingerprint, + 'command': command_dict, + 'dispatchState': 'reserved', + }) + self._write_raw(directory, data) + return None + except ProjectError as err: + if err.status == 404: + return None + raise + + def begin_pending_write(self, project_id: UUID, turn_id: UUID, command_id: str, session: str) -> None: + with self._open_existing_store(project_id) as (db, directory, data): + if data is None: + return + task = self._find_task(data, turn_id) + if task is None or task['stage'] == 'running': + return + pending = next((item for item in task.get('pendingWrites', []) if item['commandId'] == command_id), None) + if pending is None or pending.get('dispatchState') != 'reserved' or pending['turnId'] != str(turn_id): + raise ProjectError('该操作的派发状态已变更。', 409, code='continuation_status_unknown') + try: + self.projects._lease(db, project_id, directory, session) + if not write_allowed(task, turn_id): + raise ProjectError('当前计划尚未确认,不能派发写入。', 409, code='plan_confirmation_required') + except ProjectError: + task['pendingWrites'].remove(pending) + self._write_raw(directory, data) + raise + pending['dispatchState'] = 'dispatched' + self._write_raw(directory, data) + + def command_id_for_write(self, project_id: UUID, turn_id: UUID, call_id: str) -> UUID: + if call_id.startswith('cli:'): + task = self.task_for_turn(project_id, turn_id) + if task is not None and task['stage'] != 'running': + for item in (*task.get('acceptedReceipts', []), *task.get('pendingWrites', [])): + if item.get('callId') == call_id and not item.get('receipt', {}).get('stepId'): + return UUID(item['commandId']) + return agent_command_id(turn_id, call_id) + + def record_accepted_receipt( + self, + project_id: UUID, + turn_id: UUID, + call_id: str, + command_dict: dict, + input_fingerprint: str, + receipt: dict, + ) -> None: + command_id = str(command_dict['commandId']) + try: + with self._open_existing_store(project_id) as (_, directory, data): + if data is None: + return + task = self._find_task(data, turn_id) + if task is None or task['stage'] == 'running': + return + task['pendingWrites'] = [p for p in task.get('pendingWrites', []) if p.get('commandId') != command_id] + self._store_committed_receipt( + task, + self._receipt_entry(command_id, call_id, turn_id, command_dict['type'], receipt, input_fingerprint=input_fingerprint), + ) + self._write_raw(directory, data) + except ProjectError as err: + if err.status == 404: + return + raise + + def record_pre_write_failure( + self, + project_id: UUID, + turn_id: UUID, + call_id: str, + command_dict: dict, + input_fingerprint: str, + error: str, + code: str | None = None, + ) -> bool: + """Record a failure proven to have occurred before any business write was committed.""" + command_id = str(command_dict['commandId']) + try: + with self._open_existing_store(project_id) as (_, directory, data): + if data is None: + return False + task = self._find_task(data, turn_id) + if task is None or task['stage'] == 'running': + return False + task['pendingWrites'] = [p for p in task.get('pendingWrites', []) if p.get('commandId') != command_id] + existing_receipts = task.setdefault('acceptedReceipts', []) + if any(r.get('commandId') == command_id and not r.get('retryable') for r in existing_receipts): + self._write_raw(directory, data) + return True + task['acceptedReceipts'] = [r for r in existing_receipts if r.get('commandId') != command_id] + task['acceptedReceipts'].append( + self._retryable_rejection( + command_id, call_id, turn_id, command_dict['type'], error, + code=code, input_fingerprint=input_fingerprint, + ) + ) + self._write_raw(directory, data) + return True + except ProjectError as err: + if err.status == 404: + return False + raise + + def record_step_completion( + self, + project_id: UUID, + turn_id: UUID, + call_id: str, + tool_name: str, + summary: str, + *, + step_id: str | None = None, + ) -> dict | None: + """Record verifiable completion of a read or inspection step during plan execution.""" + try: + with self._open_store(project_id) as (_, directory, _, data): + task = self._find_task(data, turn_id) + if task is None: + if step_id is not None: + raise ProjectError('找不到当前对话任务上下文。', 404, code='missing_object') + return None + if not write_allowed(task, turn_id): + if step_id is not None: + raise ProjectError('当前计划尚未确认,不能标记执行步骤完成。', 409, code='plan_confirmation_required') + return None + steps = (task.get('plan') or {}).get('steps', []) + by_call = {f"cli:{step_operation_id(task, step)}": step for step in steps} + by_id = {step['id']: step for step in steps} + if step_id is not None: + target = by_id.get(step_id) + if target is None: + err = ProjectError(f'未知计划步骤:{step_id}。', 422, code='invalid_input') + err._invalid_tool_input = True + raise err + expected_call = f"cli:{step_operation_id(task, target)}" + if call_id != expected_call: + raise ProjectError('步骤标识与操作 ID 不一致。', 409) + effective_call = expected_call + else: + target = by_call.get(call_id) + if target is None: + return None + effective_call = call_id + + kind = 'inspection' if step_id is not None else 'read' + if target.get('kind', 'write') != kind: + if step_id is not None: + raise ProjectError('只有检查步骤可以登记检查结果。', 422, code='plan_step_kind_mismatch') + return None + + command_id = str(step_operation_id(task, target)) + receipt = {'status': 'verified', 'stepId': target['id'], 'tool': tool_name, 'summary': summary} + existing_receipts = task.setdefault('acceptedReceipts', []) + if not any(r.get('callId') == effective_call and not r.get('retryable') for r in existing_receipts): + task['acceptedReceipts'] = [ + r for r in existing_receipts if not (r.get('callId') == effective_call and r.get('retryable')) + ] + task['acceptedReceipts'].append( + self._receipt_entry(command_id, effective_call, turn_id, tool_name, receipt) + ) + target['status'] = 'completed' + self._write_raw(directory, data) + return { + 'status': 'completed', + 'stepId': target['id'], + 'taskId': task['taskId'], + 'planRevision': task['planRevision'], + 'task': task, + } + except ProjectError as err: + if err.status == 404 and step_id is None: + return None + raise + + @staticmethod + def _has_continuation_plan(task: dict, decision: dict) -> bool: + plan = task.get('plan') + return bool( + plan and plan['updatedAtTurnId'] == decision.get('continuationId') + and plan['revision'] > decision['planRevision'] + ) + + @staticmethod + def _complete_continuation(task: dict, decision: dict) -> None: + decision.update(status='completed', error=None, errorCode=None) + if task.get('activeDecisionId') == decision['requestId']: + task['activeDecisionId'] = None + if task.get('pendingContinuationId') == decision['continuationId']: + task['pendingContinuationId'] = None + + def reconcile_interrupted(self, project_id: UUID, active_turn_id: UUID | None = None) -> dict: + """Reconcile tasks and decisions after a server restart or crash without duplicate writes.""" + live_id = str(active_turn_id) if active_turn_id is not None else None + with self.projects.local.transaction() as db: + self.projects._recover() + path, _ = self.projects._find(db, project_id) + if not self._file(path).is_file(): + return {'tasks': {}, 'decisions': {}} + directory, _, records = self.projects._load(db, project_id) + data = self._read_raw(directory) + snapshot = records[0].snapshot + version_view = snapshot.model_dump(mode='json') + jobs = {str(job.id): job for job in snapshot.jobs} + changed = False + resuming_decisions = {} + + for decision in data['decisions'].values(): + task = data['tasks'].get(decision['taskId']) + if decision['status'] == 'resuming': + resuming_decisions[decision['taskId']] = decision + elif decision['status'] in {'waiting_input', 'answer_saved', 'resume_failed'}: + if not related_versions_valid(version_view, task, decision): + decision['status'] = 'invalidated' + if task and task.get('activeDecisionId') == decision['requestId']: + task['activeDecisionId'] = None + changed = True + + for task in data['tasks'].values(): + if live_id is not None and (live_id == task['taskId'] or live_id in task.get('segmentTurnIds', [])): + continue + + remaining_pending: list[dict] = [] + for pending in list(task.get('pendingWrites', [])): + cmd_uuid = UUID(pending['commandId']) + uncertain = False + committed = None + if pending['type'] == 'timeline_package_import': + try: + request = TimelinePackageImportFile.model_validate(pending['command']['payload']) + result = CreationTimelinePackages(self.projects).reconcile_execution_import(project_id, request) + except (ProjectError, ValueError, KeyError, OSError): + uncertain = True + else: + if result is not None: + uncertain = result.status == 'registered' + if not uncertain: + committed = {'status': result.status, 'result': result.model_dump(mode='json')} + else: + try: + if pending['type'] in {'voice_create', 'voice_delete'}: + uncertain = pending.get('dispatchState') != 'reserved' + else: + committed = self.projects.receipt(project_id, cmd_uuid).model_dump(mode='json') + except ProjectError as err: + if err.status != 404: + raise + + if committed is not None: + self._store_committed_receipt( + task, + self._receipt_entry( + pending['commandId'], pending['callId'], pending['turnId'], pending['type'], + committed, input_fingerprint=pending.get('inputFingerprint'), + ), + ) + changed = True + elif uncertain: + remaining_pending.append(pending) + elif pending.get('dispatchState') != 'reserved': + if not any(r.get('commandId') == pending['commandId'] for r in task.get('acceptedReceipts', [])): + task.setdefault('acceptedReceipts', []).append( + self._retryable_rejection( + pending['commandId'], pending['callId'], pending['turnId'], pending['type'], + '操作在提交工程写入前中断,可按原输入重试。', + input_fingerprint=pending.get('inputFingerprint'), + ) + ) + changed = True + + if remaining_pending != task.get('pendingWrites', []): + task['pendingWrites'] = remaining_pending + changed = True + + pending_model = task.pop('pendingModelTurnId', None) + if pending_model: + changed = True + decision = resuming_decisions.get(task['taskId']) + if decision is not None and self._has_continuation_plan(task, decision): + self._complete_continuation(task, decision) + changed = True + elif task['stage'] == 'resuming': + can_retry = decision is not None and decision.get('continuationId') == pending_model + task['stage'] = 'answer_saved' if can_retry else 'status_unknown' + if decision is not None: + decision['status'] = 'answer_saved' if can_retry else 'status_unknown' + changed = True + if task['stage'] == 'executing' and pending_model == task.get('executionContinuationId') and pending_model: + task['stage'] = 'waiting_confirmation' + task['confirmedPlanRevision'] = None + changed = True + elif ( + task['stage'] in {'executing', 'status_unknown', 'waiting_jobs'} + and task.get('executionContinuationId') + and task.get('confirmedPlanRevision') == task.get('planRevision') + ): + previous_steps = [step['status'] for step in (task.get('plan') or {}).get('steps', [])] + next_stage = execution_outcome(task, jobs) + changed = changed or task['stage'] != next_stage or previous_steps != [ + step['status'] for step in (task.get('plan') or {}).get('steps', []) + ] + task['stage'] = next_stage + + if changed: + self._write_raw(directory, data) + return data + + def public_state(self, project_id: UUID, conversation_id: UUID | str, active_turn_id: UUID | None = None) -> dict: + data = self.reconcile_interrupted(project_id, active_turn_id) + cid = str(conversation_id) + return { + 'tasks': [task for task in data['tasks'].values() if task.get('conversationId') == cid], + 'decisions': [dec for dec in data['decisions'].values() if dec.get('conversationId') == cid], + } diff --git a/packages/core/src/opendirector/agent/deepseek.py b/packages/core/src/opendirector/agent/deepseek.py index dfb561c4b..892b3886e 100644 --- a/packages/core/src/opendirector/agent/deepseek.py +++ b/packages/core/src/opendirector/agent/deepseek.py @@ -143,7 +143,7 @@ async def model_choices(selected=None): await terminate(process, group=True) -async def run(process, work, blocks, model, thinking, server, observe, session_id=None): +async def run(process, work, blocks, model, thinking, server, observe, session_id=None, *, before_prompt=None): client = Client(process, observe) try: async with asyncio.timeout(30): @@ -152,6 +152,8 @@ async def run(process, work, blocks, model, thinking, server, observe, session_i await client.request('session/set_config_option', {'sessionId': client.session, 'configId': 'model', 'value': model}) if thinking != 'auto': await client.request('session/set_config_option', {'sessionId': client.session, 'configId': 'reasoning_effort', 'value': thinking}) + if before_prompt is not None: + await before_prompt() result = await client.request('session/prompt', {'sessionId': client.session, 'prompt': [{'type': 'text', 'text': block} for block in blocks]}) if result['stopReason'] != 'end_turn': diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index 04fa9db94..e40897fb9 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -18,6 +18,8 @@ class ToolResult: value: JsonValue error: str | None = None + retryable: bool = False + release_id: bool = False def event(self, name: str) -> AgentEvent: code = self.value.get('code') if isinstance(self.value, dict) else None @@ -40,6 +42,19 @@ def event(self, name: str) -> AgentEvent: # that has not been answered is worth nothing once the turn is over. WAITING_QUERIES = frozenset({'job.status', 'canvas.status'}) +READ_AND_PLANNING_TOOLS = frozenset({ + 'read_project', + 'read', + 'model_availability', + 'query', + 'command_schema', + 'prompt_optimize', + 'voice_list', + 'timeline_package_export', + 'ask_user', + 'update_plan', +}) + def _read_only(name, arguments) -> bool: """Whether this call may skip the execution lock. @@ -62,11 +77,28 @@ def __init__(self, business: AgentTools, run: RunContext): self.execution_directory: Path | None = None self.roots: list[Path] = [] self.closed = False - self.calls: dict[str, tuple[str, asyncio.Task[ToolResult]]] = {} + self.waiting_input = False + self.waiting_decision: dict | None = None + self.waiting_task: dict | None = None + self.waiting_event = asyncio.Event() + self.attempted_after_waiting = asyncio.Event() + self.calls: dict[str, tuple[str, asyncio.Task[ToolResult] | None]] = {} self.lock = asyncio.Lock() self.execution_lock = asyncio.Lock() self.names = {item['function']['name'] for item in tools()} + async def _current_stage(self) -> str: + if self.waiting_input: + return 'waiting_input' + if self.run.task_stage == 'running' and self.waiting_task is None: + return 'running' + decisions = getattr(self.business, 'decisions', None) + if decisions is not None: + task = await asyncio.to_thread(decisions.task_for_turn, self.run.project_id, self.run.turn_id) + if task is not None and isinstance(task.get('stage'), str): + return task['stage'] + return self.run.task_stage + async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -> ToolResult: identity = json.dumps([name, arguments], ensure_ascii=False, sort_keys=True) async with self.lock: @@ -78,10 +110,20 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) - return ToolResult(value={'error': '工具调用标识被用于不同输入。'}, error='工具调用标识被用于不同输入。') task = previous[1] else: + task = None + if task is None: task = asyncio.create_task(self.execute(call_id, name, deepcopy(arguments))) self.calls[call_id] = (identity, task) # Transport cancellation must not discard an accepted write or its receipt. - return await asyncio.shield(task) + outcome = await asyncio.shield(task) + if outcome.release_id or outcome.retryable: + async with self.lock: + if self.calls.get(call_id) == (identity, task): + if outcome.release_id: + self.calls.pop(call_id, None) + else: + self.calls[call_id] = (identity, None) + return outcome async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -> ToolResult: async with (nullcontext() if _read_only(name, arguments) else self.execution_lock): @@ -90,10 +132,24 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue] raise ProjectError('本轮工具入口已关闭。', 409) if not call_id or len(call_id) > 512 or name not in self.names: raise ProjectError('工具调用标识或名称无效。') + if self.run.on_dispatched is not None and self.run.runtime != 'deepseek': + await self.run.on_dispatched() + stage = await self._current_stage() + if stage == 'waiting_input': + self.attempted_after_waiting.set() + raise ProjectError('当前任务正在等待用户回答,已停止派发后续业务操作。', 409, code='task_waiting_input') + if stage in {'planning', 'resuming', 'waiting_confirmation'} and name not in READ_AND_PLANNING_TOOLS: + raise ProjectError( + '当前处于交互式计划阶段,需用户确认当前计划版本后才能修改工程或发起生成。', + 409, + code='plan_confirmation_required', + ) arguments = TypeAdapter(dict[str, JsonValue]).validate_python(arguments, strict=True) schema = next(item['function']['parameters'] for item in tools() if item['function']['name'] == name) if 'properties' in schema and (set(arguments) - set(schema['properties']) or set(schema.get('required', [])) - set(arguments)): - raise ProjectError('工具参数缺失或包含未定义字段。') + err = ProjectError('工具参数缺失或包含未定义字段。') + err._invalid_tool_input = True + raise err value = await self.business.execute(self.run.project_id, self.run.turn_id, self.run.session, call_id, name, arguments, self.roots, self.run.config, self.run.runtime if self.run.config is None else None, @@ -101,6 +157,14 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue] if name == 'prompt_optimize' else {})) if name == 'read_project': value['modelSelections'] = dict(self.model_selections) + elif name == 'ask_user' and isinstance(value, dict) and value.get('status') == 'waiting_input': + self.waiting_input = True + self.run.task_stage = 'waiting_input' + self.waiting_decision = value.get('decision') + self.waiting_task = value.get('task') + self.waiting_event.set() + elif name == 'update_plan' and isinstance(value, dict): + self.waiting_task = value.get('task') error = None if isinstance(value, dict): if value.get('status') == 'rejected': @@ -117,17 +181,24 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue] path = '.'.join(str(part) for part in location) messages.append(f"{path or 'command'}: {issue['msg']}") error = '; '.join(messages) - return ToolResult(value={'error': error}, error=error) + return ToolResult(value={'error': error}, error=error, release_id=True) except (ProjectError, ValueError, KeyError, OSError, UnicodeError) as failure: details = {'error': str(failure)} if isinstance(failure, ProjectError): details['code'] = failure.code - return ToolResult(value=details, error=str(failure)) + return ToolResult( + value=details, + error=str(failure), + retryable=bool(getattr(failure, '_retryable_pre_write', False)), + release_id=bool(getattr(failure, '_invalid_tool_input', False)), + ) async def close(self) -> None: self.closed = True for identity, task in self.calls.values(): + if task is None: + continue name, arguments = json.loads(identity) if name == 'query' and isinstance(arguments, dict) and arguments.get('type') in WAITING_QUERIES: task.cancel() - await asyncio.gather(*(task for _, task in self.calls.values()), return_exceptions=True) + await asyncio.gather(*(task for _, task in self.calls.values() if task is not None), return_exceptions=True) diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 5b23f3c5c..bba1db0a8 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -1,6 +1,6 @@ """CLI runtimes use native skills and a turn-scoped business CLI.""" import asyncio -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, suppress import json import os from pathlib import Path @@ -10,7 +10,7 @@ import sys from tempfile import TemporaryDirectory from urllib.request import getproxies -from uuid import UUID +from uuid import UUID, uuid4 from opendirector.agent.model_gateway import ModelGateway from opendirector.agent import cli_transport, deepseek, pi, windows_powershell @@ -19,7 +19,14 @@ from opendirector.agent.citations import search_sources from opendirector.agent.gateway import ToolGateway from opendirector.agent.process import terminate -from opendirector.agent.tools import ROOT, SUGGESTED_REPLIES, SYSTEM, runtime_instructions +from opendirector.agent.tools import ( + AUTO_MODE_GUIDANCE, + ROOT, + SUGGESTED_REPLIES, + SYSTEM, + build_ask_mode_guidance, + runtime_instructions, +) from opendirector.installation import BUNDLED from opendirector.agent.skill_snapshot import prepare_skills from opendirector.agent.directory_links import link_directory, unlink_directory @@ -201,17 +208,23 @@ async def stream(self, run: RunContext, gateway: ToolGateway): queue = asyncio.Queue(maxsize=128) pending = set() token = secrets.token_urlsafe(32) - process = pump = stderr_task = None + process = pump = stderr_task = waiting_guard = None with TemporaryDirectory(prefix='od-agent-', dir=None if os.name == 'nt' else '/tmp') as temporary: reuse_workspace = session_directory is not None and runtime in {'codex', 'claude', 'deepseek', 'pi'} - work = session_directory if reuse_workspace else (directory / 'agent-runs' / str(turn_id) / 'work').resolve() + candidate_work = (directory / 'agent-runs' / str(turn_id) / 'work').resolve() + if reuse_workspace: + work = session_directory + elif not candidate_work.exists(): + work = candidate_work + else: + work = (directory / 'agent-runs' / str(uuid4()) / 'work').resolve() work.mkdir(parents=True, exist_ok=reuse_workspace) gateway.execution_directory = work # OpenCode emits session events in the session's original instance # directory. Keep that engine directory stable, while the gateway, # CLI, skills and all published outputs remain scoped to this turn. native_work = session_directory or work - server = model_server = model = None + server = model_server = model = workspace_socket = None permissions = AsyncExitStack() try: if runtime == 'deepseek': @@ -231,19 +244,22 @@ async def stream(self, run: RunContext, gateway: ToolGateway): roots = prepare_skills(work, catalog) roots += [Path(item['filePath']).resolve().parent for item in catalog] gateway.roots = roots - endpoint = str(Path(temporary) / 'cli.sock') + private_endpoint = str(Path(temporary) / 'cli.sock') + if runtime == 'deepseek' and sys.platform == 'linux': + workspace_socket = work / f'.opendirector-{turn_id.hex[:12]}.sock' + endpoint = str(workspace_socket) if workspace_socket else private_endpoint server, bridge_env = await cli_transport.start_server(gateway, queue, endpoint, pending) if run.runtime == 'default': model = ModelGateway( config, thinking, token, str(project_id), str(turn_id), self.transport, - trace_path=work.parent.with_suffix('.model.jsonl'), + trace_path=directory / 'agent-runs' / f'{turn_id}.model.jsonl', ) model_server = await asyncio.start_server(model.connect, '127.0.0.1', 0) if model else None model_url = f'http://127.0.0.1:{model_server.sockets[0].getsockname()[1]}' if model_server else '' deepseek_server = None if runtime == 'deepseek': env = cli_transport.environment(work, endpoint, bridge_env) - args, _, deepseek_server = deepseek.command(work, endpoint, token, bridge_env) + args, _, deepseek_server = deepseek.command(work, private_endpoint, token, bridge_env) else: args, env = command(run.runtime, work, endpoint, token, config['modelId'] if config else runtime_model, model_url, catalog, bridge_env=bridge_env, @@ -264,13 +280,23 @@ async def stream(self, run: RunContext, gateway: ToolGateway): args += ['--session-id', session_id] else: args += ['--session' if runtime == 'opencode' else '--resume', session_id] + mode_guidance = '' + if run.mode == 'ask' and run.task_stage == 'planning': + mode_guidance = build_ask_mode_guidance(run.current_plan) + elif run.mode == 'auto' and run.task_stage == 'running': + mode_guidance = AUTO_MODE_GUIDANCE + include_suggestions = ( + run.mode == 'auto' + and run.task_stage not in {'planning', 'waiting_input', 'resuming', 'waiting_confirmation'} + ) execution_context = (f'Execution directory: {work}\nNative session directory: {native_work}\n' 'Set the native shell workdir to this execution directory for file and media operations. ' 'Use inherited PATH to discover installed programs with Get-Command in PowerShell or command -v in POSIX shells. ' 'Read source assets at their supplied absolute paths; do not move or modify them. ' 'Write all intermediate files and outputs into the execution directory. ' 'Use opendirector --help to discover OpenDirector commands and opendirector --help for usage. Use opendirector for project changes.\n' - + SUGGESTED_REPLIES) + + mode_guidance + + (SUGGESTED_REPLIES if include_suggestions else '')) prompt = execution_context + '\n' + json.dumps(context[-1:] if session_id else context, ensure_ascii=False) skill_instruction = '' if selected: @@ -301,6 +327,8 @@ async def drain_stderr(): del stderr_tail[:-8192] stderr_task = asyncio.create_task(drain_stderr()) if runtime != 'deepseek': + if run.on_dispatched is not None: + await run.on_dispatched() process.stdin.write(prompt.encode() + b'\n') await process.stdin.drain() process.stdin.close() @@ -311,12 +339,29 @@ async def record_exit(): diagnostic = diagnostic.replace(config['apiKey'], '[redacted]') await queue.put({'native': {'type': 'diagnostic', 'stderr': diagnostic, 'exitCode': process.returncode}}) + terminated_for_waiting = False + async def finish_waiting(): + nonlocal terminated_for_waiting + await gateway.waiting_event.wait() + with suppress(TimeoutError): + await asyncio.wait_for(process.wait(), 10) + return + terminated_for_waiting = True + await terminate(process, group=True) + + waiting_guard = asyncio.create_task(finish_waiting()) if hasattr(gateway, 'waiting_event') else None async def output(): + nonlocal terminated_for_waiting try: reported_session = None + saw_completion_event = False if runtime == 'deepseek': async def observe(raw): + nonlocal terminated_for_waiting await queue.put({'native': raw}) + if hasattr(gateway, 'attempted_after_waiting') and gateway.attempted_after_waiting.is_set(): + terminated_for_waiting = True + await terminate(process, group=True) blocks = [execution_context] if session_id else [SYSTEM, execution_context] if skill_instruction: blocks.append(skill_instruction) @@ -324,8 +369,15 @@ async def observe(raw): blocks.append('Conversation history\n' + json.dumps(context[:-1], ensure_ascii=False)) if context: blocks.append('Current user request\n' + context[-1]['content']) - reported_session = await deepseek.run(process, work, blocks, runtime_model, thinking, - deepseek_server, observe, session_id) + try: + reported_session = await deepseek.run( + process, work, blocks, runtime_model, thinking, deepseek_server, observe, + session_id, before_prompt=run.on_dispatched, + ) + saw_completion_event = reported_session is not None + except ProjectError: + if not terminated_for_waiting: + raise else: while line := await process.stdout.readline(): raw = json.loads(line) @@ -338,19 +390,40 @@ async def observe(raw): reported_session = raw.get('session_id') or reported_session elif runtime == 'pi' and raw['type'] == 'session': reported_session = raw.get('id') or reported_session + event_type = raw.get('type') + if runtime == 'codex' and event_type == 'turn.completed': + saw_completion_event = True + elif runtime == 'opencode' and event_type == 'step_finish': + saw_completion_event = raw.get('part', {}).get('reason') == 'stop' + elif runtime == 'claude' and event_type == 'result' and not raw.get('is_error'): + saw_completion_event = True + elif runtime == 'pi' and event_type == 'agent_end': + assistant = [item for item in raw.get('messages') or [] + if (item or {}).get('role') == 'assistant'] + last = assistant[-1] if assistant else {} + if last.get('stopReason') != 'error': + saw_completion_event = True + elif run.mode == 'auto' and run.task_stage == 'running' and event_type in {'item.completed', 'text', 'assistant', 'message_end'}: + saw_completion_event = True if (previous_session and reported_session != previous_session or session_id and reported_session and reported_session != session_id): raise ProjectError('Harness 返回了不同的会话 ID。', 502) await queue.put({'native': raw}) - if await process.wait(): - await record_exit() - raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。', 502) - if reported_session: + if hasattr(gateway, 'attempted_after_waiting') and gateway.attempted_after_waiting.is_set(): + terminated_for_waiting = True + await terminate(process, group=True) + break + exit_code = await process.wait() + if exit_code: + if not terminated_for_waiting: + await record_exit() + raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。', 502) + elif reported_session and saw_completion_event and not terminated_for_waiting: run.save_native_session(reported_session, selection, engine_directory=native_work, - work_turn_id=run.turn_id if native_work == work and not reuse_workspace else UUID(native_work.parent.name)) + work_turn_id=UUID(native_work.parent.name)) except ProjectError: - if runtime == 'deepseek' and process.returncode: + if runtime == 'deepseek' and process.returncode and not terminated_for_waiting: await record_exit() raise finally: @@ -373,11 +446,16 @@ async def observe(raw): yield event await pump finally: + if waiting_guard is not None: + waiting_guard.cancel() + await asyncio.gather(waiting_guard, return_exceptions=True) try: await gateway.close() if server: server.close() await server.wait_closed() + if workspace_socket: + workspace_socket.unlink(missing_ok=True) if model_server: model.closed = True model_server.close() diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 150487756..c0b93c68b 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -1,14 +1,17 @@ """Business commands shared by every agent runtime.""" import asyncio +from contextlib import asynccontextmanager from opendirector.application.model_availability import ModelAvailability import difflib +import hashlib +import json import shutil from pathlib import Path from typing import get_args from uuid import UUID, uuid5 from pydantic import JsonValue, TypeAdapter, ValidationError -from opendirector.domain.creation.base import agent_command_id +from opendirector.agent.decisions import AskUserInput, CompleteStepInput, DecisionStore, UpdatePlanInput from opendirector.application.creation_artifacts import publish_artifact from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_timeline_packages import CreationTimelinePackages @@ -19,7 +22,7 @@ from opendirector.application.voice_library import VoiceLibrary from opendirector.domain.creation.assets import AssetProvenance from opendirector.domain.creation.base import ObjectVersion -from opendirector.domain.creation.commands import Query, COMMAND_MODELS, parse_command +from opendirector.domain.creation.commands import Query, COMMAND_MODELS, command_fingerprint, parse_command from opendirector.domain.creation.models import ModelSnapshot from opendirector.domain.projects import ProjectError from opendirector.domain.voices import VOICE_CREATE_TEXT_LIMITS @@ -60,7 +63,7 @@ def query_guidance(failure): for command_name, command_model in COMMANDS.items(): assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' SYSTEM = '''You are OpenDirector, a video creation assistant. -Respond directly when the user's request can be answered without project state or tool execution. +Unless the turn specifies ASK MODE (`ask`), respond directly when the user's request can be answered without project state or tool execution. When the task needs project capabilities, run the opendirector executable on PATH through the harness's native shell tool. Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload only when one field's shape is unclear. Do not run --help for each command. Accepted receipts return ready-to-run next commands with current revisions; use them instead of re-reading the project. @@ -94,6 +97,44 @@ def query_guidance(failure): '[opendirector-replies]: #\n\n' ) +def build_ask_mode_guidance(current_plan: dict | None = None) -> str: + base = ( + 'Interaction mode for this turn: ASK MODE (`ask`) — Mandatory Interactive Clarification Stage.\n' + 'The user explicitly selected ASK MODE (`ask`) for this turn. This instruction OVERRIDES the general "respond directly" rule.\n' + 'Project write commands and generation submissions are locked by the gateway until the user answers your questions and confirms the resulting plan.\n' + 'Even if the request is pure creative writing (such as scripts, worldbuilding, character profiles, or storyboards) or refines an existing plan in this conversation, ' + 'do NOT write out the requested deliverable or final revised plan in prose first, and do NOT ask questions in plain text.\n' + 'Instead, you MUST first call `opendirector ask-user --file questions.json` (or `--file -` via stdin) through the native shell tool to submit 1 to 4 structured questions ' + 'covering the key creative or technical choices that shape the requested result (for example: character arc/relationship tension, narrative perspective, tone, pacing, target duration, shot structure, or scope changes).\n' + 'Write `questions.json` in the execution directory as UTF-8 JSON with this structure:\n' + '{"questions":[{"id":"duration","question":"视频成片的目标时长是多少?","multiSelect":false,"required":true,' + '"options":[{"id":"8s","label":"8 秒","impact":"采用紧凑的三镜头叙事,适合快速展示核心画面。"},' + '{"id":"5s","label":"5 秒","impact":"浓缩为单主镜头与结尾定格,节奏最快。"},' + '{"id":"15s","label":"15 秒","impact":"展开完整起承转合,留出环境铺垫与呼吸感。"}]}]}\n' + 'Order `options` from highest recommendation to lowest. Do NOT include "(Recommended)" or "(推荐)" in `label` (the UI adds the badge automatically). ' + 'Every option MUST include `id`, `label`, and a one-sentence `impact` explaining what changes if selected.\n' + 'Once `opendirector ask-user` returns `status: "waiting_input"`, output 1 brief sentence introducing the question and END THIS TURN IMMEDIATELY without calling any more tools and without outputting `[opendirector-replies]: #`.\n' + 'Whenever you save a plan via `opendirector plan save`, keep your prose reply to 1 to 3 brief sentences on key choices or trade-offs and do NOT repeat the numbered step list in Markdown (the UI renders the saved plan card directly below your reply).\n' + ) + if current_plan and isinstance(current_plan, dict): + plan_view = { + 'revision': current_plan.get('revision'), + 'summary': current_plan.get('summary'), + 'steps': [step.get('content') for step in current_plan.get('steps', []) if isinstance(step, dict)], + } + base += ( + 'Active unconfirmed plan in this conversation (to be refined into the next revision AFTER the user answers your new question):\n' + + json.dumps(plan_view, ensure_ascii=False) + + '\nDo NOT deliver the expanded content or save the revised plan yet — ask your structured clarification question(s) for the user’s latest refinement request first via `opendirector ask-user`.\n' + ) + return base + + +AUTO_MODE_GUIDANCE = ( + 'Interaction mode for this task: AUTO MODE (`auto`). ' + 'Do not ask the user about inferable preferences; proceed directly unless required inputs are missing or explicit authorization is required.\n' +) + def runtime_instructions(runtime: str) -> str: if runtime == 'pi': @@ -320,6 +361,23 @@ def tools() -> list[dict]: ['modelConfigId', 'connectionId', 'voiceId']), ]: result.append(tool_schema(name, description, {'type': 'object', 'properties': properties, 'required': required, 'additionalProperties': False})) + result.append(tool_schema( + 'ask_user', + 'Persist 1 to 4 structured decision questions for the user and pause the current task segment until the user answers. ' + 'Options are ordered from highest recommendation to lowest without hardcoding recommendation markers in option labels; ' + 'each option includes a one-sentence impact describing what changes if selected.', + AskUserInput.model_json_schema(), + )) + result.append(tool_schema( + 'update_plan', + 'Persist a versioned plan snapshot for the current logical task and enter the waiting_confirmation stage.', + UpdatePlanInput.model_json_schema(), + )) + result.append(tool_schema( + 'complete_step', + 'Record the outcome of an inspection step in the confirmed execution plan.', + CompleteStepInput.model_json_schema(), + )) return result @@ -339,6 +397,17 @@ def __init__(self, projects, generation, configs, chat_provider=None): self.availability = getattr(generation, 'availability', None) or ModelAvailability(configs) self.assets = CreationAssets(projects) self.voices = getattr(generation, 'voices', None) or VoiceLibrary(configs) + self.decisions = DecisionStore(projects) + self._write_locks: dict[UUID, asyncio.Lock] = {} + + def write_lock(self, project_id: UUID) -> asyncio.Lock: + return self._write_locks.setdefault(project_id, asyncio.Lock()) + + @asynccontextmanager + async def _dispatch_write(self, project_id: UUID, turn_id: UUID, command_id: str, session: str): + async with self.write_lock(project_id): + await asyncio.to_thread(self.decisions.begin_pending_write, project_id, turn_id, command_id, session) + yield async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: str, name: str, arguments: dict, roots: list[Path], config: dict | None, native_runtime: str | None = None, @@ -350,6 +419,122 @@ async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: runtimeModel=runtime_model, thinking=thinking) if native_runtime or config else None return await self.prompt_optimization.rewrite(project_id, item_id, value.prompt, value.inlineReferences, value.preferredModelId, selection) + args = (project_id, turn_id, session, call_id, name, arguments, roots, config, native_runtime, execution_directory) + if name not in {'timeline_package_import', 'voice_create', 'voice_delete'}: + result = await self._execute(*args) + if call_id.startswith('cli:') and not (isinstance(result, dict) and result.get('error')) and name in { + 'read_project', 'query', 'read', 'model_availability', 'voice_list', 'timeline_package_export', + }: + await asyncio.to_thread( + self.decisions.record_step_completion, project_id, turn_id, call_id, name, 'completed', + ) + return result + import_request = TimelinePackageImportFile.model_validate(arguments) if name == 'timeline_package_import' else None + command_id = await asyncio.to_thread(self.decisions.command_id_for_write, project_id, turn_id, call_id) + command = {'commandId': str(command_id), 'type': name, 'payload': arguments} + fingerprint = hashlib.sha256(json.dumps(command, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + replayed = await asyncio.to_thread( + self.decisions.record_pending_write, project_id, turn_id, call_id, command, fingerprint, session=session, + ) + if replayed is not None: + return replayed.get('result', replayed) + async with self.write_lock(project_id): + dispatched = False + + def mark_dispatched(): + nonlocal dispatched + self.decisions.begin_pending_write(project_id, turn_id, str(command_id), session) + dispatched = True + + try: + if import_request is not None: + await asyncio.to_thread(mark_dispatched) + result = await self._execute(*args) + else: + result = await asyncio.to_thread( + self._execute_voice_write, name, arguments, execution_directory, mark_dispatched, + ) + except (ProjectError, ValueError, KeyError, OSError) as failure: + if dispatched: + if import_request is None: + raise + # An unreadable journal leaves the existing dispatch unresolved. + receipt = await asyncio.to_thread( + CreationTimelinePackages(self.projects).reconcile_execution_import, project_id, import_request, + ) + if receipt is not None: + if receipt.status == 'registered': + raise + result = receipt.model_dump(mode='json') + else: + dispatched = False + if not dispatched: + code = failure.code if isinstance(failure, ProjectError) else None + failure._retryable_pre_write = await asyncio.to_thread( + self.decisions.record_pre_write_failure, + project_id, turn_id, call_id, command, fingerprint, str(failure), code, + ) + raise + if name != 'timeline_package_import' or result['status'] != 'registered': + status = result['status'] if name == 'timeline_package_import' else 'applied' + await asyncio.to_thread( + self.decisions.record_accepted_receipt, project_id, turn_id, call_id, command, fingerprint, + {'status': status, 'result': result}, + ) + return result + + def _execute_voice_write(self, name, arguments, execution_directory, mark_dispatched): + model_id = str(UUID(arguments['modelConfigId'])) + connection = arguments['connectionId'] + if name == 'voice_delete': + self.voices.delete(model_id, arguments['voiceId'], connection, before_submit=mark_dispatched) + return {'deleted': True, 'voiceId': arguments['voiceId'], 'connectionId': connection} + target = Path(arguments['path']) + if execution_directory is None: + raise ProjectError('只能上传本轮执行目录内的录音。', 403) + _, capabilities = self.voices._config(model_id) + with execution_file(execution_directory, str(target)) as stream: + data = stream.read(capabilities['maxBytes'] + 1) + return self.voices.create( + model_id, data, filename=target.name, name=arguments['name'], consent=arguments.get('consent'), + connection_id=connection, ref_text=arguments.get('refText'), + speaker_description=arguments.get('speakerDescription'), before_submit=mark_dispatched, + ) + + async def _execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: str, + name: str, arguments: dict, roots: list[Path], config: dict | None, native_runtime: str | None, + execution_directory: Path | None) -> JsonValue: + if name == 'ask_user': + payload = AskUserInput.model_validate(arguments) + recorded = await asyncio.to_thread(self.decisions.record_question, project_id, turn_id, call_id, payload) + return { + 'status': 'waiting_input', + 'requestId': recorded['decision']['requestId'], + 'taskId': recorded['task']['taskId'], + 'planRevision': recorded['task']['planRevision'], + 'decision': recorded['decision'], + 'task': recorded['task'], + 'message': 'Question persisted. Stop this turn immediately and wait for the user answer without calling any more tools.', + } + if name == 'update_plan': + payload = UpdatePlanInput.model_validate(arguments) + saved = await asyncio.to_thread(self.decisions.save_plan, project_id, turn_id, payload) + return { + 'status': 'waiting_confirmation', + 'taskId': saved['task']['taskId'], + 'planRevision': saved['plan']['revision'], + 'plan': saved['plan'], + 'task': saved['task'], + } + if name == 'complete_step': + payload = CompleteStepInput.model_validate(arguments) + completed = await asyncio.to_thread( + self.decisions.record_step_completion, + project_id, turn_id, call_id, 'complete_step', payload.summary, step_id=payload.stepId, + ) + if completed is None: + raise ProjectError('找不到待标记的计划步骤。', 404, code='missing_object') + return completed if name in {'timeline_package_export', 'timeline_package_import'}: with self.projects.local.transaction() as db: project_directory, _, _ = self.projects._load(db, project_id) @@ -362,25 +547,10 @@ async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: receipt = await asyncio.to_thread(packages.import_execution_file, project_id, request, execution_directory=work, session=session) return receipt.model_dump(mode='json') - if name in {'voice_list', 'voice_create', 'voice_delete'}: + if name == 'voice_list': model_id = str(UUID(arguments['modelConfigId'])) - if name == 'voice_list': - return await asyncio.to_thread(self.voices.list, model_id, page_size=arguments.get('pageSize'), - after=arguments.get('after'), connection_id=arguments.get('connectionId')) - if name == 'voice_delete': - await asyncio.to_thread(self.voices.delete, model_id, arguments['voiceId'], arguments['connectionId']) - return {'deleted': True, 'voiceId': arguments['voiceId'], 'connectionId': arguments['connectionId']} - target = Path(arguments['path']) - if execution_directory is None: - raise ProjectError('只能上传本轮执行目录内的录音。', 403) - _, capabilities = self.voices._config(model_id) - def recording(): - with execution_file(execution_directory, str(target)) as stream: - return stream.read(capabilities['maxBytes'] + 1) - data = await asyncio.to_thread(recording) - return await asyncio.to_thread(self.voices.create, model_id, data, filename=target.name, - name=arguments['name'], consent=arguments.get('consent'), connection_id=arguments['connectionId'], - ref_text=arguments.get('refText'), speaker_description=arguments.get('speakerDescription')) + return await asyncio.to_thread(self.voices.list, model_id, page_size=arguments.get('pageSize'), + after=arguments.get('after'), connection_id=arguments.get('connectionId')) if name == 'read_project': snapshot = await asyncio.to_thread(self.projects.snapshot, project_id) return {'project': snapshot.model_dump(mode='json'), 'models': self.availability.catalog(), 'commands': list(COMMANDS), @@ -402,7 +572,9 @@ def recording(): except ValidationError as failure: # A rejected query must name the accepted types rather than echo a # tag list the model has to reinterpret. - raise ProjectError(query_guidance(failure)) from None + err = ProjectError(query_guidance(failure)) + err._invalid_tool_input = True + raise err from None if query.type in {'pipeline.plan', 'pipeline.execution.get', 'pipeline.executions.list'}: executor = getattr(self.generation, 'pipelines', None) if executor is None: @@ -489,29 +661,80 @@ def narrow(value: JsonValue) -> None: return command_help(schema, arguments.get('path', ''), project_id) if name != 'execute_command': raise ProjectError('未知业务工具。') - command = parse_command({**arguments, 'projectId': str(project_id), - 'commandId': str(agent_command_id(turn_id, call_id))}) + command_id = await asyncio.to_thread(self.decisions.command_id_for_write, project_id, turn_id, call_id) + command = parse_command({**arguments, 'projectId': str(project_id), 'commandId': str(command_id)}) if command.type == 'creation.batch' and any(operation.type not in COMMANDS for operation in command.payload.operations): raise ProjectError('批量命令包含未开放的 Agent 操作。', 403) - if command.type == 'generation.submit': - receipt = await self.generation.execute(command, session=session, source='agent', agent_origin=(turn_id, call_id)) - elif command.type in {'job.cancel', 'job.recover', 'pipeline.start', 'pipeline.pause', - 'pipeline.resume', 'pipeline.cancel', 'pipeline.retry', 'pipeline.adopt'}: - receipt = await self.generation.execute(command, session=session, source='agent') - elif command.type in {'asset.writeText', 'artifact.publish'}: - if config is not None: - provenance = AssetProvenance(source='agent_written', agentRunId=turn_id, - modelSnapshot=ModelSnapshot(modelConfigId=config['id'], kind='agent', modelId=config['modelId'], - url=config['url'], protocol=config['protocol'], connectionType=config['connectionType'])) - else: - provenance = AssetProvenance(source='agent_written', agentRunId=turn_id, agentRuntime=native_runtime) - if command.type == 'artifact.publish': - with self.projects.local.transaction() as db: - project_directory, _, _ = self.projects._load(db, project_id) - receipt = await asyncio.to_thread(publish_artifact, self.assets, command, - execution_directory=execution_directory or project_directory / 'agent-runs' / str(turn_id) / 'work', session=session, provenance=provenance) + command_dict = command.model_dump(mode='json') + input_fp = command_fingerprint(command) + replayed = await asyncio.to_thread( + self.decisions.record_pending_write, + project_id, + turn_id, + call_id, + command_dict, + input_fp, + session=session, + ) + if replayed is not None: + return replayed + async with self._dispatch_write(project_id, turn_id, str(command_id), session): + return await self._execute_project_write( + project_id, turn_id, session, call_id, command, command_dict, input_fp, config, native_runtime, + execution_directory, + ) + + async def _execute_project_write( + self, project_id, turn_id, session, call_id, command, command_dict, input_fp, config, native_runtime, + execution_directory, + ): + try: + if command.type == 'generation.submit': + receipt = await self.generation.execute(command, session=session, source='agent', agent_origin=(turn_id, call_id)) + elif command.type in {'job.cancel', 'job.recover', 'pipeline.start', 'pipeline.pause', + 'pipeline.resume', 'pipeline.cancel', 'pipeline.retry', 'pipeline.adopt'}: + receipt = await self.generation.execute(command, session=session, source='agent') + elif command.type in {'asset.writeText', 'artifact.publish'}: + if config is not None: + provenance = AssetProvenance(source='agent_written', agentRunId=turn_id, + modelSnapshot=ModelSnapshot(modelConfigId=config['id'], kind='agent', modelId=config['modelId'], + url=config['url'], protocol=config['protocol'], connectionType=config['connectionType'])) + else: + provenance = AssetProvenance(source='agent_written', agentRunId=turn_id, agentRuntime=native_runtime) + if command.type == 'artifact.publish': + with self.projects.local.transaction() as db: + project_directory, _, _ = self.projects._load(db, project_id) + receipt = await asyncio.to_thread(publish_artifact, self.assets, command, + execution_directory=execution_directory or project_directory / 'agent-runs' / str(turn_id) / 'work', session=session, provenance=provenance) + else: + receipt = await asyncio.to_thread(self.assets.execute, command, session=session, source='agent', provenance=provenance) else: - receipt = await asyncio.to_thread(self.assets.execute, command, session=session, source='agent', provenance=provenance) - else: - receipt = await asyncio.to_thread(self.projects.execute, command, session=session, source='agent') - return receipt.model_dump(mode='json') + receipt = await asyncio.to_thread(self.projects.execute, command, session=session, source='agent') + except (ProjectError, ValueError, KeyError, OSError, ValidationError) as failure: + committed = await asyncio.to_thread(self.projects.replay, command) + if committed is not None: + receipt_dict = committed.model_dump(mode='json') + await asyncio.to_thread( + self.decisions.record_accepted_receipt, + project_id, turn_id, call_id, command_dict, input_fp, receipt_dict, + ) + return receipt_dict + code = failure.code if isinstance(failure, ProjectError) else None + await asyncio.to_thread( + self.decisions.record_pre_write_failure, + project_id, turn_id, call_id, command_dict, input_fp, str(failure), code, + ) + failure._retryable_pre_write = True + raise + receipt_dict = receipt.model_dump(mode='json') + if receipt_dict.get('status') in {'applied', 'accepted', 'noop', 'rejected'}: + await asyncio.to_thread( + self.decisions.record_accepted_receipt, + project_id, + turn_id, + call_id, + command_dict, + input_fp, + receipt_dict, + ) + return receipt_dict diff --git a/packages/core/src/opendirector/application/creation_timeline_packages.py b/packages/core/src/opendirector/application/creation_timeline_packages.py index 96e2f733f..bc244bf3d 100644 --- a/packages/core/src/opendirector/application/creation_timeline_packages.py +++ b/packages/core/src/opendirector/application/creation_timeline_packages.py @@ -118,8 +118,8 @@ def export_execution_file(self, project_id, request, *, execution_directory): target.unlink(missing_ok=True) def import_execution_file(self, project_id, request, *, execution_directory, session): - handle = uuid5(request.operationId, 'archive-upload') - value = TimelinePackageImportRequest(**request.model_dump(exclude={'path'}), uploadHandle=handle) + value = self._execution_import_request(request) + handle = value.uploadHandle # Replays use the durable fixed request and never need to reopen input bytes. prior = self.imports.read(project_id, request.operationId) if prior is not None: @@ -275,6 +275,38 @@ def unique_pairs(pairs): def receipt(self, project_id, operation_id): return self.imports.receipt(project_id, operation_id) + @staticmethod + def _execution_import_request(request): + return TimelinePackageImportRequest( + **request.model_dump(exclude={'path'}), uploadHandle=uuid5(request.operationId, 'archive-upload'), + ) + + def reconcile_execution_import(self, project_id, request): + """Read the journal and final project receipt without dispatching an import.""" + record = self.imports.read(project_id, request.operationId) + if record is None: + return None + if record['request'] != self._execution_import_request(request).model_dump(mode='json'): + raise timeline_error('timeline_import_conflict', 409) + receipt = TimelinePackageImportReceipt.model_validate(record['receipt']) + if receipt.status != 'registered': + return receipt + try: + result = self.projects.receipt(project_id, uuid5(request.operationId, 'apply')) + except ProjectError as error: + if error.status != 404: + raise + return receipt + return self._finish_import_receipt(receipt, result) + + @staticmethod + def _finish_import_receipt(receipt, result): + return receipt.model_copy(update={ + 'status': 'applied' if result.status in {'applied', 'noop'} else 'rejected', + 'receipt': result, + 'errorCode': None, + }) + def import_package(self, project_id, request, *, session=None, source='ui'): request = TimelinePackageImportRequest.model_validate(request) with self.imports.lock(project_id, request.operationId): @@ -364,7 +396,7 @@ def remap(value): command = parse_command(dict(commandId=uuid5(request.operationId, 'apply'), projectId=project_id, type='creation.batch', expectedVersions=versions, payload=dict(operations=operations))) result = self.projects.execute(command, session=session, source=source) - receipt = receipt.model_copy(update={'status': 'applied' if result.status in {'applied', 'noop'} else 'rejected', 'receipt': result, 'errorCode': None}) + receipt = self._finish_import_receipt(receipt, result) self.imports.write(project_id, request, receipt) archive.unlink(missing_ok=True) return receipt diff --git a/packages/core/src/opendirector/application/voice_library.py b/packages/core/src/opendirector/application/voice_library.py index 77fdc6ff1..ec47c636d 100644 --- a/packages/core/src/opendirector/application/voice_library.py +++ b/packages/core/src/opendirector/application/voice_library.py @@ -278,7 +278,8 @@ def _find(self, config, capabilities, voice_id): return record, locator return None, None - def create(self, model_config_id, data, *, filename, name, consent=None, ref_text=None, speaker_description=None, connection_id=_CURRENT_CONNECTION): + def create(self, model_config_id, data, *, filename, name, consent=None, ref_text=None, speaker_description=None, + connection_id=_CURRENT_CONNECTION, before_submit=None): config, capabilities = self._config(model_config_id) if connection_id is not _CURRENT_CONNECTION and connection_id != capabilities['connectionId']: raise voice_error('voice_connection_changed', 409) @@ -311,6 +312,8 @@ def create(self, model_config_id, data, *, filename, name, consent=None, ref_tex seconds = media['durationSeconds'] if (capabilities['minSeconds'] is not None and seconds < capabilities['minSeconds']) or (capabilities['maxSeconds'] is not None and seconds > capabilities['maxSeconds']): raise voice_error('voice_duration') fields = {'name': name} + if before_submit is not None: + before_submit() if capabilities['provider'] == 'zhipu': return self._zhipu_create(config, capabilities, data, extension, name, text) if capabilities['provider'] == 'vllm_omni': @@ -386,7 +389,7 @@ def origin(value): return value.scheme, value.hostname, value.port or (443 if va except httpx.TimeoutException: raise voice_error('voice_provider_timeout', 504) from None except httpx.HTTPError: raise voice_error('voice_provider_error', 502) from None - def delete(self, model_config_id, voice_id, connection_id): + def delete(self, model_config_id, voice_id, connection_id, *, before_submit=None): _, capabilities = self._config(model_config_id) if connection_id != capabilities['connectionId']: raise voice_error('voice_connection_changed', 409) if not capabilities['canDelete']: raise voice_error('voice_delete_unsupported', 409) @@ -396,6 +399,8 @@ def delete(self, model_config_id, voice_id, connection_id): if not record['canDelete']: raise voice_error('voice_delete_unsupported', 409) config, current = self._config(model_config_id) if current['connectionId'] != connection_id: raise voice_error('voice_connection_changed', 409) + if before_submit is not None: + before_submit() if current['provider'] == 'zhipu': value = self._request(config, 'POST', path='/voice/delete', json={'voice': voice_id}) if value.get('voice') != voice_id: raise voice_error('voice_provider_protocol', 502) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index a59c2fdf0..cb7b8de6f 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -62,6 +62,7 @@ "group": "Save and publish segment run plans.", "history": "Undo or redo reversible project operations.", "creation": "Apply multiple project operations atomically.", + "plan": "Save or update a versioned plan snapshot for the active agent task.", } groups: dict[str, typer.Typer] = {} @@ -130,7 +131,8 @@ def timeline_export(ctx: typer.Context, editor_id: Annotated[UUID, typer.Option( client = ctx.obj client.command = ctx.command_path if client.live: - emit(client.call("timeline_package_export", dict(editorId=str(editor_id), revision=revision, path=str(output)))) + emit(client.call("timeline_package_export", dict(editorId=str(editor_id), revision=revision, path=str(output)), + identity=client.operation_id)) return with client.http.stream("GET", client.path(f"/timelines/{editor_id}/package"), params={"revision": revision}) as response: if not response.is_success: @@ -229,7 +231,16 @@ def call(self, name, arguments, *, identity=None): with connection: connection.settimeout(SOCKET_TIMEOUT) if not endpoint: - connection.connect(self.gateway["OPENDIRECTOR_AGENT_SOCKET"]) + address = self.gateway["OPENDIRECTOR_AGENT_SOCKET"] + if sys.platform == "linux" and len(os.fsencode(address)) >= 104: + path = Path(address) + descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + connection.connect(f"/proc/self/fd/{descriptor}/{path.name}") + finally: + os.close(descriptor) + else: + connection.connect(address) first = not _STARTUP_REPORTED _STARTUP_REPORTED = True connection.sendall((json.dumps({ @@ -242,12 +253,12 @@ def call(self, name, arguments, *, identity=None): raise ProjectError(response["error"], code=response.get('code')) return response["value"] - def models(self): - return (self.call("read_project", {})["models"] if self.live else + def models(self, *, identity=None): + return (self.call("read_project", {}, identity=identity)["models"] if self.live else self.request("GET", "/api/model-configs")) - def snapshot(self): - return (self.call("read_project", {})["project"] if self.live else + def snapshot(self, *, identity=None): + return (self.call("read_project", {}, identity=identity)["project"] if self.live else self.request("GET", self.path())) def open(self): @@ -303,8 +314,8 @@ def execute(self, kind, payload, versions=(), preview=None, *, identity=None): value["geometryReadError"] = str(error) return value - def query(self, kind, **arguments): - result = (self.call("query", {"type": kind, **arguments}) if self.live else + def query(self, kind, *, identity=None, **arguments): + result = (self.call("query", {"type": kind, **arguments}, identity=identity) if self.live else self.request("POST", self.path("/queries"), json={"type": kind, "queryId": str(uuid4()), "projectId": str(self.project), **arguments})) if kind == "job.get" and result.get("status") == "succeeded" and result.get("asset"): @@ -329,7 +340,7 @@ def options(ctx: typer.Context, project: Annotated[UUID | None, typer.Option(envvar="OPENDIRECTOR_PROJECT_ID", help="Target project UUID.")] = None, url: Annotated[str, typer.Option(envvar="OPENDIRECTOR_API_URL", help="Running OpenDirector server.")] = "http://127.0.0.1:18000", session: Annotated[UUID | None, typer.Option(envvar="OPENDIRECTOR_SESSION", help="Existing authorized edit session.")] = None, - operation_id: Annotated[UUID | None, typer.Option(help="Stable write identity for safe replay.")] = None): + operation_id: Annotated[UUID | None, typer.Option(help="Stable identity for safe replay or a confirmed plan step.")] = None): client = Client(project, url, session, operation_id) ctx.obj = client @@ -435,7 +446,8 @@ def summarize(snapshot): def project_show(ctx: typer.Context, summary: Annotated[bool, typer.Option("--summary", help="Print identities, revisions and status without full records.")] = False): ctx.obj.command = ctx.command_path - snapshot = ctx.obj.snapshot() + operation_id = getattr(ctx.obj, "operation_id", None) + snapshot = ctx.obj.snapshot(identity=operation_id) if operation_id is not None else ctx.obj.snapshot() emit(summarize(snapshot) if summary else snapshot) @@ -476,7 +488,7 @@ def model_availability(ctx: typer.Context, if model: arguments['configIds'] = [str(item) for item in model] if client.live: - emit(client.call('model_availability', {**arguments, 'refresh': refresh})) + emit(client.call('model_availability', {**arguments, 'refresh': refresh}, identity=client.operation_id)) elif refresh: emit(client.request('POST', '/api/model-configs/availability', json=arguments)) else: @@ -489,7 +501,7 @@ def model_list(ctx: typer.Context, typer.Option(help="Filter by model kind.")] = None, search: Annotated[str, typer.Option(help="Case-insensitive substring of model name or configuration UUID.")] = ""): ctx.obj.command = ctx.command_path - emit([model for model in ctx.obj.models() + emit([model for model in ctx.obj.models(identity=ctx.obj.operation_id) if (kind is None or model["kind"] == kind) and (search.casefold() in model["modelId"].casefold() or search.casefold() in model["id"].casefold())]) @@ -498,7 +510,7 @@ def model_list(ctx: typer.Context, def model_show(ctx: typer.Context, selector: Annotated[str, typer.Argument(help="Configuration UUID or unique exact model name.")]): ctx.obj.command = ctx.command_path - emit(select_model(ctx.obj.models(), selector)) + emit(select_model(ctx.obj.models(identity=ctx.obj.operation_id), selector)) @group("asset").command("import", help="Register a local file as a project asset.") @@ -647,8 +659,8 @@ def text_content(client, asset_id): return content.decode("utf-8") -def text_item(client, item_id, revision=None): - item = client.query("object.get", objectId=str(item_id), **({"revision": revision} if revision else {})) +def text_item(client, item_id, revision=None, *, identity=None): + item = client.query("object.get", identity=identity, objectId=str(item_id), **({"revision": revision} if revision else {})) if item.get("kind") != "text" or "binding" not in item: raise ValueError("--id must identify a text canvas item.") return item @@ -711,7 +723,7 @@ def text_create(ctx: typer.Context, file: MarkdownFile, def text_show(ctx: typer.Context, id: Annotated[UUID, typer.Option(help="Text canvas item ID.")]): client = ctx.obj client.command = ctx.command_path - item = text_item(client, id) + item = text_item(client, id, identity=client.operation_id) asset = text_asset(client, item) text = item["binding"].get("manualText") or "" if asset: @@ -808,7 +820,7 @@ def video_create(ctx: typer.Context, @group("job").command("show", help="Read job status once. Use job wait to wait for completion.") def job_show(ctx: typer.Context, job_id: UUID): ctx.obj.command = ctx.command_path - emit(ctx.obj.query("job.get", objectId=str(job_id))) + emit(ctx.obj.query("job.get", identity=ctx.obj.operation_id, objectId=str(job_id))) TERMINAL_JOB_STATES = frozenset({"succeeded", "failed", "cancelled", "interrupted"}) @@ -823,7 +835,8 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg help="Generation job IDs. Omit them with --all.")] = None, all_jobs: Annotated[bool, typer.Option("--all", help="Wait for every unfinished job in this project.")] = False, timeout: Annotated[float, typer.Option(min=0, help="Maximum wait in seconds.")] = 300): - ctx.obj.command = ctx.command_path + client = ctx.obj + client.command = ctx.command_path if not job_ids and not all_jobs: raise typer.BadParameter("Pass job IDs or --all.") ids = [str(identity) for identity in (job_ids or ())] @@ -832,7 +845,7 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg # the same jobs, so a job that fails while we wait is still named below. while True: remaining = max(0.0, deadline - time.monotonic()) - result = ctx.obj.query("job.status", objectIds=ids, + result = client.query("job.status", objectIds=ids, waitSeconds=min(WAIT_WINDOW, remaining), until="all") jobs = result.get("jobs", []) if not job_ids: @@ -840,6 +853,10 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg failed = [job for job in jobs if job["status"] in TERMINAL_JOB_STATES and job["status"] != "succeeded"] settled = all(job["status"] in TERMINAL_JOB_STATES for job in jobs) if settled: + if jobs and not failed and getattr(client, "live", False) and getattr(client, "operation_id", None): + # The gateway replays calls with the same ID. Bind only the successful terminal read to the step. + client.call("query", {"type": "job.status", "objectIds": ids, "waitSeconds": 0, "until": "all"}, + identity=client.operation_id) report = {"jobs": jobs, "completed": len(jobs) - len(failed), "failed": len(failed)} if not jobs: report["note"] = ("No job in this project is still running. " @@ -903,9 +920,89 @@ def query(ctx: typer.Context, kind: str, arguments = read_file(file) if file else {} if object_id: arguments["objectId"] = str(object_id) + arguments["identity"] = ctx.obj.operation_id emit(ctx.obj.query(kind, **arguments)) +@app.command( + "ask-user", + help="Submit 1 to 4 structured decision questions for the user and pause the active task segment.", + epilog=( + 'Example JSON for --file:\n' + '{\n' + ' "questions": [\n' + ' {\n' + ' "id": "duration",\n' + ' "question": "视频成片的目标时长是多少?",\n' + ' "multiSelect": false,\n' + ' "required": true,\n' + ' "options": [\n' + ' {"id": "8s", "label": "8 秒", "impact": "采用紧凑的三镜头叙事,适合快速展示核心画面。"},\n' + ' {"id": "5s", "label": "5 秒", "impact": "浓缩为单主镜头与结尾定格,节奏最快。"},\n' + ' {"id": "15s", "label": "15 秒", "impact": "展开完整起承转合,留出环境铺垫与呼吸感。"}\n' + ' ]\n' + ' }\n' + ' ]\n' + '}\n' + 'Options are ordered from highest recommendation to lowest. Do not include (Recommended) or (推荐) in label.' + ), +) +def ask_user_command( + ctx: typer.Context, + file: Annotated[Path, typer.Option(help="UTF-8 JSON file with questions (1-4 items); use - for stdin.")], +): + from opendirector.agent.decisions import AskUserInput + client = ctx.obj + client.command = ctx.command_path + body = AskUserInput.model_validate(read_file(file)).model_dump(mode="json") + emit(client.call("ask_user", body, identity=client.operation_id)) + + +@group("plan").command( + "save", + help="Save or update the versioned plan snapshot for the active task before user confirmation.", + epilog=( + 'Example JSON for --file (plain strings default to kind "write"; use objects for "read" or "inspection"):\n' + '{\n' + ' "summary": "12 秒视频创作方案,最后留 3 秒空镜。",\n' + ' "steps": [{"content": "读取画布现状", "kind": "read"}, "前 9 秒展开主体叙事", "结尾 3 秒保留空镜画面"]\n' + '}' + ), +) +def plan_save_command( + ctx: typer.Context, + file: Annotated[Path | None, typer.Option(help="UTF-8 JSON file with summary and steps; use - for stdin.")] = None, + summary: Annotated[str | None, typer.Option(help="Complete updated plan summary or Markdown text.")] = None, + step: Annotated[list[str] | None, typer.Option(help="Repeat for each ordered plan step.")] = None, +): + from opendirector.agent.decisions import UpdatePlanInput + client = ctx.obj + client.command = ctx.command_path + body = read_file(file) if file is not None else {} + if summary is not None: + body["summary"] = summary + if step: + body["steps"] = list(step) + payload = UpdatePlanInput.model_validate(body).model_dump(mode="json") + emit(client.call("update_plan", payload, identity=client.operation_id)) + + +@group("plan").command( + "complete-step", + help="Record the outcome of an inspection step in the confirmed execution plan.", +) +def plan_complete_step_command( + ctx: typer.Context, + step: Annotated[str, typer.Option(help="Plan step ID, e.g. step-1.")], + summary: Annotated[str, typer.Option(help="Concise result of the inspection.")], +): + from opendirector.agent.decisions import CompleteStepInput + client = ctx.obj + client.command = ctx.command_path + payload = CompleteStepInput.model_validate({"stepId": step, "summary": summary}).model_dump(mode="json") + emit(client.call("complete_step", payload, identity=client.operation_id)) + + def read_file(path): if str(path) == "-": source = sys.stdin.buffer.read().decode("utf-8-sig") @@ -927,6 +1024,9 @@ def register_command(kind, model): inspect.Parameter("file", inspect.Parameter.KEYWORD_ONLY, default=None, annotation=Annotated[Path | None, typer.Option(help="Command JSON file with payload and expectedVersions; - reads stdin.")]), ] + if kind == "asset.writeText": + parameters.append(inspect.Parameter("text_file", inspect.Parameter.KEYWORD_ONLY, default=None, + annotation=Annotated[Path | None, typer.Option(help="Literal UTF-8 text or Markdown file; - reads stdin.")])) for name, definition in properties.items(): description = definition.get("description", name) if name == "spec": @@ -940,15 +1040,30 @@ def register_command(kind, model): parameters.append(inspect.Parameter("expected_version", inspect.Parameter.KEYWORD_ONLY, default=None, annotation=Annotated[list[str] | None, typer.Option(help="Repeat object_type:UUID:revision for each changed existing object.")])) - def execute(ctx, file=None, expected_version=None, help_field=None, **values): + def execute(ctx, file=None, text_file=None, expected_version=None, help_field=None, **values): ctx.obj.command = ctx.command_path if help_field is not None: emit(command_help(payload_schema, help_field, ctx.obj.project or UUID(int=0))) return - body = read_file(file) if file else {"payload": {}} + if text_file is not None: + if file is not None or values.get("text") is not None: + raise typer.BadParameter("Use one of --text-file, --file, or --text.") + default_name = "plan.md" if str(text_file) == "-" else text_file.name + body = {"payload": {"name": default_name, "text": markdown_file(text_file).removeprefix("\ufeff")}} + else: + body = read_file(file) if file else {"payload": {}} if body.get("type", kind) != kind: raise ValueError("Command file type does not match this subcommand.") - arguments = dict(body.get("payload", {})) + unexpected = sorted(set(body) - {"type", "payload", "expectedVersions", "expectedPreview"}) + if unexpected: + raise ValueError( + "Unexpected top-level field(s) in --file: " + ", ".join(unexpected) + + '. Wrap command arguments in {"payload": {...}}.' + ) + raw_payload = body.get("payload", {}) + if not isinstance(raw_payload, dict): + raise ValueError('--file field "payload" must be a JSON object.') + arguments = dict(raw_payload) for name, value in values.items(): if value is not None: definition = properties[name] @@ -1027,7 +1142,8 @@ def voice_list(ctx: typer.Context, if page_size is not None: arguments['pageSize'] = page_size if after is not None: arguments['after'] = after if connection is not None: arguments['connectionId'] = connection - emit(client.call('voice_list', arguments) if client.live else client.request('GET', '/api/voices', params=arguments)) + emit(client.call('voice_list', arguments, identity=client.operation_id) if client.live + else client.request('GET', '/api/voices', params=arguments)) @group('voice').command('create', help='Upload an authorized recording to the speech model voice library.') @@ -1046,7 +1162,8 @@ def voice_create(ctx: typer.Context, if ref_text is not None: fields['refText'] = ref_text if speaker_description is not None: fields['speakerDescription'] = speaker_description if client.live: - emit(client.call('voice_create', {**fields, 'modelConfigId': str(model), 'path': str(file.resolve())})) + emit(client.call('voice_create', {**fields, 'modelConfigId': str(model), 'path': str(file.resolve())}, + identity=client.operation_id)) else: from opendirector.domain.voices import voice_error with file.open('rb') as stream: data = stream.read(10 * 1024 * 1024 + 1) @@ -1063,7 +1180,8 @@ def voice_delete(ctx: typer.Context, client = ctx.obj client.command = ctx.command_path arguments = dict(modelConfigId=str(model), connectionId=connection, voiceId=voice_id) - if client.live: emit(client.call('voice_delete', arguments)) + if client.live: + emit(client.call('voice_delete', arguments, identity=client.operation_id)) else: response = client.http.delete('/api/voices/' + quote(voice_id, safe=''), params={'modelConfigId': str(model), 'connectionId': connection}) if not response.is_success: raise ProjectError(response.text, response.status_code) diff --git a/packages/core/src/opendirector/infrastructure/creation_catalog.py b/packages/core/src/opendirector/infrastructure/creation_catalog.py index a3b3e88c8..3e2ac1664 100644 --- a/packages/core/src/opendirector/infrastructure/creation_catalog.py +++ b/packages/core/src/opendirector/infrastructure/creation_catalog.py @@ -226,10 +226,9 @@ def _published_manifest(self, project_id): self._recover() return self._find(db, project_id) - @staticmethod - def _cleanup_blocker(db, project_id, path): + def _cleanup_blocker(self, db, project_id, path): active = db.execute('SELECT 1 FROM sessions WHERE expires>? AND (path=? OR project_id=?)', - (time.time(), str(path), project_id or '')).fetchone() + (self.local.now(), str(path), project_id or '')).fetchone() if active: return '工程仍在其他窗口中打开,请关闭后再清理。' tools = path / 'tool-tasks' diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index ec6d7572a..afa0c8a6c 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -12,7 +12,6 @@ """ import os import threading -import time from collections import OrderedDict from collections.abc import Callable from functools import partial @@ -96,7 +95,7 @@ def _lease(self, db, project_id, path, session, *, browser_only=False): identifier(session) agent_key = session if browser_only else self.local.agent_session_key(session) lease = db.execute('SELECT path FROM sessions WHERE id IN (?,?) AND project_id=? AND expires>?', - (session, agent_key, str(project_id), time.time())).fetchone() + (session, agent_key, str(project_id), self.local.now())).fetchone() if lease is None: # A stable code lets the page renew its lease and resend instead of failing every save. raise ProjectError('工程已关闭或会话已过期,请重新打开后保存。', 409, code='session_expired') @@ -104,7 +103,7 @@ def _lease(self, db, project_id, path, session, *, browser_only=False): raise ProjectError('工程目录已在应用外改名或移动,请复制未保存内容并重新打开。', 409) def _closed(self, db, project_id, snapshot, verb='重命名'): - if db.execute('SELECT 1 FROM sessions WHERE project_id=? AND expires>?', (str(project_id), time.time())).fetchone(): + if db.execute('SELECT 1 FROM sessions WHERE project_id=? AND expires>?', (str(project_id), self.local.now())).fetchone(): raise ProjectError(f'请先保存并关闭工程后再{verb}。', 409) if any(job.status in {'queued', 'running'} for job in snapshot.jobs): raise ProjectError(f'工程仍在生成素材,请等待或取消任务后再{verb}。', 409) diff --git a/packages/core/src/opendirector/infrastructure/local_projects.py b/packages/core/src/opendirector/infrastructure/local_projects.py index e4d531c65..e79b0c639 100644 --- a/packages/core/src/opendirector/infrastructure/local_projects.py +++ b/packages/core/src/opendirector/infrastructure/local_projects.py @@ -92,6 +92,8 @@ def __init__(self, repository: Path): self.root = self.repository / "projects" self.state_dir = self.repository / ".opendirector" self.state_dir.mkdir(parents=True, exist_ok=True) + self._wall_origin = time.time() + self._mono_origin = time.monotonic() self.lock = FileLock(self.state_dir / "catalog.lock", timeout=15) self.database = self.state_dir / "catalog.sqlite3" with self.transaction() as db: @@ -102,7 +104,11 @@ def __init__(self, repository: Path): ); CREATE INDEX IF NOT EXISTS sessions_project ON sessions(project_id); """) - db.execute("DELETE FROM sessions WHERE expires<=?", (time.time(),)) + db.execute("DELETE FROM sessions WHERE expires<=?", (self.now(),)) + + def now(self) -> float: + """Epoch-scaled monotonic clock so NTP/wall-clock steps never expire live leases early.""" + return self._wall_origin + (time.monotonic() - self._mono_origin) @contextmanager @@ -137,7 +143,7 @@ def _conflict(parent: Path, name: str, source: Path | None = None): def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str, *, persistent=False, allow_preview=False) -> bool: identifier(session) - now = time.time() + now = self.now() editor = self.editor(db, project["id"], now=now) if editor and editor["id"] != session: if not allow_preview: @@ -160,7 +166,7 @@ def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], se def editor(self, db, project_id, *, now=None): return db.execute( "SELECT id, path, expires FROM sessions WHERE project_id=? AND id NOT LIKE ? AND expires>? LIMIT 1", - (project_id, self._AGENT_SESSION_PREFIX + "%", time.time() if now is None else now), + (project_id, self._AGENT_SESSION_PREFIX + "%", self.now() if now is None else now), ).fetchone() def editing_state(self, db, project_id, session): @@ -179,7 +185,7 @@ def agent_session_key(self, session: str) -> str: def start_agent_session(self, db, project_id, path: Path, session: str): """Called in the transaction that validates the browser lease and accepts the turn.""" - now = time.time() + now = self.now() db.execute("DELETE FROM sessions WHERE expires<=? AND id LIKE ?", (now, self._AGENT_SESSION_PREFIX + "%")) db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?)", @@ -187,7 +193,7 @@ def start_agent_session(self, db, project_id, path: Path, session: str): def renew_agent_session(self, session: str) -> bool: with self.transaction() as db: - now = time.time() + now = self.now() return bool(db.execute("UPDATE sessions SET expires=? WHERE id=? AND expires>?", (now + self.LEASE_SECONDS, self.agent_session_key(session), now)).rowcount) diff --git a/src/backend/api.ts b/src/backend/api.ts index b6e7d9d91..ef9173e15 100644 --- a/src/backend/api.ts +++ b/src/backend/api.ts @@ -105,18 +105,11 @@ export function backgroundRead(task: () => Promise, signal?: AbortSignal) const BACKGROUND_PROJECT_READ = /^\/creation\/projects\/[^/]+\/(?:assistant(?:\/[^?]*)?|reference-catalog|reference-evidence|canvas-texts|history|version-counts)(?:\?|$)/; -export function request(path: string, options: RequestInit = {}, leaseRenewed = false): Promise { - const run = () => requestNow(path, options, leaseRenewed); - if ((options.method === undefined || options.method === "GET") && BACKGROUND_PROJECT_READ.test(path)) - return backgroundRead(run, options.signal ?? undefined); - return run(); -} - -async function requestNow( +export async function sessionFetch( path: string, options: RequestInit = {}, leaseRenewed = false, -): Promise { +): Promise { await sessionReady; const requestedSession = sessionId; let response: Response; @@ -130,26 +123,48 @@ async function requestNow( throw new ApiError(tNow("api.networkError"), null, "network_error"); } if (!response.ok) { - const error = await responseError(response); const projectId = PROJECT_PATH.exec(path)?.[1]; if ( - error.status === 409 && - error.code === "session_expired" && + response.status === 409 && !leaseRenewed && requestedSession === sessionId && projectId && leaseRecovery && - !options.signal?.aborted && - (await leaseRecovery(projectId).catch(() => false)) + !options.signal?.aborted ) { - if (requestedSession === sessionId) return requestNow(path, options, true); + const error = await responseError(response.clone()); + if ( + error.code === "session_expired" && + (await leaseRecovery(projectId).catch(() => false)) && + requestedSession === sessionId + ) { + return sessionFetch(path, options, true); + } } - throw error; } + return response; +} + +async function requestNow( + path: string, + options: RequestInit = {}, +): Promise { + const response = await sessionFetch(path, options); + if (!response.ok) throw await responseError(response); if (response.status === 204) return undefined as T; return (await response.json()) as T; } +export function request( + path: string, + options: RequestInit = {}, +): Promise { + const run = () => requestNow(path, options); + if ((options.method === undefined || options.method === "GET") && BACKGROUND_PROJECT_READ.test(path)) + return backgroundRead(run, options.signal ?? undefined); + return run(); +} + export function json( method: string, value: unknown, diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 02afe1f93..784da7c06 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -2,7 +2,7 @@ import { assistant as chineseAssistant } from "../i18n/messages/zh-CN/assistant. import type { ReferenceContent } from "../canvas/chatReferenceContent.ts"; import { defaultTranslate } from "../canvas/assistantTranslate.ts"; import type { Translate } from "../i18n/I18nProvider.tsx"; -import { headers, json, request, responseError } from "./api.ts"; +import { json, request, responseError, sessionFetch } from "./api.ts"; export type AgentRuntime = | "default" @@ -63,6 +63,106 @@ export interface ChatSource { url: string; title: string; } +export type InteractionMode = "auto" | "ask"; + +export interface DecisionOption { + id: string; + label: string; + impact: string; +} + +export interface DecisionQuestion { + id: string; + question: string; + multiSelect?: boolean; + required?: boolean; + defaultOptionIds?: string[]; + defaultText?: string | null; + options: DecisionOption[]; +} + +export type AnswerSource = "options" | "custom" | "default"; + +export interface QuestionAnswerItem { + questionId: string; + source: AnswerSource; + selectedOptionIds: string[]; + selectedLabels?: string[]; + customText?: string | null; + displayText?: string; +} + +export type DecisionStatus = + | "waiting_input" + | "answer_saved" + | "resuming" + | "completed" + | "invalidated" + | "resume_failed" + | "status_unknown"; + +export interface DecisionRecord { + requestId: string; + taskId: string; + conversationId: string; + turnId: string; + messageId: string; + stage: string; + planRevision: number; + questions: DecisionQuestion[]; + status: DecisionStatus; + answers?: QuestionAnswerItem[] | null; + answerFingerprint?: string | null; + continuationId?: string | null; + error?: string | null; + errorCode?: string | null; +} + +export interface VersionedPlanStep { + kind?: "write" | "read" | "inspection"; + id: string; + content: string; + status: "pending" | "in_progress" | "completed" | "failed"; +} + +export interface VersionedPlan { + revision: number; + summary: string; + steps: VersionedPlanStep[]; + updatedAtTurnId: string; +} + +export type LogicalTaskStage = + | "running" + | "planning" + | "waiting_input" + | "answer_saved" + | "resuming" + | "waiting_confirmation" + | "executing" + | "waiting_jobs" + | "execution_failed" + | "completed" + | "interrupted" + | "status_unknown"; + +export interface LogicalTaskRecord { + taskId: string; + conversationId: string; + mode: InteractionMode; + runtime: AgentRuntime; + planOnly?: boolean; + stage: LogicalTaskStage; + planRevision: number; + plan?: VersionedPlan | null; + confirmedPlanRevision?: number | null; + executionContinuationId?: string | null; + activeDecisionId?: string | null; + pendingContinuationId?: string | null; + segmentTurnIds: string[]; + error?: string | null; +} + export interface ChatMessage { sources?: ChatSource[]; plan?: ChatPlanEntry[]; @@ -79,6 +179,12 @@ export interface ChatMessage { runtimeModel?: string | null; thinking?: Thinking; source?: "preview" | "model"; + mode?: InteractionMode; + turnId?: string; + taskId?: string; + segmentKind?: "continuation" | "execution"; + parentRequestId?: string; + decisionRequestId?: string; startedAt?: string | null; finishedAt?: string | null; durationMs?: number | null; @@ -118,6 +224,8 @@ export interface ChatDraft { } export interface Conversation extends ChatDraft { messages: ChatMessage[]; + decisions?: DecisionRecord[]; + tasks?: LogicalTaskRecord[]; } export function draftContentIsEmpty( @@ -143,13 +251,16 @@ export function conversationIsEmpty(value: Conversation) { } export type ChatEvent = - | { type: "start"; conversation: Conversation } + | { type: "start"; turnId?: string; conversation: Conversation } + | { type: "queued"; message: ChatMessage } | { type: "thinking" } | { type: "plan"; entries: ChatPlanEntry[] } | ({ type: "tool" } & ChatTool) | { type: "delta"; text: string } | { type: "sources"; sources: ChatSource[] } - | { type: "end"; conversation: Conversation | null; error: string | null }; + | { type: "decision"; decision: DecisionRecord; task?: LogicalTaskRecord | null } + | { type: "task"; task: LogicalTaskRecord } + | { type: "end"; turnId?: string; nextTurnId?: string | null; conversation: Conversation | null; error: string | null }; export interface ChatRequest { conversationId?: string; @@ -163,6 +274,8 @@ export interface ChatRequest { runtime?: AgentRuntime; runtimeModel?: string | null; skills?: string[]; + mode?: InteractionMode; + planOnly?: boolean; } function normalizeConversation(value: Conversation): Conversation { @@ -223,8 +336,28 @@ export async function conversation( >(path(id)); return { conversation: normalizeConversation(saved), activeTurnId: activeTurnId ?? null }; } +/** + * The draft endpoint validates strictly and rejects unknown members, so send + * the fields it owns instead of forwarding whatever a view or conversation read + * happens to hold (`messages`, `activeTurnId`, `decisions`, `tasks`). + */ +export function draftOf(value: ChatDraft): ChatDraft { + return { + conversationId: value.conversationId, + draft: value.draft, + draftContent: value.draftContent, + assets: value.assets, + thinking: value.thinking, + builtinModelThinking: value.builtinModelThinking, + modelSelections: value.modelSelections, + runtime: value.runtime, + runtimeModel: value.runtimeModel, + harnessModels: value.harnessModels, + skills: value.skills, + }; +} export const saveChatDraft = (id: string, draft: ChatDraft) => - request(path(id) + "/draft", json("PUT", draft)); + request(path(id) + "/draft", json("PUT", draftOf(draft))); export const chatSkills = (id: string, signal?: AbortSignal) => request(path(id) + "/skills", { signal }); export const stopChat = (id: string, turn: string) => @@ -236,9 +369,8 @@ export async function streamChat( onEvent: (event: ChatEvent) => void, t: Translate = defaultTranslate, ) { - const response = await fetch("/api" + path(id) + "/turns", { + const response = await sessionFetch(path(id) + "/turns", { ...json("POST", value), - headers: { ...headers, "Content-Type": "application/json" }, signal, }); await readChatEvents(response, onEvent, t); @@ -259,8 +391,7 @@ export async function attachChat( onEvent: (event: ChatEvent) => void, t: Translate = defaultTranslate, ) { - const response = await fetch("/api" + path(id) + `/turns/${turn}/events`, { - headers, + const response = await sessionFetch(path(id) + `/turns/${turn}/events`, { signal, }); if (response.status === 404) throw new ChatTurnEnded(); @@ -289,7 +420,8 @@ async function readChatEvents( buffer = buffer.slice(boundary + 2); if (frame.startsWith("data: ")) { const event = JSON.parse(frame.slice(6)) as ChatEvent; - ended ||= event.type === "end"; + if (event.type === "start") ended = false; + if (event.type === "end" && !event.nextTurnId) ended = true; if ((event.type === "start" || event.type === "end") && event.conversation) { event.conversation = normalizeConversation(event.conversation); } @@ -319,3 +451,88 @@ export async function runtimeModels(projectId: string, runtime: AgentRuntime, se if (!selected) runtimeModelCatalogs.set(runtime, { value, expires: Date.now() + discoveryTtlMs }); return value; } + +export interface DecisionAnswerSubmissionItem { + questionId: string; + source: AnswerSource; + selectedOptionIds: string[]; + customText?: string | null; +} + +export interface DecisionAnswerReceipt { + replayed: boolean; + requestId: string; + status: DecisionStatus; + continuationId: string; + busy: boolean; + decision: DecisionRecord; + task: LogicalTaskRecord; +} + +async function streamSegmentPost( + endpoint: string, + body: Record, + signal: AbortSignal, + onEvent: (event: ChatEvent) => void, + t: Translate, +) { + const response = await sessionFetch(endpoint, { + ...json("POST", body), + signal, + }); + await readChatEvents(response, onEvent, t); +} + +export function submitDecisionAnswer( + projectId: string, + requestId: string, + answers: DecisionAnswerSubmissionItem[], +): Promise { + return request( + path(projectId) + `/decisions/${requestId}/answers`, + json("POST", { answers }), + ); +} + +export const streamDecisionContinuation = ( + projectId: string, + continuationId: string, + signal: AbortSignal, + onEvent: (event: ChatEvent) => void, + t: Translate = defaultTranslate, +) => + streamSegmentPost( + path(projectId) + `/continuations/${continuationId}`, + {}, + signal, + onEvent, + t, + ); + +export const streamPlanConfirmation = ( + projectId: string, + taskId: string, + planRevision: number, + signal: AbortSignal, + onEvent: (event: ChatEvent) => void, + t: Translate = defaultTranslate, +) => + streamSegmentPost( + path(projectId) + `/tasks/${taskId}/confirm-plan`, + { planRevision }, + signal, + onEvent, + t, + ); + +export function adjustTaskPlan( + projectId: string, + taskId: string, + planRevision: number, + prompt?: string | null, +) { + return request<{ task: LogicalTaskRecord }>( + path(projectId) + `/tasks/${taskId}/adjust-plan`, + json("POST", { planRevision, prompt: prompt ?? null }), + ); +} diff --git a/src/backend/chatDrafts.ts b/src/backend/chatDrafts.ts index fc5615c01..e40224b19 100644 --- a/src/backend/chatDrafts.ts +++ b/src/backend/chatDrafts.ts @@ -1,31 +1,11 @@ -import { saveChatDraft, type ChatDraft, type Conversation } from "./chat.ts"; +import { draftOf, saveChatDraft, type Conversation } from "./chat.ts"; + +export { draftOf }; // Only unsaved UI drafts live here; the backend owns persisted conversation state. const latest = new Map(); const pending = new Map>(); -/** - * The draft endpoint validates strictly and rejects unknown members, so send - * the fields it owns instead of forwarding whatever the view happens to hold. - * `activeTurnId` in particular is only present on a conversation read while a - * reply is running; echoing it back made every autosave fail with a 422. - */ -function draftOf(value: Conversation): ChatDraft { - return { - conversationId: value.conversationId, - draft: value.draft, - draftContent: value.draftContent, - assets: value.assets, - thinking: value.thinking, - builtinModelThinking: value.builtinModelThinking, - modelSelections: value.modelSelections, - runtime: value.runtime, - runtimeModel: value.runtimeModel, - harnessModels: value.harnessModels, - skills: value.skills, - }; -} - export function rememberChat(projectId: string, value: Conversation) { latest.set(projectId, value); } diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 50ff8d5eb..30b14144d 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -12,7 +12,18 @@ import { AttachmentStrip, AttachmentHover } from "./AssistantMedia"; import { AssistantReply } from "./AssistantReply"; import { AssistantConversations } from "./AssistantConversations"; import { AgentPicker } from "./AgentPicker"; -import { ModelPicker } from "./AssistantPickers"; +import { ModePicker, ModelPicker } from "./AssistantPickers"; +import { QuestionAnswerPanel } from "./QuestionAnswerPanel.tsx"; +import { + applyComposerAnswerInput, + applyCustomAnswerText, + isQuestionAnswered, + readQuestionDraft, + resolveNextAnswerAction, + writeQuestionDraft, + type QuestionAnswerDraftItem, + type QuestionGroupDraft, +} from "./questionAnswerDrafts.ts"; import { SkillPicker } from "./SkillPicker"; import { CanvasIcon } from "./CanvasIcon"; import { @@ -115,6 +126,14 @@ export function AssistantPanel({ const projectReferences = useProjectMentionAssets(documentId); const editor = useRef(null); const [slashQuery, setSlashQuery] = useState(null); + const [dismissedDecisionIds, setDismissedDecisionIds] = useState( + [], + ); + const [questionDraftState, setQuestionDraft] = useState<{ + scope: string; + answers: QuestionGroupDraft; + } | null>(null); + const [activeQuestionIndex, setActiveQuestionIndex] = useState(0); const [dragOver, setDragOver] = useState(false); const [mediaPreview, setMediaPreview] = useState<{assetId: string; anchor: DOMRect} | null>(null); const log = useRef(null); @@ -334,14 +353,118 @@ export function AssistantPanel({ const hoveredAsset = mediaPreview && displayedAssets.find(item => item.id === mediaPreview.assetId); const latestUser = value.messages.at(-2); - const latestTrace = latestReply?.role === "assistant" && latestUser?.role === "user" && + const latestTurnId = + latestReply?.role === "assistant" + ? (latestReply.turnId ?? + (latestUser?.role === "user" ? latestUser.id : undefined)) + : undefined; + const latestTrace = latestReply?.role === "assistant" && latestTurnId && new URLSearchParams({ traceProject: documentId, ...(value.conversationId ? { conversation: value.conversationId } : {}), - turn: latestUser.id, + turn: latestTurnId, runtime: latestReply.runtime === "default" ? "opencode" : latestReply.runtime ?? "opencode", ...(latestReply.status === "streaming" ? { live: "1" } : {}), }); + const decisionsById = new Map( + (value.decisions ?? []).map((item) => [item.requestId, item]), + ); + const tasksById = new Map( + (value.tasks ?? []).map((item) => [item.taskId, item]), + ); + const latestWaitingDecision = + [...(value.decisions ?? [])] + .reverse() + .find((item) => item.status === "waiting_input") ?? null; + const activeExpandedDecision = + !readOnly && + latestWaitingDecision && + !dismissedDecisionIds.includes(latestWaitingDecision.requestId) + ? latestWaitingDecision + : null; + const answerScope = activeExpandedDecision + ? `${documentId}:${activeExpandedDecision.taskId}:${activeExpandedDecision.requestId}` + : null; + const questionDraft = questionDraftState?.scope === answerScope + ? questionDraftState.answers + : {}; + + useEffect(() => { + if (!activeExpandedDecision || !answerScope) { + setQuestionDraft(null); + setActiveQuestionIndex(0); + return; + } + setSlashQuery(null); + const saved = readQuestionDraft( + documentId, + activeExpandedDecision.taskId, + activeExpandedDecision.requestId, + ); + setQuestionDraft({ scope: answerScope, answers: saved }); + const firstUnanswered = activeExpandedDecision.questions.findIndex( + (q) => !isQuestionAnswered(q, saved[q.id]), + ); + setActiveQuestionIndex(firstUnanswered >= 0 ? firstUnanswered : 0); + }, [answerScope]); + + const updateQuestionDraft = ( + questionId: string, + updater: ( + current: QuestionAnswerDraftItem | undefined, + ) => QuestionAnswerDraftItem, + ): QuestionGroupDraft => { + if (!activeExpandedDecision || !answerScope) return questionDraft; + const next: QuestionGroupDraft = { + ...questionDraft, + [questionId]: updater(questionDraft[questionId]), + }; + writeQuestionDraft( + documentId, + activeExpandedDecision.taskId, + activeExpandedDecision.requestId, + next, + ); + setQuestionDraft({ scope: answerScope, answers: next }); + return next; + }; + + const safeQuestionIndex = activeExpandedDecision + ? Math.min( + activeQuestionIndex, + Math.max(0, activeExpandedDecision.questions.length - 1), + ) + : 0; + const activeQuestion = + activeExpandedDecision?.questions[safeQuestionIndex] ?? null; + const answerText = activeQuestion ? questionDraft[activeQuestion.id]?.composerText ?? "" : ""; + const typedAnswerText = answerText.trim(); + const composerReferencesDisabled = referenceDisabled || Boolean(answerScope); + const composerPlaceholder = activeQuestion + ? activeExpandedDecision!.questions.length > 1 + ? t("assistant.question.composerPlaceholderStep", { + current: safeQuestionIndex + 1, + total: activeExpandedDecision!.questions.length, + }) + : t("assistant.question.composerPlaceholder") + : undefined; + + const submitComposer = () => { + nearBottom.current = true; + if (activeExpandedDecision && activeQuestion) { + if (locked || chat.changing || chat.submittingDecision || !typedAnswerText) return; + const nextDraft = updateQuestionDraft(activeQuestion.id, (prev) => + applyCustomAnswerText(prev, typedAnswerText), + ); + const action = resolveNextAnswerAction(activeExpandedDecision.questions, nextDraft, safeQuestionIndex); + if (!action) return; + if ("nextIndex" in action) setActiveQuestionIndex(action.nextIndex); + else void chat.answerDecision(activeExpandedDecision.requestId, action.answers); + return; + } + pendingReferences.cancel(); + void chat.send(); + }; return (