dsh-punky-swarm 0.3.6

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +661 -0
  3. package/README.en.md +281 -0
  4. package/README.md +281 -0
  5. package/cordis.patch.yml +59 -0
  6. package/lib/acps/certs.js +310 -0
  7. package/lib/acps/discovery-client.js +283 -0
  8. package/lib/acps/registry-client.js +527 -0
  9. package/lib/acps/server.js +302 -0
  10. package/lib/aip/agent-descriptor.js +170 -0
  11. package/lib/aip/identity.js +469 -0
  12. package/lib/aip/tool-descriptor.js +93 -0
  13. package/lib/api.js +266 -0
  14. package/lib/artifact-types.js +48 -0
  15. package/lib/assembly/audit-blind-review.js +170 -0
  16. package/lib/assembly/schema.js +253 -0
  17. package/lib/assembly.js +41 -0
  18. package/lib/assets.js +103 -0
  19. package/lib/bridge/trajectory.js +202 -0
  20. package/lib/client.js +704 -0
  21. package/lib/comms/acps-bridge.js +219 -0
  22. package/lib/comms/aip-format.js +141 -0
  23. package/lib/comms/budget.js +124 -0
  24. package/lib/comms/mailbox.js +221 -0
  25. package/lib/comms/topic-runtime.js +76 -0
  26. package/lib/comms/topic.js +115 -0
  27. package/lib/discovery/filter.js +199 -0
  28. package/lib/discovery/schema.js +157 -0
  29. package/lib/discovery/service.js +251 -0
  30. package/lib/hot/config-watch.js +252 -0
  31. package/lib/index.js +433 -0
  32. package/lib/lock.js +69 -0
  33. package/lib/panel/batch-detail.js +163 -0
  34. package/lib/panel/batch-list.js +84 -0
  35. package/lib/panel/locales.js +93 -0
  36. package/lib/panel/main.js +270 -0
  37. package/lib/panel/stream.js +348 -0
  38. package/lib/panel/theme.js +103 -0
  39. package/lib/panel/widgets.js +63 -0
  40. package/lib/schema.d.ts +192 -0
  41. package/lib/schema.js +259 -0
  42. package/lib/schema.ts +398 -0
  43. package/lib/state/archive.js +174 -0
  44. package/lib/state/command-exec.js +148 -0
  45. package/lib/state/constants.js +37 -0
  46. package/lib/state/corrupt-registry.js +103 -0
  47. package/lib/state/event-types.js +65 -0
  48. package/lib/state/gates.d.ts +226 -0
  49. package/lib/state/gates.js +428 -0
  50. package/lib/state/gates.ts +348 -0
  51. package/lib/state/machine-rules.d.ts +14 -0
  52. package/lib/state/machine-rules.js +76 -0
  53. package/lib/state/machine-rules.ts +88 -0
  54. package/lib/state/machine.js +68 -0
  55. package/lib/state/resume.js +201 -0
  56. package/lib/state/schema-v3.d.ts +10 -0
  57. package/lib/state/schema-v3.js +57 -0
  58. package/lib/state/schema-v3.ts +80 -0
  59. package/lib/state/store.js +607 -0
  60. package/lib/state/task-utils.js +40 -0
  61. package/lib/tools/core.js +323 -0
  62. package/lib/tools/git-utils.js +44 -0
  63. package/lib/tools/lane-tools.js +455 -0
  64. package/lib/tools/log-tools.js +173 -0
  65. package/lib/tools/mailbox-tools.js +121 -0
  66. package/lib/tools/merge-agent.js +127 -0
  67. package/lib/tools/register.js +85 -0
  68. package/lib/tools/shared.js +32 -0
  69. package/lib/types/contracts.d.ts +277 -0
  70. package/lib/types/contracts.js +17 -0
  71. package/lib/types/contracts.ts +279 -0
  72. package/lib/verify/evidence.js +249 -0
  73. package/lib/verify/gate.js +161 -0
  74. package/lib/verify/mount.js +48 -0
  75. package/lib/verify/selector.js +101 -0
  76. package/lib/watch/lane-heartbeat.js +333 -0
  77. package/lib/wave-plan.d.ts +48 -0
  78. package/lib/wave-plan.js +473 -0
  79. package/lib/wave-plan.ts +465 -0
  80. package/package.json +71 -0
  81. package/presets/jiufeng/NOTICE +5 -0
  82. package/presets/jiufeng/agent.cordis.yml +275 -0
  83. package/presets/jiufeng/preset.yml +3 -0
  84. package/skills/jiufeng-team/SKILL.md +214 -0
  85. package/skills/jiufeng-team/references/constitution.md +62 -0
  86. package/skills/jiufeng-team/references/roles/coder.md +17 -0
  87. package/skills/jiufeng-team/references/roles/coordinator.md +13 -0
  88. package/skills/jiufeng-team/references/roles/designer.md +14 -0
  89. package/skills/jiufeng-team/references/roles/doc-manager.md +13 -0
  90. package/skills/jiufeng-team/references/roles/manager.md +22 -0
  91. package/skills/jiufeng-team/references/roles/reviewer.md +19 -0
  92. package/skills/jiufeng-team/references/roles/supervisor.md +13 -0
  93. package/skills/jiufeng-team/references/roles/tester.md +13 -0
  94. package/skills/jiufeng-team/references/templates/call-chain-matrix-template.md +121 -0
  95. package/skills/jiufeng-team/references/templates/endpoint-behavior-template.md +60 -0
  96. package/skills/jiufeng-team/references/templates/gap-list.json +33 -0
  97. package/skills/jiufeng-team/references/templates/leader-decision-pack.md +92 -0
  98. package/skills/jiufeng-team/references/templates/plan-template.md +61 -0
  99. package/skills/jiufeng-team/references/templates/success-pattern-seeds.md +126 -0
  100. package/skills/jiufeng-team/references/workflow.md +98 -0
  101. package/skills/jiufeng-team/scripts/check-v3-density.mjs +98 -0
