@xdxer/dingtalk-agent 0.1.1 → 0.1.4-beta.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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -76
  3. package/dist/bin/dingtalk-agent.js +763 -0
  4. package/dist/bin/dingtalk-agent.js.map +1 -0
  5. package/dist/src/actions.js +562 -0
  6. package/dist/src/actions.js.map +1 -0
  7. package/dist/src/boot.js +70 -0
  8. package/dist/src/boot.js.map +1 -0
  9. package/dist/src/bootstrap.js +144 -0
  10. package/dist/src/bootstrap.js.map +1 -0
  11. package/dist/src/config.js +86 -0
  12. package/dist/src/config.js.map +1 -0
  13. package/dist/src/doctor.js +166 -0
  14. package/dist/src/doctor.js.map +1 -0
  15. package/dist/src/driver.js +45 -0
  16. package/dist/src/driver.js.map +1 -0
  17. package/{src → dist/src}/duty.js +42 -44
  18. package/dist/src/duty.js.map +1 -0
  19. package/dist/src/dws.js +270 -0
  20. package/dist/src/dws.js.map +1 -0
  21. package/dist/src/events.js +233 -0
  22. package/dist/src/events.js.map +1 -0
  23. package/dist/src/fields.js +132 -0
  24. package/dist/src/fields.js.map +1 -0
  25. package/dist/src/init.js +41 -0
  26. package/dist/src/init.js.map +1 -0
  27. package/dist/src/kb.js +240 -0
  28. package/dist/src/kb.js.map +1 -0
  29. package/dist/src/package-root.js +17 -0
  30. package/dist/src/package-root.js.map +1 -0
  31. package/dist/src/runs.js +79 -0
  32. package/dist/src/runs.js.map +1 -0
  33. package/dist/src/sessions.js +668 -0
  34. package/dist/src/sessions.js.map +1 -0
  35. package/dist/src/setup.js +101 -0
  36. package/dist/src/setup.js.map +1 -0
  37. package/dist/src/skill-manager.js +288 -0
  38. package/dist/src/skill-manager.js.map +1 -0
  39. package/dist/src/skills.js +200 -0
  40. package/dist/src/skills.js.map +1 -0
  41. package/dist/src/types.js +2 -0
  42. package/dist/src/types.js.map +1 -0
  43. package/dist/src/waits.js +945 -0
  44. package/dist/src/waits.js.map +1 -0
  45. package/dist/src/workspace.js +173 -0
  46. package/dist/src/workspace.js.map +1 -0
  47. package/docs/ARCHITECTURE.md +217 -0
  48. package/docs/INSTALLATION.md +135 -0
  49. package/docs/MINIMAL-WORKSPACE-V1.md +172 -0
  50. package/docs/OPEN-SOURCE-REFERENCES.md +107 -0
  51. package/docs/SELF-TEST.md +252 -0
  52. package/docs/architecture/dingtalk-agent-blueprint.png +0 -0
  53. package/docs/architecture/dingtalk-agent-blueprint.svg +144 -0
  54. package/docs/architecture/durable-async-agent-runtime.png +0 -0
  55. package/docs/architecture/durable-async-agent-runtime.svg +234 -0
  56. package/docs//345/206/205/347/275/221/345/256/236/347/233/270.md +77 -0
  57. package/evals/baselines/2026-07-14/behavior-summary.json +28 -0
  58. package/evals/baselines/2026-07-14/contract-summary.json +18 -0
  59. package/evals/baselines/2026-07-14/live-canary-summary.json +25 -0
  60. package/evals/baselines/2026-07-15/dingtalk-basic-behavior-0.3.0/SKILL.md +72 -0
  61. package/evals/baselines/2026-07-15/dingtalk-basic-behavior-0.3.0/references/action-contract.md +31 -0
  62. package/evals/baselines/2026-07-15/dingtalk-basic-behavior-0.3.0/references/event-to-behavior.md +22 -0
  63. package/evals/baselines/2026-07-15/dingtalk-basic-behavior-0.3.0/references/memory-and-evolution.md +25 -0
  64. package/evals/baselines/2026-07-15/dingtalk-basic-behavior-0.3.0/references/runtime-modes.md +34 -0
  65. package/evals/baselines/2026-07-15/task-lifecycle-summary.json +50 -0
  66. package/evals/evals.json +316 -0
  67. package/evals/fixtures/dm-ambiguous-send.json +4 -0
  68. package/evals/fixtures/dm-blocked.json +4 -0
  69. package/evals/fixtures/dm-clear.json +4 -0
  70. package/evals/fixtures/dm-discussion.json +4 -0
  71. package/evals/fixtures/dm-doc-write-no-tool.json +4 -0
  72. package/evals/fixtures/dm-long-task-ack.json +4 -0
  73. package/evals/fixtures/dm-nonblocking-gap.json +4 -0
  74. package/evals/fixtures/dm-structured-task.json +4 -0
  75. package/evals/fixtures/group.json +10 -0
  76. package/evals/fixtures/mentioned.json +3 -0
  77. package/evals/run-contract-evals.mjs +1106 -0
  78. package/evals/run-shadow-evals.mjs +267 -0
  79. package/evals/runners/README.md +66 -0
  80. package/evals/runners/claude-shadow.mjs +533 -0
  81. package/evals/schemas/action-request.schema.json +77 -0
  82. package/evals/shadow-evals.json +133 -0
  83. package/package.json +28 -6
  84. package/skills/AGENTS.md +21 -3
  85. package/skills/dingtalk-basic-behavior/SKILL.md +86 -0
  86. package/skills/dingtalk-basic-behavior/assets/task-checkpoint.md +37 -0
  87. package/skills/dingtalk-basic-behavior/references/action-contract.md +31 -0
  88. package/skills/dingtalk-basic-behavior/references/event-to-behavior.md +24 -0
  89. package/skills/dingtalk-basic-behavior/references/memory-and-evolution.md +27 -0
  90. package/skills/dingtalk-basic-behavior/references/runtime-modes.md +34 -0
  91. package/skills/dingtalk-basic-behavior/references/task-lifecycle.md +108 -0
  92. package/skills//345/237/272/347/241/200/350/241/214/344/270/272.md +44 -0
  93. package/skills//345/277/203/350/267/263.md +11 -0
  94. package/skills//346/266/210/346/201/257.md +14 -14
  95. package/skills//350/257/204/346/265/213.md +14 -1
  96. package/skills//351/222/211/351/222/211.md +3 -2
  97. package/templates/behaviors/basic.json +68 -0
  98. package/templates/fields/default/field.json +25 -0
  99. package/bin/dingtalk-agent.js +0 -289
  100. package/src/boot.js +0 -65
  101. package/src/config.js +0 -42
  102. package/src/dws.js +0 -192
  103. package/src/init.js +0 -84
  104. package/src/kb.js +0 -221
  105. package/src/runs.js +0 -77
