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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Antigravity 沿用本机 agy 的账号登录,命令行里不传模型凭证。

业务入口使用 Typer CLI。Agent 每轮先运行一次 `opendirector capabilities`,取得全部业务命令及其必填字段,只有某个字段的结构不明确时才用 `opendirector COMMAND --help-field payload` 查看;系统提示和各 runtime 的本轮执行上下文共用同一句发现规则(`CLI_DISCOVERY`),不再提示逐个命令运行 `--help`。人在终端里仍可用 `opendirector --help` 和子命令的 `--help`。

工具记录的 `status` 表示这次调用本身的结果:一个等待窗口在 job 仍未结束时返回,也是 `complete`。`job.status` 和 `canvas.status` 的等待另外记录 `waitOutcome`(`kind`、`settled`,以及各 job 状态的计数或画布项状态),用来区分已结束的等待和超时返回的窗口。执行记录把 `complete` 且 `waitOutcome.settled` 为 `false` 的等待显示为"未结束",进度"已完成"不计入它们,并单独显示"N 次返回时任务未结束";没有 `waitOutcome` 的旧记录照常显示。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。
工具记录的 `status` 表示这次调用本身的结果:一次状态查询或等待窗口在 job 仍未结束时正常返回,也是 `complete`。`job.status` 和 `canvas.status` 另外记录 `waitOutcome`(`kind`、`settled`、`satisfied`、`waitSeconds`、`until` 以及各 job 状态计数或画布项状态),用来区分等待窗口超时未满足(`waitSeconds > 0` 且未满足 `all`/`any` 条件)与已满足条件或零时长查询但返回时仍有任务在运行的情况。执行记录的进度"已完成"按工具调用本身是否成功返回计数;等待窗口未满足的记录显示为"未结束"并附标"N 次等待未结束",已满足条件(如 `until=any` 已有任务终态)或 `waitSeconds=0` 查询但仍有任务运行的记录显示为"仍有任务运行"并附标"N 次返回时仍有任务运行";没有 `waitOutcome` 的旧记录照常显示。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。

