@1agents/acp-service 0.8.3 → 0.9.0
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/README.md +6 -0
- package/dist/bin/a2a.js +10 -2
- package/dist/bin/acp-service.js +6 -0
- package/dist/bin/roles.d.ts +1 -0
- package/dist/bin/roles.js +24 -0
- package/dist/src/a2a/executor.d.ts +16 -1
- package/dist/src/a2a/executor.js +205 -19
- package/dist/src/a2a/gateway.d.ts +77 -0
- package/dist/src/a2a/gateway.js +349 -27
- package/dist/src/a2a/index.d.ts +7 -1
- package/dist/src/a2a/index.js +4 -0
- package/dist/src/a2a/result-metadata.d.ts +3 -0
- package/dist/src/a2a/result-metadata.js +2 -1
- package/dist/src/a2a/server.js +2 -1
- package/dist/src/a2a/store.js +7 -1
- package/dist/src/a2a/types.d.ts +32 -1
- package/dist/src/a2a/types.js +11 -1
- package/dist/src/acp-connection.js +93 -12
- package/dist/src/bridge.js +127 -4
- package/dist/src/capacity-lifecycle.d.ts +5 -0
- package/dist/src/capacity-lifecycle.js +57 -0
- package/dist/src/capacity-queue.d.ts +23 -0
- package/dist/src/capacity-queue.js +251 -0
- package/dist/src/capacity.d.ts +76 -0
- package/dist/src/capacity.js +377 -0
- package/dist/src/execution/human-review.d.ts +103 -0
- package/dist/src/execution/human-review.js +87 -0
- package/dist/src/execution/ledger.d.ts +5 -0
- package/dist/src/execution/ledger.js +39 -8
- package/dist/src/execution/ppt-delivery.d.ts +36 -3
- package/dist/src/execution/ppt-delivery.js +243 -53
- package/dist/src/execution/project-discovery.d.ts +56 -0
- package/dist/src/execution/project-discovery.js +429 -0
- package/dist/src/execution/report-review.d.ts +60 -0
- package/dist/src/execution/report-review.js +173 -0
- package/dist/src/execution/targets.d.ts +5 -0
- package/dist/src/execution/targets.js +1 -0
- package/dist/src/execution/workbench.d.ts +131 -0
- package/dist/src/execution/workbench.js +265 -0
- package/dist/src/index.d.ts +4 -0
- package/dist/src/index.js +3 -0
- package/dist/src/roles/index.d.ts +1 -0
- package/dist/src/roles/index.js +1 -0
- package/dist/src/roles/skills.d.ts +71 -0
- package/dist/src/roles/skills.js +427 -0
- package/package.json +5 -1
- package/skills/acp-service/SKILL.md +21 -7
- package/skills/acp-service/references/a2a.md +9 -5
- package/skills/acp-service/references/async-caller.md +48 -0
- package/skills/acp-service/references/roles-and-tasks.md +120 -0
- package/skills/acp-service/scripts/a2a-caller.py +242 -0
- package/vendor/dsh/README.md +2 -0
- package/vendor/dsh/a2a-executor.d.ts +4 -1
- package/vendor/dsh/a2a-executor.js +46 -2
- package/vendor/dsh/adapter.d.ts +10 -0
- package/vendor/dsh/adapter.js +67 -3
- package/vendor/dsh/index.js +2 -1
- package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
- package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
- package/vendor/runtime/dist/cli.js +7 -7
- package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
- package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
- package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
- package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
- package/vendor/runtime/dist/flows.js +1 -1
- package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
- package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
- package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
- package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
- package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
- package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
- package/vendor/runtime/dist/runtime.js +1 -1
- package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
- package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
- package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Codex 主会话:现稿 PPT 只验收与计步
|
|
2
|
+
|
|
3
|
+
`scripts/a2a-caller.py` 专用于现稿 PPT 的独立只验收测试:需要冻结产物摘要、制作会话、验收报告及 Codex 主会话 transcript,结论固定为保留原稿和问题报告,不接受或改写原 PPT。普通角色、临时任务和完整 PPT 制作/交付按 [统一 API 路由](roles-and-tasks.md) 调用;这些任务遵守同样的异步边界,但不使用本脚本的 PPT 专属字段或结论。
|
|
4
|
+
|
|
5
|
+
此入口落实“开发部署先完成 → 一次派单 → 立即结束本轮 → 真实通知唤醒 → 回执/结论/ack”。网关后台核对可以继续;主会话不主动 get/list/inbox、等待、读子会话日志或重复产物验收。它不是全局禁用查询 API 的权限系统;明确的单次状态请求和排障应单独授权、单独记录。
|
|
6
|
+
|
|
7
|
+
使用本技能 `scripts/a2a-caller.py`,Python 3 标准库即可。当前计步器读取 **Codex 主会话自己的**原生 transcript,只读取工具 ID、通知与轮次边界,不输出推理、不读取任何子会话。其他宿主应遵守同一交接纪律,但不能套用 Codex 记录格式宣称计步通过。
|
|
8
|
+
|
|
9
|
+
## 开发部署阶段
|
|
10
|
+
|
|
11
|
+
技能、目标、绑定、执行宿主、输入冻结、网络预检、部署测试、合同与目录都在正式派单前完成。不得派单后继续开发或部署并将这些步骤从统计中删除。不要用主会话等待函数代替结束轮次。
|
|
12
|
+
|
|
13
|
+
一次性准备私有 RUN.json(路径和值必须来自真实环境):
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"phase": "prepared",
|
|
18
|
+
"developmentReady": {"sourceCommit": "实际代码版本", "deploymentReceipt": "/absolute/receipt.json"},
|
|
19
|
+
"gatewayUrl": "http://127.0.0.1:36814",
|
|
20
|
+
"originSessionId": "原主会话归属ID",
|
|
21
|
+
"rootTranscript": "/absolute/current-root-rollout.jsonl",
|
|
22
|
+
"request": {
|
|
23
|
+
"targetId": "已登记的独立验收目标",
|
|
24
|
+
"title": "现稿只验收",
|
|
25
|
+
"clientRequestId": "本次稳定请求编号",
|
|
26
|
+
"input": {"prompt": "自包含合同与边界,报告保存到本轮独立目录", "preflight": {"jobDirectory": "/absolute/new-job"}, "resultContract": {"jobId": "本次关联编号", "artifactManifestPath": "/absolute/new-job/report-manifest.json"}}
|
|
27
|
+
},
|
|
28
|
+
"review": {
|
|
29
|
+
"reportPath": "/absolute/new-job/review-report.json",
|
|
30
|
+
"artifactDigest": "冻结的原PPT产物清单SHA256",
|
|
31
|
+
"producerSessionId": "原制作会话ID",
|
|
32
|
+
"links": [{"title": "现稿PPT", "url": "http://actual-host/existing.pptx"}, {"title": "预览", "url": "http://actual-host/preview.png"}]
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
报告契约为 `verdict: passed|changes_requested`、`artifactDigest`、`factsChecked`、`allSlidesViewed`、`issues`、`limitations`、`evidence`。由独立验收 Agent 自己核验事实、实际读图、检查冻结原文件未变,报告加入本轮宿主验证的 artifact manifest。旧 PPT 不移动、不重导出;manifest 只登记本轮新报告。报告与任务完成不自动代表 PPT 业务接受。
|
|
38
|
+
|
|
39
|
+
## 正式调用:预期四次主会话工具调用
|
|
40
|
+
|
|
41
|
+
1. `python3 SKILL/scripts/a2a-caller.py dispatch --run RUN.json`。入口保存当前原生调用 ID,再执行一次 execution_submit;返回 mustEndTurn=true 后**立即 final 结束本轮**,仅说明已派单、等待通知。不能为了取状态、等完成、验证模型、检查日志或统计步骤再调用工具。受理不确定也落盘并结束,不自动重派。
|
|
42
|
+
2. 真实任务通知到达后的新轮次:`... inspect --run RUN.json --notice-id 实际NOTICE`。入口必须在本主会话派单后的 user message 中找到匹配的 origin 与 job/task;否则拒绝查询。仅调用一次 execution_get,核对宿主 producer、task/session、报告摘要和冻结 PPT 版本,读取本轮新报告;不读 PPT/PNG、不重新 HTTP/hash/读图、不读子日志。
|
|
43
|
+
3. `... record --run RUN.json`。按本次“不改稿、只验收”合同,保存结论和问题,不重派、不记录原 PPT 业务通过。只有真实完成且有版本/digest 的业务接受合同才使用 execution_review;本入口不伪造不存在的接受记录。
|
|
44
|
+
4. `... ack --run RUN.json`。确认实际通知;同一操作统计派单至当前调用的全部唯一主会话工具 ID,包含等待、调试和额外调用,不重置窗口;然后立即 final 答复用户,不再单独查 inbox、审计或提交文档。
|
|
45
|
+
|
|
46
|
+
每次命令对应一次主会话工具调用,不等于底层 RPC/文件操作数。若工具传输需要等待同一尚未返回的调用,该等待也照实计步,不能删除。步骤数、派单后无额外操作、真实通知与此前已结束轮次必须同时通过,不能只挑四个业务操作证明达标。`step-count.json` 与 `processing-conclusion.json` 自动保存在 RUN.json 同目录。
|
|
47
|
+
|
|
48
|
+
开发部署成本另计,不混入日常测试。质量不通过如实写 changes_requested;即使调用步数达标,也不能据此宣称 PPT 已通过。异常回传后不继续循环处理。脚本失败或收到重复旧通知时沿用已有持久记录,不重置请求、窗口或原结论。
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# 角色管理、固定角色调用与临时任务
|
|
2
|
+
|
|
3
|
+
这是统一 API 技能的任务路由。`resident-agent` 若已安装,用于创建和维护专职角色;本技能负责实际接口调用。领域方法仍由角色引用的技能负责。创建角色是管理阶段,日常调用不重复创建、部署或预热角色。
|
|
4
|
+
|
|
5
|
+
## 三种工作
|
|
6
|
+
|
|
7
|
+
| 请求 | 操作 | 所需信息 |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| 创建固定角色 | 配置角色与宿主,再登记 resident_agent 目标 | 职责、网络技能源、缓存、预设、工作根目录及交付约定 |
|
|
10
|
+
| 调用固定角色 | `execution_submit` 到已有 resident_agent target | targetId、完整任务要求;cwd/preset/role 由目标固定 |
|
|
11
|
+
| 一次性临时任务 | `execution_submit` 到已有 agent_host target | targetId、执行端 cwd、preset、完整任务要求;无需创建角色 |
|
|
12
|
+
|
|
13
|
+
没有一条 `role_create` API 可完成全部创建与部署。`execution_target_create` 只登记目标,不生成 persona/profile、不安装技能、不配置宿主、不证明模型能执行。固定角色的持久配置可反复接单,每个独立任务仍创建独立执行上下文;同目录不等于同会话。
|
|
14
|
+
|
|
15
|
+
## 可选项目与角色候选探查
|
|
16
|
+
|
|
17
|
+
已配置 `projectDiscovery` 时,网关通过 Session Reader 的 `1session projects --json` CLI 读取项目/PWD 元数据,并只读检查 `.1agents/roles/*/profile.json` 结构。Reader 没有 projects HTTP 接口;不臆造该接口,不安装 Reader,不读会话全文、ROLE 或脚本,不加载角色代码。能力为可选集成,缺失时保留手填目录。
|
|
18
|
+
|
|
19
|
+
可信网关配置为 `projectDiscovery:{readerExecutable,allowedRoots,explicitRoots?,timeoutMs?,maxProjects?}`:readerExecutable 指向已安装 CLI,allowedRoots 为非空绝对路径列表,explicitRoots 可补充已知项目根,timeoutMs 默认 15000、maxProjects 默认 200。任务参数不能更换可执行文件或扩展根目录范围。公开配置示例位于工程 `.1agents/config/project-discovery.example.json`,示例本身不自动激活服务;未配置时接口明确返回未启用,不隐式扫描。
|
|
20
|
+
|
|
21
|
+
| 可信管理接口 | 参数与行为 |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| `execution_project_scan` | `{}`;显式扫描一次,返回并保存有界候选与诊断 |
|
|
24
|
+
| `execution_project_list` | `{}`;读取已保存快照,不触发 Reader |
|
|
25
|
+
| `execution_discovery_config_get` | `{}`;读取持久的 manual/interval 模式与 intervalMs,不扫描 |
|
|
26
|
+
| `execution_discovery_config_update` | `{mode:"manual"}` 或 `{mode:"interval",intervalMs:60000}`;intervalMs 在定频模式必须显式填写,范围 60000–86400000 |
|
|
27
|
+
|
|
28
|
+
默认 manual;用户选择定频后,由网关后台扫描,切回 manual 停止周期扫描。目录探查不派模型任务、不创建或注册目标、不产生任务完成通知、不唤醒原主会话;主会话只执行用户要求的一次管理动作,不循环 scan/list 等待变化。
|
|
29
|
+
|
|
30
|
+
快照及模式保存在 `.1agents/state/a2a-gateway/project-discovery/discovery.json`,失败时保留旧候选并标 partial/stale。依据诊断与读取时间使用候选,不能把陈旧目录当作当前可执行位置;本机路径也不能默认当作远端 cwd。角色候选仍需完成宿主映射、运行环境和目标登记,目录权限由实际执行端接单验证。本次只实现发现;一键填入任务 cwd、自动注册目标及新工作台 UI 不属于本次能力。
|
|
31
|
+
|
|
32
|
+
## 创建与更新角色(管理阶段)
|
|
33
|
+
|
|
34
|
+
1. 复用当前网关、宿主及认证配置,明确职责、工具权限、读写目录、输入和交付。技能通过能力网络检索,精确记录来源及名称/标识;发现结果不等于实际加载。
|
|
35
|
+
2. 创建薄 `ROLE.md` 与网络技能 profile。profile 原生字段为 `id/version/instructionsPath/network/skills/entrySkill`;skills 每项包含 `key/name`,可用 `sourceId/skillId` 消除歧义,并可声明 `nodeUrl/assetsManifest`。不要把登记清单误当原生 profile,也不要把领域脚本和模板写入 persona。源码示例见工程 `.1agents/roles/ppt-beautifier`;项目运行数据统一放在 `./.1agents/`。
|
|
36
|
+
3. 在执行宿主 `a2a.roleSkills` 配置可信的 `cacheRoot`、`profiles: {逻辑roleId:绝对profile路径}`;可选 `presetRoles` 仅为专用 preset 自动绑定。通用 preset 不隐式改成某领域角色。DSH/Codex 共用宿主加载入口;运行依赖和工具仍由宿主管理。
|
|
37
|
+
4. 有专用预设时安装/更新该预设;也可使用已可用的通用预设配合目标绑定的 roleId。凭据只在受保护宿主/网关配置。需要重载共享宿主时先确认没有运行中会话。
|
|
38
|
+
5. 复用已登记 connection,通过可信本机管理入口登记或更新 resident_agent target。最小登记参数如下,值均需替换为真实部署值:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{
|
|
42
|
+
"targetId": "my-role",
|
|
43
|
+
"kind": "resident_agent",
|
|
44
|
+
"name": "角色显示名",
|
|
45
|
+
"connectionId": "registered-connection",
|
|
46
|
+
"binding": {
|
|
47
|
+
"cwd": "/absolute/existing/role-workspace",
|
|
48
|
+
"agentPreset": "installed-preset",
|
|
49
|
+
"roleId": "host-configured-role-id",
|
|
50
|
+
"skillPolicy": "network_pinned"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`execution_target_update` 参数是 `targetId/expectedConfigVersion?/patch`;`patch.binding` 按整体替换,保留未改的 cwd/preset/role/目录限制。目标管理方法只开放可信本机管理入口,不能当远端公开任务 API。
|
|
56
|
+
|
|
57
|
+
6. 在管理阶段预热并校验完整技能包、资源及资产,核验宿主配置;只有用户授权实际试单时才测试模型执行和通知闭环。HTTP 200、目标已登记或 preset 可见仅证明对应管理步骤。
|
|
58
|
+
|
|
59
|
+
目录约定:角色定义为 `.1agents/roles/<role>`,技能缓存与锁为 `.1agents/cache/roles`,本地技能源为 `.1agents/skills`,角色 bundle/工作目录/产物/状态为 `.1agents/runtime/<role>`,项目网关账本与通知为 `.1agents/state/a2a-gateway`;私密配置在 `.1agents/config`,不提交 Git。
|
|
60
|
+
|
|
61
|
+
工程统一更新入口:`node scripts/update-role-skills.mjs --config .1agents/config/role-skills.local.json`。部署环境也可用 `acp-service roles sync --profile PROFILE --cache-root CACHE [--lock EXISTING]` 管理缓存。新任务解析当前版本;同任务续派、返工与恢复使用原锁。更新不会安装二进制依赖或隐式派模型任务。
|
|
62
|
+
|
|
63
|
+
## 调用固定角色
|
|
64
|
+
|
|
65
|
+
先读已登记 target;确认已具备原主会话绑定和输入条件后提交。以下为 `execution_submit` 的合法结构,示例不代表已执行:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{
|
|
69
|
+
"originSessionId": "actual-parent-session-id",
|
|
70
|
+
"targetId": "ppt-beautifier",
|
|
71
|
+
"clientRequestId": "stable-request-id",
|
|
72
|
+
"title": "演示文稿设计",
|
|
73
|
+
"input": {
|
|
74
|
+
"prompt": "按已冻结合同执行,说明输入路径、授权目录、受众、交付要求和验收边界;完成后给出真实产物链接。"
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
固定目标禁止传 `input.cwd/agentPreset/roleId/driver`,即使值与绑定相同也拒绝。任务目录等检查和系统产物清单使用 `input.preflight/resultContract`,详细字段见 [A2A](a2a.md#派单前预检和系统结果元数据)。需要由项目总结→制作→独立验收自动推进的完整 PPT 交付,应选择部署中绑定 `driver=ppt_delivery` 的目标及其输入契约;普通 PPT 角色调用只执行当前合同。
|
|
80
|
+
|
|
81
|
+
## 派发临时任务
|
|
82
|
+
|
|
83
|
+
向已登记的 agent_host 目标调用同一个 `execution_submit`,每单提供执行端目录与 preset:
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
{
|
|
87
|
+
"originSessionId": "actual-parent-session-id",
|
|
88
|
+
"targetId": "registered-agent-host",
|
|
89
|
+
"clientRequestId": "stable-temporary-request-id",
|
|
90
|
+
"input": {
|
|
91
|
+
"cwd": "/absolute/existing/project",
|
|
92
|
+
"agentPreset": "oneagents-acp-codex",
|
|
93
|
+
"prompt": "只读总结该项目,在本任务授权目录保存报告;不得修改项目源码。"
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
preset 必须在执行宿主真实可用;要用普通 DSH 时显式选 `standard`。临时任务无需新建角色或复制技能。若需复用宿主已配置的网络角色,可显式传 `input.roleId`,仍不能自定义 profile、网络地址或缓存根。兼容旧客户端可使用 `remote_agent_spawn`,见 [A2A](a2a.md#远端任务工具)。
|
|
99
|
+
|
|
100
|
+
## 账本、通知与处理
|
|
101
|
+
|
|
102
|
+
提交参数共同使用 `originSessionId/targetId/input`,建议稳定 `clientRequestId`;返回后保存 `sourceId/jobId/attemptId` 及可用的 `remote/taskId/contextId/sessionId`,立即结束本轮。受理未知不自动换编号重派。父子任务用 `parentJobRef:{sourceId,jobId}` 和可选 `parentAttemptId/purpose/resultRevision/replacesJobRef` 关联,不另造“外层任务”术语。
|
|
103
|
+
|
|
104
|
+
| 操作 | 方法与关键参数 |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| 通知后或用户明确要求的单次读取 | `execution_get {originSessionId,jobId}`;保留历史 attempt,查询不唤醒主会话 |
|
|
107
|
+
| 同任务继续/返工 | `execution_continue {originSessionId,jobId,input,clientRequestId?}`;保留原 job,增加执行轮次 |
|
|
108
|
+
| 关闭任务并取消子任务 | `execution_cancel {originSessionId,jobId,cascade?}`;PPT 交付默认级联,通用任务需显式 cascade=true;未决取消不能冒记全部停止 |
|
|
109
|
+
| 记录业务接受/退回 | `execution_review {originSessionId,jobId,attemptId,resultRevision,resultDigest,reviewStatus,note?}`;reviewStatus 为 pending/accepted/changes_requested,值来自真实当前回执 |
|
|
110
|
+
|
|
111
|
+
通用 A2A 结果完成后由账本自动生成轮次内 `resultRevision` 与 `resultDigest`;从 `execution_get` 或 `remote_agent_get` 取真实值,不用技能 revision、请求中的父子关联版本或手工编号替代。digest 覆盖结果正文、回执引用、链接及宿主返回的文件大小/SHA256 清单;没有清单时不代表已验证文件字节。重复读取/重启保持版本稳定,结果变化追加新版本,`execution_get/list` 的 `resultHistory` 和 `attempts[].resultHistory` 留存版本快照。只接受当前已完成且结果可用的轮次及版本;新结果不继承旧验收。升级从缓存回执补齐旧任务缺失版本,不重派、不自动验收;需补登时核对本地既有结论与同一回执的身份、正文和产物清单后另调 `execution_review`。
|
|
112
|
+
|
|
113
|
+
**按实际通知类型选择收件箱和 ack,不能按提交方法推断。** 普通 resident_agent/agent_host 即使由 execution_submit 提交,也可能返回 A2A 通知。
|
|
114
|
+
|
|
115
|
+
| 通知定位 | 单次读取 | 保存结论后的确认 |
|
|
116
|
+
| --- | --- | --- |
|
|
117
|
+
| A2A 通知,含 remote/taskId | `remote_agent_get` 或已保存 job 的 `execution_get`;无 task 定位时用 `remote_agent_inbox` | `remote_agent_ack {originSessionId,noticeId}` |
|
|
118
|
+
| 领域交付通知,含 sourceId/jobId/attemptId | `execution_get` 或 `execution_inbox` | `execution_ack {originSessionId,noticeId}` |
|
|
119
|
+
|
|
120
|
+
业务接受和通知 ack 分开记录,均不能替代执行成功或独立验收证据。通知正文和已有产物不等于最终交付通过。主会话不主动轮询、不读子会话日志、不重复验收;真实通知后只核对合同要求的回执/新报告、记录结论并确认。现稿 PPT 只验收及 Codex 四步计数另用 [专用流程](async-caller.md),普通任务不套用其报告字段与结论。
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Bounded, notification-driven A2A caller. No polling or child-session log reader."""
|
|
3
|
+
import argparse
|
|
4
|
+
import datetime
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def now():
|
|
15
|
+
return datetime.datetime.now(datetime.timezone.utc).isoformat()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def save(path, value):
|
|
19
|
+
path = Path(path)
|
|
20
|
+
temporary = path.with_name(path.name + '.tmp')
|
|
21
|
+
with temporary.open('w') as stream:
|
|
22
|
+
os.chmod(temporary, 0o600)
|
|
23
|
+
json.dump(value, stream, ensure_ascii=False, indent=2)
|
|
24
|
+
stream.write('\n')
|
|
25
|
+
os.replace(temporary, path)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def transcript(run):
|
|
29
|
+
# Only this root's native records; never open a worker session or print reasoning.
|
|
30
|
+
with Path(run['rootTranscript']).open() as stream:
|
|
31
|
+
for line in stream:
|
|
32
|
+
# Image/tool outputs can be huge; they are not calls, user notices or turn boundaries.
|
|
33
|
+
header = line[:320]
|
|
34
|
+
if any('"' + kind + '"' in header for kind in ['custom_tool_call_output', 'function_call_output', 'reasoning']):
|
|
35
|
+
continue
|
|
36
|
+
try:
|
|
37
|
+
yield json.loads(line)
|
|
38
|
+
except json.JSONDecodeError:
|
|
39
|
+
continue
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def calls(run):
|
|
43
|
+
output, seen = [], set()
|
|
44
|
+
for row in transcript(run):
|
|
45
|
+
item = row.get('payload', {})
|
|
46
|
+
if row.get('type') == 'response_item' and item.get('type') in ['function_call', 'custom_tool_call']:
|
|
47
|
+
key = item.get('call_id')
|
|
48
|
+
if key and key not in seen:
|
|
49
|
+
seen.add(key)
|
|
50
|
+
output.append({'callId': key, 'name': item.get('name'), 'timestamp': row.get('timestamp')})
|
|
51
|
+
return output
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def action(run, name):
|
|
55
|
+
current = calls(run)[-1]
|
|
56
|
+
run.setdefault('actionCalls', {})[name] = current['callId']
|
|
57
|
+
return current
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def rpc(run, method, params):
|
|
61
|
+
request = urllib.request.Request(run['gatewayUrl'].rstrip('/') + '/invoke',
|
|
62
|
+
data=json.dumps({'method': method, 'params': params}).encode(),
|
|
63
|
+
headers={'Content-Type': 'application/json'})
|
|
64
|
+
with urllib.request.urlopen(request, timeout=20) as response:
|
|
65
|
+
return json.load(response)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def actual_notice(run, notice_id):
|
|
69
|
+
entered = False
|
|
70
|
+
for row in transcript(run):
|
|
71
|
+
item = row.get('payload', {})
|
|
72
|
+
if item.get('call_id') == run['actionCalls']['dispatch']:
|
|
73
|
+
entered = True
|
|
74
|
+
if not entered or row.get('type') != 'response_item' or item.get('type') != 'message' or item.get('role') != 'user':
|
|
75
|
+
continue
|
|
76
|
+
text = ''.join(c.get('text', '') for c in item.get('content', []) if isinstance(c, dict))
|
|
77
|
+
for candidate in re.findall(r'\{[^{}]*"noticeId"\s*:[^{}]*\}', text):
|
|
78
|
+
try:
|
|
79
|
+
notice = json.loads(candidate)
|
|
80
|
+
except json.JSONDecodeError:
|
|
81
|
+
continue
|
|
82
|
+
receipt = run['dispatchReceipt']
|
|
83
|
+
if notice.get('noticeId') == notice_id and notice.get('originSessionId') == run['originSessionId']:
|
|
84
|
+
matches = (notice.get('jobId') == receipt['jobId'] if 'jobId' in notice
|
|
85
|
+
else notice.get('taskId') == receipt.get('taskId') and notice.get('remote') == receipt.get('remote'))
|
|
86
|
+
if matches:
|
|
87
|
+
return {**notice, 'receivedAt': row.get('timestamp')}
|
|
88
|
+
raise ValueError('No matching real user notification in the root transcript; querying before wake is prohibited')
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def dispatch(path, run, invoke=rpc):
|
|
92
|
+
if run['phase'] != 'prepared' or not run.get('developmentReady'):
|
|
93
|
+
raise ValueError('Dispatch requires finished development/deployment and a prepared run; never automatically resend')
|
|
94
|
+
if not run['request'].get('clientRequestId'):
|
|
95
|
+
raise ValueError('A stable clientRequestId is required')
|
|
96
|
+
run['dispatchBoundary'] = action(run, 'dispatch')
|
|
97
|
+
run['phase'] = 'admission_inflight'
|
|
98
|
+
save(path, run) # Crash after sending never creates permission to resend.
|
|
99
|
+
try:
|
|
100
|
+
receipt = invoke(run, 'execution_submit', {'originSessionId': run['originSessionId'], **run['request']})
|
|
101
|
+
if receipt.get('error') or receipt.get('submissionStatus') != 'accepted':
|
|
102
|
+
run['phase'] = 'admission_requires_attention'
|
|
103
|
+
else:
|
|
104
|
+
run['phase'] = 'waiting_notification'
|
|
105
|
+
run['dispatchReceipt'] = receipt
|
|
106
|
+
except Exception as error:
|
|
107
|
+
run['phase'] = 'admission_unknown'
|
|
108
|
+
run['admissionError'] = str(error)
|
|
109
|
+
save(path, run)
|
|
110
|
+
summary = {k: v for k, v in run.get('dispatchReceipt', {}).items() if k in
|
|
111
|
+
['jobId', 'attemptId', 'remote', 'taskId', 'contextId', 'sessionId', 'submissionStatus', 'executionStatus', 'error']}
|
|
112
|
+
return {'phase': run['phase'], 'receipt': summary, 'error': run.get('admissionError'),
|
|
113
|
+
'mustEndTurn': True, 'nextAction': 'End this turn now. Handle only a real arriving notice.',
|
|
114
|
+
'prohibited': ['task polling', 'sleep/wait for completion', 'worker session logs', 'repeat artifact QA', 'post-dispatch development']}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def inspect(path, run, notice_id, invoke=rpc):
|
|
118
|
+
if run['phase'] != 'waiting_notification':
|
|
119
|
+
raise ValueError('Inspect is a one-shot operation after a notification, not a polling command')
|
|
120
|
+
notice = actual_notice(run, notice_id)
|
|
121
|
+
action(run, 'inspect')
|
|
122
|
+
run['notice'] = notice
|
|
123
|
+
run['phase'] = 'inspection_inflight'
|
|
124
|
+
save(path, run)
|
|
125
|
+
errors, report, receipt = [], None, None
|
|
126
|
+
try:
|
|
127
|
+
receipt = invoke(run, 'execution_get', {'originSessionId': run['originSessionId'], 'jobId': run['dispatchReceipt']['jobId']})
|
|
128
|
+
if receipt['attemptId'] != run['dispatchReceipt']['attemptId'] or receipt.get('taskId') != run['dispatchReceipt'].get('taskId'):
|
|
129
|
+
raise ValueError('Receipt execution identity changed')
|
|
130
|
+
metadata = receipt.get('resultMetadata') or {}
|
|
131
|
+
if receipt['executionStatus'] != 'completed' or metadata.get('producer') != '1agents/a2a-host' or metadata.get('outcome') != 'completed':
|
|
132
|
+
raise ValueError('Worker did not deliver a completed host-authored result')
|
|
133
|
+
if metadata.get('taskId') != receipt['taskId'] or metadata.get('validation', {}).get('status') != 'passed':
|
|
134
|
+
raise ValueError('Host result validation or task binding failed')
|
|
135
|
+
if metadata.get('sessionId') == run['review'].get('producerSessionId'):
|
|
136
|
+
raise ValueError('Reviewer must be independent of the PPT producer')
|
|
137
|
+
if receipt.get('sessionId') and metadata.get('sessionId') != receipt['sessionId']:
|
|
138
|
+
raise ValueError('Host result session differs from the execution receipt')
|
|
139
|
+
if run['review'].get('expectedPreset') and metadata.get('agentPreset') != run['review']['expectedPreset']:
|
|
140
|
+
raise ValueError('Reviewer preset differs from the frozen target')
|
|
141
|
+
# Read only the NEW report, bound to the host receipt. Never reopen PPTs/PNGs or download them here.
|
|
142
|
+
target = Path(run['review']['reportPath']).resolve()
|
|
143
|
+
artifact = next(a for a in metadata.get('artifacts', []) if Path(a['path']).resolve() == target)
|
|
144
|
+
raw = target.read_bytes()
|
|
145
|
+
if hashlib.sha256(raw).hexdigest() != artifact['sha256'] or len(raw) != artifact['size']:
|
|
146
|
+
raise ValueError('Review report differs from the host receipt')
|
|
147
|
+
report = json.loads(raw)
|
|
148
|
+
if report.get('artifactDigest') != run['review']['artifactDigest']:
|
|
149
|
+
raise ValueError('Report is bound to a different PPT version')
|
|
150
|
+
if report.get('verdict') not in ['passed', 'changes_requested'] or not isinstance(report.get('issues'), list):
|
|
151
|
+
raise ValueError('Invalid report verdict or issues')
|
|
152
|
+
if report['verdict'] == 'passed' and (report['issues'] or report.get('factsChecked') is not True or report.get('allSlidesViewed') is not True):
|
|
153
|
+
raise ValueError('Passed report lacks required independent checks')
|
|
154
|
+
except Exception as error:
|
|
155
|
+
errors.append(str(error))
|
|
156
|
+
run['inspection'] = {'receipt': receipt, 'report': report, 'errors': errors, 'valid': not errors}
|
|
157
|
+
run['phase'] = 'inspected'
|
|
158
|
+
save(path, run)
|
|
159
|
+
return {'phase': run['phase'], 'valid': not errors, 'report': report, 'errors': errors,
|
|
160
|
+
'existingArtifacts': run['review'].get('links', []), 'nextAction': 'Record the conclusion once; do not repeat worker QA or dispatch fixes.'}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def record(path, run):
|
|
164
|
+
if run['phase'] != 'inspected':
|
|
165
|
+
raise ValueError('Record requires the one-shot receipt inspection')
|
|
166
|
+
action(run, 'record')
|
|
167
|
+
report = run['inspection'].get('report') or {}
|
|
168
|
+
run['conclusion'] = {'recordedAt': now(), 'jobId': run['dispatchReceipt']['jobId'],
|
|
169
|
+
'attemptId': run['dispatchReceipt']['attemptId'], 'noticeId': run['notice']['noticeId'],
|
|
170
|
+
'reportValid': run['inspection']['valid'], 'verdict': report.get('verdict', 'unverified'),
|
|
171
|
+
'issues': report.get('issues', []), 'errors': run['inspection']['errors'],
|
|
172
|
+
'decision': 'Preserve the existing PPT and report; no edits or follow-up production authorized',
|
|
173
|
+
'pptBusinessAccepted': False, 'executionReviewRecorded': False}
|
|
174
|
+
save(Path(path).with_name('processing-conclusion.json'), run['conclusion'])
|
|
175
|
+
run['phase'] = 'conclusion_recorded'
|
|
176
|
+
save(path, run)
|
|
177
|
+
return run['conclusion']
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def audit(run):
|
|
181
|
+
native = calls(run)
|
|
182
|
+
start = next(i for i, c in enumerate(native) if c['callId'] == run['actionCalls']['dispatch'])
|
|
183
|
+
stop = next(i for i, c in enumerate(native) if c['callId'] == run['actionCalls']['ack'])
|
|
184
|
+
measured = native[start:stop + 1]
|
|
185
|
+
notice = actual_notice(run, run['notice']['noticeId'])
|
|
186
|
+
before_wake = [c for c in measured[1:] if c['timestamp'] < notice['receivedAt']]
|
|
187
|
+
unexpected = [c for c in measured if c['callId'] not in run['actionCalls'].values()]
|
|
188
|
+
yielded = False
|
|
189
|
+
for row in transcript(run):
|
|
190
|
+
if not (run['dispatchBoundary']['timestamp'] <= row.get('timestamp', '') < notice['receivedAt']):
|
|
191
|
+
continue
|
|
192
|
+
item = row.get('payload', {})
|
|
193
|
+
if row.get('type') == 'response_item' and item.get('role') == 'assistant' and (item.get('phase') == 'final_answer' or item.get('channel') == 'final'):
|
|
194
|
+
yielded = True
|
|
195
|
+
if row.get('type') == 'event_msg' and item.get('type') in ['task_complete', 'task_completed', 'turn_complete', 'turn_completed']:
|
|
196
|
+
yielded = True
|
|
197
|
+
return {'countingRule': 'Every unique native root tool call from dispatch through this ack inclusive; development before dispatch and worker calls excluded; no reset.',
|
|
198
|
+
'rootToolCalls': len(measured), 'calls': measured, 'actionCalls': run['actionCalls'],
|
|
199
|
+
'callsBeforeNotification': before_wake, 'unexpectedCalls': unexpected,
|
|
200
|
+
'nativeNotificationReceived': True, 'rootTurnEndedBeforeNotification': yielded,
|
|
201
|
+
'stepBudgetMet': 3 <= len(measured) <= 5,
|
|
202
|
+
'strictAsyncFlowPassed': 3 <= len(measured) <= 5 and not before_wake and not unexpected and yielded,
|
|
203
|
+
'qualityVerdict': run['conclusion']['verdict'], 'pptChanged': False}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def acknowledge(path, run, invoke=rpc):
|
|
207
|
+
if run['phase'] != 'conclusion_recorded':
|
|
208
|
+
raise ValueError('Save a conclusion before acknowledging')
|
|
209
|
+
action(run, 'ack')
|
|
210
|
+
method = 'execution_ack' if 'jobId' in run['notice'] else 'remote_agent_ack'
|
|
211
|
+
run['ack'] = invoke(run, method, {'originSessionId': run['originSessionId'], 'noticeId': run['notice']['noticeId']})
|
|
212
|
+
run['phase'] = 'acknowledged'
|
|
213
|
+
run['measurement'] = audit(run)
|
|
214
|
+
save(path, run)
|
|
215
|
+
save(Path(path).with_name('step-count.json'), run['measurement'])
|
|
216
|
+
return {'phase': run['phase'], 'ack': run['ack'], 'measurement': run['measurement'],
|
|
217
|
+
'existingArtifacts': run['review'].get('links', []), 'nextAction': 'Final answer now; no extra query or audit call.'}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def main():
|
|
221
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
222
|
+
parser.add_argument('action', choices=['dispatch', 'inspect', 'record', 'ack'])
|
|
223
|
+
parser.add_argument('--run', required=True)
|
|
224
|
+
parser.add_argument('--notice-id')
|
|
225
|
+
args = parser.parse_args()
|
|
226
|
+
path = Path(args.run)
|
|
227
|
+
lock = path.with_name(path.name + '.lock')
|
|
228
|
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
229
|
+
try:
|
|
230
|
+
run = json.loads(path.read_text())
|
|
231
|
+
if args.action == 'dispatch': result = dispatch(path, run)
|
|
232
|
+
elif args.action == 'inspect': result = inspect(path, run, args.notice_id)
|
|
233
|
+
elif args.action == 'record': result = record(path, run)
|
|
234
|
+
else: result = acknowledge(path, run)
|
|
235
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
236
|
+
finally:
|
|
237
|
+
os.close(fd)
|
|
238
|
+
lock.unlink()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
if __name__ == '__main__':
|
|
242
|
+
main()
|
package/vendor/dsh/README.md
CHANGED
|
@@ -97,6 +97,8 @@ This plugin supports **text prompts**. Attachments and specialized external-tool
|
|
|
97
97
|
|
|
98
98
|
The bundle's `oneagents-acp` row accepts `serviceUrl`, `serviceMode`, `serviceStartupTimeoutMs`, `serviceShutdownTimeoutMs`, `agents`, `stateDirectory`, `diagnosticsDirectory`, `reconnectAttempts` and `reconnectDelayMs`. Change it through the profile's `cordis.patch.yml`, not the DSH repository. Use a new session after changing endpoint or workspace. When `agents` is omitted, plugin startup fetches `GET /agents` from acp-service and registers presets for entries with `chat_ready: true`, using their service-provided names. Discovery runs on the service host. Restart the plugin after installing or removing a harness. An explicit `agents` list bypasses discovery and preserves manual registry selection; `[]` registers no presets. Service startup, connection errors and invalid inventory responses fail plugin initialization instead of selecting fallback agents.
|
|
99
99
|
|
|
100
|
+
Explicitly authorized unattended work can declare `sessionPolicies`, with an exact absolute `cwd`, ACP registry `agent`, `permissionMode` (`approve-reads`, `approve-all`, or `deny-all`) and optional `initialModeId`. A policy matches only that workspace and Agent; wildcards and duplicate scopes are rejected. New sessions select the advertised native mode before sending any prompt; an unavailable mode fails without prompting. Existing sessions keep their native mode. For example, an authorized Codex video workspace can use `permissionMode: "approve-all"` and `initialModeId: "agent-full-access"` without changing the host's global model or other workspaces. Remove the declaration when the authorized batch ends; existing native sessions retain their own stored mode.
|
|
101
|
+
|
|
100
102
|
Diagnostic storage defaults to `stateDirectory/diagnostics`; `diagnosticsDirectory` selects a separate explicit location. Keep this directory with the A2A state when moving a host. Its version is independent of DSH Session formats. The plugin privately mounts official storage components; it does not require a shared host storage-domain configuration. Only one plugin instance may write the directory at a time.
|
|
101
103
|
|
|
102
104
|
### Local service lifecycle
|
|
@@ -17,7 +17,9 @@ export declare class DshA2ABackend implements A2ABackend {
|
|
|
17
17
|
* @param input Remote host directory, preset, and optional existing DSH session identity.
|
|
18
18
|
* @returns The resolved DSH session and its durable workspace and preset.
|
|
19
19
|
*/
|
|
20
|
-
prepare(input: A2APrepareInput
|
|
20
|
+
prepare(input: A2APrepareInput, options?: {
|
|
21
|
+
signal: AbortSignal;
|
|
22
|
+
}): Promise<A2ATarget>;
|
|
21
23
|
/** Admit one identified queued prompt and wait only for its own turn, independent of the HTTP connection.
|
|
22
24
|
* @param target Previously prepared DSH session.
|
|
23
25
|
* @param prompt Plain-text A2A message content.
|
|
@@ -27,6 +29,7 @@ export declare class DshA2ABackend implements A2ABackend {
|
|
|
27
29
|
run(target: A2ATarget, prompt: string, options: {
|
|
28
30
|
requestId: string;
|
|
29
31
|
signal: AbortSignal;
|
|
32
|
+
beforeStart?: (signal?: AbortSignal) => Promise<void>;
|
|
30
33
|
}): Promise<A2ARunResult>;
|
|
31
34
|
private execute;
|
|
32
35
|
private agent;
|
|
@@ -36,6 +36,20 @@ function answerOf(content, turn) {
|
|
|
36
36
|
authoritative: false, phased,
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
|
+
async function waitForIdle(agent, signal) {
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
let abort;
|
|
42
|
+
const canceled = new Promise((_, reject) => {
|
|
43
|
+
abort = () => reject(signal.reason);
|
|
44
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
45
|
+
});
|
|
46
|
+
try {
|
|
47
|
+
await Promise.race([agent.whenIdle(), canceled]);
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
signal.removeEventListener('abort', abort);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
39
53
|
/** Uses public session-controller and inbox events to account for one A2A prompt's exact DSH turn. */
|
|
40
54
|
export class DshA2ABackend {
|
|
41
55
|
ctx;
|
|
@@ -57,10 +71,13 @@ export class DshA2ABackend {
|
|
|
57
71
|
* @param input Remote host directory, preset, and optional existing DSH session identity.
|
|
58
72
|
* @returns The resolved DSH session and its durable workspace and preset.
|
|
59
73
|
*/
|
|
60
|
-
async prepare(input) {
|
|
74
|
+
async prepare(input, options) {
|
|
75
|
+
const signal = options?.signal;
|
|
76
|
+
signal?.throwIfAborted();
|
|
61
77
|
const previous = input.sessionId === undefined
|
|
62
78
|
? undefined
|
|
63
79
|
: await this.ctx.sessionController.inspect(input.sessionId);
|
|
80
|
+
signal?.throwIfAborted();
|
|
64
81
|
if (input.sessionId !== undefined && previous == null)
|
|
65
82
|
throw new Error(`Session ${input.sessionId} not found`);
|
|
66
83
|
if (previous !== undefined && previous.meta.id !== input.sessionId)
|
|
@@ -69,9 +86,12 @@ export class DshA2ABackend {
|
|
|
69
86
|
if (!isAbsolute(requestedCwd))
|
|
70
87
|
throw new Error('A2A cwd must be an absolute directory on the DSH host');
|
|
71
88
|
const cwd = await realpath(requestedCwd);
|
|
89
|
+
signal?.throwIfAborted();
|
|
72
90
|
if (!(await stat(cwd)).isDirectory())
|
|
73
91
|
throw new Error('A2A cwd must point to a directory on the DSH host');
|
|
92
|
+
signal?.throwIfAborted();
|
|
74
93
|
const preflight = await this.preflight({ ...input.preflight, cwd });
|
|
94
|
+
signal?.throwIfAborted();
|
|
75
95
|
if (!preflight.ok)
|
|
76
96
|
throw new A2APreflightError(preflight);
|
|
77
97
|
const agentPreset = input.agentPreset ?? previous?.meta.agentPreset;
|
|
@@ -83,10 +103,12 @@ export class DshA2ABackend {
|
|
|
83
103
|
// create() only reuses blank Sessions on current DSH; resolve the saved
|
|
84
104
|
// identity directly so an active or completed context keeps its queue.
|
|
85
105
|
const agent = await this.agent(input.sessionId);
|
|
106
|
+
signal?.throwIfAborted();
|
|
86
107
|
if (agent.id !== input.sessionId || agent.session.id !== input.sessionId)
|
|
87
108
|
throw new Error('Existing session identity conflicts');
|
|
88
109
|
if (agent.session.header.cwd === undefined || await realpath(agent.session.header.cwd) !== cwd)
|
|
89
110
|
throw new Error('Existing session cwd conflicts');
|
|
111
|
+
signal?.throwIfAborted();
|
|
90
112
|
if (agent.session.header.agentPreset !== previous.meta.agentPreset)
|
|
91
113
|
throw new Error('Existing session preset conflicts');
|
|
92
114
|
return { sessionId: input.sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }), preflight };
|
|
@@ -95,7 +117,11 @@ export class DshA2ABackend {
|
|
|
95
117
|
cwd,
|
|
96
118
|
...(agentPreset === undefined ? {} : { agentPreset }),
|
|
97
119
|
});
|
|
120
|
+
// Native create owns a durable blank session, not an ACP launch or prompt.
|
|
121
|
+
// If its non-abortable host operation finishes late, do not restore or run it.
|
|
122
|
+
signal?.throwIfAborted();
|
|
98
123
|
const agent = await this.agent(created.sessionId);
|
|
124
|
+
signal?.throwIfAborted();
|
|
99
125
|
return {
|
|
100
126
|
sessionId: created.sessionId,
|
|
101
127
|
cwd: agent.session.header.cwd ?? cwd,
|
|
@@ -134,6 +160,8 @@ export class DshA2ABackend {
|
|
|
134
160
|
const agent = await this.agent(target.sessionId);
|
|
135
161
|
options.signal.throwIfAborted();
|
|
136
162
|
const completion = Promise.withResolvers();
|
|
163
|
+
const startupAbort = new AbortController();
|
|
164
|
+
const startupSignal = AbortSignal.any([options.signal, startupAbort.signal]);
|
|
137
165
|
const listeners = [];
|
|
138
166
|
let messageId;
|
|
139
167
|
let turn;
|
|
@@ -209,9 +237,11 @@ export class DshA2ABackend {
|
|
|
209
237
|
}
|
|
210
238
|
}));
|
|
211
239
|
listeners.push(agent.ctx.on('agent/disposed', event => {
|
|
212
|
-
if (event.agent === agent)
|
|
240
|
+
if (event.agent === agent) {
|
|
213
241
|
settle({ outcome: 'failed', text, failureReason: 'disposed', detail: 'DSH session was disposed before the task finished',
|
|
214
242
|
error: toSafeError(undefined, { origin: 'dsh', operationId: options.requestId, outcomeUnknown: turn !== undefined }) });
|
|
243
|
+
startupAbort.abort(new Error('DSH session was disposed before startup'));
|
|
244
|
+
}
|
|
215
245
|
}));
|
|
216
246
|
listeners.push(agent.ctx.on('session/event', (session, event) => {
|
|
217
247
|
if (session !== agent.session || turn === undefined)
|
|
@@ -238,6 +268,20 @@ export class DshA2ABackend {
|
|
|
238
268
|
try {
|
|
239
269
|
// Recheck after event registration; cancellation can arrive during Agent restoration.
|
|
240
270
|
options.signal.throwIfAborted();
|
|
271
|
+
// Native user turns do not share this backend's execution map.
|
|
272
|
+
try {
|
|
273
|
+
if (options.beforeStart)
|
|
274
|
+
await waitForIdle(agent, startupSignal);
|
|
275
|
+
await options.beforeStart?.(startupSignal);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (settled)
|
|
279
|
+
return await completion.promise;
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
if (settled)
|
|
283
|
+
return await completion.promise;
|
|
284
|
+
options.signal.throwIfAborted();
|
|
241
285
|
await this.ctx.sessionController.prompt({
|
|
242
286
|
requestId: options.requestId,
|
|
243
287
|
sessionId: agent.id,
|
package/vendor/dsh/adapter.d.ts
CHANGED
|
@@ -4,13 +4,22 @@ import type { LlmAdapter, GenerateOptions, StreamChunk, LlmModelInfo } from '@de
|
|
|
4
4
|
import type { Diagnostics } from './diagnostics.js';
|
|
5
5
|
import type { SessionConfigOption, SessionModeState, AvailableCommand } from '@agentclientprotocol/sdk';
|
|
6
6
|
import { type Binding } from './state.js';
|
|
7
|
+
export interface SessionPolicy {
|
|
8
|
+
/** Exact workspace and ACP registry name; no global or wildcard policy. */
|
|
9
|
+
cwd: string;
|
|
10
|
+
agent: string;
|
|
11
|
+
permissionMode: 'approve-reads' | 'approve-all' | 'deny-all';
|
|
12
|
+
initialModeId?: string;
|
|
13
|
+
}
|
|
7
14
|
export interface Config {
|
|
8
15
|
serviceUrl: string;
|
|
9
16
|
agents: string[];
|
|
10
17
|
stateDirectory: string;
|
|
11
18
|
reconnectAttempts: number;
|
|
12
19
|
reconnectDelayMs: number;
|
|
20
|
+
sessionPolicies?: SessionPolicy[];
|
|
13
21
|
}
|
|
22
|
+
export declare function validateSessionPolicies(policies?: SessionPolicy[]): SessionPolicy[];
|
|
14
23
|
export interface Capabilities {
|
|
15
24
|
agent: string;
|
|
16
25
|
writable?: boolean;
|
|
@@ -24,6 +33,7 @@ export declare class AcpAdapter implements LlmAdapter {
|
|
|
24
33
|
private config;
|
|
25
34
|
private readonly diagnostics?;
|
|
26
35
|
private state;
|
|
36
|
+
private initializationFailures;
|
|
27
37
|
private controllers;
|
|
28
38
|
private jobs;
|
|
29
39
|
private links;
|