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
13 changes: 13 additions & 0 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from opendirector.agent.catalog import model_choices
from opendirector.agent.context import RunContext, RuntimeId
from opendirector.domain.creation.base import agent_command_id
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
Expand Down Expand Up @@ -257,6 +258,18 @@ def trace(project_id: UUID, turn_id: UUID,
raise ProjectError('轨迹文件不存在。', 404)
return FileResponse(file, media_type='text/plain', headers={'Cache-Control': 'no-store'})

@router.get('/turns/{turn_id}/jobs')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a follow-up, could we connect this endpoint to the trace page so each turn shows its linked Jobs, their status, results and errors?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion! I've included the Trace page integration in this PR in commit 4c6c6a56. Each turn now shows its linked Jobs with IDs, statuses, generated asset details (kind, ID, revision) and failure messages. The section stays hidden when no Jobs are linked, and a lookup failure doesn't disrupt the trace. Both en-US and zh-CN are covered.

I also fixed the EOF formatting issue in tools.py and added real browser screenshots (using clearly labeled demo/provider-double data) to the PR's Evidence that it works section. The new CI run is awaiting maintainer approval, so the full checks are not yet confirmed. Would appreciate another look when you have a chance!

def turn_jobs(project_id: UUID, turn_id: UUID):
# Read-only like the trace routes: no session lease, and the Agent trace is not consulted.
# It reads the committed snapshot and never starts, resumes or replays a command.
jobs = sorted((job for job in projects.snapshot(project_id).jobs if job.agentRunId == turn_id),
key=lambda job: (job.createdAt, str(job.id)))
return [dict(jobId=job.id, callId=job.agentCallId, commandId=agent_command_id(turn_id, job.agentCallId),
status=job.status, phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed,
cancelRequested=job.cancelRequested, remoteCancellation=job.remoteCancellation,
errorDetails=job.errorDetails, asset=job.asset, adopted=job.adopted)
for job in jobs]

active: dict[UUID, tuple[UUID, asyncio.Task, RunEvents]] = {}
admission: dict[UUID, asyncio.Lock] = {}

Expand Down
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ This directory is the entry point for the repository's shared documentation. The
| [BigModel video](guides/bigmodel-video.md) ([中文](guides/bigmodel-video.zh-CN.md)) | CogVideoX-3 text, single-image and first/last-frame generation, task recovery and adoption | BigModel protocol, inputs, output sizes or recovery behavior change |
| [BigModel GLM-Image](guides/bigmodel-image.md) ([中文](guides/bigmodel-image.zh-CN.md)) | Account setup, text-to-image generation, adoption and recovery | BigModel integration fields or behavior change |
| [GLM-Image validation](development/glm-image-validation.md) | Real provider workflow screenshots and automated checks | GLM-Image acceptance is repeated |
| [Agent runtime](architecture/agent-runtime.md) | Agent runtime architecture | Runtime architecture changes |
| [Agent runtime](architecture/agent-runtime.md) | Agent runtime architecture and Job origin tracing | Runtime architecture or Job origin semantics change |

The root [README](../README.md) introduces the product and examples and links to quick-start and documentation. See [installation and updates](guides/installation.md) ([中文](guides/installation.zh-CN.md)) for installation, and the [user guide](guides/user-guide.md) ([中文](guides/user-guide.zh-CN.md)) for configuration, creation, and troubleshooting. The README does not contain the full manual, implementation architecture, development tests, research sources, or iteration history. Source code and generated contracts describe the implementation; architecture and roadmap documents describe goals and do not establish that a capability is already available.

Expand Down
25 changes: 25 additions & 0 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,31 @@ Default 的模型网关在 `agent-runs/<turn-id>.model.jsonl` 记录实际转发

停止或流连接断开时,适配层终止进程组,Gateway 关闭新调用入口并等待已接受操作结束;API 保存部分回复并释放运行占用。业务操作以各自回执确认,远端生成任务仍通过任务取消命令处理。

## Agent 来源追溯

Agent 的 `generation.submit` 接受任务时,把本轮标识和工具调用标识写入 Job 自身:

| 字段 | 含义 |
| --- | --- |
| `agentRunId` | 提交该任务的 Agent 轮次(turn)ID |
| `agentCallId` | 该轮内的工具调用 ID,CLI 调用形如 `cli:<id>` |

两个字段同时存在或同时缺失,缺失时不出现在序列化结果中,旧数据的序列化不变。命令 ID 仍由 `agent_command_id(agentRunId, agentCallId)`(即 UUID5)推导,也是幂等键;Command 本身没有新增字段,指纹和幂等规则不变。来源与 Job、回执、快照、事件在同一次提交中落盘,经提交日志恢复后仍在。`job.cancel`、`job.recover` 不改写来源。

两个方向的查询都只读取已提交的工程数据,不读取 Agent 轨迹:

- Job → 轮次:`job.get` 或工程快照中的 `agentRunId`、`agentCallId`。
- 轮次 → Job:`GET /api/creation/projects/{project_id}/assistant/turns/{turn_id}/jobs`,返回该轮提交的 Job(按创建时间、ID 排序):`jobId`、`callId`、`commandId`、`status`、`phase`、`recovery`、`resumeAllowed`、`cancelRequested`、`remoteCancellation`、`errorDetails`、`asset`、`adopted`。工程不存在按既有错误语义返回 404;轮次没有任务返回空列表。该路由与轨迹路由一样不申请编辑会话,不执行、不重放命令,也不启动 Provider。

兼容性:

- 此前创建的 Job 没有来源,只能通过 Agent 轨迹追溯;不回填。
- 旧工程在新版本中可正常打开。
- 含来源字段的工程不能被更早的 OpenDirector 版本打开:Job 模型禁止未知字段,旧版会以存储不可用拒绝该工程。项目格式没有版本号或降级机制,按 [AGENTS.md](../../AGENTS.md) 的约定不静默忽略字段,也不提供兼容层。需要回退版本时,先备份工程目录。
- Agent 轨迹是调试文件,不是业务事实来源,删除它不影响上述查询。

English summary: a Job created by an Agent `generation.submit` records `agentRunId` (turn) and `agentCallId` (tool call), both or neither, and omits them when absent so existing jobs serialize unchanged. The command ID is still `uuid5(run id, call id)` and no Command field was added. Job to turn uses `job.get` or the snapshot. Turn to jobs uses the read-only `GET .../assistant/turns/{turn_id}/jobs`, which reads the committed snapshot, needs no editing session, never replays a command and does not read the Agent trace. Jobs created before this change have no origin and remain traceable only through the trace. Older OpenDirector builds reject a project containing these fields because Job forbids unknown fields; the project format has no version or downgrade mechanism, so back up a project before opening it with an older build.

## 原生工具权限

| Harness | 执行约束 |
Expand Down
8 changes: 5 additions & 3 deletions packages/core/src/opendirector/agent/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from uuid import UUID, uuid5

from pydantic import JsonValue, TypeAdapter, ValidationError
from opendirector.domain.creation.base import agent_command_id
from opendirector.application.creation_artifacts import publish_artifact
from opendirector.application.creation_assets import CreationAssets
from opendirector.application.creation_timeline_packages import CreationTimelinePackages
Expand Down Expand Up @@ -407,10 +408,12 @@ def narrow(value: JsonValue) -> None:
if name != 'execute_command':
raise ProjectError('未知业务工具。')
command = parse_command({**arguments, 'projectId': str(project_id),
'commandId': str(uuid5(turn_id, call_id))})
'commandId': str(agent_command_id(turn_id, call_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 in {'generation.submit', 'job.cancel', 'job.recover'}:
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'}:
receipt = await self.generation.execute(command, session=session, source='agent')
elif command.type in {'asset.writeText', 'artifact.publish'}:
if config is not None:
Expand All @@ -429,4 +432,3 @@ def narrow(value: JsonValue) -> None:
else:
receipt = await asyncio.to_thread(self.projects.execute, command, session=session, source='agent')
return receipt.model_dump(mode='json')

Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ async def _run(self, task, pinned, config, mode='submit'):
remote.release()
claim.release()

def prepare(self, command, *, session=None, source='ui'):
def prepare(self, command, *, session=None, source='ui', agent_origin=None):
replay = self.projects.replay(command)
if replay is not None:
return replay
Expand Down Expand Up @@ -394,6 +394,7 @@ def accept(before):
createdAt=datetime.now(timezone.utc),
inputFingerprint=snapshot.fingerprint(), execution={'kind': spec.kind, **({'size': '2K'} if spec.kind == 'image' else {'format': 'mp3', 'sampleRate': 24000} if spec.kind == 'audio' else {})},
originItemId=origin, previousJobId=command.payload.previousJobId,
**({'agentRunId': agent_origin[0], 'agentCallId': agent_origin[1]} if agent_origin else {}),
adoptionPolicy=command.payload.adoptionPolicy, adoptionResultId=old.currentResultId, adoptionMaterial=material,
batchId=command.payload.batchId, showAdditionalResult=command.payload.showAdditionalResult)
task = self.task(stub)
Expand All @@ -409,9 +410,9 @@ def accept(before):
return ProjectSnapshot.model_validate(data)
return self.projects.commit(command, accept, session=session, source=source)

async def execute(self, command, *, session=None, source='ui'):
async def execute(self, command, *, session=None, source='ui', agent_origin=None):
if command.type == 'generation.submit':
pending = asyncio.create_task(asyncio.to_thread(self.prepare, command, session=session, source=source))
pending = asyncio.create_task(asyncio.to_thread(self.prepare, command, session=session, source=source, agent_origin=agent_origin))
async def finish():
try:
receipt = await pending
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/opendirector/domain/creation/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Versioned JSON contracts for the new project format; no storage or UI code."""
from typing import Annotated, Literal
from uuid import UUID
from uuid import UUID, uuid5
import hashlib
import json

Expand Down Expand Up @@ -72,6 +72,11 @@ def digest(value: Contract, *, exclude=None) -> str:
return hashlib.sha256(encoded).hexdigest()


def agent_command_id(run_id: UUID, call_id: str) -> UUID:
"""Command identity the host derives for one Agent tool call; it is also the idempotency key."""
return uuid5(run_id, call_id)


def unique(values, label):
if len(values) != len(set(values)):
raise ValueError(f'Duplicate {label}')
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,13 @@ class Job(ProjectEntity):
adoptionMaterial: AssetRef | None = Field(default=None, description='Material version reserved for adoption.')
adopted: bool = Field(default=False, description='Whether the generated result was adopted.')
adapterParameters: dict[str, JsonValue] = Field(default_factory=dict, description='Fixed provider-specific execution parameters.')
agentRunId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, description='Agent turn that submitted this job; omitted for jobs not submitted by an Agent.')
agentCallId: str | None = Field(default=None, min_length=1, max_length=512, exclude_if=lambda value: value is None, description='Tool call within that turn that submitted this job; the command ID derives from both.')

@model_validator(mode='after')
def execution_identity(self):
if (self.agentRunId is None) != (self.agentCallId is None):
raise ValueError('Agent run and call identity are recorded together')
if self.showAdditionalResult and (self.originItemId is None or self.adoptionPolicy != 'candidate_only'):
raise ValueError('Additional result display requires an origin and candidate-only adoption')
if self.inputSnapshot.spec.projectId != self.projectId:
Expand Down
31 changes: 31 additions & 0 deletions src/canvas/AssistantTracePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { normalizeClaudeTrace } from "./claudeTrace.ts";
import { normalizeCodexTrace } from "./codexTrace.ts";
import { normalizeDeepseekTrace } from "./deepseekTrace.ts";

import { readTurnJobs, turnJobView, type TurnJob } from "./traceJobs.ts";

import "./assistant-trace.css";

type TraceRecord = {
Expand Down Expand Up @@ -183,6 +185,28 @@ function TraceEntries({ traces, rawModel }: { traces: string[]; rawModel: boolea
});
}

function TraceJobs({ jobs }: { jobs: TurnJob[] }) {
const t = useT();
return (
<section className="cw-trace-jobs" aria-label={t("trace.jobs.title")}>
<h2>{t("trace.jobs.title")}</h2>
{jobs.map((job) => {
const view = turnJobView(job, t);
return (
<div key={view.key} className="cw-trace-row cw-trace-job">
<span className={`cw-trace-badge is-job-${view.status}`}>{view.statusText}</span>
<span className="cw-trace-preview">
<code>{job.jobId}</code>
{[view.assetText, view.adoptedText, view.cancelText, view.errorText]
.filter(Boolean).map((text) => ` · ${text}`).join("")}
</span>
</div>
);
})}
</section>
);
}

export default function AssistantTracePage({ params }: { params: URLSearchParams }) {
const project = params.get("traceProject") ?? "";
const turn = params.get("turn") ?? "";
Expand All @@ -193,6 +217,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
const [showModel, setShowModel] = useState(false);
const rawModel = runtime === "opencode" && showModel;
const [status, setStatus] = useState<number | null>(null);
const [jobs, setJobs] = useState<TurnJob[]>([]);
const t = useT();

useEffect(() => {
Expand All @@ -209,18 +234,23 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
}).catch(() => {});
setStatus(null);
setTraces([]);
setJobs([]);
let timer: number | undefined;
async function refresh() {
try {
if (live && document.hidden) return;
const jobsRequest = fetch(`/api/creation/projects/${projectPath}/assistant/turns/${turnPath}/jobs`, options)
.then(readTurnJobs, () => [] as TurnJob[]);
const snapshots = await Promise.all(sources.map(async (name) => {
const response = await fetch(`${traceUrl}/${encodeURIComponent(name)}`, options);
const body = response.ok ? await response.text() : "";
return { status: response.status, body: name === "deepseek" ? normalizeDeepseekTrace(body) : name === "codex" ? normalizeCodexTrace(body) : name === "claude" ? normalizeClaudeTrace(body) : body };
}));
const nextJobs = await jobsRequest;
const status = snapshots.some((item) => item.status === 200) ? 200 : snapshots[0].status;
if (controller.signal.aborted) return;
setStatus(status);
setJobs((previous) => JSON.stringify(previous) === JSON.stringify(nextJobs) ? previous : nextJobs);
const bodies = snapshots.map((item) => item.body);
setTraces((previous) => bodies.every((body, index) => body === previous[index]) ? previous : bodies);
} catch {
Expand Down Expand Up @@ -265,6 +295,7 @@ export default function AssistantTracePage({ params }: { params: URLSearchParams
status === 404 ? t("trace.notFound") :
t("trace.loadFailed")}</p>
)}
{jobs.length > 0 && <TraceJobs jobs={jobs} />}
</main>
);
}
6 changes: 6 additions & 0 deletions src/canvas/assistant-trace.css
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,9 @@
.cw-trace-command-detail pre { margin: 0; padding: 10px 12px; border-radius: 6px; background: #191919; white-space: pre-wrap; overflow-wrap: anywhere; }
.cw-trace-command-detail p { font-size: 12px; color: #aaa; }
@media (max-width: 600px) { .cw-trace-command-detail { padding-left: 20px; } }
.cw-trace-job { display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 12px; padding: 6px 20px; align-items: center; }
.cw-trace-jobs { margin-top: 16px; border-top: 1px solid #333; }
.cw-trace-jobs h2 { margin: 0; padding: 10px 20px 6px; font-size: 14px; }
.cw-trace-job .cw-trace-preview { white-space: normal; overflow-wrap: anywhere; }
.cw-trace-badge.is-job-succeeded { background: #254034; color: #91d6ab; }
.cw-trace-badge.is-job-failed, .cw-trace-badge.is-job-interrupted { background: #4d2a2a; color: #f0a3a3; }
68 changes: 68 additions & 0 deletions src/canvas/traceJobs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/** Display fields for the Jobs a Turn submitted, shown on the Trace page. */
import type { AssetRef, GenerationFailure } from "../contracts/generated.ts";
import type { Translate } from "../i18n/I18nProvider.tsx";
import type { MessageKey } from "../i18n/types.ts";
import { generationFailureMessage } from "./generationFailureText.ts";

export type TurnJobStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled" | "interrupted";

/** One item of GET /assistant/turns/{turn}/jobs. */
export type TurnJob = {
jobId: string;
callId: string;
commandId: string;
status: TurnJobStatus;
phase?: string | null;
recovery?: string | null;
resumeAllowed?: boolean;
cancelRequested?: boolean;
remoteCancellation?: string | null;
errorDetails: GenerationFailure | null;
asset: AssetRef | null;
adopted: boolean;
};

const STATUS_KEYS: Record<TurnJobStatus, MessageKey> = {
queued: "trace.jobs.status.queued",
running: "trace.jobs.status.running",
succeeded: "trace.jobs.status.succeeded",
failed: "trace.jobs.status.failed",
cancelled: "trace.jobs.status.cancelled",
interrupted: "trace.jobs.status.interrupted",
};

export type TurnJobView = {
key: string;
status: TurnJobStatus;
statusText: string;
assetText: string | null;
errorText: string | null;
adoptedText: string | null;
cancelText: string | null;
};

export function turnJobView(job: TurnJob, t: Translate): TurnJobView {
const status = job.status in STATUS_KEYS ? job.status : "failed";
return {
key: job.jobId,
status,
statusText: t(STATUS_KEYS[status]),
assetText: job.asset
? t("trace.jobs.asset", { kind: job.asset.kind, assetId: job.asset.assetId, revision: job.asset.revision })
: null,
errorText: job.errorDetails ? generationFailureMessage(job.errorDetails, t) : null,
adoptedText: job.asset ? t(job.adopted ? "trace.jobs.adopted" : "trace.jobs.notAdopted") : null,
cancelText: job.cancelRequested && status !== "cancelled" ? t("trace.jobs.cancelRequested") : null,
};
}

/** Parse a jobs response; any failure yields no jobs so the trace is unaffected. */
export async function readTurnJobs(response: Pick<Response, "ok" | "json">): Promise<TurnJob[]> {
if (!response.ok) return [];
try {
const body: unknown = await response.json();
return Array.isArray(body) ? body.filter((job) => job && typeof job.jobId === "string") : [];
} catch {
return [];
}
}
Loading
Loading