接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。

Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/opendirector/agent/cli_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ async def connection(reader, writer):
if outcome.error and isinstance(outcome.value, dict) and isinstance(outcome.value.get('code'), str):
response['code'] = outcome.value['code']
detail = json.dumps(outcome.value, ensure_ascii=False, indent=2)
observed = None if outcome.error else wait_outcome(name, arguments, outcome.value)
observed = None if outcome.error else getattr(outcome, 'wait_outcome', None)
if not outcome.error and observed is None:
observed = wait_outcome(name, arguments, outcome.value)
await queue.put({**outcome.event(display_name), 'id': 'cli:' + key,
'arguments': arguments, 'result': detail[:65536],
'resultTruncated': len(detail) > 65536,
Expand Down
83 changes: 66 additions & 17 deletions packages/core/src/opendirector/agent/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
from pydantic import Field, JsonValue, TypeAdapter, ValidationError

from opendirector.agent.context import AgentEvent, RunContext
from opendirector.agent.tools import AgentTools, tools
from opendirector.agent.tools import AgentTools, parse_query, tools
from opendirector.domain.projects import ProjectError
from opendirector.domain.creation.commands import COMMAND_MODELS
from opendirector.domain.creation.commands import COMMAND_MODELS, CanvasStatusQuery, JobStatusQuery
from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES
from opendirector.domain.rule_facts import MAX_REFERENCES

Expand All @@ -24,6 +24,7 @@
class ToolResult:
value: JsonValue
error: str | None = None
wait_outcome: dict[str, JsonValue] | None = None

def event(self, name: str) -> AgentEvent:
code = self.value.get('code') if isinstance(self.value, dict) else None
Expand All @@ -45,6 +46,7 @@ def event(self, name: str) -> AgentEvent:
# Queries that wait for a business state. Closing a turn cancels them; a read
# that has not been answered is worth nothing once the turn is over.
WAITING_QUERIES = frozenset({'job.status', 'canvas.status'})
TERMINAL_JOB_STATES = frozenset({'succeeded', 'failed', 'cancelled', 'interrupted'})

COMMAND_CONFLICT_ZH = (
'工具调用标识被用于不同输入。修改输入后请省略 --operation-id 或使用新的操作标识;'
Expand Down Expand Up @@ -77,26 +79,67 @@ def _command_conflict(call_id: str) -> ToolResult:
return ToolResult(value=value, error=COMMAND_CONFLICT_ZH)


def wait_outcome(name, arguments, value):
"""What a completed wait actually observed, recorded beside the tool record.
_PLACEHOLDER_ID = UUID(int=0)

A wait window is a successful call even when its jobs are still running, so
the record's status alone cannot tell a finished wait from one that timed
out (#449). This records the observed states as data; how the execution
record presents them is left to the interface.
"""
if name != 'query' or not isinstance(arguments, dict) or not isinstance(value, dict):

def wait_outcome_for_query(query, value):
if not isinstance(value, dict):
return None
kind = arguments.get('type')
if kind == 'job.status' and isinstance(value.get('jobs'), list):
if isinstance(query, JobStatusQuery) and isinstance(value.get('jobs'), list):
statuses = {}
for job in value['jobs']:
status = job.get('status') if isinstance(job, dict) else None
if isinstance(status, str):
statuses[status] = statuses.get(status, 0) + 1
return {'kind': kind, 'settled': value.get('terminal') is True, 'statuses': statuses}
if kind == 'canvas.status' and isinstance(value.get('status'), str):
return {'kind': kind, 'settled': value['status'] not in {'queued', 'running'}, 'status': value['status']}
all_terminal = value.get('terminal') is True
has_terminal = any(state in TERMINAL_JOB_STATES for state in statuses)
satisfied = query.waitSeconds <= 0 or all_terminal or (query.until == 'any' and has_terminal)
return {
'kind': query.type,
'settled': all_terminal,
'satisfied': satisfied,
'until': query.until,
'waitSeconds': query.waitSeconds,
'statuses': statuses,
}
if isinstance(query, CanvasStatusQuery) and isinstance(value.get('status'), str):
settled = value['status'] not in {'queued', 'running'}
return {
'kind': query.type,
'settled': settled,
'satisfied': query.waitSeconds <= 0 or settled,
'waitSeconds': query.waitSeconds,
'status': value['status'],
}
return None


def wait_outcome(name, arguments, value):
"""What a completed status query or wait observed, recorded beside the tool record."""
if name != 'query' or not isinstance(arguments, dict) or not isinstance(value, dict):
return None
kind = arguments.get('type')
if kind == 'job.status':
try:
query = JobStatusQuery.model_validate({
'projectId': _PLACEHOLDER_ID,
'queryId': _PLACEHOLDER_ID,
**arguments,
})
except ValidationError:
return None
return wait_outcome_for_query(query, value)
if kind == 'canvas.status':
try:
query = CanvasStatusQuery.model_validate({
'projectId': _PLACEHOLDER_ID,
'queryId': _PLACEHOLDER_ID,
'objectId': _PLACEHOLDER_ID,
**arguments,
})
except ValidationError:
return None
return wait_outcome_for_query(query, value)
return None


Expand Down Expand Up @@ -153,8 +196,13 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]
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('工具参数缺失或包含未定义字段。')
validated_query = parse_query(self.run.project_id, self.run.turn_id, call_id, arguments) if name == 'query' else None
forwarded = (
validated_query.model_dump(mode='json', exclude={'projectId', 'queryId'})
if validated_query is not None else arguments
)
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,
call_id, name, forwarded, self.roots, self.run.config,
self.run.runtime if self.run.config is None else None,
self.execution_directory, **({'runtime_model': self.run.runtime_model, 'thinking': self.run.thinking}
if name == 'prompt_optimize' else {}))
Expand Down Expand Up @@ -182,7 +230,8 @@ async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]
error = '; '.join(issue['message'] for issue in value.get('issues', (value.get('receipt') or {}).get('issues', []))) or 'Timeline package import was rejected.'
elif value.get('error'):
error = str(value['error'])
return ToolResult(value={**value, 'error': error} if error else value, error=error)
observed = None if error or validated_query is None else wait_outcome_for_query(validated_query, value)
return ToolResult(value={**value, 'error': error} if error else value, error=error, wait_outcome=observed)
except ValidationError as failure:
messages, codes = [], []
for issue in failure.errors(include_input=False, include_url=False):
Expand Down
23 changes: 14 additions & 9 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ def query_guidance(failure):
hint = f' Did you mean {closest[0]}?' if closest else ''
return f'Unsupported query type {given!r}.{hint} Valid types: {", ".join(QUERY_TYPES)}.'
return str(failure)