@@ -0,0 +1,219 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ // 文件 acps-bridge:内部 ACPs 桥接(file mailbox ↔ ACPs 消息,进程内双向,默认关)
19
+ // 零破坏:mailbox ackId 原子写、三 box、outbox lane 隔离语义逐字保留。
20
+ //
21
+ // 职责与红线:
22
+ // - inbound:外部 ACPs TaskCommand → mailbox 消息。**经 lib/comms/mailbox.js 公共接口原子写(ackId 由 mailbox
23
+ // 生成),绝不绕过、无旁路写**;写入目标仅 inbox(按 mentions/groupId 推导 lane 进 meta),outbox 不可由外部直接写。
24
+ // - outbound:mailbox 消息 → ACPs Message/TaskResult。复用 lib/comms/aip-format.js 三映射
25
+ // (toAipMessage/toAipTask/toAipSession,本模块 re-export 供端点单一入口);只投影/投递视图,不反写 mailbox 存储。
26
+ // - 零路径:enabled=false 时 mountBridge 返回 null(不实例化),模块顶层无任何副作用(无监听/定时器/订阅);
27
+ // 桥不自带监听——/rpc 监听归 endpoint 侧(衔接点见 handleInbound/toTaskResult 签名)。
28
+ // - 生命周期:start/stop/dispose 幂等(开→关销毁、关→开重建,秒级无迁移)。
29
+
30
+ import { join } from 'node:path';
31
+ import * as mailbox from './mailbox.js';
32
+ import {
33
+ toAipMessage,
34
+ toAipTask,
35
+ toAipSession,
36
+ toAipDataItems,
37
+ AIP_COMMAND_TYPES,
38
+ TASK_STATES,
39
+ } from './aip-format.js';
40
+ import { resolveBridgeConfig } from '../schema.js';
41
+
42
+ // lane 合法性(与 mailbox.js sanitizeLane 同正则,fail-soft:外部输入不合法 → null 而非 throw)
43
+ const LANE_RE = /^[a-zA-Z0-9._-]+$/;
44
+
45
+ function boxRoot(root, sessionId, batchId) {
46
+ return join(root, 'sessions', sessionId, 'mailbox', batchId);
47
+ }
48
+
49
+ // ── inbound:ACPs TaskCommand → mailbox 消息(纯转换,不写存储)──
50
+ // lane 推导:mentions 单元素数组/非 'all' 字符串 → 该值;否则 groupId;均非法 → null(inbox 无 lane 概念,
51
+ // lane 仅为路由元数据)。mentions='all'(广播语义)外部投递不支持 → null(外部不可写 broadcast,红线)。
52
+ export function deriveLane(taskCommand) {
53
+ const mentions = taskCommand?.mentions;
54
+ let candidate = null;
55
+ if (Array.isArray(mentions) && mentions.length === 1 && typeof mentions[0] === 'string' && mentions[0] !== 'all') {
56
+ candidate = mentions[0];
57
+ } else if (typeof mentions === 'string' && mentions.length > 0 && mentions !== 'all') {
58
+ candidate = mentions;
59
+ } else if (typeof taskCommand?.groupId === 'string' && taskCommand.groupId.length > 0) {
60
+ candidate = taskCommand.groupId;
61
+ }
62
+ return candidate !== null && LANE_RE.test(candidate) ? candidate : null;
63
+ }
64
+
65
+ // TaskCommand → mailbox { message, meta }(纯函数;command 枚举透传否则 start,与 aip-format.toAipTask 同语义)
66
+ export function taskCommandToInbound(taskCommand) {
67
+ const command = AIP_COMMAND_TYPES.includes(taskCommand?.command) ? taskCommand.command : 'start';
68
+ const message = {
69
+ command,
70
+ ...(taskCommand?.commandParams !== undefined ? { commandParams: taskCommand.commandParams } : {}),
71
+ ...(taskCommand?.taskId !== undefined ? { taskId: taskCommand.taskId } : {}),
72
+ };
73
+ const meta = {
74
+ sessionId: taskCommand?.sessionId ?? null,
75
+ taskId: taskCommand?.taskId ?? null,
76
+ lane: deriveLane(taskCommand), // 路由元数据(可为 null)
77
+ };
78
+ return { message, meta };
79
+ }
80
+
81
+ // inbound 投递:经 mailbox.send 公共接口原子写 inbox(ackId 由 mailbox 生成)。
82
+ // inboundEnabled 缺省 false(默认关):外部写 mailbox 需显式开启——调用方(endpoint /rpc)在
83
+ // bridge.inboundEnabled 门控通过后才传 { inboundEnabled: true }。
84
+ export function deliverInbound(root, sessionId, batchId, taskCommand, { inboundEnabled = false } = {}) {
85
+ if (!inboundEnabled) {
86
+ return { ok: false, code: 'INBOUND_DISABLED', detail: 'acps.bridge.inbound is false: external writes to mailbox disabled' };
87
+ }
88
+ const { message, meta } = taskCommandToInbound(taskCommand);
89
+ const res = mailbox.send(boxRoot(root, sessionId, batchId), { type: 'inbox' }, message, meta);
90
+ return { ok: res.ok, ackId: res.ackId, lane: meta.lane };
91
+ }
92
+
93
+ // ── outbound:mailbox 消息 → ACPs Message/TaskResult(纯投影,不反写 mailbox)──
94
+ // toTaskResult:outbox/broadcast 消息 → ACPs TaskResult。
95
+ // taskId ← message.taskId ?? meta.taskId ?? ackId;status.state 由调用方按成员状态映射(缺省 completed,
96
+ // 状态映射契约归 endpoint/Leader lane,见 exec/bridge.md 衔接点);dataItems 复用 toAipDataItems(与 aip-format 同源)。
97
+ export function toTaskResult(msg, { state = 'completed', stateChangedAt = null, products = null } = {}) {
98
+ const taskId = msg?.message?.taskId ?? msg?.meta?.taskId ?? msg?.ackId ?? null;
99
+ const lane = msg?.box?.lane ?? msg?.meta?.lane ?? msg?.meta?.sender ?? 'worker';
100
+ const status = {
101
+ state: TASK_STATES.includes(state) ? state : 'completed', // fail-soft:非枚举 → completed
102
+ stateChangedAt: stateChangedAt ?? msg?.ts ?? new Date().toISOString(),
103
+ };
104
+ const dataItems = toAipDataItems(msg?.message);
105
+ if (dataItems) status.dataItems = dataItems;
106
+ const out = {
107
+ type: 'task-result',
108
+ id: msg?.ackId ?? null,
109
+ sentAt: msg?.ts ?? null,
110
+ senderRole: 'partner', // outbox=worker→Leader=partner(与 aip-format.toAipMessage 方向语义一致)
111
+ senderId: lane,
112
+ taskId,
113
+ status,
114
+ };
115
+ if (products) out.products = products;
116
+ if (msg?.meta?.sessionId) out.sessionId = msg.meta.sessionId;
117
+ return out;
118
+ }
119
+
120
+ // ── 工厂(进程内双向;enabled 门控,inbound 子门控)──
121
+ export function createBridge({ root, config = {}, mailbox: mb = mailbox, logger = null } = {}) {
122
+ const cfg = resolveBridgeConfig(config);
123
+ const enabled = cfg.enabled;
124
+ const inboundEnabled = cfg.enabled && cfg.inbound;
125
+ let mounted = false;
126
+
127
+ // endpoint /rpc 衔接点:收到 TaskCommand 后调用 handleInbound(taskCommand, { sessionId, batchId })。
128
+ // inbound 关(默认)→ 拒绝(视图只读);缺 sessionId/batchId → 拒绝(mailbox 按会话/批次隔离,缺上下文不可投递)。
129
+ function handleInbound(taskCommand, { sessionId, batchId } = {}) {
130
+ if (!enabled) return { ok: false, code: 'BRIDGE_DISABLED', detail: 'acps.bridge.enabled is false' };
131
+ if (!inboundEnabled) return { ok: false, code: 'INBOUND_DISABLED', detail: 'acps.bridge.inbound is false' };
132
+ if (!sessionId || !batchId) {
133
+ return { ok: false, code: 'MISSING_CONTEXT', detail: 'sessionId/batchId required for mailbox write' };
134
+ }
135
+ return deliverInbound(root, sessionId, batchId, taskCommand, { inboundEnabled: true });
136
+ }
137
+
138
+ return {
139
+ enabled,
140
+ inboundEnabled,
141
+ mode: cfg.mode,
142
+ // inbound 衔接点(endpoint /rpc 调用)
143
+ handleInbound,
144
+ // outbound 衔接点(endpoint/视图调用;Message 投影复用 aip-format,单一入口)
145
+ toOutbound: (msg) => toAipMessage(msg),
146
+ toTaskResult,
147
+ // 生命周期:桥不自带监听/定时器(/rpc 监听归 endpoint 侧);start/stop 幂等标记
148
+ start() { mounted = true; return { mounted }; },
149
+ stop() { mounted = false; return { mounted }; },
150
+ dispose() { mounted = false; },
151
+ get mounted() { return mounted; },
152
+ };
153
+ }
154
+
155
+ // ── 装配短路:enabled=false → null,不实例化(零路径)。index.js 装配处唯一调用点。──
156
+ export function mountBridge(config, deps) {
157
+ if (!resolveBridgeConfig(config).enabled) return null;
158
+ return createBridge({ ...deps, config });
159
+ }
160
+
161
+ // ── endpoint /rpc → bridge inbound 接线 ──
162
+ // createEndpointRpcHandler(bridge) 生成适配 createAcpsServer 的 rpcHandler(server.js:269 注入点):
163
+ // (command, ctx) → TaskResult。行为:
164
+ // - bridge 未装配(null)→ fallback(缺省独立回执 accepted,不落 mailbox);
165
+ // - sessionId/batchId 上下文注入:sessionId ← command.sessionId(ACPs Message 基类字段,
166
+ // aip_base_model.py:151)?? command.commandParams.sessionId;batchId ← command.commandParams.batchId;
167
+ // - bridge.handleInbound 成功 → TaskResult accepted(任务已入 inbox 待派发);
168
+ // - bridge 拒绝(BRIDGE_DISABLED/INBOUND_DISABLED/MISSING_CONTEXT)→ TaskResult rejected
169
+ // (协议级拒绝,AIP TaskState.rejected,aip_base_model.py:33;status.dataItems 附 code/detail),
170
+ // HTTP 200 返回——传输成功、协议层拒绝(对端可消费,不触发 AipRpcClient 传输错误路径)。
171
+ export function createEndpointRpcHandler(bridge, { logger = null } = {}) {
172
+ return function endpointRpcHandler(command, ctx = {}) {
173
+ if (!bridge) {
174
+ // bridge 未装配:独立行为(回 accepted 但不落 mailbox,向后兼容)
175
+ return acceptedInboundResult(command, ctx);
176
+ }
177
+ const sessionId = command?.sessionId ?? command?.commandParams?.sessionId ?? null;
178
+ const batchId = command?.commandParams?.batchId ?? null;
179
+ const res = bridge.handleInbound(command, { sessionId, batchId });
180
+ if (!res.ok) {
181
+ logger?.warn?.('[dsh-punky-swarm] acps /rpc inbound rejected: ' + res.code + ' ' + (res.detail ?? ''));
182
+ return rejectedInboundResult(command, ctx, res);
183
+ }
184
+ return acceptedInboundResult(command, ctx);
185
+ };
186
+ }
187
+
188
+ // inbound 回执 TaskResult 构造:
189
+ // accepted = 任务已入 inbox;rejected = bridge 拒绝(INBOUND_DISABLED 等,status.dataItems 附 code/detail)
190
+ function inboundResult(taskCommand, state, ctx = {}) {
191
+ const now = new Date().toISOString();
192
+ const taskId = typeof taskCommand?.taskId === 'string' && taskCommand.taskId.length > 0
193
+ ? taskCommand.taskId
194
+ : (typeof taskCommand?.id === 'string' ? taskCommand.id : 'task-' + Date.now().toString(36));
195
+ const out = {
196
+ type: 'task-result',
197
+ id: typeof taskCommand?.id === 'string' ? taskCommand.id : taskId,
198
+ sentAt: now,
199
+ senderRole: 'partner',
200
+ senderId: ctx?.peerAic ?? 'dsh-punky-swarm',
201
+ taskId,
202
+ status: { state, stateChangedAt: now },
203
+ commandHistory: [taskCommand],
204
+ };
205
+ return out;
206
+ }
207
+
208
+ function acceptedInboundResult(taskCommand, ctx) {
209
+ return inboundResult(taskCommand, 'accepted', ctx);
210
+ }
211
+
212
+ function rejectedInboundResult(taskCommand, ctx, res) {
213
+ const out = inboundResult(taskCommand, 'rejected', ctx);
214
+ out.status.dataItems = [{ type: 'data', data: { code: res?.code ?? 'INBOUND_REJECTED', detail: res?.detail ?? null } }];
215
+ return out;
216
+ }
217
+
218
+ // re-export aip-format 三映射 + 枚举(端点单一入口;与投影层同源,保证 ACPs 形态一致)
219
+ export { toAipMessage, toAipTask, toAipSession, toAipDataItems, AIP_COMMAND_TYPES, TASK_STATES };
@@ -0,0 +1,141 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ // 文件 aip-format:ACPs AIP 消息/任务/会话结构投影(ACPs 交互,参考实现 ACPs v2.1.0)
19
+ // 契约:字段级汇总(AIP spec 原文)
20
+ // 三函数均为纯函数:输入引擎自有结构 → 输出 ACPs AIP 兼容结构;不做任何文件/存储写操作,
21
+ // mailbox 的 ackId 原子写、inbox/outbox/broadcast 三 box、outbox lane 隔离、ack 语义全部保留(红线:既有 mailbox 行为不变)。
22
+ //
23
+ // 字段对齐原则(spec.md §3.6 与 AIP 规范原文核对):
24
+ // - Message 基类字段:type(id) / id / sentAt / senderRole("leader"|"partner") / senderId / mentions? / dataItems? / groupId? / sessionId?
25
+ // - TaskCommand extends Message:type="task-command" / command(TaskCommandType) / commandParams? / taskId?
26
+ // - Session:id / taskResults[] / taskCommands[] / createdAt / updatedAt
27
+ // - 引擎自推导字段(messageId/timestamp/sender/receiver/channel/contentType/content/meta;
28
+ // dependencies/inputContract/outputContract/executor/executionModel;agentIds/state/taskIds/concurrency)
29
+ // 在 ACPs 结构中不存在 → 剔除或移入 commandParams(值域开放,注明引擎扩展键),不在顶层臆造。
30
+
31
+ // TaskCommandType 枚举(参考实现原文,逐字)
32
+ export const AIP_COMMAND_TYPES = ['get', 'start', 'continue', 'cancel', 'complete', 're-stream'];
33
+
34
+ // TaskState 枚举(aip_base_model.py:23-33;任务状态枚举唯一源——acps-bridge/server 经 re-export 消费,禁止再自持定义)
35
+ export const TASK_STATES = [
36
+ 'accepted', 'working', 'awaiting-input', 'awaiting-completion',
37
+ 'completed', 'canceled', 'failed', 'rejected',
38
+ ];
39
+
40
+ // Message 基类投影:mailbox payload { ackId, ts, box, message, meta } → ACPs Message 结构
41
+ // type 值 'message' 为投影标记(Message 基类 type 值域未限定,子类型如 task-command 由任务投影覆盖);
42
+ // senderRole/senderId 由 box 方向推导(inbox=Leader→worker=leader;outbox=worker→Leader=partner;
43
+ // broadcast=Leader 广播=leader;引擎无 AIC,senderId 保留引擎侧标识,注明为占位)。
44
+ export function toAipMessage(msg) {
45
+ const box = msg?.box ?? {};
46
+ const type = box.type;
47
+ let senderRole;
48
+ let senderId;
49
+ let mentions;
50
+ if (type === 'broadcast') {
51
+ senderRole = 'leader';
52
+ senderId = msg?.meta?.sender ?? 'broadcaster';
53
+ mentions = 'all';
54
+ } else if (type === 'outbox') {
55
+ senderRole = 'partner';
56
+ senderId = msg?.meta?.sender ?? box.lane ?? 'worker';
57
+ } else {
58
+ // inbox(含缺省):Leader 发往 worker
59
+ senderRole = 'leader';
60
+ senderId = msg?.meta?.sender ?? 'leader';
61
+ }
62
+ const out = {
63
+ type: 'message',
64
+ id: msg?.ackId ?? null,
65
+ sentAt: msg?.ts ?? null,
66
+ senderRole,
67
+ senderId,
68
+ };
69
+ const dataItems = toAipDataItems(msg?.message);
70
+ if (dataItems) out.dataItems = dataItems;
71
+ if (mentions) out.mentions = mentions;
72
+ if (msg?.meta?.sessionId) out.sessionId = msg.meta.sessionId;
73
+ return out;
74
+ }
75
+
76
+ // 引擎 message → ACPs DataItem[](Text/File/Structured 联合;null/undefined → undefined 省略)
77
+ export function toAipDataItems(message) {
78
+ if (message === null || message === undefined) return undefined;
79
+ if (typeof message === 'string') return [{ type: 'text', text: message }];
80
+ if (typeof message === 'object') {
81
+ if (message.type === 'text' && typeof message.text === 'string') return [{ type: 'text', text: message.text }];
82
+ if (message.type === 'file') {
83
+ const item = { type: 'file' };
84
+ if (message.name) item.name = message.name;
85
+ if (message.mimeType) item.mimeType = message.mimeType;
86
+ if (message.uri) item.uri = message.uri;
87
+ if (message.bytes) item.bytes = message.bytes;
88
+ return [item];
89
+ }
90
+ if (message.type === 'data' && message.data !== undefined) return [{ type: 'data', data: message.data }];
91
+ // 结构化兜底:任意对象 → StructuredDataItem(注明:非 ACPs 判别器推导,投影层包装)
92
+ return [{ type: 'data', data: message }];
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ // 任务命令投影:wavePlan task → ACPs TaskCommand 结构
98
+ // ACPs 无独立『任务定义』对象——任务由 TaskCommand(命令)+ TaskResult(状态/结果)承载(spec.md §3.6)。
99
+ // wavePlan task 派发语义 = start 命令;task.cmd 若本身命中 TaskCommandType 枚举则透传,否则默认 'start'(注明推导)。
100
+ // 引擎自有键(layer/role/skills/deps/consume/produce/outputs/cmd/model/tools)移入 commandParams(值域开放,非 ACPs 顶层字段)。
101
+ export function toAipTask(task) {
102
+ const rawCmd = String(task?.cmd ?? '');
103
+ const command = AIP_COMMAND_TYPES.includes(rawCmd) ? rawCmd : 'start';
104
+ return {
105
+ type: 'task-command',
106
+ id: task?.id ?? null,
107
+ sentAt: null, // 引擎 wavePlan task 无时间戳(AIP sentAt 必填 ISO 8601,由派发侧注入;此处如实置 null)
108
+ senderRole: 'leader', // Leader 派发推导(引擎无 AIC,占位)
109
+ senderId: 'leader',
110
+ command,
111
+ commandParams: {
112
+ // —— 以下为引擎扩展键(非 ACPs 顶层字段,注明)——
113
+ cmd: rawCmd || null,
114
+ layer: task?.layer ?? null,
115
+ role: task?.role ?? null,
116
+ skills: task?.skills ?? null,
117
+ deps: task?.deps ?? null,
118
+ consume: task?.consume ?? null,
119
+ produce: task?.produce ?? task?.outputs ?? null,
120
+ model: task?.model ?? null,
121
+ tools: task?.tools ?? null,
122
+ },
123
+ taskId: task?.id ?? null,
124
+ };
125
+ }
126
+
127
+ // 会话投影:批次状态 { sessionId, phase, concurrency, wavePlan, lanes, createdAt, updatedAt, ... } → ACPs Session
128
+ // ACPs Session 只存在于 Leader,仅 sessionId 进消息(spec.md §3.6);taskResults 引擎无数据 → 空数组(如实);
129
+ // taskCommands ← wavePlan 任务投影;agentIds/state/taskIds/concurrency 非 ACPs 字段 → 剔除(agentIds 由消息 senderId 表达、
130
+ // 状态由 TaskResult.status 表达、taskIds 由 taskCommands[].taskId 表达、并发为引擎调度参数,均非 Session 契约)。
131
+ export function toAipSession(session) {
132
+ const waves = session?.wavePlan ?? [];
133
+ const tasks = waves.flatMap((w) => w.tasks ?? []);
134
+ return {
135
+ id: session?.sessionId ?? null,
136
+ taskResults: [],
137
+ taskCommands: tasks.map((t) => toAipTask(t)),
138
+ createdAt: session?.createdAt ?? null,
139
+ updatedAt: session?.updatedAt ?? null,
140
+ };
141
+ }
@@ -0,0 +1,124 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ // 文件 budget:mailbox 循环防护(C4,dsh-team 循环防护三件套语义适配)
19
+ // 借鉴 dsh-team config.ts:41-42(maxChainHops/maxChainRoundTrips)、service.ts:514-571(chainFor/REPEATED_MESSAGE/记账+CHAIN_MEMORY 裁剪)、errors.ts(错误码闭环)。
20
+ // 纯函数模块:不 import store/mailbox(状态由调用方传入),接线在 tools/mailbox-tools.js。
21
+ // 链语义:蟛蜞 worker 读多封消息无「正在处理哪条」机械绑定 → 链由发送方在 meta.chain 显式声明 {id, hop};
22
+ // 不声明 = 新链 hop=0(向后兼容,现有调用零感知)。
23
+ import { randomUUID } from 'node:crypto';
24
+
25
+ // 记账上限:chains 保留最近 64 条链(dsh-team CHAIN_MEMORY=64),batch JSON 不膨胀
26
+ export const CHAIN_MEMORY = 64;
27
+
28
+ // 有序对 key:from→to
29
+ export function chainKey(from, to) {
30
+ return String(from ?? '?') + '→' + String(to ?? '?');
31
+ }
32
+
33
+ function validChainId(id) {
34
+ return typeof id === 'string' && id.length > 0;
35
+ }
36
+
37
+ // chainFor:显式 meta.chain 继承 hop+1;无显式声明 → 开新链(hop=0)
38
+ // msg: { meta?: { chain?: {id, hop} } };chainsState 当前未用于派生(链身份由发送方声明),保留入参以对齐契约签名
39
+ export function chainFor(_chainsState, msg) {
40
+ const explicit = msg?.meta?.chain;
41
+ if (explicit && validChainId(explicit.id)) {
42
+ const hop = Number.isInteger(explicit.hop) && explicit.hop >= 0 ? explicit.hop + 1 : 1;
43
+ return { id: explicit.id, hop };
44
+ }
45
+ return { id: randomUUID(), hop: 0 };
46
+ }
47
+
48
+ // checkBudget:环防护校验(纯函数,不 mutate 任何入参)
49
+ // meta: { chain?: {id, hop}, from?, to?, text? }(text 用于一字不差重发拒绝)
50
+ // chainsState: { chains: { [chainId]: { edges: { [from→to]: count }, said: { [from→to]: lastText } } }, order: [chainId] }
51
+ // 返回 { ok:true, chain } | { ok:false, code:'CHAIN_EXHAUSTED'|'PING_PONG'|'REPEATED_MESSAGE', chain, detail }
52
+ export function checkBudget(meta, chainsState, { maxChainHops = 4, maxChainRoundTrips = 2 } = {}) {
53
+ const chain = meta?.chain;
54
+ if (!chain || !validChainId(chain.id)) {
55
+ // 无链声明 → 视为新链 hop=0(向后兼容,现有调用零感知)
56
+ return { ok: true, chain: { id: randomUUID(), hop: 0 } };
57
+ }
58
+ const hop = Number.isInteger(chain.hop) && chain.hop >= 0 ? chain.hop : 0;
59
+ // 环检测:链跳数超限
60
+ if (hop > maxChainHops) {
61
+ return {
62
+ ok: false,
63
+ code: 'CHAIN_EXHAUSTED',
64
+ chain: { id: chain.id, hop },
65
+ detail: 'chain ' + chain.id + ' hop=' + hop + ' exceeded maxChainHops=' + maxChainHops
66
+ + '; settle it yourself and report to the leader',
67
+ };
68
+ }
69
+ const rec = chainsState?.chains?.[chain.id];
70
+ const from = meta?.from;
71
+ const to = meta?.to;
72
+ if (rec && from != null && to != null) {
73
+ const key = chainKey(from, to);
74
+ // 往返上限:同链同有序对往返 ≥ maxChainRoundTrips → PING_PONG
75
+ const count = rec.edges?.[key] ?? 0;
76
+ if (count >= maxChainRoundTrips) {
77
+ return {
78
+ ok: false,
79
+ code: 'PING_PONG',
80
+ chain: { id: chain.id, hop },
81
+ detail: 'chain ' + chain.id + ' round-trips ' + key + '=' + count + ' reached maxChainRoundTrips=' + maxChainRoundTrips
82
+ + '; settle it yourself and report to the leader',
83
+ };
84
+ }
85
+ // 重发拒绝:同链同向同文本 → REPEATED_MESSAGE(跨链/新链同文本放行)
86
+ if (typeof meta.text === 'string' && typeof rec.said?.[key] === 'string' && rec.said[key] === meta.text) {
87
+ return {
88
+ ok: false,
89
+ code: 'REPEATED_MESSAGE',
90
+ chain: { id: chain.id, hop },
91
+ detail: 'chain ' + chain.id + ' repeated identical message on ' + key
92
+ + '; start a new chain to resend',
93
+ };
94
+ }
95
+ }
96
+ return { ok: true, chain: { id: chain.id, hop } };
97
+ }
98
+
99
+ // recordChain:记账(edges 计数 + said 文本 + CHAIN_MEMORY=64 插入序裁剪);纯函数返回新链状态,不 mutate
100
+ export function recordChain(chainsState, msg) {
101
+ const base = chainsState ?? { chains: {}, order: [] };
102
+ const chain = msg?.meta?.chain;
103
+ if (!chain || !validChainId(chain.id)) return base;
104
+ const chainId = chain.id;
105
+ const from = msg?.meta?.from;
106
+ const to = msg?.meta?.to;
107
+ const prev = base.chains?.[chainId] ?? { edges: {}, said: {} };
108
+ const edges = { ...(prev.edges ?? {}) };
109
+ const said = { ...(prev.said ?? {}) };
110
+ if (from != null && to != null) {
111
+ const key = chainKey(from, to);
112
+ edges[key] = (edges[key] ?? 0) + 1;
113
+ if (typeof msg.meta.text === 'string') said[key] = msg.meta.text;
114
+ }
115
+ const chains = { ...(base.chains ?? {}), [chainId]: { edges, said } };
116
+ // 插入序裁剪:order 记录链创建顺序,超 CHAIN_MEMORY 删除最旧链(batch JSON 不膨胀)
117
+ const order = Array.isArray(base.order) ? [...base.order] : [];
118
+ if (!order.includes(chainId)) order.push(chainId);
119
+ while (order.length > CHAIN_MEMORY) {
120
+ const drop = order.shift();
121
+ delete chains[drop];
122
+ }
123
+ return { chains, order };
124
+ }