diff --git a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.i18n.yaml index 938198ae47..0fe026850b 100644 --- a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.i18n.yaml @@ -9,8 +9,8 @@ en: 5071232d9743096c zh: b553a626538b3466 /agent-note-delivering-messages-from-outside-an-agent-through-the-agent-controller/decision: - en: 3a8ac7102fdc9ae8 - zh: 762184146694a0ae + en: 093ee597e6f888b9 + zh: 0723dbc5c186a620 /agent-note-delivering-messages-from-outside-an-agent-through-the-agent-controller/alternatives-considered: en: acc465cfe02b624c zh: db1d06574f647130 diff --git a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.md b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.md index 669392f809..4cc0404ba4 100644 --- a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.md +++ b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.md @@ -18,7 +18,7 @@ The core package `dsh-agent-controller` owns how a message from outside an Agent | Sender work | `prepare` turns the sender's content into durable message content inside the Agent's delivery order; the optional `beforeInsert` runs synchronously immediately before the append, for bookkeeping that must precede the Agent's wake | | Listeners | Run in registration order with Agent scope filtering and receive the Agent, the message, and a signal that aborts when the sender cancels or the controller stops; return the decision of `next()` to admit, await before `next()` to hold, and return `{ kind: 'reject', reason, message, presented }` to refuse without asking later listeners; throw only when the check itself fails | | Delivery mode | Stays with the sender; listeners do not see it, because no admission policy depends on it | -| Order | Messages to one Agent are prepared, decided, and appended one at a time in arrival order; a sender that cancels before the append is not admitted, and disposing the controller stops every message that has not entered an inbox | +| Order | Messages to one Agent are prepared, decided, and appended one at a time in arrival order; a sender that cancels before the append is not admitted and stops waiting at once, even behind a held message; disposing the controller stops every message that has not entered an inbox and finishes once those deliveries settled | | Failures | A rejection raises `AgentAdmissionRejected` with its reason and `presented`; a thrown listener error raises it with `agent-controller/admission-failed`, and an Agent that left the registry with `agent-controller/agent-gone`; errors from `prepare`, `beforeInsert`, `followup()`, and `steer()` pass through; no listener runs after the message entered the inbox | Only senders that deliver work on someone's behalf call `deliver()`. Messages the Agent's own machinery produces, such as job results, goal rounds, plan transitions, and question answers, keep `followup()`, `steer()`, and `inject()`: they belong to work that was already admitted. A listener must not wait for a person when the message source is unattended, such as a schedule or a webhook; it passes or refuses such a message. diff --git a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.zh.md b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.zh.md index 767e38e842..97da1fc6c6 100644 --- a/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.zh.md @@ -18,7 +18,7 @@ core 包 `dsh-agent-controller` 负责来自 Agent 外部的消息如何进入 | 发送方的工作 | `prepare` 在该 Agent 的投递顺序内把发送方的内容转成持久的消息内容;可选的 `beforeInsert` 紧挨在放入之前同步运行,用于必须先于 Agent 唤醒完成的登记 | | 监听器 | 按注册顺序运行,按 Agent 作用域过滤,拿到 Agent、消息和一个在发送方取消或控制器停止时中止的信号;返回 `next()` 的决定即放行,在 `next()` 前 await 即暂留,返回 `{ kind: 'reject', reason, message, presented }` 即拒绝且不再询问后面的监听器;只在检查本身执行失败时抛出异常 | | 投递方式 | 留在发送方,监听器看不到,因为目前没有按投递方式区分的准入策略 | -| 顺序 | 同一个 Agent 的消息按到达顺序逐条准备、决定并放入;在放入之前取消的发送方不会被接纳,销毁控制器会停止所有尚未进入收件箱的消息 | +| 顺序 | 同一个 Agent 的消息按到达顺序逐条准备、决定并放入;在放入之前取消的发送方不会被接纳,并立即结束等待,即使排在被暂留的消息之后;销毁控制器会停止所有尚未进入收件箱的消息,并在这些投递结束后才完成 | | 失败 | 拒绝时抛出带其 reason 与 `presented` 的 `AgentAdmissionRejected`;监听器抛出异常时 reason 为 `agent-controller/admission-failed`,Agent 离开注册表时为 `agent-controller/agent-gone`;`prepare`、`beforeInsert`、`followup()` 与 `steer()` 的错误原样抛出;消息进入收件箱之后不再有监听器运行 | 只有代表他人送来工作的发送方调用 `deliver()`。Agent 自身机制产生的消息,例如后台任务结果、goal 轮次、plan 切换和问题答复,继续使用 `followup()`、`steer()` 与 `inject()`:它们属于已经接纳的工作。消息来源无人值守时(例如定时任务或 webhook),监听器不得等待人来处理,只能放行或拒绝。 diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 8206f3e6dc..8ba6244399 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -18,11 +18,11 @@ en: b9eeb18645121a8b zh: 70d87a12c43e042a /deepseek-harness-architecture/core-packages: - en: 20ef882e44b06a10 - zh: c10c3934ed5570e9 + en: f4dde8809a713bad + zh: ccbee814b4e8b4b7 /deepseek-harness-architecture/events: - en: e89802f066e4955d - zh: ea2fb4bef94e086d + en: c00467ff3a210ef5 + zh: 7619d7cca723fa6b /deepseek-harness-architecture/turn-flow: en: e6402b28c0ed15fa zh: 6c07be9047b42056 diff --git a/docs/architecture.md b/docs/architecture.md index 03d88148c7..2aea688db0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -61,6 +61,7 @@ Electron starts the private Desktop Host in Electron Node mode. The Host invokes | [`core/tools`](subsystems/tools.md) | The scoped tool registry and guarded execution pipeline | `ctx.tools` | | [`core/agent`](subsystems/core.md) | The `Agent` interface, live registry, and `agent/*` events | `ctx.agents` | | [`core/agent-loop`](subsystems/core.md) | The default driver implementing that interface | `ctx.agentLoop` | +| [`core/agent-controller`](subsystems/core.md#messages-from-outside-an-agent) | Admission and delivery of outside messages | `ctx.agentController` | | [`core/scope`](subsystems/scope.md) | The per-agent scoped-registration primitive | library, no key | | [`llm/llm`](subsystems/llm-streaming.md) | Message and stream vocabulary plus the adapter seam | `ctx.llm` | @@ -70,6 +71,7 @@ Events are the extension points, and picking the right domain is the first decis - **Session events** are durable facts appended to the log and broadcast through `session/event`. Use one when the fact must survive a reload. - **Agent events** (`agent/*`) carry a live `Agent`: inbox, step, status, request, validation, continuation. Use one to observe or intercept work in flight. +- **Delivery admission** (`agent-controller/admission`) holds or refuses outside input before it enters the inbox. - **Capability events** attach policy and adapters to a seam (`fs/*`, `tools/*`, `telemetry/*`) without importing the loop. AgentLoop awaits serial `agent/created` before queued work and rolls back failed initialization. Unload retains resources through Agent teardown; [agent-loop](../packages/core/agent-loop/README.md#understand-the-implementation) defines ordering. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 870fa1c996..98258507d1 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -61,6 +61,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 | [`core/tools`](subsystems/tools.zh.md) | 作用域化的工具注册表和带把关的执行流水线 | `ctx.tools` | | [`core/agent`](subsystems/core.zh.md) | `Agent` 接口、活跃 agent 注册表和 `agent/*` 事件 | `ctx.agents` | | [`core/agent-loop`](subsystems/core.zh.md) | 实现该接口的默认驱动器 | `ctx.agentLoop` | +| [`core/agent-controller`](subsystems/core.zh.md#messages-from-outside-an-agent) | 外部消息的准入与投递 | `ctx.agentController` | | [`core/scope`](subsystems/scope.zh.md) | 按 agent 划分作用域的注册原语 | 库,无 ctx 键 | | [`llm/llm`](subsystems/llm-streaming.zh.md) | 消息与流式词汇表,以及适配器 seam | `ctx.llm` | @@ -72,6 +73,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 - **会话事件**是追加到日志并通过 `session/event` 广播的持久事实。当某个事实必须在重新加载后仍然存在时,使用它。 - **Agent 事件**(`agent/*`)携带活跃 `Agent`:inbox、步骤、状态、请求、验证、续跑。要观察或拦截进行中的工作时,使用它。 +- **投递准入**(`agent-controller/admission`)在外部输入进入收件箱之前暂留或拒绝它。 - **能力事件**无需导入循环即可向某个 seam(`fs/*`、`tools/*`、`telemetry/*`)附加策略和适配器。 AgentLoop 在启动已排队工作前等待串行 `agent/created`,初始化失败则回滚。卸载在 Agent teardown 期间保留所需资源;[agent-loop](../packages/core/agent-loop/README.zh.md#understand-the-implementation)定义顺序。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c20dc051f8..55ce4542c3 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -8,7 +8,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-controller/admission` | `waterfall` | [`packages/core/agent-controller/src/types.ts:78`](../packages/core/agent-controller/src/types.ts) | [`agent-controller`](../packages/core/agent-controller) (`waterfall`) | - | +| `agent-controller/admission` | `waterfall` | [`packages/core/agent-controller/src/types.ts:79`](../packages/core/agent-controller/src/types.ts) | [`agent-controller`](../packages/core/agent-controller) (`waterfall`) | - | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index c0614d406f..141810510a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -10,7 +10,7 @@ | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-controller/admission` | `waterfall` | [`packages/core/agent-controller/src/types.ts:78`](../packages/core/agent-controller/src/types.ts) | [`agent-controller`](../packages/core/agent-controller) (`waterfall`) | - | +| `agent-controller/admission` | `waterfall` | [`packages/core/agent-controller/src/types.ts:79`](../packages/core/agent-controller/src/types.ts) | [`agent-controller`](../packages/core/agent-controller) (`waterfall`) | - | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:249`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:69`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:363`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 94bed76054..a5cc8a18a5 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -6,8 +6,8 @@ en: f6ae07d8902e8edf zh: c92fef531c6da331 /core/the-spine-package-by-package: - en: c90cb23528ddb6c8 - zh: 62724b7255b586b6 + en: 60926dc99f41024d + zh: f40370b034f91463 /core/creation-and-ownership: en: ab09a38b4e1f0883 zh: 81e2d14c4036ab6c @@ -16,7 +16,10 @@ zh: 25bc9cb60ee1520a /core/initiating-agent: en: 6c8c47ac78de2dde - zh: c9d527a25a85d1d9 + zh: acde99c8808ea891 +/core/messages-from-outside-an-agent: + en: cf087fd9ff5edb87 + zh: c3bb56b17cd76c52 /core/interception-decisions: en: 6fccceb0a5f1cad9 zh: f43c30c2386d8cc8 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 69e5cbf4af..de314f1546 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -15,9 +15,10 @@ A turn flows through the six packages in one loop: the driver in [`agent-loop`]( | `tools/` | The scoped tool registry and guarded execution pipeline (`ctx.tools`) | [tools.md](tools.md) | | `agent/` | The `Agent` interface, live registry, initiator scope, and `agent/*` event vocabulary (`ctx.agents`) | this page | | `agent-loop/` | The concrete driver implementing the public `Agent` contract (`ctx.agentLoop`) | this page | +| `agent-controller/` | Delivery of messages from outside an Agent through the `agent-controller/admission` stage (`ctx.agentController`) | this page | | `scope/` | The scoped-registration primitive the registries and loop build per-agent scoping on | [scope.md](scope.md) | -`scope/` is the one non-service package: a dependency-free library (`createScope`/`scopeOf`/`scopeTarget`) that sits below `session/` and `system-prompt/` in the module graph precisely so they can consume it without a cycle. `agent-loop` is the one concrete implementation of the public `Agent` contract and lives here because it is the harness's default product loop; it runs each driver inside `ctx.agents.withInitiator()`. Extension plugins depend on `agent` — including when they need the initiating Agent — and never on `agent-loop` directly, so the loop stays swappable. [`dsh-base`](../../packages/bundle/base/README.md) is the default product composition, while [`dsh-sdk-minimal`](../../packages/bundle/sdk-minimal/README.md) declares a smaller standalone tree. +`scope/` is the one non-service package: a dependency-free library (`createScope`/`scopeOf`/`scopeTarget`) that sits below `session/` and `system-prompt/` in the module graph precisely so they can consume it without a cycle. `agent-loop` is the one concrete implementation of the public `Agent` contract and lives here because it is the harness's default product loop; it runs each driver inside `ctx.agents.withInitiator()`. Extension plugins depend on `agent` — including when they need the initiating Agent — and never on `agent-loop` directly, so the loop stays swappable. `agent-controller` sits in front of the loop: a sender that brings a message on someone's behalf delivers it through `ctx.agentController` instead of appending to the inbox itself. [`dsh-base`](../../packages/bundle/base/README.md) is the default product composition, while [`dsh-sdk-minimal`](../../packages/bundle/sdk-minimal/README.md) declares a smaller standalone tree. ## Creation and ownership @@ -305,6 +306,65 @@ The [event taxonomy](../architecture.md#events) owns the `agent/*` lifecycle, ch The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules. +## Messages from outside an Agent + +A sender that brings a message on someone's behalf, such as the Web Session Remote, calls `ctx.agentController.deliver` from [`agent-controller`](../../packages/core/agent-controller/README.md) instead of `followup()` or `steer()`. The controller prepares the content in the Agent's delivery order, asks the `agent-controller/admission` waterfall for a decision, and appends an admitted message; messages the Agent's own machinery produces enter without the stage. The [delivery decision](../../.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.md) explains why the stage lives outside `agent`. + +Source: [`packages/core/agent-controller/src/types.ts`](../../packages/core/agent-controller/src/types.ts) + +```ts type-equiv +/** How a delivered message enters the inbox: `followup` for its own turn, `steer` for the nearest step. */ +type DeliveryMode = 'followup' | 'steer' +``` + +```ts type-equiv +/** One message a sender delivers on someone's behalf. */ +interface DeliveryRequest { + /** Where the message enters once it is admitted. */ + readonly mode: DeliveryMode + /** Durable attribution recorded on the message. */ + readonly source: MessageSource + /** The sender's cancellation; it ends the sender's wait at once and stops a message that has not entered the inbox. */ + readonly signal: AbortSignal + /** + * Turn the sender's content into durable message content, such as by + * storing attachments. It runs in the Agent's delivery order, after the + * earlier messages to the same Agent settled; its failure reaches the + * sender unchanged. + * @param signal - aborted when the sender cancels or the controller stops; controller disposal waits for the preparation to settle. + * @returns the content of the message. + */ + readonly prepare: (signal: AbortSignal) => Promise + /** + * Record what the sender needs before the Agent wakes. It runs + * synchronously after admission, immediately before the message enters the + * inbox. A throw keeps the message out of the inbox and reaches the sender + * unchanged; the sender reverts its own effects when `deliver` rejects. + * @param message - the admitted message. + */ + readonly beforeInsert?: (message: UserMessage) => void +} +``` + +A listener admits by returning the decision of `next()`, holds the message by awaiting before `next()`, and refuses it by returning a `reject` decision: + +```ts type-equiv +/** The outcome of the admission stage for one message. */ +type AdmissionDecision = + /** The message enters the inbox. */ + | { readonly kind: 'admit' } + /** The message stays out of the inbox. */ + | { + readonly kind: 'reject' + /** Code of the refusal, owned by its source, such as `forge/worktree-missing`. */ + readonly reason: string + /** Explanation for a sender that shows nothing of the refusing plugin. */ + readonly message: string + /** Whether the refusing plugin explains the refusal in its own interface. */ + readonly presented: boolean + } +``` + ## Interception decisions Pre-step decisions use the same identified `UserMessage` type as durable user-role input. The entered batch is authoritative and preserves every message's `id` and `source`. Hook bridges map their native decision fields onto this typed result. @@ -421,7 +481,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.agentController` — `AgentController` -Delivers the messages that senders, such as the Web Session Remote, bring on someone's behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox. +Delivers the messages that senders, such as the Web Session Remote, bring on someone's behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox and finishes once each delivery it stopped has settled. ```ts cordis-catalog /** @@ -433,10 +493,11 @@ Delivers the messages that senders, such as the Web Session Remote, bring on som * @returns the id of the message once it is in the inbox. * @throws {@link AgentAdmissionRejected} when a listener rejects the message * or throws, or when the Agent left the registry first; the error of - * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the - * cancellation reason once the sender cancels or the controller stops. + * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the sender's + * cancellation reason as soon as it cancels, also while the message waits + * behind another one; the stop reason once the controller stops. */ -deliver(agent: Agent, request: DeliveryRequest): Promise +async deliver(agent: Agent, request: DeliveryRequest): Promise ``` Types: [MessageId](llm-streaming.md) @@ -1114,7 +1175,8 @@ Decide whether one message from outside an Agent enters its inbox. `ctx.agentCon * when the message source is unattended, such as a schedule or a webhook. * @param payload.agent - the receiving Agent. * @param payload.message - the message as it will enter the inbox. - * @param payload.signal - aborted when the sender cancels or the controller stops. + * @param payload.signal - aborted when the sender cancels or the controller stops; a holding + * listener must settle once it aborts, because controller disposal waits for it. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): Agent-scoped listeners receive only that Agent. * @mode waterfall */ diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index c216a5b2b2..2520a601de 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -15,9 +15,10 @@ | `tools/` | 带作用域的工具注册表与受保护的执行流水线(`ctx.tools`) | [tools.md](tools.zh.md) | | `agent/` | `Agent` 接口、实时注册表、发起者作用域与 `agent/*` 事件词汇(`ctx.agents`) | 本页 | | `agent-loop/` | 实现公开 `Agent` 约定的具体 driver(`ctx.agentLoop`) | 本页 | +| `agent-controller/` | 外部消息经 `agent-controller/admission` 阶段投递进 Agent(`ctx.agentController`) | 本页 | | `scope/` | 注册表与循环用于构建按 agent 作用域的注册原语 | [scope.md](scope.zh.md) | -`scope/` 是这里唯一的非服务包:一个零依赖库(`createScope`/`scopeOf`/`scopeTarget`),在模块图中位于 `session/` 与 `system-prompt/` 之下,正是为了让它们消费它而不形成环。`agent-loop` 是公开 `Agent` 约定的唯一具体实现,放在这里因为它是 harness 的默认产品循环;它在 `ctx.agents.withInitiator()` 内运行每个 driver。扩展插件依赖 `agent`——包括需要发起 Agent 时——而绝不直接依赖 `agent-loop`,因此循环保持可替换。[`dsh-base`](../../packages/bundle/base/README.zh.md) 是默认产品组合,[`dsh-sdk-minimal`](../../packages/bundle/sdk-minimal/README.zh.md) 则声明一棵更小的独立配置树。 +`scope/` 是这里唯一的非服务包:一个零依赖库(`createScope`/`scopeOf`/`scopeTarget`),在模块图中位于 `session/` 与 `system-prompt/` 之下,正是为了让它们消费它而不形成环。`agent-loop` 是公开 `Agent` 约定的唯一具体实现,放在这里因为它是 harness 的默认产品循环;它在 `ctx.agents.withInitiator()` 内运行每个 driver。扩展插件依赖 `agent`——包括需要发起 Agent 时——而绝不直接依赖 `agent-loop`,因此循环保持可替换。`agent-controller` 位于循环之前:代表他人送来消息的发送方经 `ctx.agentController` 投递,而不是自己写入收件箱。[`dsh-base`](../../packages/bundle/base/README.zh.md) 是默认产品组合,[`dsh-sdk-minimal`](../../packages/bundle/sdk-minimal/README.zh.md) 则声明一棵更小的独立配置树。 @@ -311,6 +312,67 @@ cause 是由 TypeScript 强制约束的同进程输入。活跃的取消持有 `ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;[initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.zh.md)定义其生命周期和作用域规则。 + + +## 来自 Agent 外部的消息 + +代表他人送来消息的发送方(例如 Web Session Remote)调用 [`agent-controller`](../../packages/core/agent-controller/README.zh.md) 的 `ctx.agentController.deliver`,而不是 `followup()` 或 `steer()`。控制器按该 Agent 的投递顺序准备内容,向 `agent-controller/admission` waterfall 请求决定,再放入被接纳的消息;Agent 自身机制产生的消息不经过这个阶段。[投递决策](../../.agents/notes/implemented/architecture/2026-10-17-agent-controller-message-delivery.zh.md)说明了这个阶段为什么不放在 `agent` 里。 + +源码:[`packages/core/agent-controller/src/types.ts`](../../packages/core/agent-controller/src/types.ts) + +```ts type-equiv +/** How a delivered message enters the inbox: `followup` for its own turn, `steer` for the nearest step. */ +type DeliveryMode = 'followup' | 'steer' +``` + +```ts type-equiv +/** One message a sender delivers on someone's behalf. */ +interface DeliveryRequest { + /** Where the message enters once it is admitted. */ + readonly mode: DeliveryMode + /** Durable attribution recorded on the message. */ + readonly source: MessageSource + /** The sender's cancellation; it ends the sender's wait at once and stops a message that has not entered the inbox. */ + readonly signal: AbortSignal + /** + * Turn the sender's content into durable message content, such as by + * storing attachments. It runs in the Agent's delivery order, after the + * earlier messages to the same Agent settled; its failure reaches the + * sender unchanged. + * @param signal - aborted when the sender cancels or the controller stops; controller disposal waits for the preparation to settle. + * @returns the content of the message. + */ + readonly prepare: (signal: AbortSignal) => Promise + /** + * Record what the sender needs before the Agent wakes. It runs + * synchronously after admission, immediately before the message enters the + * inbox. A throw keeps the message out of the inbox and reaches the sender + * unchanged; the sender reverts its own effects when `deliver` rejects. + * @param message - the admitted message. + */ + readonly beforeInsert?: (message: UserMessage) => void +} +``` + +监听器返回 `next()` 的决定即放行,在 `next()` 之前 await 即暂留消息,返回 `reject` 决定即拒绝: + +```ts type-equiv +/** The outcome of the admission stage for one message. */ +type AdmissionDecision = + /** The message enters the inbox. */ + | { readonly kind: 'admit' } + /** The message stays out of the inbox. */ + | { + readonly kind: 'reject' + /** Code of the refusal, owned by its source, such as `forge/worktree-missing`. */ + readonly reason: string + /** Explanation for a sender that shows nothing of the refusing plugin. */ + readonly message: string + /** Whether the refusing plugin explains the refusal in its own interface. */ + readonly presented: boolean + } +``` + ## 拦截决策 @@ -433,7 +495,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.agentController` — `AgentController` -Delivers the messages that senders, such as the Web Session Remote, bring on someone's behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox. +Delivers the messages that senders, such as the Web Session Remote, bring on someone's behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox and finishes once each delivery it stopped has settled. ```ts cordis-catalog /** @@ -445,10 +507,11 @@ Delivers the messages that senders, such as the Web Session Remote, bring on som * @returns the id of the message once it is in the inbox. * @throws {@link AgentAdmissionRejected} when a listener rejects the message * or throws, or when the Agent left the registry first; the error of - * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the - * cancellation reason once the sender cancels or the controller stops. + * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the sender's + * cancellation reason as soon as it cancels, also while the message waits + * behind another one; the stop reason once the controller stops. */ -deliver(agent: Agent, request: DeliveryRequest): Promise +async deliver(agent: Agent, request: DeliveryRequest): Promise ``` Types: [MessageId](llm-streaming.zh.md) @@ -1126,7 +1189,8 @@ Decide whether one message from outside an Agent enters its inbox. `ctx.agentCon * when the message source is unattended, such as a schedule or a webhook. * @param payload.agent - the receiving Agent. * @param payload.message - the message as it will enter the inbox. - * @param payload.signal - aborted when the sender cancels or the controller stops. + * @param payload.signal - aborted when the sender cancels or the controller stops; a holding + * listener must settle once it aborts, because controller disposal waits for it. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): Agent-scoped listeners receive only that Agent. * @mode waterfall */ diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 8d081a53fb..e8afb243af 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: ba76393ac7f226a9 - zh: 12925c6d961ddaba + en: 9348161f652592ed + zh: d9c4919381bf0f77 /session-controller/client-references: en: 41bdda1ac32df558 zh: aa5d0e325924066b diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 4cdecdc497..b2cf8e4ff5 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -31,7 +31,7 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host. -Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. A prompt enters the Agent through [`ctx.agentController.deliver`](../../core/agent-controller/README.md#use-this-package), which runs the receipt resolution and attachment storage in the Agent's delivery order and binds the receipts immediately before the message enters the inbox, so the call stays open while an `agent-controller/admission` listener holds it. A refusal returns `session/prompt-rejected` with the listener's `reason` and `presented`, a listener failure returns the same code with reason `agent-controller/admission-failed`, and an Agent disposed meanwhile returns `session/not-found`. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. +Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. A prompt enters the Agent through [`ctx.agentController.deliver`](../../core/agent-controller/README.md#use-this-package), which runs the receipt resolution and attachment storage in the Agent's delivery order and binds the receipts immediately before the message enters the inbox, so the call stays open while an `agent-controller/admission` listener holds it. An image prompt takes the Session's image admission turn when its preparation starts and keeps it until the prompt settles, so a model selection lands either before its image check or after it entered the inbox, and waits while a listener holds that image prompt. A refusal returns `session/prompt-rejected` with the listener's `reason` and `presented`, a listener failure returns the same code with reason `agent-controller/admission-failed`, and an Agent disposed meanwhile returns `session/not-found`. A client that predates `session/prompt-rejected` shows it as an ordinary failure with its message and code. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 9057c6a4ac..c969f9f953 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。 -每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。提示词经 [`ctx.agentController.deliver`](../../core/agent-controller/README.zh.md#use-this-package) 进入 Agent:控制器按该 Agent 的投递顺序完成凭证解析与附件存储,并在消息进入收件箱前一刻绑定凭证,因此 `agent-controller/admission` 监听器暂留它期间调用保持未完成。被拒绝时返回 `session/prompt-rejected`,并带上监听器给出的 `reason` 与 `presented`;监听器失败时返回同一错误码,reason 为 `agent-controller/admission-failed`;期间 Agent 被销毁则返回 `session/not-found`。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 +每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。提示词经 [`ctx.agentController.deliver`](../../core/agent-controller/README.zh.md#use-this-package) 进入 Agent:控制器按该 Agent 的投递顺序完成凭证解析与附件存储,并在消息进入收件箱前一刻绑定凭证,因此 `agent-controller/admission` 监听器暂留它期间调用保持未完成。图片提示词在开始准备时取得该 Session 的图片准入顺位,并持有到提示词结束,因此模型切换要么发生在它的图片检查之前,要么发生在它进入收件箱之后;监听器暂留这条图片提示词期间,模型切换会等待。被拒绝时返回 `session/prompt-rejected`,并带上监听器给出的 `reason` 与 `presented`;监听器失败时返回同一错误码,reason 为 `agent-controller/admission-failed`;期间 Agent 被销毁则返回 `session/not-found`。早于 `session/prompt-rejected` 的旧客户端把它显示为普通失败,带消息与错误码。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index aaacc886e7..4ecd2af8ec 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -379,6 +379,27 @@ export class ApiSessionAgentController { return result } + /** + * Take the image admission turn for one Agent: wait until earlier image + * admissions and model selections settled, then hold the turn until the + * returned release runs. + * @param agent - live Agent that owns the serialization chain. + * @param signal - the waiting caller's cancellation; a caller cancelled by its turn passes the turn on. + * @returns the release, which the caller runs once its image prompt settled. + * @throws the cancellation reason when the caller was cancelled by its turn. + */ + acquireImageAdmission(agent: Agent, signal: AbortSignal): Promise<() => void> { + const previous = this.imageAdmissionChains.get(agent) ?? Promise.resolve() + const held = Promise.withResolvers() + this.imageAdmissionChains.set(agent, previous.then(() => held.promise)) + const release = (): void => { held.resolve(undefined) } + return previous.then(() => { + if (signal.aborted) release() + signal.throwIfAborted() + return release + }) + } + /** * Resolve the preset id and pre-publication Agent setup for a create or resume. * @param presetId - requested preset or the configured default when omitted. diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 962cdb047b..4a1df4744b 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -318,8 +318,10 @@ export class SessionCommandController { * attachment storage) in the Agent's delivery order and binds the upload * receipts immediately before the message enters the inbox. A repeated * request identity is acknowledged without delivering it again. An image - * prompt waits for model selection changes, so the selection it was checked - * against is the one it runs with. + * prompt takes the Session's image admission turn when its preparation + * starts and keeps it until the prompt settles, so a model selection lands + * either before its image check or after it entered the inbox; a selection + * waits while a listener holds that image prompt. * @param request - Session identity, prompt content, and delivery mode. * @param source - the `user-rpc` source recorded on the accepted message. * @param signal - the requesting client's cancellation; it stops a prompt that waits for its turn or is held at the admission stage. @@ -330,35 +332,38 @@ export class SessionCommandController { const agent = await this.resolveAgent(request.sessionId) if (hasPromptRequest(agent, request.requestId)) return { accepted: true } const hasImage = request.content.some(part => part.type === 'image') - const deliver = async (): Promise => { - const uploads: { receiptIds: readonly FileUploadReceiptId[]; binding?: PromptFileBinding } = { receiptIds: [] } - try { - await this.ctx.agentController.deliver(agent, { - mode: request.mode === 'steer' ? 'steer' : 'followup', - source, - signal, - prepare: async () => { - if (hasImage) await this.requireImageInput(agent) - const admission = resolvePromptFileReceipts( - request.content, - receiptId => this.ctx.fileUploads.resolve(agent, receiptId), - ) - uploads.receiptIds = admission.receiptIds - return await this.ctx.attachments.admitPromptContent(admission.content) - }, - beforeInsert: () => { - uploads.binding = this.ctx.fileUploads.bindPrompt(agent, uploads.receiptIds, request.requestId) - }, - }) - uploads.binding?.commit() - } catch (error) { - throw promptFailure(agent, error, signal) - } finally { - uploads.binding?.[Symbol.dispose]() - } - return { accepted: true } + const uploads: { receiptIds: readonly FileUploadReceiptId[]; binding?: PromptFileBinding } = { receiptIds: [] } + const imageTurn: { release?: () => void } = {} + try { + await this.ctx.agentController.deliver(agent, { + mode: request.mode === 'steer' ? 'steer' : 'followup', + source, + signal, + prepare: async (preparing) => { + if (hasImage) { + // Taken in the Agent's delivery order, so a waiting image prompt keeps its place among the others. + imageTurn.release = await this.agents.acquireImageAdmission(agent, preparing) + await this.requireImageInput(agent) + } + const admission = resolvePromptFileReceipts( + request.content, + receiptId => this.ctx.fileUploads.resolve(agent, receiptId), + ) + uploads.receiptIds = admission.receiptIds + return await this.ctx.attachments.admitPromptContent(admission.content) + }, + beforeInsert: () => { + uploads.binding = this.ctx.fileUploads.bindPrompt(agent, uploads.receiptIds, request.requestId) + }, + }) + uploads.binding?.commit() + } catch (error) { + throw promptFailure(agent, error, signal) + } finally { + uploads.binding?.[Symbol.dispose]() + imageTurn.release?.() } - return hasImage ? this.agents.serializeImageAdmission(agent, deliver) : deliver() + return { accepted: true } } /** Refuse an image prompt when the Session's current model does not declare image input. */ diff --git a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts index 13a7649a4e..223a2f6c52 100644 --- a/packages/api/session-controller/tests/commands-upload-file.host.spec.ts +++ b/packages/api/session-controller/tests/commands-upload-file.host.spec.ts @@ -99,6 +99,8 @@ async function uploadHarness(origin?: 'subagent'): Promise<{ selectionFor: () => selection, serializeImageAdmission: (_agent: Agent, operation: () => Promise) => operation(), } as unknown as ApiSessionAgentController + // Image prompts take their admission turn at once; no model selection competes in these tests. + Object.assign(agents, { acquireImageAdmission: () => Promise.resolve(() => {}) }) const uploads = new FileUploads(ctx) if (uploadRoute === undefined) throw new Error('file upload route was not registered') return { diff --git a/packages/api/session-controller/tests/session-models.host.spec.ts b/packages/api/session-controller/tests/session-models.host.spec.ts index e852460e93..6a86663df5 100644 --- a/packages/api/session-controller/tests/session-models.host.spec.ts +++ b/packages/api/session-controller/tests/session-models.host.spec.ts @@ -135,6 +135,46 @@ async function harness(logged?: { return { ctx, agent, sessionId: session.id } } +/** An image store whose saved attachments are one-pixel PNGs. */ +function provideImageStore(ctx: Context): void { + const attachments = { + imageLimits: { + maxImageBytes: 4, + maxImagesPerMessage: 2, + maxMessageImageBytes: 4, + maxImagePixels: 4, + maxImageDimension: 2000, + mediaTypes: ['image/png'], + }, + validateImage: () => Promise.resolve(), + saveImage: (input: { data: Uint8Array; mediaType: 'image/png' }) => Promise.resolve({ + attachmentId: `att-${String(input.data[0])}`, mediaType: input.mediaType, bytes: input.data.byteLength, width: 1, height: 1, + }), + } + ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never) +} + +/** A queued prompt with its text, after a one-pixel image when `withImage` is set. */ +function imagePrompt(sessionId: SessionId, text: string, withImage: boolean): SessionPromptRequest { + return promptRequest({ + sessionId, + mode: 'queue', + content: [ + ...withImage ? [{ type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==' }] : [], + { type: 'text' as const, text }, + ], + }) +} + +function textOf(message: UserMessage): string { + return message.content.map(block => block.type === 'text' ? block.text : '').join('') +} + +/** Let pending prompts run as far as they can. */ +async function settle(): Promise { + await new Promise((resolve) => { setImmediate(resolve) }) +} + function expectValue(result: { ok: true; value: T } | { ok: false }): T { if (!result.ok) throw new Error('expected successful response') return result.value @@ -311,6 +351,110 @@ describe('Web session model selection', () => { await ctx.fiber.dispose() }) + it('admits image prompts in arrival order behind an image prompt that a listener holds', async () => { + const { ctx, agent, sessionId } = await harness() + provideImageStore(ctx) + const followed: string[] = [] + Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } }) + const release = Promise.withResolvers() + ctx.on('agent-controller/admission', async ({ message }, next) => { + if (textOf(message) === 'held') await release.promise + return await next() + }) + const remote = createSessionTestRemote(ctx, { + defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), + cwd: '/tmp', + }) + + const prompts = [ + remote.prompt(imagePrompt(sessionId, 'held', true)), + remote.prompt(imagePrompt(sessionId, 'second image', true)), + remote.prompt(imagePrompt(sessionId, 'third text', false)), + ] + await settle() + expect(followed).toEqual([]) + release.resolve(undefined) + expect((await Promise.all(prompts)).map(result => result.ok)).toEqual([true, true, true]) + expect(followed).toEqual(['held', 'second image', 'third text']) + await ctx.fiber.dispose() + }) + + it('keeps a model selection behind the image prompt being admitted but not behind one still queued', async () => { + const { ctx, agent, sessionId } = await harness() + registerTextOnly(ctx) + provideImageStore(ctx) + const events: string[] = [] + Object.assign(agent, { followup: (message: UserMessage) => { events.push(`admitted ${textOf(message)}`) } }) + const releases = new Map([['held image', Promise.withResolvers()], ['held text', Promise.withResolvers()]]) + ctx.on('agent-controller/admission', async ({ message }, next) => { + await releases.get(textOf(message))?.promise + return await next() + }) + const remote = createSessionTestRemote(ctx, { + defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), + cwd: '/tmp', + }) + const select = () => remote.selectModel(request({ sessionId, provider: 'text-only', model: 'plain' })) + .then((result) => { events.push('selected'); return result }) + + // A held image prompt was checked against the current model, so the selection waits for its append. + const heldImage = remote.prompt(imagePrompt(sessionId, 'held image', true)) + await settle() + const first = select() + await settle() + expect(events).toEqual([]) + releases.get('held image')?.resolve(undefined) + expect((await heldImage).ok).toBe(true) + expect((await first).ok).toBe(true) + expect(events).toEqual(['admitted held image', 'selected']) + + // An image prompt queued behind a held text prompt has not been checked yet, so the selection does not wait for it. + const heldText = remote.prompt(imagePrompt(sessionId, 'held text', false)) + const queuedImage = remote.prompt(imagePrompt(sessionId, 'queued image', true)) + await settle() + expect((await select()).ok).toBe(true) + expect(events).toEqual(['admitted held image', 'selected', 'selected']) + releases.get('held text')?.resolve(undefined) + expect((await heldText).ok).toBe(true) + expect(await queuedImage).toMatchObject({ + ok: false, error: { code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } }, + }) + expect(events).toEqual(['admitted held image', 'selected', 'selected', 'admitted held text']) + await ctx.fiber.dispose() + }) + + it('passes the image admission turn on when the sender of a waiting image prompt leaves', async () => { + const { ctx, agent, sessionId } = await harness() + provideImageStore(ctx) + const followed: string[] = [] + Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } }) + const listing = Promise.withResolvers() + ctx.llm.registerAdapter(['gated'], new class extends CatalogAdapter { + override listModels(): Promise { + return listing.promise + } + }('Gated', [])) + const remote = createSessionTestRemote(ctx, { + defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }), + cwd: '/tmp', + }) + + // The selection holds the image admission turn while the provider lists its models. + const selection = remote.selectModel(request({ sessionId, provider: 'gated', model: 'slow' })) + await settle() + const sender = new AbortController() + const leaving = remote.prompt(imagePrompt(sessionId, 'left', true), sender.signal) + await settle() + sender.abort(new Error('client left')) + expect(await leaving).toMatchObject({ ok: false, error: { code: 'gateway/cancelled' } }) + + listing.resolve([{ provider: 'gated', id: 'slow', name: 'Slow' }]) + expect((await selection).ok).toBe(true) + expect((await remote.prompt(imagePrompt(sessionId, 'after', true))).ok).toBe(true) + expect(followed).toEqual(['after']) + await ctx.fiber.dispose() + }) + it('authorizes attachment bytes only when the session event stream references the id', async () => { const { ctx, agent, sessionId } = await harness() const ref = { diff --git a/packages/core/agent-controller/README.i18n.yaml b/packages/core/agent-controller/README.i18n.yaml index 632ee2563f..91f8f8aa51 100644 --- a/packages/core/agent-controller/README.i18n.yaml +++ b/packages/core/agent-controller/README.i18n.yaml @@ -18,17 +18,17 @@ en: 9fc767473d82e29c zh: c9ba0267b0661af7 /deepseek-ai-dsh-agent-controller/use-this-package/deliver-a-message: - en: 8a8e1d299fecd407 - zh: d6ccdae0e1907e78 + en: d74acf0ead720242 + zh: c44eed7072221adb /deepseek-ai-dsh-agent-controller/use-this-package/hold-or-refuse-a-message: - en: 5ecd169dd1f3682e - zh: 620964ebbc840b75 + en: 7c453bf4191f2bd5 + zh: c58cd73e925f0138 /deepseek-ai-dsh-agent-controller/understand-the-implementation: en: 592af7e68423bd1c zh: d7640d838b8bda1f /deepseek-ai-dsh-agent-controller/understand-the-implementation/design-concept: - en: 8bafd147fa4392bd - zh: 7c18eb4762f7b161 + en: 839265471948929a + zh: 5409775cee9833a8 /deepseek-ai-dsh-agent-controller/understand-the-implementation/source-map: en: f5daeafebe5a482b zh: 9360afa7d5a117b7 diff --git a/packages/core/agent-controller/README.md b/packages/core/agent-controller/README.md index c439d5d276..6d80c30d83 100644 --- a/packages/core/agent-controller/README.md +++ b/packages/core/agent-controller/README.md @@ -43,11 +43,11 @@ const messageId = await ctx.agentController.deliver(agent, { `prepare` runs after the earlier messages to the same Agent settled, so content admission happens in arrival order; its error reaches the sender unchanged. `beforeInsert` runs synchronously after admission, immediately before the message enters the inbox, for bookkeeping the sender needs before the Agent wakes. A throw from it keeps the message out of the inbox, and the sender reverts its own effects when `deliver()` rejects. -`deliver()` rejects with `AgentAdmissionRejected` when a listener refuses the message (with the listener's `reason` and `presented`), when a listener throws (`agent-controller/admission-failed`, with the error as `cause`), or when the Agent left the registry before its message entered the inbox (`agent-controller/agent-gone`). A cancelled sender gets its cancellation reason, and errors from `prepare`, `beforeInsert`, `followup()`, and `steer()` pass through unchanged. The Web Session Remote maps these failures onto `session/prompt-rejected` and its other Session errors. +`deliver()` rejects with `AgentAdmissionRejected` when a listener refuses the message (with the listener's `reason` and `presented`), when a listener throws (`agent-controller/admission-failed`, with the error as `cause`), or when the Agent left the registry before its message entered the inbox (`agent-controller/agent-gone`). A cancelled sender gets its cancellation reason at once, also while its message waits behind a held one, and errors from `prepare`, `beforeInsert`, `followup()`, and `steer()` pass through unchanged. The Web Session Remote maps these failures onto `session/prompt-rejected` and its other Session errors. ### Hold or refuse a message -Listeners of the `agent-controller/admission` waterfall run in registration order and return an `AdmissionDecision`. A listener admits by returning the decision of `next()`, whose last step is `{ kind: 'admit' }`; it holds the message by awaiting before `next()`, and refuses it by returning `{ kind: 'reject', reason, message, presented }` without calling `next()`. `reason` names the refusal, and `presented` says whether the refusing plugin explains it in its own interface. A listener throws only when its check itself fails, and it must not wait for a person when the message source is unattended, such as a schedule or a webhook. +Listeners of the `agent-controller/admission` waterfall run in registration order and return an `AdmissionDecision`. A listener admits by returning the decision of `next()`, whose last step is `{ kind: 'admit' }`; it holds the message by awaiting before `next()`, and refuses it by returning `{ kind: 'reject', reason, message, presented }` without calling `next()`. `reason` names the refusal, and `presented` says whether the refusing plugin explains it in its own interface. A listener throws only when its check itself fails, and it must not wait for a person when the message source is unattended, such as a schedule or a webhook. The `signal` in its payload aborts when the sender cancels or the controller stops; a holding listener must settle once it aborts. ```text ctx.on('agent-controller/admission', async ({ agent, message, signal }, next) => { @@ -70,7 +70,7 @@ This section explains how the service realizes the behavior above; the observabl ### Design concept -The controller chains each Agent's deliveries on one promise, so a held message keeps later messages to the same Agent waiting while other Agents proceed. The chain covers preparation, the decision, and the append, so messages enter the inbox in arrival order. Before preparing, and again after the stage returns, the controller checks cancellation and that the registry still holds the Agent; it then calls `beforeInsert` and `followup()` or `steer()` with no await in between. Listeners therefore never run after the message entered the inbox; a plugin that reacts to admitted messages listens to `agent/inbox/inserted`. Disposing the controller aborts the signal that every pending delivery observes, so the messages that have not entered an inbox are rejected. +The controller chains each Agent's deliveries on one promise, so a held message keeps later messages to the same Agent waiting while other Agents proceed. The chain covers preparation, the decision, and the append, so messages enter the inbox in arrival order. Before preparing, and again after the stage returns, the controller checks cancellation and that the registry still holds the Agent; it then calls `beforeInsert` and `followup()` or `steer()` with no await in between. Listeners therefore never run after the message entered the inbox; a plugin that reacts to admitted messages listens to `agent/inbox/inserted`. A message whose sender cancels while it waits keeps its place in the chain and is dropped when its turn comes, so the order of the others does not change. Disposing the controller aborts the signal that every pending delivery observes, so the messages that have not entered an inbox are rejected; disposal finishes only after every pending delivery, including its preparation and listeners, has settled. ### Source map diff --git a/packages/core/agent-controller/README.zh.md b/packages/core/agent-controller/README.zh.md index 9ed8badff9..34ce2cf3fa 100644 --- a/packages/core/agent-controller/README.zh.md +++ b/packages/core/agent-controller/README.zh.md @@ -43,11 +43,11 @@ const messageId = await ctx.agentController.deliver(agent, { `prepare` 在发给同一 Agent 的更早消息结算之后才运行,因此内容准入按到达顺序进行;它的错误原样交给发送方。`beforeInsert` 在接纳之后同步运行,紧挨在消息进入收件箱之前,用于发送方在 Agent 被唤醒前必须完成的登记。它抛出异常时消息不会进入收件箱,`deliver()` 失败时由发送方撤销自己做过的改动。 -以下情况 `deliver()` 抛出 `AgentAdmissionRejected`:监听器拒绝消息(带监听器给出的 `reason` 与 `presented`);监听器抛出异常(reason 为 `agent-controller/admission-failed`,`cause` 为原异常);消息进入收件箱之前 Agent 已离开注册表(reason 为 `agent-controller/agent-gone`)。发送方取消时得到其取消原因;`prepare`、`beforeInsert`、`followup()` 与 `steer()` 的错误原样抛出。Web Session Remote 把这些失败映射为 `session/prompt-rejected` 及其他 Session 错误。 +以下情况 `deliver()` 抛出 `AgentAdmissionRejected`:监听器拒绝消息(带监听器给出的 `reason` 与 `presented`);监听器抛出异常(reason 为 `agent-controller/admission-failed`,`cause` 为原异常);消息进入收件箱之前 Agent 已离开注册表(reason 为 `agent-controller/agent-gone`)。发送方取消时立即得到其取消原因,消息排在被暂留的消息之后时也是如此;`prepare`、`beforeInsert`、`followup()` 与 `steer()` 的错误原样抛出。Web Session Remote 把这些失败映射为 `session/prompt-rejected` 及其他 Session 错误。 ### 暂留或拒绝一条消息 -`agent-controller/admission` waterfall 的监听器按注册顺序运行,返回 `AdmissionDecision`。监听器放行时返回 `next()` 的决定,链的最后一步是 `{ kind: 'admit' }`;在调用 `next()` 前 await 即暂留消息;不调用 `next()`、直接返回 `{ kind: 'reject', reason, message, presented }` 即拒绝它。`reason` 标明拒绝原因,`presented` 表示拒绝它的插件是否在自己的界面里给出说明。监听器只在自身的检查执行失败时抛出异常;消息来源无人值守时(例如定时任务或 webhook),监听器不得等待人来处理。 +`agent-controller/admission` waterfall 的监听器按注册顺序运行,返回 `AdmissionDecision`。监听器放行时返回 `next()` 的决定,链的最后一步是 `{ kind: 'admit' }`;在调用 `next()` 前 await 即暂留消息;不调用 `next()`、直接返回 `{ kind: 'reject', reason, message, presented }` 即拒绝它。`reason` 标明拒绝原因,`presented` 表示拒绝它的插件是否在自己的界面里给出说明。监听器只在自身的检查执行失败时抛出异常;消息来源无人值守时(例如定时任务或 webhook),监听器不得等待人来处理。载荷里的 `signal` 在发送方取消或控制器停止时中止;暂留消息的监听器必须在它中止后结束。 ```text ctx.on('agent-controller/admission', async ({ agent, message, signal }, next) => { @@ -70,7 +70,7 @@ ctx.on('agent-controller/admission', async ({ agent, message, signal }, next) => ### 设计思路 -控制器把每个 Agent 的投递串在同一个 promise 上,因此被暂留的消息会让同一 Agent 后续的消息等待,其他 Agent 不受影响。这条串行包住准备、决定和放入,所以消息按到达顺序进入收件箱。准备之前,以及接纳阶段返回之后,控制器都会检查是否已取消、注册表是否仍持有该 Agent;随后调用 `beforeInsert` 和 `followup()` 或 `steer()`,中间没有 await。因此监听器不会在消息进入收件箱之后运行;需要对已接纳消息作出反应的插件监听 `agent/inbox/inserted`。销毁控制器会中止所有待处理投递共同观察的信号,尚未进入收件箱的消息因此被拒绝。 +控制器把每个 Agent 的投递串在同一个 promise 上,因此被暂留的消息会让同一 Agent 后续的消息等待,其他 Agent 不受影响。这条串行包住准备、决定和放入,所以消息按到达顺序进入收件箱。准备之前,以及接纳阶段返回之后,控制器都会检查是否已取消、注册表是否仍持有该 Agent;随后调用 `beforeInsert` 和 `followup()` 或 `steer()`,中间没有 await。因此监听器不会在消息进入收件箱之后运行;需要对已接纳消息作出反应的插件监听 `agent/inbox/inserted`。排队期间被发送方取消的消息保留它在串行中的位置,轮到它时被丢弃,其余消息的顺序不变。销毁控制器会中止所有待处理投递共同观察的信号,尚未进入收件箱的消息因此被拒绝;所有待处理投递(包括其准备和监听器)都结束之后,销毁才完成。 ### 源码地图 diff --git a/packages/core/agent-controller/src/index.ts b/packages/core/agent-controller/src/index.ts index ec4a93bcc7..8340265513 100644 --- a/packages/core/agent-controller/src/index.ts +++ b/packages/core/agent-controller/src/index.ts @@ -48,26 +48,47 @@ export class AgentAdmissionRejected extends Error { } } +/** + * Follow a delivery until its sender cancels. The sender's wait ends with the + * cancellation reason at once; the delivery keeps its place in the Agent's + * order and stops at its next cancellation check, before any append. + */ +async function untilCancelled(delivery: Promise, signal: AbortSignal): Promise { + signal.throwIfAborted() + const cancelled = Promise.withResolvers() + const onAbort = (): void => { cancelled.reject(signal.reason) } + signal.addEventListener('abort', onAbort, { once: true }) + try { + return await Promise.race([delivery, cancelled.promise]) + } finally { + signal.removeEventListener('abort', onAbort) + } +} + /** * Delivers the messages that senders, such as the Web Session Remote, bring * on someone's behalf. Messages to one Agent are prepared, decided, and * appended one at a time in arrival order; messages to different Agents do * not wait for each other. Disposal stops every message that has not entered - * an inbox. + * an inbox and finishes once each delivery it stopped has settled. */ export class AgentController extends Service { static inject = ['agents'] /** Per Agent, the settlement of its latest delivery; the next message waits for it. */ private readonly deliveries = new WeakMap>() + /** Settlements of the deliveries that have not finished; disposal waits for them. */ + private readonly pending = new Set>() /** Aborted on disposal; stops the messages that have not entered an inbox. */ private readonly lifetime = new AbortController() /** @param ctx - Host context carrying the Agent registry. */ constructor(ctx: Context) { super(ctx, 'agentController') - ctx.effect(() => () => { + ctx.effect(() => async () => { this.lifetime.abort(new Error('The agent controller stopped before the message entered the inbox.')) + // Preparation and listeners observe the abort; the Agent registry stays available until they settle. + await Promise.all(this.pending) }, 'agent-controller.lifetime') } @@ -80,13 +101,18 @@ export class AgentController extends Service { * @returns the id of the message once it is in the inbox. * @throws {@link AgentAdmissionRejected} when a listener rejects the message * or throws, or when the Agent left the registry first; the error of - * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the - * cancellation reason once the sender cancels or the controller stops. + * `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the sender's + * cancellation reason as soon as it cancels, also while the message waits + * behind another one; the stop reason once the controller stops. */ - deliver(agent: Agent, request: DeliveryRequest): Promise { + async deliver(agent: Agent, request: DeliveryRequest): Promise { + this.lifetime.signal.throwIfAborted() const delivery = (this.deliveries.get(agent) ?? Promise.resolve()).then(() => this.run(agent, request)) - this.deliveries.set(agent, delivery.then(() => undefined, () => undefined)) - return delivery + const settled = delivery.then(() => undefined, () => undefined) + this.deliveries.set(agent, settled) + this.pending.add(settled) + void settled.then(() => { this.pending.delete(settled) }) + return await untilCancelled(delivery, request.signal) } private async run(agent: Agent, request: DeliveryRequest): Promise { diff --git a/packages/core/agent-controller/src/types.ts b/packages/core/agent-controller/src/types.ts index 5ec2b4d0c8..e00ae463eb 100644 --- a/packages/core/agent-controller/src/types.ts +++ b/packages/core/agent-controller/src/types.ts @@ -19,14 +19,14 @@ export interface DeliveryRequest { readonly mode: DeliveryMode /** Durable attribution recorded on the message. */ readonly source: MessageSource - /** The sender's cancellation; it stops a message that has not entered the inbox. */ + /** The sender's cancellation; it ends the sender's wait at once and stops a message that has not entered the inbox. */ readonly signal: AbortSignal /** * Turn the sender's content into durable message content, such as by * storing attachments. It runs in the Agent's delivery order, after the * earlier messages to the same Agent settled; its failure reaches the * sender unchanged. - * @param signal - aborted when the sender cancels or the controller stops. + * @param signal - aborted when the sender cancels or the controller stops; controller disposal waits for the preparation to settle. * @returns the content of the message. */ readonly prepare: (signal: AbortSignal) => Promise @@ -71,7 +71,8 @@ declare module '@deepseek-ai/cordis' { * when the message source is unattended, such as a schedule or a webhook. * @param payload.agent - the receiving Agent. * @param payload.message - the message as it will enter the inbox. - * @param payload.signal - aborted when the sender cancels or the controller stops. + * @param payload.signal - aborted when the sender cancels or the controller stops; a holding + * listener must settle once it aborts, because controller disposal waits for it. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): Agent-scoped listeners receive only that Agent. * @mode waterfall */ diff --git a/packages/core/agent-controller/tests/agent-controller.spec.ts b/packages/core/agent-controller/tests/agent-controller.spec.ts index 851a9ff5b2..a3c4963769 100644 --- a/packages/core/agent-controller/tests/agent-controller.spec.ts +++ b/packages/core/agent-controller/tests/agent-controller.spec.ts @@ -50,6 +50,14 @@ function request(text: string, overrides: Partial = {}): Delive } } +/** A preparation that records its text, then returns it as the message content. */ +function recordingPrepare(prepared: string[], text: string): DeliveryRequest['prepare'] { + return () => { + prepared.push(text) + return Promise.resolve([{ type: 'text', text }]) + } +} + /** Let pending deliveries run as far as they can. */ async function settle(): Promise { await new Promise((resolve) => { setImmediate(resolve) }) @@ -149,10 +157,7 @@ describe('agent controller delivery', () => { if (textOf(message) === 'first') await release.promise return await next() }) - const prepareText = (text: string): DeliveryRequest['prepare'] => () => { - prepared.push(text) - return Promise.resolve([{ type: 'text', text }]) - } + const prepareText = (text: string): DeliveryRequest['prepare'] => recordingPrepare(prepared, text) const first = ctx.agentController.deliver(agent, request('first', { prepare: prepareText('first') })) const second = ctx.agentController.deliver(agent, request('second', { prepare: prepareText('second') })) @@ -349,6 +354,75 @@ describe('agent controller delivery', () => { expect(delivered.map(delivery => delivery.text)).toEqual(['blocking']) }) + it('ends the wait of a message whose sender cancels behind a held one, keeping later messages in order', async () => { + const { ctx, agent, delivered } = await harness() + const release = Promise.withResolvers() + const prepared: string[] = [] + ctx.on('agent-controller/admission', async ({ message, signal }, next) => { + if (textOf(message) === 'held') { + // Holds until released, and lets a stopping controller end the hold. + await new Promise((resolve, reject) => { + void release.promise.then(() => { resolve() }) + signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true }) + }) + } + return await next() + }) + const prepareText = (text: string): DeliveryRequest['prepare'] => recordingPrepare(prepared, text) + + const held = ctx.agentController.deliver(agent, request('held', { prepare: prepareText('held') })) + const queuedSender = new AbortController() + const queued = refusalOf(ctx.agentController.deliver(agent, request('queued', { + signal: queuedSender.signal, prepare: prepareText('queued'), + }))) + const goneSender = new AbortController() + const goneReason = new Error('sender left before delivering') + goneSender.abort(goneReason) + const gone = refusalOf(ctx.agentController.deliver(agent, request('gone', { + signal: goneSender.signal, prepare: prepareText('gone'), + }))) + const later = ctx.agentController.deliver(agent, request('later', { prepare: prepareText('later') })) + await settle() + const queuedReason = new Error('queued sender left') + queuedSender.abort(queuedReason) + // Both senders hear their own reason while the held message still blocks the Agent. + expect(await Promise.race([queued, settle().then(() => 'still waiting')])).toBe(queuedReason) + expect(await gone).toBe(goneReason) + expect(prepared).toEqual(['held']) + + release.resolve(undefined) + await Promise.all([held, later]) + expect(prepared).toEqual(['held', 'later']) + expect(delivered.map(delivery => delivery.text)).toEqual(['held', 'later']) + }) + + it('finishes disposal only after the deliveries it stopped have settled', async () => { + const { ctx, controller, disposeController, agent, delivered } = await harness() + const cleanup = Promise.withResolvers() + const steps: string[] = [] + ctx.on('agent-controller/admission', async ({ signal }, next) => { + await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + steps.push('stop observed') + await cleanup.promise + steps.push('cleaned up') + return await next() + }) + + const held = refusalOf(controller.deliver(agent, request('held'))) + await settle() + let disposed = false + const disposal = disposeController().then(() => { disposed = true }) + await settle() + expect(steps).toEqual(['stop observed']) + expect(disposed).toBe(false) + + cleanup.resolve(undefined) + await disposal + expect(steps).toEqual(['stop observed', 'cleaned up']) + expect(await held).toHaveProperty('message', expect.stringContaining('agent controller stopped')) + expect(delivered).toEqual([]) + }) + it('stops every message that has not entered the inbox when the controller is disposed', async () => { const { ctx, controller, disposeController, agent, delivered } = await harness() const seen: string[] = [] diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 42f71aa32e..168ce4a09a 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -84,14 +84,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'agentController', summary: 'Delivers the messages that senders, such as the Web Session Remote, bring on someone\'s behalf.', - description: 'Delivers the messages that senders, such as the Web Session Remote, bring on someone\'s behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox.', + description: 'Delivers the messages that senders, such as the Web Session Remote, bring on someone\'s behalf. Messages to one Agent are prepared, decided, and appended one at a time in arrival order; messages to different Agents do not wait for each other. Disposal stops every message that has not entered an inbox and finishes once each delivery it stopped has settled.', methods: [ { - signature: 'deliver(agent: Agent, request: DeliveryRequest): Promise', + signature: 'async deliver(agent: Agent, request: DeliveryRequest): Promise', description: 'Deliver one message from outside the Agent: prepare its content, ask the `agent-controller/admission` stage for a decision, then append an admitted message with `followup` or `steer`.', parameters: [{ name: 'agent', description: 'the receiving Agent.' }, { name: 'request', description: 'delivery mode, source, cancellation, and the sender\'s content preparation.' }], returns: 'the id of the message once it is in the inbox.', - throws: ['{@link AgentAdmissionRejected} when a listener rejects the message or throws, or when the Agent left the registry first; the error of `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the cancellation reason once the sender cancels or the controller stops.'], + throws: ['{@link AgentAdmissionRejected} when a listener rejects the message or throws, or when the Agent left the registry first; the error of `prepare`, `beforeInsert`, `followup`, or `steer` unchanged; the sender\'s cancellation reason as soon as it cancels, also while the message waits behind another one; the stop reason once the controller stops.'], }, ], }, @@ -4059,7 +4059,7 @@ export const EVENT_API: readonly EventApiEntry[] = [ signature: '\'agent-controller/admission\'(this: Scoped, payload: { agent: Agent; message: UserMessage; signal: AbortSignal }, next: () => Promise): Promise', summary: 'Decide whether one message from outside an Agent enters its inbox.', description: 'Decide whether one message from outside an Agent enters its inbox. `ctx.agentController.deliver` runs this stage and appends the message only after the whole chain admitted it; messages the Agent\'s own machinery produces enter through `followup`, `steer`, or `inject` without it. Listeners run in registration order, and messages to one Agent are decided one at a time in arrival order. A listener admits by returning the decision of `next()`, whose last step admits; awaiting before `next()` holds the message, and returning a `reject` decision refuses it without asking later listeners. A thrown error means the listener\'s check itself failed. A listener must not wait for a person when the message source is unattended, such as a schedule or a webhook.', - parameters: [{ name: 'payload', description: '.signal - aborted when the sender cancels or the controller stops. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): Agent-scoped listeners receive only that Agent.' }], + parameters: [{ name: 'payload', description: '.signal - aborted when the sender cancels or the controller stops; a holding listener must settle once it aborts, because controller disposal waits for it. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): Agent-scoped listeners receive only that Agent.' }], }, { name: 'agent-loop/config-start-failed', diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index f301060236..e002578c5a 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,7 +1,7 @@ { "AGENTS.md": 2080, "docs/AGENTS.md": 1430, - "docs/architecture.md": 2410, + "docs/architecture.md": 2430, "docs/cordis-primer.md": 600, "docs/testing.md": 1350, "packages/AGENTS.md": 810, diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 39752bafd3..5e7d419df3 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -2511,6 +2511,21 @@ "doc": "docs/subsystems/session-projection.md", "symbol": "ProjectionKeySelection", "source": "packages/session/session-projection/src/index.ts" + }, + { + "doc": "docs/subsystems/core.md", + "symbol": "DeliveryMode", + "source": "packages/core/agent-controller/src/types.ts" + }, + { + "doc": "docs/subsystems/core.md", + "symbol": "DeliveryRequest", + "source": "packages/core/agent-controller/src/types.ts" + }, + { + "doc": "docs/subsystems/core.md", + "symbol": "AdmissionDecision", + "source": "packages/core/agent-controller/src/types.ts" } ] }