def parse_query(project_id: UUID, turn_id: UUID, call_id: str, arguments: dict[str, JsonValue]):
if {'projectId', 'queryId'} & arguments.keys():
raise ProjectError('查询身份与工程范围由宿主提供。')
try:
return TypeAdapter(Query).validate_python({
**arguments,
'projectId': project_id,
'queryId': uuid5(turn_id, call_id),
})
except ValidationError as failure:
raise ProjectError(query_guidance(failure)) from None
COMMANDS = {name: model for name, model in COMMAND_MODELS.items()
if name not in EXCLUDED}
for command_name, command_model in COMMANDS.items():
Expand Down Expand Up @@ -740,15 +753,7 @@ def recording():
[str(item) for item in config_ids] if config_ids is not None else None, manual=manual)
return self.availability.list()
if name == 'query':
if {'projectId', 'queryId'} & arguments.keys():
raise ProjectError('查询身份与工程范围由宿主提供。')
try:
query = TypeAdapter(Query).validate_python({**arguments, 'projectId': project_id,
'queryId': uuid5(turn_id, call_id)})
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
query = parse_query(project_id, turn_id, call_id, arguments)
if query.type == 'receipt.get':
candidates = (
query.objectId,
Expand Down
3 changes: 3 additions & 0 deletions src/backend/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ export interface ChatTool {
waitOutcome?: {
kind: "job.status" | "canvas.status";
settled: boolean;
satisfied?: boolean;
until?: "all" | "any";
waitSeconds?: number;
statuses?: Record<string, number>;
status?: string;
};
Expand Down
8 changes: 5 additions & 3 deletions src/canvas/AssistantReply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ const STATUS: Record<ToolDisplayStatus, MessageKey> = {
running: "assistant.reply.status.running",
complete: "assistant.reply.status.complete",
unsettled: "assistant.reply.status.unsettled",
jobsRunning: "assistant.reply.status.jobsRunning",
failed: "assistant.reply.status.failed",
interrupted: "assistant.reply.status.interrupted",
};

function ToolActivity({ tool, t }: { tool: ChatTool; t: Translate }) {
const status = toolDisplayStatus(tool);
const statusClass = status === "jobsRunning" ? "jobs-running" : status;
return (
<details className={`cw-chat-activity is-${status}`}>
<details className={`cw-chat-activity is-${statusClass}`}>
<summary>
<CanvasIcon
name="sparkle"
Expand Down Expand Up @@ -77,7 +79,7 @@ function ToolGroup({ tools, t }: { tools: ChatTool[]; t: Translate }) {
<summary>
<CanvasIcon name="sparkle" size={15} />
<span>{t("assistant.reply.tools", { count: tools.length })}</span>
<small>{t("assistant.reply.progress", { done: counts.complete, total: tools.length })}{counts.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: counts.unsettled })}`}{counts.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: counts.failed })}`}{counts.interrupted > 0 && ` · ${t("assistant.reply.interruptedCount", { count: counts.interrupted })}`}</small>
<small>{t("assistant.reply.progress", { done: counts.complete, total: tools.length })}{counts.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: counts.unsettled })}`}{counts.jobsRunning > 0 && ` · ${t("assistant.reply.jobsRunningCount", { count: counts.jobsRunning })}`}{counts.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: counts.failed })}`}{counts.interrupted > 0 && ` · ${t("assistant.reply.interruptedCount", { count: counts.interrupted })}`}</small>
<CanvasIcon name="chevronRight" size={14} />
</summary>
{open && <div className="cw-chat-tool-group-items">
Expand Down Expand Up @@ -163,7 +165,7 @@ export const AssistantReply = memo(function AssistantReply({
<summary>
<CanvasIcon name="sparkle" size={15} />
<span>{t("assistant.reply.tools", { count: message.tools?.length ?? 0 })}</span>
<small>{t("assistant.reply.progress", { done: history.complete, total: message.tools?.length ?? 0 })}{history.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: history.unsettled })}`}{history.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: history.failed })}`}</small>
<small>{t("assistant.reply.progress", { done: history.complete, total: message.tools?.length ?? 0 })}{history.unsettled > 0 && ` · ${t("assistant.reply.unsettledCount", { count: history.unsettled })}`}{history.jobsRunning > 0 && ` · ${t("assistant.reply.jobsRunningCount", { count: history.jobsRunning })}`}{history.failed > 0 && ` · ${t("assistant.reply.failedCount", { count: history.failed })}`}</small>
<CanvasIcon name="chevronRight" size={14} />
</summary>
<div className="cw-chat-activity-detail">{sections.activity.map(renderPart)}</div>
Expand Down
42 changes: 38 additions & 4 deletions src/canvas/assistantActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,49 @@ export function toolLabel(
return typeof operation === "string" ? `${name} ${operation}` : name;
}

export type ToolDisplayStatus = ChatTool["status"] | "unsettled";
export type ToolDisplayStatus = ChatTool["status"] | "unsettled" | "jobsRunning";

const TERMINAL_JOB_STATES = new Set(["succeeded", "failed", "cancelled", "interrupted"]);

function waitSatisfied(tool: ChatTool): boolean {
const outcome = tool.waitOutcome;
if (!outcome) return true;
if (typeof outcome.satisfied === "boolean") return outcome.satisfied;
if (outcome.settled) return true;
const waitSeconds =
outcome.waitSeconds ??
(typeof tool.arguments?.waitSeconds === "number" ? tool.arguments.waitSeconds : undefined);
if (waitSeconds === 0) return true;
const until = outcome.until ?? tool.arguments?.until;
if (outcome.kind === "job.status" && until === "any" && outcome.statuses) {
return Object.entries(outcome.statuses).some(([state, count]) => count > 0 && TERMINAL_JOB_STATES.has(state));
}
return false;
}

export function toolDisplayStatus(tool: ChatTool): ToolDisplayStatus {
return tool.status === "complete" && tool.waitOutcome?.settled === false ? "unsettled" : tool.status;
if (tool.status !== "complete" || !tool.waitOutcome || tool.waitOutcome.settled) return tool.status;
return waitSatisfied(tool) ? "jobsRunning" : "unsettled";
}

export function toolCounts(tools: readonly ChatTool[]): Record<ToolDisplayStatus, number> {
const counts: Record<ToolDisplayStatus, number> = { running: 0, complete: 0, unsettled: 0, failed: 0, interrupted: 0 };
for (const tool of tools) counts[toolDisplayStatus(tool)] += 1;
const counts: Record<ToolDisplayStatus, number> = {
running: 0,
complete: 0,
unsettled: 0,
jobsRunning: 0,
failed: 0,
interrupted: 0,
};
for (const tool of tools) {
const display = toolDisplayStatus(tool);
if (tool.status === "complete") {
counts.complete += 1;
if (display !== "complete") counts[display] += 1;
} else {
counts[display] += 1;
}
}
return counts;
}

Expand Down
7 changes: 6 additions & 1 deletion src/i18n/messages/en-US/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,19 @@ export const assistant = {
"assistant.reply.status.failed": "Failed",
"assistant.reply.status.interrupted": "Interrupted",
"assistant.reply.status.unsettled": "Not finished",
"assistant.reply.status.jobsRunning": "Jobs running",
"assistant.reply.tools": {
one: "Activity · {count} call",
other: "Activity · {count} calls",
},
"assistant.reply.progress": "{done}/{total} complete",
"assistant.reply.failedCount": "{count} failed",
"assistant.reply.interruptedCount": "{count} interrupted",
"assistant.reply.unsettledCount": "{count} returned before jobs finished",
"assistant.reply.unsettledCount": {
one: "{count} wait not finished",
other: "{count} waits not finished",
},
"assistant.reply.jobsRunningCount": "{count} with jobs still running",
"assistant.reply.showEarlier": {
one: "Show {count} earlier call",
other: "Show {count} earlier calls",
Expand Down
Loading
Loading