@hasna-internal/kai-tool-subagent-control 0.1.1-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/subagent/tool-subagent-control/README.md
5
+ README.md: 91f8d23ac092049e5315418070cdaae025054860
6
+ README.zh.md: ca63383e541ccb157f5ee8a6a7a7de7be84b9f5a
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # @hasna-internal/kai-tool-subagent-control
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ The optional, globally named `send_message`, `interrupt_agent`, and `list_agents` tools are thin adapters over `ctx.subagents`. Provider-bound `@hasna-internal/kai-tool-subagent` instances register distinct delegation tools per transport; this separately loaded package registers shared control tools once, so multiple delegation tools never register duplicate global controls. The root plugin registers `send_message` and `interrupt_agent` and requires only `subagents`; the separately loadable `./list-agents` plugin registers `list_agents` and declares `subagents` plus `agents` as load-time dependencies. Its catalog reads additionally require the session store and projection registry at call time, but no query service. A deployment can keep the root tools while omitting the list tool. No tool's presence determines whether a delegation tool starts continuable work. These tools own only the parent-to-child direction; the independently installed [`@hasna-internal/kai-tool-subagent-report`](../tool-subagent-report/README.md) owns the child-to-parent direction.
6
+
7
+ The tool performs no lifecycle routing — residency and cold resume belong to the subagent service. It passes `exec.agent` as the exact live parent that authorizes delivery and records every message source as `{ kind: 'coordinator', senderSessionId: parent.id }`, which the service retains but never treats as authority. Every message becomes the subagent's next FIFO turn through `Agent.followup()`: if the child is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. The tool forwards its execution signal, which owns admission only until inbox acceptance; once the child accepts the message the accepted turn cannot be cancelled through this tool. This call returns no child reply — its transcript by that id is the source of what it did — and a child with `report` sends content on its own initiative as a separate parent message. A delivery failure becomes an errored tool result stating the message was not delivered.
8
+
9
+ `interrupt_agent(agent_id)` passes `exec.agent` as the exact live ancestor authority for `ctx.subagents.interrupt()`: the target may be a direct child or a deeper descendant, and the service — never this tool — verifies the caller against the target Activation's recorded lineage. Only the target's current turn stops (`keepInbox`): queued messages stay parked until a later `send_message`, published descendants keep running, and the child stays available for follow-ups. The call returns as soon as the stop request is accepted, without waiting for target quiescence; an absent or already-settled target is an accepted no-op, while self, sibling, stale, and non-ancestor callers become errored results.
10
+
11
+ `list_agents` takes one optional `scope` argument, derives the root id from the calling agent, and projects the service catalog to continuable children without a cursor. The default `children` scope reads `ctx.subagents.listChildren()`; `descendants` reads `ctx.subagents.listDescendants()`, whose one-corpus walk crosses ordinary sessions and one-shot children and renders surviving rows in stable pre-order with `parent=<id> depth=<n>`. The `parent` annotation is the durable direct-parent session id and may name an ordinary session omitted from the output. For the calling agent, only depth-1 child entries are `send_message` candidates; deeper child entries are `interrupt_agent` candidates only. Status comes from the live Agent registry: `running` (active driver), `idle` (resident between turns, possibly waiting on agents it started), or `ready` (storage only and resumable rather than terminal). The service result also contains one-shot session-backed subagents for consumers such as a UI, but those entries are omitted from this model tool because they cannot accept `send_message`. Diagnostics remain visible, with positions in the descendants scope. Durable identity and mode come from each child's descriptor, while delivery-time authority and Activation ownership checks remain the service's.
12
+
13
+ ## Model Experience
14
+
15
+ ### Tool schema
16
+
17
+ #### What the model sees
18
+
19
+ The generated [schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tool-subagent-control): `send_message` takes `subagent_id` and `message`, describing that the message becomes the subagent's next turn, that this call returns no answer from the subagent, and that a failure means the message was not delivered; `interrupt_agent` takes `agent_id`, describing that only the current turn stops, queued messages park, descendants keep running, and acceptance precedes the actual stop; `list_agents` takes the optional `scope` enum.
20
+
21
+ #### Token effect
22
+
23
+ Fixed schema cost per parent request.
24
+
25
+ #### KV Cache effect
26
+
27
+ Prefix-stable; the schema does not change at runtime.
28
+
29
+ ### Interrupt result
30
+
31
+ #### What the model sees
32
+
33
+ `interrupt requested for agent <agent_id>` on acceptance. An unauthorized caller — self, sibling, stale, or non-ancestor — is an errored result naming the rejection; an absent or settled target still renders the acceptance line.
34
+
35
+ #### Token effect
36
+
37
+ One short acknowledgement per call; the interrupted turn's abort is visible only in the child's own transcript.
38
+
39
+ #### KV Cache effect
40
+
41
+ Append-only; each result follows the reusable request prefix.
42
+
43
+ ### Delivery result
44
+
45
+ #### What the model sees
46
+
47
+ `message queued as the next turn for subagent <subagent_id>` on acceptance; the canonical output carries the accepted `messageId`. A failure — an unauthorized or unknown child, a descriptor-less child that cannot be resumed, or admission rejected — is an errored result whose message states the message was not delivered.
48
+
49
+ #### Token effect
50
+
51
+ One short acknowledgement per call; the child's response never returns through this call. A separately granted `report` may append selected content to parent history.
52
+
53
+ #### KV Cache effect
54
+
55
+ Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
56
+
57
+ ### Listing result
58
+
59
+ #### What the model sees
60
+
61
+ One line per continuable child in stable catalog order: `<id> [<status>] — <label>` (`running` = active driver, `idle` = resident between turns, `ready` = storage only; resumable rather than terminal, not a result waiting to be collected — a direct child in that state can be resumed by `send_message`), plus `<id> [diagnostic: <reason>]` for a candidate that could not be read (`corrupt`, `unsupported`, or `unavailable`). The `descendants` scope inserts ` parent=<id> depth=<n>` before the label dash on every line, in pre-order. One-shot children are intentionally absent; `(no subagents)` means no continuable child or diagnostic survived the projection. Diagnostics never expose descriptor contents.
62
+
63
+ #### Token effect
64
+
65
+ Grows linearly with the listed continuable children — the whole tree under the `descendants` scope; there is no cursor or cap, so long-lived parents with many persisted children pay the full list each call.
66
+
67
+ #### KV Cache effect
68
+
69
+ Append-only; each result follows the reusable request prefix.
70
+
71
+ ## Known Limitations and Deferred Work
72
+
73
+ - **A queued message has no independent result** — acceptance returns only its inbox `messageId`; the child's work lands in the durable child Session and is never collected through this tool. A child granted `report` may send selected content back separately, but that message is not this call's result.
74
+ - **No steering of the current turn** — every message opens a later FIFO turn, so a message sent while the child is working runs only after its current turn finishes and cannot redirect it.
75
+ - **Listing is a snapshot, not a delivery promise** — it may race publication, disposal, or a later message, and another process may activate a child this process reports as `ready`; cross-process accuracy requires a shared lease. `interrupt_agent` performs the authoritative live-lineage check itself, so discovery staleness cannot grant authority.
76
+ - **No pagination or deletion** — the complete stably ordered set is returned, and persisted children remain listed for as long as their sessions remain in persistence; a service-level bound or delete operation is a later product decision.
package/README.zh.md ADDED
@@ -0,0 +1,76 @@
1
+ # @hasna-internal/kai-tool-subagent-control
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 可选的全局具名 `send_message`、`interrupt_agent` 与 `list_agents` 工具是 `ctx.subagents` 之上的轻量适配器。绑定提供方的 `@hasna-internal/kai-tool-subagent` 实例会为每种传输注册不同的委派工具;这个单独加载的包只注册一次共享控制工具,因此多个委派工具绝不会重复注册全局控制工具。根插件注册 `send_message` 与 `interrupt_agent`,且只要求 `subagents`;可单独加载的 `./list-agents` 插件注册 `list_agents`,并将 `subagents` 与 `agents` 声明为加载时依赖。其目录读取在调用时还要求会话存储与投影注册表,但不要求任何查询服务。部署可保留根插件工具并省略列表工具。是否加载这些工具不会决定委派工具是否启动可继续工作。这些工具只负责父到子的方向;单独安装的 [`@hasna-internal/kai-tool-subagent-report`](../tool-subagent-report/README.zh.md) 负责子到父的方向。
6
+
7
+ 本工具不执行生命周期路由:驻留与冷恢复归 subagent 服务所有。它将 `exec.agent` 作为授权投递的确切在线父级传入,并把每条消息的来源记录为 `{ kind: 'coordinator', senderSessionId: parent.id }`;服务会保留该来源,但绝不将其视为权限。每条消息都会通过 `Agent.followup()` 成为 subagent 的下一个 FIFO 轮次:如果子 agent(智能体)仍在工作,该消息会等待其当前轮次结束,因此无法重定向已经在进行的工作。本工具会转发其执行信号,该信号只在 inbox 接受之前掌管准入;一旦子 agent 接受消息,已接受的轮次便无法再通过本工具取消。本次调用不会返回子 agent 的回复;通过该 id 查看其 transcript(文本记录),才是了解它完成了哪些工作的真源。拥有 `report` 的子 agent 会自行把内容作为一条单独的父级消息发回。投递失败会变为出错的工具结果,并明确说明消息未送达。
8
+
9
+ `interrupt_agent(agent_id)` 将 `exec.agent` 作为 `ctx.subagents.interrupt()` 的确切在线 ancestor 授权传入:目标可以是直接 child 或更深的后代,由服务——而不是本工具——依据目标 Activation 记录的 lineage 校验调用方。只有目标的当前轮次会停止(`keepInbox`):已排队的消息保持暂停直到之后的 `send_message`,已发布的后代继续运行,child 也仍可接受后续消息。调用在停止请求被接受后立即返回,不等待目标完全停稳;目标不存在或已结算是被接受的 no-op,而 self、sibling、陈旧与非 ancestor 调用方会成为出错结果。
10
+
11
+ `list_agents` 接受一个可选的 `scope` 参数,会从调用它的 agent 推导根 id,并且不使用 cursor,将服务目录投影为可继续 child。默认的 `children` scope 读取 `ctx.subagents.listChildren()`;`descendants` 读取 `ctx.subagents.listDescendants()`,其单份语料的遍历会穿过普通会话与一次性 child,并按稳定 pre-order 以 `parent=<id> depth=<n>` 渲染保留下来的条目。`parent` 注释是持久化直接 parent 会话 id,可能指向输出中省略的普通会话。对于调用本工具的 agent,只有 depth-1 child 条目可作为 `send_message` 候选;更深的 child 条目只能作为 `interrupt_agent` 候选。状态来自在线 Agent 注册表:`running`(driver 活跃)、`idle`(驻留但处于轮次之间,可能在等待它启动的 agent)或 `ready`(仅存于存储,表示可恢复而非终态)。服务结果还包含由会话支撑的一次性 subagent,以供 UI 等消费方使用;但这些条目无法接受 `send_message`,因此会从这个模型工具中排除。diagnostic 仍然可见,并在 descendants scope 中带有位置。持久化身份和模式来自每个子 agent 的描述符,消息送达时的鉴权和 Activation 所有权检查仍归服务负责。
12
+
13
+ ## 模型体验
14
+
15
+ ### 工具 schema
16
+
17
+ #### 模型看到的内容
18
+
19
+ 已生成的 [schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-subagent-control):`send_message` 包含 `subagent_id` 和 `message`,说明消息会成为 subagent 的下一个轮次、本次调用不会返回 subagent 的回答,以及失败即表示消息未送达;`interrupt_agent` 包含 `agent_id`,说明只有当前轮次会停止、已排队消息保持暂停、后代继续运行,以及接受先于实际停止;`list_agents` 包含可选的 `scope` 枚举。
20
+
21
+ #### Token 影响
22
+
23
+ 每个父级请求支付固定的 schema 成本。
24
+
25
+ #### KV Cache 影响
26
+
27
+ 前缀保持稳定;schema 不会在运行时改变。
28
+
29
+ ### 中断结果
30
+
31
+ #### 模型看到的内容
32
+
33
+ 接受时返回 `interrupt requested for agent <agent_id>`。未授权的调用方——self、sibling、陈旧或非 ancestor——会成为指明拒绝原因的出错结果;目标不存在或已结算仍渲染接受行。
34
+
35
+ #### Token 影响
36
+
37
+ 每次调用产生一条简短确认消息;被中断轮次的中止只在 child 自己的 transcript 中可见。
38
+
39
+ #### KV Cache 影响
40
+
41
+ 仅追加;每个结果都位于可复用请求前缀之后。
42
+
43
+ ### 投递结果
44
+
45
+ #### 模型看到的内容
46
+
47
+ 接受时返回 `message queued as the next turn for subagent <subagent_id>`;规范输出携带被接受的 `messageId`。失败,包括未授权或未知的子 agent、缺少描述符而无法恢复的子 agent,或准入被拒绝,都会成为出错的结果,其消息说明该消息未送达。
48
+
49
+ #### Token 影响
50
+
51
+ 每次调用产生一条简短确认消息;子 agent 的响应绝不会通过本次调用返回。单独授予的 `report` 可以把选定内容追加到父级历史中。
52
+
53
+ #### KV Cache 影响
54
+
55
+ 仅追加;新增可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
56
+
57
+ ### 列表结果
58
+
59
+ #### 模型看到的内容
60
+
61
+ 按稳定目录顺序,每个可继续 child 占一行:渲染为 `<id> [<status>] — <label>`(`running` 表示 driver 活跃,`idle` 表示驻留但处于轮次之间,`ready` 表示仅存于存储;可恢复而非终态,也不表示有结果等待收集——处于该状态的直接 child 可通过 `send_message` 恢复),另为无法读取的候选项渲染 `<id> [diagnostic: <reason>]`(`corrupt`、`unsupported` 或 `unavailable`)。`descendants` scope 会在每行 label 破折号之前插入 ` parent=<id> depth=<n>`,按 pre-order 排列。一次性 child 会被有意排除;`(no subagents)` 表示投影后没有留下可继续 child 或 diagnostic。诊断信息绝不会暴露描述符内容。
62
+
63
+ #### Token 影响
64
+
65
+ 随所列可继续 child 数量线性增长——`descendants` scope 下为整棵树;没有 cursor 或上限,因此长期存活且有许多持久化 child 的 parent 每次调用都会承担完整列表成本。
66
+
67
+ #### KV Cache 影响
68
+
69
+ 仅追加;每个结果都位于可复用请求前缀之后。
70
+
71
+ ## 已知限制与暂缓事项
72
+
73
+ - **已排队的消息没有独立结果**:接受时只返回其 inbox `messageId`;subagent 的工作会落入持久化子 agent 会话,绝不会通过本工具收集。获得 `report` 的子 agent 可以单独发回选定内容,但该消息不是本次调用的结果。
74
+ - **不对当前轮次进行 steering(中途引导)**:每条消息都会开启后续 FIFO 轮次,因此在子 agent 工作时发送的消息只会在其当前轮次结束后运行,无法将其重定向。
75
+ - **列表是快照,而非投递承诺**:它可能与发布、dispose(资源释放)或后续消息发生竞态,另一个进程也可能激活当前进程报告为 `ready` 的 child;跨进程准确性需要共享租约。`interrupt_agent` 自己执行权威的在线 lineage 检查,因此过期的发现结果不会授予权限。
76
+ - **没有分页或删除**:系统返回完整且稳定排序的集合;只要 child 会话仍在持久化存储中,它就会继续出现在列表中,服务级上限或删除操作留待后续产品决策。
package/lib/index.js ADDED
@@ -0,0 +1,101 @@
1
+ import { defineTool } from "@hasna-internal/kai-tools";
2
+ import { SessionId } from "@hasna-internal/kai-session";
3
+ //#region lib/types/index.js
4
+ /**
5
+ * The globally named `send_message` and `interrupt_agent` tools: thin
6
+ * model-facing adapters over `ctx.subagents.followup()` and
7
+ * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
8
+ * residency, cold resume, and interrupt authorization belong to the subagent
9
+ * service — and they live apart from the provider-bound
10
+ * `@hasna-internal/kai-tool-subagent` instances so multiple delegation tools share
11
+ * one control API.
12
+ * @module @hasna-internal/kai-tool-subagent-control
13
+ */
14
+ const name = "tool-subagent-control";
15
+ const inject = ["tools", "subagents"];
16
+ /**
17
+ * Register the `send_message` and `interrupt_agent` tools.
18
+ * @param ctx - context carrying the tool registry and subagent service.
19
+ */
20
+ function apply(ctx) {
21
+ ctx.tools.register(defineTool({
22
+ name: "send_message",
23
+ description: "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent — only confirmation that the message was delivered — so use it to give it more work. A failure means the message was NOT delivered.",
24
+ parameters: {
25
+ subagent_id: {
26
+ type: "string",
27
+ required: true,
28
+ description: "The subagent id returned when the background subagent was started."
29
+ },
30
+ message: {
31
+ type: "string",
32
+ required: true,
33
+ description: "The message to deliver to the subagent."
34
+ }
35
+ },
36
+ output: {
37
+ schema: {
38
+ type: "object",
39
+ additionalProperties: false,
40
+ properties: { messageId: {
41
+ type: "string",
42
+ required: true
43
+ } }
44
+ },
45
+ render: (args, _value) => [{
46
+ type: "text",
47
+ text: `message queued as the next turn for subagent ${args.subagent_id}`
48
+ }]
49
+ },
50
+ async execute(args, exec) {
51
+ const parent = exec.agent;
52
+ if (!parent) throw new Error("send_message requires a calling agent (exec.agent was undefined)");
53
+ const message = [{
54
+ type: "text",
55
+ text: args.message
56
+ }];
57
+ return { messageId: await ctx.subagents.followup(parent, SessionId(args.subagent_id), message, {
58
+ source: {
59
+ kind: "coordinator",
60
+ form: "relay",
61
+ senderSessionId: parent.id
62
+ },
63
+ signal: exec.signal
64
+ }) };
65
+ }
66
+ }));
67
+ ctx.tools.register(defineTool({
68
+ name: "interrupt_agent",
69
+ description: "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.",
70
+ parameters: { agent_id: {
71
+ type: "string",
72
+ required: true,
73
+ description: "The agent id of the running agent to interrupt."
74
+ } },
75
+ output: {
76
+ schema: {
77
+ type: "object",
78
+ additionalProperties: false,
79
+ properties: { accepted: {
80
+ type: "boolean",
81
+ required: true
82
+ } }
83
+ },
84
+ render: (args, _value) => [{
85
+ type: "text",
86
+ text: `interrupt requested for agent ${args.agent_id}`
87
+ }]
88
+ },
89
+ execute(args, exec) {
90
+ const caller = exec.agent;
91
+ if (!caller) throw new Error("interrupt_agent requires a calling agent (exec.agent was undefined)");
92
+ ctx.subagents.interrupt(SessionId(args.agent_id), {
93
+ kind: "ancestor",
94
+ agent: caller
95
+ });
96
+ return Promise.resolve({ accepted: true });
97
+ }
98
+ }));
99
+ }
100
+ //#endregion
101
+ export { apply, inject, name };
@@ -0,0 +1,23 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@hasna-internal/kai-tool-subagent-control`.
4
+ * @module @hasna-internal/kai-tool-subagent-control/invariant
5
+ */
6
+ const PACKAGE_NAME = "@hasna-internal/kai-tool-subagent-control";
7
+ /** Cordis companion plugin name. */
8
+ const name = "tool-subagent-control-invariant";
9
+ /** Service required before the companion can reserve package ownership. */
10
+ const inject = ["invariants"];
11
+ /**
12
+ * No runtime invariant: this model-facing adapter has no independent lifecycle stream; delivery
13
+ * and activation relations are owned by the subagent service it calls.
14
+ */
15
+ const install = () => {};
16
+ /**
17
+ * Register this package's invariant companion.
18
+ * @param ctx - Cordis context carrying the invariant service.
19
+ * @returns the installed registration's disposer after setup succeeds.
20
+ */
21
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
22
+ //#endregion
23
+ export { apply, inject, name };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The globally named `send_message` and `interrupt_agent` tools: thin
3
+ * model-facing adapters over `ctx.subagents.followup()` and
4
+ * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
5
+ * residency, cold resume, and interrupt authorization belong to the subagent
6
+ * service — and they live apart from the provider-bound
7
+ * `@hasna-internal/kai-tool-subagent` instances so multiple delegation tools share
8
+ * one control API.
9
+ * @module @hasna-internal/kai-tool-subagent-control
10
+ */
11
+ import type { Context } from '@deepseek-ai/cordis';
12
+ export declare const name = "tool-subagent-control";
13
+ export declare const inject: string[];
14
+ /**
15
+ * Register the `send_message` and `interrupt_agent` tools.
16
+ * @param ctx - context carrying the tool registry and subagent service.
17
+ */
18
+ export declare function apply(ctx: Context): void;
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The globally named `send_message` and `interrupt_agent` tools: thin
3
+ * model-facing adapters over `ctx.subagents.followup()` and
4
+ * `ctx.subagents.interrupt()`. They perform no lifecycle routing of their own —
5
+ * residency, cold resume, and interrupt authorization belong to the subagent
6
+ * service — and they live apart from the provider-bound
7
+ * `@hasna-internal/kai-tool-subagent` instances so multiple delegation tools share
8
+ * one control API.
9
+ * @module @hasna-internal/kai-tool-subagent-control
10
+ */
11
+ import { defineTool } from '@hasna-internal/kai-tools';
12
+ import { SessionId } from '@hasna-internal/kai-session';
13
+ export const name = 'tool-subagent-control';
14
+ export const inject = ['tools', 'subagents'];
15
+ /**
16
+ * Register the `send_message` and `interrupt_agent` tools.
17
+ * @param ctx - context carrying the tool registry and subagent service.
18
+ */
19
+ export function apply(ctx) {
20
+ ctx.tools.register(defineTool({
21
+ name: 'send_message',
22
+ description: 'Send a message to a background subagent by its subagent id, continuing the same conversation. It '
23
+ + 'becomes the subagent\'s next turn: if it is still working, the message waits until its current turn '
24
+ + 'finishes, so it cannot redirect work already underway. This call returns no answer from the '
25
+ + 'subagent — only confirmation that the message was delivered — so use it to give it more work. A '
26
+ + 'failure means the message was NOT delivered.',
27
+ parameters: {
28
+ subagent_id: {
29
+ type: 'string',
30
+ required: true,
31
+ description: 'The subagent id returned when the background subagent was started.',
32
+ },
33
+ message: {
34
+ type: 'string',
35
+ required: true,
36
+ description: 'The message to deliver to the subagent.',
37
+ },
38
+ },
39
+ output: {
40
+ schema: {
41
+ type: 'object',
42
+ additionalProperties: false,
43
+ properties: {
44
+ messageId: { type: 'string', required: true },
45
+ },
46
+ },
47
+ render: (args, _value) => [{
48
+ type: 'text',
49
+ text: `message queued as the next turn for subagent ${args.subagent_id}`,
50
+ }],
51
+ },
52
+ async execute(args, exec) {
53
+ const parent = exec.agent;
54
+ if (!parent) {
55
+ // Parent authority requires an exact live calling agent.
56
+ throw new Error('send_message requires a calling agent (exec.agent was undefined)');
57
+ }
58
+ const message = [{ type: 'text', text: args.message }];
59
+ const messageId = await ctx.subagents.followup(parent, SessionId(args.subagent_id), message, {
60
+ source: { kind: 'coordinator', form: 'relay', senderSessionId: parent.id },
61
+ signal: exec.signal,
62
+ });
63
+ return { messageId };
64
+ },
65
+ }));
66
+ ctx.tools.register(defineTool({
67
+ name: 'interrupt_agent',
68
+ description: 'Request cancellation of a background agent\'s current turn by its agent id. The target may be your '
69
+ + 'direct child or a deeper agent created under you. Only the current turn stops: messages already '
70
+ + 'queued for the agent stay parked until a later send_message, agents it started keep running, and '
71
+ + 'the agent itself stays available for follow-ups. This call returns as soon as the stop request is '
72
+ + 'accepted, so the target may keep running briefly; interrupting an agent that already finished is '
73
+ + 'an accepted no-op.',
74
+ parameters: {
75
+ agent_id: {
76
+ type: 'string',
77
+ required: true,
78
+ description: 'The agent id of the running agent to interrupt.',
79
+ },
80
+ },
81
+ output: {
82
+ schema: {
83
+ type: 'object',
84
+ additionalProperties: false,
85
+ properties: {
86
+ accepted: { type: 'boolean', required: true },
87
+ },
88
+ },
89
+ render: (args, _value) => [{
90
+ type: 'text',
91
+ text: `interrupt requested for agent ${args.agent_id}`,
92
+ }],
93
+ },
94
+ execute(args, exec) {
95
+ const caller = exec.agent;
96
+ if (!caller) {
97
+ // Ancestor authority requires an exact live calling agent.
98
+ throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)');
99
+ }
100
+ // The service authorizes the exact live caller against the target's
101
+ // recorded lineage; the tool adds no authority of its own.
102
+ ctx.subagents.interrupt(SessionId(args.agent_id), { kind: 'ancestor', agent: caller });
103
+ return Promise.resolve({ accepted: true });
104
+ },
105
+ }));
106
+ }
107
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@hasna-internal/kai-tool-subagent-control`.
3
+ * @module @hasna-internal/kai-tool-subagent-control/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "tool-subagent-control-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Package-owned invariant companion for `@hasna-internal/kai-tool-subagent-control`.
3
+ * @module @hasna-internal/kai-tool-subagent-control/invariant
4
+ */
5
+ const PACKAGE_NAME = '@hasna-internal/kai-tool-subagent-control';
6
+ /** Cordis companion plugin name. */
7
+ export const name = 'tool-subagent-control-invariant';
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export const inject = ['invariants'];
10
+ /**
11
+ * No runtime invariant: this model-facing adapter has no independent lifecycle stream; delivery
12
+ * and activation relations are owned by the subagent service it calls.
13
+ */
14
+ const install = () => { };
15
+ /**
16
+ * Register this package's invariant companion.
17
+ * @param ctx - Cordis context carrying the invariant service.
18
+ * @returns the installed registration's disposer after setup succeeds.
19
+ */
20
+ export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
21
+ /* jscpd:ignore-end */
22
+ //# sourceMappingURL=invariant.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The globally named `list_agents` tool: a thin model-facing adapter over
3
+ * the continuable projection of `ctx.subagents.listChildren()` and, for the
4
+ * `descendants` scope, `ctx.subagents.listDescendants()`. It stays separately
5
+ * loadable from the root `send_message` plugin so a deployment can register
6
+ * continuation delivery without exposing discovery.
7
+ * @module @hasna-internal/kai-tool-subagent-control/list-agents
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis';
10
+ export declare const name = "tool-subagent-list-agents";
11
+ export declare const inject: string[];
12
+ /**
13
+ * Register the `list_agents` tool.
14
+ * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
15
+ */
16
+ export declare function apply(ctx: Context): void;
17
+ //# sourceMappingURL=list-agents.d.ts.map
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The globally named `list_agents` tool: a thin model-facing adapter over
3
+ * the continuable projection of `ctx.subagents.listChildren()` and, for the
4
+ * `descendants` scope, `ctx.subagents.listDescendants()`. It stays separately
5
+ * loadable from the root `send_message` plugin so a deployment can register
6
+ * continuation delivery without exposing discovery.
7
+ * @module @hasna-internal/kai-tool-subagent-control/list-agents
8
+ */
9
+ import { defineTool } from '@hasna-internal/kai-tools';
10
+ import { assertNever } from '@hasna-internal/kai-llm';
11
+ export const name = 'tool-subagent-list-agents';
12
+ export const inject = ['tools', 'subagents', 'agents'];
13
+ /** Resolve the optional model request into an internal required-scope spec. */
14
+ function resolveListAgentsRequest(request) {
15
+ return { scope: request.scope ?? 'children' };
16
+ }
17
+ /**
18
+ * Refine one candidate's status through the live Agent registry: `running`
19
+ * for an active driver, `idle` for a resident Agent between turns (possibly
20
+ * waiting on agents it started), and `ready` when no live Agent remains.
21
+ * `ready` preserves resumability without presenting an inactive conversation
22
+ * as a terminal result to collect.
23
+ */
24
+ function statusOf(agents, id) {
25
+ const agent = agents.get(id);
26
+ if (agent === undefined)
27
+ return 'ready';
28
+ return agent.status === 'running' ? 'running' : 'idle';
29
+ }
30
+ /** Project one service row into the model-facing entry, or omit a one-shot child. */
31
+ function project(agents, entry, position) {
32
+ const at = position === undefined ? {} : { parent: position.parentId, depth: position.depth };
33
+ if (entry.kind === 'diagnostic') {
34
+ return { kind: 'diagnostic', id: entry.id, reason: entry.reason, ...at };
35
+ }
36
+ // One-shot children cannot be continued by send_message, so the model
37
+ // never selects them; discovery still traversed them for descendants.
38
+ if (entry.mode !== 'continuable')
39
+ return undefined;
40
+ return {
41
+ kind: 'child',
42
+ id: entry.id,
43
+ label: entry.label,
44
+ status: statusOf(agents, entry.id),
45
+ ...at,
46
+ };
47
+ }
48
+ /**
49
+ * Register the `list_agents` tool.
50
+ * @param ctx - context carrying the tool registry, subagent service, and live Agent registry.
51
+ */
52
+ export function apply(ctx) {
53
+ ctx.tools.register(defineTool({
54
+ name: 'list_agents',
55
+ description: 'List your continuable background subagents by durable id and label. Use it to recall which ones '
56
+ + 'you started, not to poll for completion — you are told when one finishes. Status comes from the live '
57
+ + 'registry: running means the agent is working right now, idle means it is loaded but between turns '
58
+ + '(it may be waiting on agents it started), and ready means it exists only in storage — resumable, not '
59
+ + 'terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same '
60
+ + 'conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery '
61
+ + 'promise — `send_message` performs the authoritative check and may still fail. Children that could '
62
+ + 'not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` '
63
+ + 'walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent '
64
+ + 'session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are '
65
+ + 'candidates for `interrupt_agent` only.',
66
+ parameters: {
67
+ scope: {
68
+ type: 'string',
69
+ enum: ['children', 'descendants'],
70
+ description: 'children (default) lists direct children only; descendants walks the complete tree below you.',
71
+ },
72
+ },
73
+ output: {
74
+ schema: {
75
+ type: 'array',
76
+ items: {
77
+ oneOf: [
78
+ {
79
+ type: 'object',
80
+ additionalProperties: false,
81
+ properties: {
82
+ kind: { type: 'string', required: true, enum: ['child'] },
83
+ id: { type: 'string', required: true },
84
+ label: { type: 'string', required: true },
85
+ status: { type: 'string', required: true, enum: ['running', 'idle', 'ready'] },
86
+ parent: { type: 'string' },
87
+ depth: { type: 'number' },
88
+ },
89
+ },
90
+ {
91
+ type: 'object',
92
+ additionalProperties: false,
93
+ properties: {
94
+ kind: { type: 'string', required: true, enum: ['diagnostic'] },
95
+ id: { type: 'string', required: true },
96
+ reason: { type: 'string', required: true, enum: ['corrupt', 'unsupported', 'unavailable'] },
97
+ parent: { type: 'string' },
98
+ depth: { type: 'number' },
99
+ },
100
+ },
101
+ ],
102
+ },
103
+ },
104
+ render: (args, entries) => {
105
+ const request = resolveListAgentsRequest(args);
106
+ return [{
107
+ type: 'text',
108
+ text: entries.length === 0
109
+ ? '(no subagents)'
110
+ : entries.map((entry) => {
111
+ // A descendants row always carries its position; children rows
112
+ // never render it. String() spans the schema-optional shape
113
+ // without a dead fallback branch.
114
+ const at = request.scope === 'descendants'
115
+ ? ` parent=${String(entry.parent)} depth=${String(entry.depth)}`
116
+ : '';
117
+ return entry.kind === 'child'
118
+ ? `${entry.id} [${entry.status}]${at} — ${entry.label}`
119
+ : `${entry.id} [diagnostic: ${entry.reason}]${at}`;
120
+ }).join('\n'),
121
+ }];
122
+ },
123
+ },
124
+ async execute(args, exec) {
125
+ const parent = exec.agent;
126
+ if (!parent) {
127
+ // Non-agent callers have no session whose children could be listed.
128
+ throw new Error('list_agents requires a calling agent (exec.agent was undefined)');
129
+ }
130
+ const request = resolveListAgentsRequest(args);
131
+ // The registry drains started tool bodies, so the scan must observe the
132
+ // call's signal rather than finish a slow catalog after cancellation.
133
+ switch (request.scope) {
134
+ case 'children': {
135
+ const entries = await ctx.subagents.listChildren(parent.id, exec.signal);
136
+ return entries
137
+ .map(entry => project(ctx.agents, entry))
138
+ .filter(entry => entry !== undefined);
139
+ }
140
+ case 'descendants': {
141
+ const entries = await ctx.subagents.listDescendants(parent.id, exec.signal);
142
+ return entries
143
+ .map(entry => project(ctx.agents, entry, entry))
144
+ .filter(entry => entry !== undefined);
145
+ }
146
+ /* v8 ignore next 2 -- the resolver normalizes the schema-validated closed scope before dispatch. */
147
+ default:
148
+ return assertNever(request.scope, 'list_agents scope');
149
+ }
150
+ },
151
+ }));
152
+ }
153
+ //# sourceMappingURL=list-agents.js.map
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@hasna-internal/kai-tool-subagent-control",
3
+ "description": "Globally named send_message, interrupt_agent, and list_agents tools over ctx.subagents continuations",
4
+ "version": "0.1.1-rc.2",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
11
+ "directory": "packages/subagent/tool-subagent-control"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./invariant": {
22
+ "types": "./lib/types/invariant.d.ts",
23
+ "default": "./lib/invariant.js"
24
+ },
25
+ "./list-agents": {
26
+ "types": "./lib/types/list-agents.d.ts",
27
+ "default": "./lib/types/list-agents.js"
28
+ },
29
+ "./src/*": "./src/*",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "lib/index.js",
34
+ "lib/invariant.js",
35
+ "lib/types/**/*.js",
36
+ "lib/types/**/*.d.ts"
37
+ ],
38
+ "license": "MIT",
39
+ "peerDependencies": {
40
+ "@hasna-internal/kai-llm": "^0.1.1-rc.2",
41
+ "@hasna-internal/kai-session": "^0.1.1-rc.2",
42
+ "@hasna-internal/kai-subagent": "^0.1.1-rc.2",
43
+ "@hasna-internal/kai-invariants": "^0.1.1-rc.2",
44
+ "@hasna-internal/kai-tools": "^0.1.1-rc.2",
45
+ "@deepseek-ai/cordis": "^4.0.1"
46
+ },
47
+ "devDependencies": {
48
+ "@hasna-internal/kai-agent": "^0.1.1-rc.2",
49
+ "@hasna-internal/kai-agent-loop": "^0.1.1-rc.2",
50
+ "@hasna-internal/kai-llm": "^0.1.1-rc.2",
51
+ "@hasna-internal/kai-session": "^0.1.1-rc.2",
52
+ "@hasna-internal/kai-session-persistence": "^0.1.1-rc.2",
53
+ "@hasna-internal/kai-session-projection": "^0.1.1-rc.2",
54
+ "@hasna-internal/kai-session-persistence-jsonl": "^0.1.1-rc.2",
55
+ "@hasna-internal/kai-agent-loop-testkit": "^0.1.1-rc.2",
56
+ "@hasna-internal/kai-subagent": "^0.1.1-rc.2",
57
+ "@hasna-internal/kai-invariants": "^0.1.1-rc.2",
58
+ "@hasna-internal/kai-tools": "^0.1.1-rc.2",
59
+ "@hasna-internal/kai-subagent-spawn-in-process": "^0.1.1-rc.2",
60
+ "@deepseek-ai/cordis": "^4.0.1"
61
+ }
62
+ }