@@ -0,0 +1,562 @@
1
+ // Basic Behavior 的四个原子动作(TypeScript source)。
2
+ // Sandbox 中的 context/ 是可读投影;真正的 target/profile/policy/state 来自 sandbox 外 event index。
3
+ import { existsSync, mkdirSync, realpathSync, readdirSync } from 'node:fs';
4
+ import { dirname, join, resolve, parse, basename } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { digest, stableStringify } from './events.js';
7
+ import { acquireControlLock, acquireExecutionLock, readJson, writeJsonAtomic, } from './sessions.js';
8
+ import * as cfgmod from './config.js';
9
+ import * as dws from './dws.js';
10
+ import { verifySkillSnapshot } from './skills.js';
11
+ import { acquireSessionEffectLock, armWait, completeWaitFromReceipt, markWaitTransportAccepted, reconcileWaitFromReceipt, } from './waits.js';
12
+ const OUTWARD = new Set(['ack', 'reply', 'ask']);
13
+ const TERMINAL = new Set(['reply', 'ask', 'silence']);
14
+ const KINDS = new Set(['ack', 'reply', 'ask', 'silence']);
15
+ const SILENCE_REASONS = new Set([
16
+ 'unmentioned', 'already_answered', 'no_value', 'policy_denied', 'unsupported',
17
+ 'heartbeat_noop',
18
+ ]);
19
+ class ActionUncertainError extends Error {
20
+ receipt;
21
+ constructor(message, receipt) {
22
+ super(message);
23
+ this.name = 'ActionUncertainError';
24
+ this.receipt = receipt;
25
+ }
26
+ }
27
+ export function findRun(start = process.cwd(), explicit = '') {
28
+ const picked = explicit || process.env.DTA_RUN || start;
29
+ let dir = resolve(picked);
30
+ while (true) {
31
+ if (existsSync(join(dir, 'run.json')))
32
+ return dir;
33
+ const parent = dirname(dir);
34
+ if (parent === dir || dir === parse(dir).root)
35
+ break;
36
+ dir = parent;
37
+ }
38
+ throw new Error('找不到当前 Run;请在 prepare 返回的 cwd 中执行,或设置 DTA_RUN/--run');
39
+ }
40
+ export function previewAction(runPath, kind, options = {}) {
41
+ const context = loadContext(runPath);
42
+ const payload = normalizePayload(kind, options, context.policy);
43
+ const nextState = validate(context, kind);
44
+ return {
45
+ type: 'dingtalk-agent.action.preview',
46
+ runId: context.run.id,
47
+ kind,
48
+ fromState: context.run.state,
49
+ toState: nextState,
50
+ transport: transportName(kind),
51
+ target: kind === 'silence' ? null : context.target,
52
+ profile: context.field.dws.profile || '',
53
+ expectedUserId: context.field.dws.expectedUserId || '',
54
+ transportMode: context.field.transport.mode || '',
55
+ egressOwner: context.field.transport.egressOwner || '',
56
+ payload,
57
+ authorityHash: context.index.authorityHash,
58
+ persisted: false,
59
+ sideEffect: false,
60
+ };
61
+ }
62
+ export function executeAction(runPath, kind, options = {}) {
63
+ if (!KINDS.has(kind))
64
+ throw new Error(`原子动作只能是: ${[...KINDS].join(' / ')}`);
65
+ let context = loadContext(runPath);
66
+ const payload = normalizePayload(kind, options, context.policy);
67
+ const actionId = `act_${digest(`${context.run.id}\0${kind}\0${JSON.stringify(payload)}`).slice(0, 20)}`;
68
+ let actionPath = join(context.controlActionRoot, actionId);
69
+ let receiptPath = join(actionPath, 'receipt.json');
70
+ // Session effect lock 把 cancel 与外部副作用线性化;先拿到锁的一方定义先后。
71
+ // event execution lock 仍负责同一个 Run 的 Action 幂等,control lock 只做短时 RMW。
72
+ const releaseSessionEffect = acquireSessionEffectLock(context.root, context.sessionPath);
73
+ try {
74
+ const release = acquireExecutionLock(context.indexPath);
75
+ try {
76
+ context = loadContext(runPath);
77
+ reconcileReceipts(context);
78
+ context = loadContext(runPath);
79
+ actionPath = join(context.controlActionRoot, actionId);
80
+ receiptPath = join(actionPath, 'receipt.json');
81
+ if (existsSync(receiptPath)) {
82
+ const receipt = readJson(receiptPath);
83
+ reconcileReceiptWait(context, receipt);
84
+ return replayReceipt(context, receipt);
85
+ }
86
+ assertNoOtherUnresolvedAttempt(context, actionId);
87
+ const nextState = validate(context, kind);
88
+ mkdirSync(actionPath, { recursive: true });
89
+ const intentPath = join(actionPath, 'intent.json');
90
+ const attemptPath = join(actionPath, 'attempt.json');
91
+ let intent;
92
+ if (existsSync(intentPath)) {
93
+ intent = readJson(intentPath);
94
+ if (intent.kind !== kind || JSON.stringify(intent.payload) !== JSON.stringify(payload)) {
95
+ throw new Error(`Action intent 碰撞: ${actionId}`);
96
+ }
97
+ }
98
+ else {
99
+ intent = {
100
+ $schema: 'dingtalk-agent/action-intent@1',
101
+ id: actionId,
102
+ runId: context.run.id,
103
+ kind,
104
+ createdAt: new Date().toISOString(),
105
+ transport: transportName(kind),
106
+ target: kind === 'silence' ? null : context.target,
107
+ dwsProfile: context.field.dws.profile || '',
108
+ expectedUserId: context.field.dws.expectedUserId || '',
109
+ transportMode: context.field.transport.mode || '',
110
+ egressOwner: context.field.transport.egressOwner || '',
111
+ uuid: OUTWARD.has(kind) ? randomUUID() : null,
112
+ payload,
113
+ authorityHash: context.index.authorityHash,
114
+ };
115
+ persistArtifact(context, actionPath, 'intent.json', intent);
116
+ }
117
+ if (kind === 'silence') {
118
+ const receipt = finish(context, intent, nextState, {
119
+ outcome: 'confirmed', verified: true, verification: 'local-no-side-effect',
120
+ });
121
+ persistReceipt(context, actionPath, receipt);
122
+ completeWaitFromReceipt(context.root, cfgmod.must(context.root), context.run.resume, receipt);
123
+ projectReceipt(context, receipt);
124
+ return receipt;
125
+ }
126
+ verifyExecutionIdentity(context, intent, actionPath);
127
+ const wait = kind === 'ask' ? ensureAskWait(context, actionId, payload.text) : null;
128
+ if (kind === 'ack' && existsSync(attemptPath)) {
129
+ const receipt = uncertain(context, intent, 'ack 已有 attempt 但没有 receipt;表情动作无服务端幂等键,拒绝盲重试');
130
+ persistReceipt(context, actionPath, receipt);
131
+ projectReceipt(context, receipt);
132
+ return receipt;
133
+ }
134
+ if (!existsSync(attemptPath)) {
135
+ persistArtifact(context, actionPath, 'attempt.json', {
136
+ actionId, startedAt: new Date().toISOString(),
137
+ });
138
+ }
139
+ let result;
140
+ let checked;
141
+ try {
142
+ const transportResultPath = join(actionPath, 'transport-result.json');
143
+ if (existsSync(transportResultPath)) {
144
+ // DWS 已返回且结果已落盘时,从本地继续验证;绝不为了补 Receipt 再发一次。
145
+ result = readJson(transportResultPath);
146
+ }
147
+ else {
148
+ result = kind === 'ack'
149
+ ? dws.ackMessage(context.target, {
150
+ emoji: payload.emoji, profile: intent.dwsProfile,
151
+ })
152
+ : dws.replyMessage(context.target, payload.text, {
153
+ uuid: intent.uuid, profile: intent.dwsProfile,
154
+ });
155
+ persistArtifact(context, actionPath, 'transport-result.json', result);
156
+ }
157
+ if (kind === 'ask')
158
+ markWaitTransportAccepted(context.root, cfgmod.must(context.root), wait, result);
159
+ checked = verify(kind, context.target, result, intent.dwsProfile);
160
+ if (checked.data !== undefined) {
161
+ persistArtifact(context, actionPath, 'verification.json', checked.data);
162
+ }
163
+ }
164
+ catch (e) {
165
+ const receipt = uncertain(context, intent, String(e.message || e));
166
+ persistReceipt(context, actionPath, receipt);
167
+ if (kind === 'ask')
168
+ reconcileWaitFromReceipt(context.root, cfgmod.must(context.root), wait, receipt);
169
+ projectReceipt(context, receipt);
170
+ throw new ActionUncertainError(`动作结果不确定,禁止自动重发;action=${actionId}: ${e.message || e}`, receipt);
171
+ }
172
+ const receipt = finish(context, intent, nextState, checked);
173
+ persistReceipt(context, actionPath, receipt); // 事实先落盘
174
+ if (kind === 'ask')
175
+ reconcileWaitFromReceipt(context.root, cfgmod.must(context.root), wait, receipt);
176
+ if (kind === 'reply')
177
+ completeWaitFromReceipt(context.root, cfgmod.must(context.root), context.run.resume, receipt);
178
+ projectReceipt(context, receipt); // 再更新 control/run 投影
179
+ return receipt;
180
+ }
181
+ finally {
182
+ release();
183
+ }
184
+ }
185
+ finally {
186
+ releaseSessionEffect();
187
+ }
188
+ }
189
+ /**
190
+ * 权威数据只从 event index 读取。Run 目录里的静态上下文发生漂移时 fail closed;
191
+ * 动态 run.json 只是可修复投影,不能反过来阻塞已落盘的 Receipt。
192
+ * 这也让 --run /任意伪造目录 无法获得 DWS 外发能力。
193
+ */
194
+ function loadContext(runPath) {
195
+ const actualRunPath = realpathSync(resolve(runPath));
196
+ const projection = readJson(join(actualRunPath, 'run.json'));
197
+ const root = process.env.DTA_ROOT
198
+ ? resolve(process.env.DTA_ROOT)
199
+ : cfgmod.findRoot(actualRunPath);
200
+ if (!root)
201
+ throw new Error('找不到 control store;act 必须由能访问 DTA_ROOT 的宿主侧执行');
202
+ const cfg = cfgmod.must(root);
203
+ const indexRoot = resolve(root, cfg.runtime?.eventIndexRoot || '.dingtalk-agent/event-index');
204
+ const indexPath = join(indexRoot, `${digest(projection.eventId)}.json`);
205
+ if (!existsSync(indexPath))
206
+ throw new Error('当前 Run 不在 event index 中;拒绝任意/伪造 --run');
207
+ const index = readJson(indexPath);
208
+ if (!index.authority || !index.control ||
209
+ digest(stableStringify(index.authority)) !== index.authorityHash) {
210
+ throw new Error('event index 的权威快照损坏,禁止执行');
211
+ }
212
+ if (realpathSync(index.runPath) !== actualRunPath ||
213
+ index.runId !== index.control.id || index.eventId !== projection.eventId) {
214
+ throw new Error('Run 与 event index 身份不一致,拒绝执行');
215
+ }
216
+ if (stableStringify(projection) !== stableStringify(index.control)) {
217
+ mirrorJson(join(actualRunPath, 'run.json'), index.control);
218
+ }
219
+ const drift = [];
220
+ const targetProjection = readJson(join(actualRunPath, 'context', 'reply-target.json'));
221
+ if (stableStringify(targetProjection) !== stableStringify(index.authority.replyTarget))
222
+ drift.push('reply-target.json');
223
+ const policyProjection = readJson(join(actualRunPath, 'policy', 'allowed-actions.json'));
224
+ if (stableStringify(policyProjection) !== stableStringify(index.authority.policy))
225
+ drift.push('allowed-actions.json');
226
+ const fieldProjection = readJson(join(actualRunPath, 'context', 'field.json'));
227
+ if (stableStringify(fieldProjection.dws || {}) !== stableStringify(index.authority.dws || {}))
228
+ drift.push('field.dws');
229
+ if (stableStringify(fieldProjection.transport || {}) !== stableStringify(index.authority.transport || {}))
230
+ drift.push('field.transport');
231
+ const behaviorProjection = readJson(join(actualRunPath, 'context', 'behavior.json'));
232
+ if (behaviorProjection.hash !== index.authority.behaviorHash)
233
+ drift.push('behavior.json');
234
+ const eventProjection = readJson(join(actualRunPath, 'event.json'));
235
+ if (digest(stableStringify(eventProjection)) !== index.authority.eventHash)
236
+ drift.push('event.json');
237
+ if (index.authority.resume) {
238
+ const resumeProjection = readJson(join(actualRunPath, 'context', 'resume.json'));
239
+ if (stableStringify(resumeProjection) !== stableStringify(index.authority.resume)) {
240
+ drift.push('resume.json');
241
+ }
242
+ }
243
+ try {
244
+ verifySkillSnapshot(actualRunPath, index.authority.skillManifestHash);
245
+ }
246
+ catch (e) {
247
+ drift.push(`skill-snapshot(${e.message})`);
248
+ }
249
+ if (drift.length)
250
+ throw new Error(`Sandbox 权威投影被修改: ${drift.join(', ')};禁止执行`);
251
+ const session = readJson(join(index.sessionPath, 'session.json'));
252
+ const currentGeneration = validGeneration(session.generation, 'session.json');
253
+ const runGeneration = validGeneration(index.authority.sessionGeneration ?? index.control.sessionGeneration, 'event index');
254
+ if (currentGeneration !== runGeneration) {
255
+ throw new Error(`Session generation 已失效:run=${runGeneration}, current=${currentGeneration};` +
256
+ '该事项已被 /stop 或 /cancel 取消,禁止继续副作用');
257
+ }
258
+ const controlActionRoot = join(indexRoot, 'actions', index.runId);
259
+ mkdirSync(controlActionRoot, { recursive: true });
260
+ return {
261
+ run: index.control,
262
+ field: { dws: index.authority.dws || {}, transport: index.authority.transport || {} },
263
+ policy: index.authority.policy,
264
+ target: index.authority.replyTarget,
265
+ authority: index.authority,
266
+ index,
267
+ indexPath,
268
+ controlActionRoot,
269
+ runPath: actualRunPath,
270
+ sessionPath: index.sessionPath,
271
+ event: eventProjection,
272
+ root,
273
+ };
274
+ }
275
+ function ensureAskWait(context, actionId, questionText = '') {
276
+ return armWait(context.root, cfgmod.must(context.root), {
277
+ fieldId: context.run.fieldId,
278
+ sessionId: context.run.sessionId,
279
+ sessionPath: context.sessionPath,
280
+ sourceRunId: context.run.id,
281
+ actionId,
282
+ questionText,
283
+ event: context.event,
284
+ target: context.target,
285
+ });
286
+ }
287
+ function reconcileAskWait(context, actionId, receipt, questionText = '') {
288
+ const wait = ensureAskWait(context, actionId, questionText);
289
+ return reconcileWaitFromReceipt(context.root, cfgmod.must(context.root), wait, receipt);
290
+ }
291
+ function reconcileReceiptWait(context, receipt) {
292
+ if (receipt.kind === 'ask') {
293
+ const intentPath = join(context.controlActionRoot, receipt.actionId, 'intent.json');
294
+ const intent = existsSync(intentPath) ? readJson(intentPath) : null;
295
+ return reconcileAskWait(context, receipt.actionId, receipt, intent?.payload?.text || '');
296
+ }
297
+ if ((receipt.kind === 'reply' || receipt.kind === 'silence') &&
298
+ receipt.outcome !== 'uncertain') {
299
+ return completeWaitFromReceipt(context.root, cfgmod.must(context.root), context.run.resume, receipt);
300
+ }
301
+ return null;
302
+ }
303
+ function normalizePayload(kind, options, policy) {
304
+ if (!KINDS.has(kind))
305
+ throw new Error(`原子动作只能是: ${[...KINDS].join(' / ')}`);
306
+ if (kind === 'ack')
307
+ return { emoji: '收到' };
308
+ if (kind === 'silence') {
309
+ const reason = String(options.reason || 'no_value').trim();
310
+ if (!SILENCE_REASONS.has(reason)) {
311
+ throw new Error(`silence reason 必须是: ${[...SILENCE_REASONS].join(' / ')}`);
312
+ }
313
+ return { reason };
314
+ }
315
+ const text = String(options.text || '').trim();
316
+ if (!text)
317
+ throw new Error(`${kind} 需要 --text 或 --text-file`);
318
+ const max = Number(policy.limits?.maxTextCharacters || 4000);
319
+ if (text.length > max)
320
+ throw new Error(`正文 ${text.length} 字,超过 Basic Behavior 上限 ${max}`);
321
+ return { text };
322
+ }
323
+ function validate(context, kind) {
324
+ const { run, policy, target } = context;
325
+ if (!(policy.allowedActions || []).includes(kind)) {
326
+ throw new Error(`事件 ${run.eventKind} 不允许 ${kind};允许: ${(policy.allowedActions || []).join(', ')}`);
327
+ }
328
+ if (OUTWARD.has(kind) && (!target?.conversationId || !target?.messageId || !target?.senderOpenDingTalkId)) {
329
+ throw new Error('Run 没有完整固定回复目标,禁止外发');
330
+ }
331
+ if (OUTWARD.has(kind)) {
332
+ if (context.field.transport.egressOwner !== 'dingtalk-agent') {
333
+ throw new Error(`Field 的出口属于 ${context.field.transport.egressOwner || 'unknown'},禁止 act 外发以避免双发`);
334
+ }
335
+ const profile = context.field.dws.profile || '';
336
+ const expected = context.field.dws.expectedUserId || '';
337
+ if (!profile)
338
+ throw new Error('Workspace 没有固定 dws.profile,禁止依赖“当前登录身份”外发');
339
+ if (profile.includes(','))
340
+ throw new Error('一个 Run 只能固定一个 dws.profile,禁止多组织广播式执行');
341
+ if (!expected)
342
+ throw new Error('Workspace 没有 expectedUserId,无法核对 DWS 实际执行身份');
343
+ }
344
+ const transition = policy.stateMachine?.transitions?.[run.state]?.[kind];
345
+ if (!transition)
346
+ throw new Error(`状态 ${run.state} 不接受动作 ${kind}`);
347
+ const counts = run.actionCounts || {};
348
+ const limits = policy.limits || {};
349
+ if (kind === 'ack' && Number(counts.ack || 0) >= Number(limits.maxAckPerRun || 1)) {
350
+ throw new Error('本 Run 已 ack,禁止重复刷表情');
351
+ }
352
+ if (OUTWARD.has(kind) && Number(counts.outward || 0) >= Number(limits.maxOutwardActionsPerRun || 2)) {
353
+ throw new Error('本 Run 的外发预算已用完');
354
+ }
355
+ if (TERMINAL.has(kind) && Number(counts.terminal || 0) >= Number(limits.maxTerminalMessagesPerRun || 1)) {
356
+ throw new Error('本 Run 已产生终态动作');
357
+ }
358
+ return transition;
359
+ }
360
+ function verifyExecutionIdentity(context, intent, actionPath) {
361
+ // profile 同名重新登录会换掉真实凭据身份;因此每个外发 Action 都现查,不跨 Action 缓存。
362
+ const data = dws.getSelf(intent.dwsProfile);
363
+ const userId = String(findValue(data, ['userId', 'user_id', 'userid']) || '');
364
+ if (!userId)
365
+ throw new Error('dws contact user get-self 没有返回 userId,禁止外发');
366
+ if (userId !== String(intent.expectedUserId)) {
367
+ throw new Error(`DWS 执行身份不符:expected=${intent.expectedUserId}, actual=${userId}`);
368
+ }
369
+ const verified = { profile: intent.dwsProfile, userId, verifiedAt: new Date().toISOString(), data };
370
+ persistArtifact(context, actionPath, 'identity.json', verified);
371
+ return verified;
372
+ }
373
+ function verify(kind, target, result, profile) {
374
+ if (kind === 'ack') {
375
+ const data = dws.readMessageEmotions(target.messageId, profile);
376
+ return { outcome: 'accepted-unverified', verified: false,
377
+ verification: 'reaction-readback-cannot-prove-current-actor', data };
378
+ }
379
+ const taskId = findValue(result, ['openTaskId', 'open_task_id']);
380
+ if (taskId) {
381
+ const data = dws.querySendStatus(taskId, profile);
382
+ const sentId = findValue(data, ['openMessageId', 'openMsgId', 'open_message_id']);
383
+ return sentId
384
+ ? { outcome: 'confirmed', verified: true, verification: 'query-send-status', data }
385
+ : { outcome: 'accepted-unverified', verified: false,
386
+ verification: 'query-send-status-without-message-id', data };
387
+ }
388
+ const messageId = findValue(result, ['openMessageId', 'openMsgId', 'open_message_id']);
389
+ if (messageId) {
390
+ const data = dws.readMessagesByIds(messageId, profile);
391
+ const seen = data && JSON.stringify(data).includes(String(messageId));
392
+ return seen
393
+ ? { outcome: 'confirmed', verified: true, verification: 'message-readback', data }
394
+ : { outcome: 'accepted-unverified', verified: false,
395
+ verification: 'message-readback-miss', data };
396
+ }
397
+ return { outcome: 'accepted-unverified', verified: false,
398
+ verification: 'reply-result-has-no-queryable-id', data: result };
399
+ }
400
+ function finish(context, intent, nextState, checked) {
401
+ return {
402
+ $schema: 'dingtalk-agent/action-receipt@1',
403
+ actionId: intent.id,
404
+ runId: intent.runId,
405
+ kind: intent.kind,
406
+ completedAt: new Date().toISOString(),
407
+ fromState: context.run.state,
408
+ toState: nextState,
409
+ ...checked,
410
+ };
411
+ }
412
+ function uncertain(context, intent, reason) {
413
+ return finish(context, intent, 'needs-reconciliation', {
414
+ outcome: 'uncertain', verified: false, verification: reason,
415
+ });
416
+ }
417
+ function replayReceipt(context, receipt) {
418
+ projectReceipt(context, receipt);
419
+ return { ...receipt, duplicate: true };
420
+ }
421
+ function projectReceipt(context, receipt) {
422
+ const release = acquireControlLock(context.indexPath);
423
+ try {
424
+ const latest = readJson(context.indexPath);
425
+ if (digest(stableStringify(latest.authority)) !== latest.authorityHash) {
426
+ throw new Error('投影 Receipt 时 authority hash 不一致');
427
+ }
428
+ const current = latest.control;
429
+ const applied = new Set(current.appliedActionIds || []);
430
+ if (applied.has(receipt.actionId)) {
431
+ mirrorJson(join(context.runPath, 'run.json'), current);
432
+ context.index = latest;
433
+ context.run = current;
434
+ return current;
435
+ }
436
+ // 兼容旧 control:若计数已表明该 kind 投影过,只回填 actionId,不重复计数/转移。
437
+ if (Number(current.actionCounts?.[receipt.kind] || 0) > 0) {
438
+ const next = { ...current, appliedActionIds: [...applied, receipt.actionId] };
439
+ const updated = { ...latest, control: next, updatedAt: new Date().toISOString() };
440
+ writeJsonAtomic(context.indexPath, updated);
441
+ context.index = updated;
442
+ context.run = next;
443
+ mirrorJson(join(context.runPath, 'run.json'), next);
444
+ return next;
445
+ }
446
+ if (current.state !== receipt.fromState) {
447
+ throw new Error(`Receipt 状态冲突: control=${current.state}, receipt=${receipt.fromState}→${receipt.toState}`);
448
+ }
449
+ const next = {
450
+ ...current,
451
+ updatedAt: receipt.completedAt,
452
+ state: receipt.toState,
453
+ appliedActionIds: [...applied, receipt.actionId],
454
+ };
455
+ bump(next, receipt.kind);
456
+ if (receipt.toState === 'needs-reconciliation')
457
+ next.status = 'blocked';
458
+ else if (receipt.toState === 'waiting-input')
459
+ next.status = receipt.verified ? 'waiting-input' : 'waiting-input-unverified';
460
+ else if (receipt.toState === 'ignored')
461
+ next.status = 'completed';
462
+ else if (receipt.toState === 'completed')
463
+ next.status = receipt.verified ? 'completed' : 'completed-unverified';
464
+ else
465
+ next.status = 'active';
466
+ const updated = { ...latest, control: next, updatedAt: new Date().toISOString() };
467
+ writeJsonAtomic(context.indexPath, updated);
468
+ context.index = updated;
469
+ context.run = next;
470
+ mirrorJson(join(context.runPath, 'run.json'), next);
471
+ return next;
472
+ }
473
+ finally {
474
+ release();
475
+ }
476
+ }
477
+ /** 已有 Receipt 是真值;新动作前先把“Receipt 已落盘、control 未更新”的窗口收敛。 */
478
+ function reconcileReceipts(context) {
479
+ const receipts = [];
480
+ for (const entry of readdirSync(context.controlActionRoot, { withFileTypes: true })) {
481
+ if (!entry.isDirectory())
482
+ continue;
483
+ const path = join(context.controlActionRoot, entry.name, 'receipt.json');
484
+ if (existsSync(path))
485
+ receipts.push(readJson(path));
486
+ }
487
+ receipts.sort((a, b) => String(a.completedAt).localeCompare(String(b.completedAt)));
488
+ for (const receipt of receipts) {
489
+ reconcileReceiptWait(context, receipt);
490
+ projectReceipt(context, receipt);
491
+ }
492
+ }
493
+ /** 旧 Action 可能已命中 DWS 但尚无 Receipt;此时换文本会生成新 actionId,必须 fail closed。 */
494
+ function assertNoOtherUnresolvedAttempt(context, currentActionId) {
495
+ for (const entry of readdirSync(context.controlActionRoot, { withFileTypes: true })) {
496
+ if (!entry.isDirectory() || entry.name === currentActionId)
497
+ continue;
498
+ const path = join(context.controlActionRoot, entry.name);
499
+ if (existsSync(join(path, 'attempt.json')) && !existsSync(join(path, 'receipt.json'))) {
500
+ throw new Error(`Run 存在未对账 Action ${entry.name};禁止更换正文再外发,请先 reconcile`);
501
+ }
502
+ }
503
+ }
504
+ function bump(run, kind) {
505
+ run.actionCounts = { ack: 0, reply: 0, ask: 0, silence: 0, outward: 0, terminal: 0,
506
+ ...(run.actionCounts || {}) };
507
+ run.actionCounts[kind]++;
508
+ if (OUTWARD.has(kind))
509
+ run.actionCounts.outward++;
510
+ if (TERMINAL.has(kind))
511
+ run.actionCounts.terminal++;
512
+ }
513
+ function persistArtifact(context, actionPath, name, value) {
514
+ writeJsonAtomic(join(actionPath, name), value);
515
+ const mirrorDir = join(context.runPath, 'actions', basename(actionPath));
516
+ try {
517
+ mkdirSync(mirrorDir, { recursive: true });
518
+ writeJsonAtomic(join(mirrorDir, name), value);
519
+ }
520
+ catch (e) {
521
+ console.error(` ⚠️ sandbox 投影写入失败(control store 已保留真值): ${e.message}`);
522
+ }
523
+ }
524
+ function persistReceipt(context, actionPath, receipt) {
525
+ persistArtifact(context, actionPath, 'receipt.json', receipt);
526
+ mirrorJson(join(context.runPath, 'receipts', `${receipt.actionId}.json`), receipt);
527
+ }
528
+ function mirrorJson(path, value) {
529
+ try {
530
+ writeJsonAtomic(path, value);
531
+ }
532
+ catch (e) {
533
+ console.error(` ⚠️ sandbox 投影写入失败(control store 已保留真值): ${e.message}`);
534
+ }
535
+ }
536
+ function transportName(kind) {
537
+ if (kind === 'ack')
538
+ return 'dws.chat.message.add-emoji';
539
+ if (kind === 'reply' || kind === 'ask')
540
+ return 'dws.chat.message.reply';
541
+ return 'local.silence';
542
+ }
543
+ function findValue(value, keys) {
544
+ if (!value || typeof value !== 'object')
545
+ return '';
546
+ for (const key of keys)
547
+ if (value[key])
548
+ return value[key];
549
+ for (const child of Object.values(value)) {
550
+ const found = findValue(child, keys);
551
+ if (found)
552
+ return found;
553
+ }
554
+ return '';
555
+ }
556
+ function validGeneration(value, label) {
557
+ const n = Number(value ?? 1);
558
+ if (!Number.isInteger(n) || n < 1)
559
+ throw new Error(`${label} 的 Session generation 非法`);
560
+ return n;
561
+ }
562
+ //# sourceMappingURL=actions.js.map