@1agents/acp-service 0.8.1 → 0.8.3

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 (103) hide show
  1. package/README.md +37 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/src/a2a/executor.d.ts +2 -0
  4. package/dist/src/a2a/executor.js +63 -10
  5. package/dist/src/a2a/gateway.d.ts +407 -14
  6. package/dist/src/a2a/gateway.js +719 -37
  7. package/dist/src/a2a/index.d.ts +8 -1
  8. package/dist/src/a2a/index.js +4 -0
  9. package/dist/src/a2a/notices.d.ts +24 -0
  10. package/dist/src/a2a/notices.js +56 -0
  11. package/dist/src/a2a/preflight.d.ts +52 -0
  12. package/dist/src/a2a/preflight.js +153 -0
  13. package/dist/src/a2a/result-metadata.d.ts +59 -0
  14. package/dist/src/a2a/result-metadata.js +156 -0
  15. package/dist/src/a2a/server.js +30 -0
  16. package/dist/src/a2a/session-delivery.d.ts +69 -0
  17. package/dist/src/a2a/session-delivery.js +260 -0
  18. package/dist/src/a2a/session-hosts.d.ts +34 -0
  19. package/dist/src/a2a/session-hosts.js +211 -0
  20. package/dist/src/a2a/store.js +3 -1
  21. package/dist/src/a2a/types.d.ts +33 -0
  22. package/dist/src/execution/delivery-progress.d.ts +108 -0
  23. package/dist/src/execution/delivery-progress.js +57 -0
  24. package/dist/src/execution/ledger.d.ts +235 -0
  25. package/dist/src/execution/ledger.js +396 -0
  26. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  27. package/dist/src/execution/ppt-delivery.js +625 -0
  28. package/dist/src/execution/targets.d.ts +349 -0
  29. package/dist/src/execution/targets.js +428 -0
  30. package/package.json +11 -12
  31. package/skills/acp-service/SKILL.md +9 -2
  32. package/skills/acp-service/references/a2a.md +72 -4
  33. package/vendor/dsh/a2a-executor.d.ts +2 -1
  34. package/vendor/dsh/a2a-executor.js +28 -1
  35. package/vendor/dsh/a2a.js +1 -0
  36. package/vendor/dsh/client.js +95 -27
  37. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  38. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  39. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  40. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  41. package/vendor/runtime/dist/agent-registry.js +1 -2
  42. package/vendor/runtime/dist/{cli-Bdzplbpj.js → cli-DeOpE2Xz.js} +4 -4
  43. package/vendor/runtime/dist/{cli-Bdzplbpj.js.map → cli-DeOpE2Xz.js.map} +1 -1
  44. package/vendor/runtime/dist/cli.d.ts +2 -1
  45. package/vendor/runtime/dist/cli.js +10 -10
  46. package/vendor/runtime/dist/cli.js.map +1 -1
  47. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  48. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  51. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  52. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  53. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  54. package/vendor/runtime/dist/docs-site/config.html +450 -0
  55. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  56. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  57. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  58. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  59. package/vendor/runtime/dist/docs-site/index.html +367 -0
  60. package/vendor/runtime/dist/docs-site/install.html +386 -0
  61. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  62. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  63. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  64. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  65. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  66. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  67. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  68. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  69. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/{flows-BKlAuzM8.js → flows-oaBGn31w.js} +5 -5
  75. package/vendor/runtime/dist/{flows-BKlAuzM8.js.map → flows-oaBGn31w.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +2 -2
  77. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  78. package/vendor/runtime/dist/flows.js +1 -2
  79. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js → invocation-options-CUDEE8vW.js} +5 -5
  80. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  81. package/vendor/runtime/dist/{ipc-CLv2iL89.js → ipc-BQQpcEdP.js} +98 -20
  82. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  83. package/vendor/runtime/dist/{output-I-t-v55D.js → output-CFv3jcOQ.js} +86 -22
  84. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  85. package/vendor/runtime/dist/{queue-owner-runtime-RN3uSid0.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  86. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  87. package/vendor/runtime/dist/runtime.d.ts +5 -2
  88. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  89. package/vendor/runtime/dist/runtime.js +77 -29
  90. package/vendor/runtime/dist/runtime.js.map +1 -1
  91. package/vendor/runtime/dist/{session-options-DNnDfiUt.d.ts → session-options-NjpFwf-c.d.ts} +5 -1
  92. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  93. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js → session-watch-Di-wIdCH.js} +4 -4
  94. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  95. package/vendor/runtime/dist/{watch-BE-kKa7o.js → watch-CIpoMaWD.js} +2 -2
  96. package/vendor/runtime/dist/{watch-BE-kKa7o.js.map → watch-CIpoMaWD.js.map} +1 -1
  97. package/vendor/runtime/package.json +1 -1
  98. package/vendor/runtime/skills/acpx/SKILL.md +7 -2
  99. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  100. package/vendor/runtime/dist/ipc-CLv2iL89.js.map +0 -1
  101. package/vendor/runtime/dist/output-I-t-v55D.js.map +0 -1
  102. package/vendor/runtime/dist/queue-owner-runtime-RN3uSid0.js.map +0 -1
  103. package/vendor/runtime/dist/session-options-DNnDfiUt.d.ts.map +0 -1
@@ -0,0 +1,396 @@
1
+ /** Durable Job/Attempt facts. This module does not execute or schedule work. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
4
+ const statuses = new Set(['not_started', 'submitted', 'working', 'input_required', 'auth_required', 'completed', 'failed', 'canceled', 'rejected', 'unknown']);
5
+ const clone = (value) => structuredClone(value);
6
+ const now = () => new Date().toISOString();
7
+ function nonempty(value, name) {
8
+ if (typeof value !== 'string' || !value.trim())
9
+ throw new Error(`${name} must be a nonempty string`);
10
+ }
11
+ /** Canonical JSON, including nested object keys; unsupported values cannot acquire a misleading digest. */
12
+ function canonical(value) {
13
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
14
+ return JSON.stringify(value);
15
+ if (typeof value === 'number' && Number.isFinite(value))
16
+ return JSON.stringify(value);
17
+ if (Array.isArray(value))
18
+ return `[${value.map(item => canonical(item)).join(',')}]`;
19
+ if (value && typeof value === 'object' && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
20
+ return `{${Object.keys(value).sort().filter(key => value[key] !== undefined)
21
+ .map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
22
+ }
23
+ throw new Error('Ledger request must contain JSON values');
24
+ }
25
+ function safeSnapshot(value) {
26
+ nonempty(value.targetId, 'targetId');
27
+ const inspect = (item) => {
28
+ if (!item || typeof item !== 'object')
29
+ return;
30
+ for (const [key, nested] of Object.entries(item)) {
31
+ if (/^(token|password|secret|authorization|apiKey|accessToken|refreshToken)$/i.test(key) && nested !== undefined) {
32
+ throw new Error(`Plaintext credential field is not allowed in targetSnapshot: ${key}`);
33
+ }
34
+ inspect(nested);
35
+ }
36
+ };
37
+ inspect(value);
38
+ canonical(value);
39
+ }
40
+ export class JobLedger {
41
+ persist;
42
+ state;
43
+ constructor(initial, persist) {
44
+ this.persist = persist;
45
+ if (initial) {
46
+ if (initial.version !== 1 || !initial.sourceId || !initial.jobs || !initial.attempts || !initial.requests || !Array.isArray(initial.events)
47
+ || !Number.isSafeInteger(initial.nextSequence) || !initial.acceptances)
48
+ throw new Error('Invalid execution ledger state');
49
+ this.state = clone(initial);
50
+ }
51
+ else {
52
+ this.state = { version: 1, sourceId: randomUUID(), jobs: {}, attempts: {}, requests: {}, events: [], nextSequence: 1, acceptances: {} };
53
+ }
54
+ }
55
+ snapshot() { return clone(this.state); }
56
+ /** Trusted adapter use only; public reads must call scoped get/list. */
57
+ getAttempt(attemptId) { return clone(this.attempt(this.state, attemptId)); }
58
+ get sourceId() { return this.state.sourceId; }
59
+ /** A crash during dispatch proves neither acceptance nor rejection; never silently send it again. */
60
+ recoverAfterRestart() {
61
+ const ids = Object.values(this.state.attempts).filter(attempt => attempt.submissionStatus === 'dispatching').map(attempt => attempt.attemptId);
62
+ if (!ids.length)
63
+ return [];
64
+ return this.mutate(state => {
65
+ for (const attemptId of ids) {
66
+ const attempt = state.attempts[attemptId];
67
+ attempt.submissionStatus = 'submission_unknown';
68
+ attempt.executionStatus = 'unknown';
69
+ attempt.stale = true;
70
+ attempt.diagnostic = 'Gateway restarted before backend acceptance was durably confirmed';
71
+ attempt.updatedAt = now();
72
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.submission_unknown', { reason: 'restart_during_dispatch' });
73
+ }
74
+ return ids;
75
+ });
76
+ }
77
+ mutate(operation) {
78
+ const next = clone(this.state), value = operation(next);
79
+ this.persist(clone(next)); // The caller atomically persists ledger together with task/notice facts.
80
+ this.state = next;
81
+ return clone(value);
82
+ }
83
+ job(state, origin, jobId) {
84
+ const job = state.jobs[jobId];
85
+ if (!job || job.originSessionId !== origin)
86
+ throw new Error('Job not found in origin scope');
87
+ return job;
88
+ }
89
+ attempt(state, attemptId) {
90
+ const attempt = Object.hasOwn(state.attempts, attemptId) ? state.attempts[attemptId] : undefined;
91
+ if (!attempt)
92
+ throw new Error('Attempt not found');
93
+ return attempt;
94
+ }
95
+ event(state, job, attemptId, type, data) {
96
+ const timestamp = now();
97
+ job.jobVersion++;
98
+ job.updatedAt = timestamp;
99
+ this.refresh(state, job);
100
+ state.events.push({ eventId: randomUUID(), sourceId: state.sourceId, sequence: state.nextSequence++, jobId: job.jobId,
101
+ attemptId, jobVersion: job.jobVersion, type, observedAt: timestamp, ...(data === undefined ? {} : { data: clone(data) }) });
102
+ }
103
+ refresh(state, job) {
104
+ const attempts = Object.values(state.attempts).filter(attempt => attempt.jobId === job.jobId);
105
+ job.executionStatus = state.attempts[job.currentAttemptId].executionStatus;
106
+ job.inFlightAttemptIds = attempts.filter(attempt => attempt.submissionStatus === 'accepted' && !terminal.has(attempt.executionStatus)).map(attempt => attempt.attemptId);
107
+ job.unresolvedAttemptIds = attempts.filter(attempt => attempt.submissionStatus === 'submission_unknown' || attempt.executionStatus === 'unknown').map(attempt => attempt.attemptId);
108
+ }
109
+ checkRef(state, origin, ref, name) {
110
+ if (ref.sourceId !== state.sourceId)
111
+ throw new Error(`${name} must use the same ledger source`);
112
+ return this.job(state, origin, ref.jobId);
113
+ }
114
+ requestIdentity(input) {
115
+ nonempty(input.originSessionId, 'originSessionId');
116
+ nonempty(input.targetSnapshot.targetId, 'targetId');
117
+ if (input.clientRequestId !== undefined)
118
+ nonempty(input.clientRequestId, 'clientRequestId');
119
+ const operation = input.operation ?? (input.jobId ? 'continue' : 'submit');
120
+ nonempty(operation, 'operation');
121
+ const request = { operation, targetId: input.targetSnapshot.targetId,
122
+ input: input.requestDigestInput === undefined ? input.input : input.requestDigestInput, jobId: input.jobId,
123
+ parentJobRef: input.parentJobRef, parentAttemptId: input.parentAttemptId, purpose: input.purpose,
124
+ title: input.title, resultRevision: input.resultRevision, replacesJobRef: input.replacesJobRef };
125
+ const digest = createHash('sha256').update(canonical(request)).digest('hex');
126
+ const requestKey = input.clientRequestId === undefined ? undefined : canonical([this.state.sourceId, input.originSessionId, operation, input.clientRequestId]);
127
+ return { operation, digest, requestKey };
128
+ }
129
+ /** Read-only idempotency check before resolving current target configuration or contacting a Provider. */
130
+ replay(input) {
131
+ const { digest, requestKey } = this.requestIdentity(input);
132
+ const existing = requestKey ? this.state.requests[requestKey] : undefined;
133
+ if (existing) {
134
+ if (existing.digest !== digest)
135
+ throw new Error('clientRequestId conflicts with an existing request');
136
+ return { job: clone(this.job(this.state, input.originSessionId, existing.jobId)), attempt: clone(this.state.attempts[existing.attemptId]), idempotent: true };
137
+ }
138
+ return undefined;
139
+ }
140
+ prepare(input) {
141
+ safeSnapshot(input.targetSnapshot);
142
+ const replay = this.replay(input);
143
+ if (replay)
144
+ return replay;
145
+ const { operation, digest, requestKey } = this.requestIdentity(input);
146
+ return this.mutate(state => {
147
+ const timestamp = now();
148
+ let job;
149
+ if (input.jobId) {
150
+ job = this.job(state, input.originSessionId, input.jobId);
151
+ if (job.targetId !== input.targetSnapshot.targetId)
152
+ throw new Error('Continue must preserve the original target');
153
+ if (Object.values(state.attempts).some(attempt => attempt.jobId === job.jobId && attempt.submissionStatus === 'submission_unknown')) {
154
+ throw new Error('Job has submission_unknown; reconcile before dispatching another attempt');
155
+ }
156
+ if (input.parentJobRef && canonical(input.parentJobRef) !== canonical(job.parentJobRef ?? null)
157
+ || input.parentAttemptId && input.parentAttemptId !== job.parentAttemptId)
158
+ throw new Error('A job cannot change its parent');
159
+ }
160
+ else {
161
+ if (Boolean(input.parentJobRef) !== Boolean(input.parentAttemptId))
162
+ throw new Error('parentJobRef and parentAttemptId are required together');
163
+ if (input.parentJobRef) {
164
+ const parent = this.checkRef(state, input.originSessionId, input.parentJobRef, 'parentJobRef');
165
+ if (this.attempt(state, input.parentAttemptId).jobId !== parent.jobId)
166
+ throw new Error('parentAttemptId does not belong to parent job');
167
+ }
168
+ if (input.replacesJobRef)
169
+ this.checkRef(state, input.originSessionId, input.replacesJobRef, 'replacesJobRef');
170
+ job = { sourceId: state.sourceId, jobId: randomUUID(), originSessionId: input.originSessionId, accessScopeRef: input.originSessionId,
171
+ originKind: 'session', originRef: input.originSessionId, targetId: input.targetSnapshot.targetId, currentAttemptId: '',
172
+ executionStatus: 'not_started', inFlightAttemptIds: [], unresolvedAttemptIds: [], jobVersion: 0, createdAt: timestamp,
173
+ updatedAt: timestamp, provenance: 'native', ...(input.title ? { title: input.title } : {}),
174
+ ...(input.targetSnapshot.roleId ? { roleId: input.targetSnapshot.roleId } : {}),
175
+ ...(input.parentJobRef ? { parentJobRef: clone(input.parentJobRef), parentAttemptId: input.parentAttemptId } : {}),
176
+ ...(input.purpose ? { purpose: input.purpose } : {}), ...(input.resultRevision ? { resultRevision: input.resultRevision } : {}),
177
+ ...(input.replacesJobRef ? { replacesJobRef: clone(input.replacesJobRef) } : {}) };
178
+ state.jobs[job.jobId] = job;
179
+ }
180
+ const attempt = { attemptId: randomUUID(), jobId: job.jobId, operation, requestDigest: digest,
181
+ ...(input.clientRequestId ? { clientRequestId: input.clientRequestId } : {}), targetId: input.targetSnapshot.targetId,
182
+ targetConfigVersion: input.targetSnapshot.configVersion ?? input.targetSnapshot.targetConfigVersion,
183
+ connectionId: input.targetSnapshot.connectionId, connectionVersion: input.targetSnapshot.connectionVersion,
184
+ provider: input.targetSnapshot.provider ?? 'a2a', targetSnapshot: clone(input.targetSnapshot), input: clone(input.input),
185
+ ...(job.currentAttemptId ? { previousAttemptId: job.currentAttemptId } : {}), submissionStatus: 'prepared',
186
+ executionStatus: 'not_started', stale: false, createdAt: timestamp, updatedAt: timestamp };
187
+ state.attempts[attempt.attemptId] = attempt;
188
+ job.currentAttemptId = attempt.attemptId;
189
+ if (requestKey)
190
+ state.requests[requestKey] = { digest, jobId: job.jobId, attemptId: attempt.attemptId };
191
+ this.event(state, job, attempt.attemptId, input.jobId ? 'attempt.prepared' : 'job.created', { operation });
192
+ return { job, attempt, idempotent: false };
193
+ });
194
+ }
195
+ markDispatching(attemptId) {
196
+ return this.mutate(state => {
197
+ const attempt = this.attempt(state, attemptId);
198
+ if (attempt.submissionStatus !== 'prepared')
199
+ throw new Error('Only a prepared attempt may begin dispatch');
200
+ attempt.submissionStatus = 'dispatching';
201
+ attempt.updatedAt = now();
202
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.dispatching');
203
+ return attempt;
204
+ });
205
+ }
206
+ accept(attemptId, backendRunRef, observation = {}) {
207
+ canonical(backendRunRef);
208
+ if (![backendRunRef.taskId, backendRunRef.flowRunId, backendRunRef.runId].some(value => typeof value === 'string' && value.trim()))
209
+ throw new Error('Backend acceptance requires a run reference');
210
+ return this.mutate(state => {
211
+ const attempt = this.attempt(state, attemptId);
212
+ if (!['dispatching', 'submission_unknown', 'accepted'].includes(attempt.submissionStatus))
213
+ throw new Error('Attempt is not awaiting backend acceptance');
214
+ if (attempt.backendRunRef) {
215
+ for (const [key, value] of Object.entries(attempt.backendRunRef)) {
216
+ if (backendRunRef[key] !== undefined && canonical(backendRunRef[key]) !== canonical(value))
217
+ throw new Error('Backend run reference cannot be replaced');
218
+ }
219
+ }
220
+ attempt.backendRunRef = { ...attempt.backendRunRef, ...clone(backendRunRef) };
221
+ attempt.submissionStatus = 'accepted';
222
+ this.applyObservation(attempt, { ...observation, executionStatus: observation.executionStatus ?? (attempt.executionStatus === 'not_started' ? 'submitted' : attempt.executionStatus) });
223
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.accepted', { backendRunRef: attempt.backendRunRef });
224
+ return attempt;
225
+ });
226
+ }
227
+ knownNotSubmitted(attemptId, input) {
228
+ if (!['failed', 'rejected', 'canceled'].includes(input.executionStatus))
229
+ throw new Error('A dispatch failure requires an execution terminal status');
230
+ return this.mutate(state => {
231
+ const attempt = this.attempt(state, attemptId);
232
+ if (!['prepared', 'dispatching', 'submission_unknown'].includes(attempt.submissionStatus))
233
+ throw new Error('An accepted attempt cannot become not submitted');
234
+ attempt.submissionStatus = 'known_not_submitted';
235
+ attempt.executionStatus = input.executionStatus;
236
+ attempt.diagnostic = input.diagnostic;
237
+ attempt.updatedAt = now();
238
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.submission_failed', input);
239
+ return attempt;
240
+ });
241
+ }
242
+ markUnknown(attemptId, diagnostic) {
243
+ return this.mutate(state => {
244
+ const attempt = this.attempt(state, attemptId);
245
+ if (!['dispatching', 'submission_unknown'].includes(attempt.submissionStatus))
246
+ throw new Error('Only an uncertain dispatch can become submission_unknown');
247
+ attempt.submissionStatus = 'submission_unknown';
248
+ attempt.executionStatus = 'unknown';
249
+ attempt.stale = true;
250
+ attempt.diagnostic = diagnostic;
251
+ attempt.updatedAt = now();
252
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.submission_unknown', { diagnostic });
253
+ return attempt;
254
+ });
255
+ }
256
+ applyObservation(attempt, input) {
257
+ const timestamp = input.checkedAt ?? now();
258
+ let conflict = false;
259
+ if (input.executionStatus !== undefined) {
260
+ if (!statuses.has(input.executionStatus))
261
+ throw new Error('Unknown execution status');
262
+ const previous = attempt.executionStatus, next = input.executionStatus;
263
+ if (terminal.has(previous) && next !== previous || previous === 'working' && ['not_started', 'submitted'].includes(next)
264
+ || previous !== 'not_started' && next === 'not_started') {
265
+ attempt.diagnostic = `Conflicting execution observation: ${previous} -> ${next}`;
266
+ conflict = true;
267
+ }
268
+ else
269
+ attempt.executionStatus = next;
270
+ }
271
+ if (input.providerState !== undefined && !conflict)
272
+ attempt.providerState = input.providerState;
273
+ if (input.phase !== undefined && !conflict)
274
+ attempt.phase = input.phase;
275
+ if (input.diagnostic !== undefined && !conflict)
276
+ attempt.diagnostic = input.diagnostic;
277
+ attempt.stale = input.stale ?? false;
278
+ attempt.checkedAt = timestamp;
279
+ attempt.updatedAt = timestamp;
280
+ if (!conflict && (input.resultSummary !== undefined || input.structuredResultRef !== undefined || input.resultDigest !== undefined
281
+ || input.artifactLinks !== undefined || input.resultAvailable !== undefined || input.resultRevision !== undefined)) {
282
+ const previous = attempt.result;
283
+ attempt.result = { ...previous, attemptId: attempt.attemptId, artifactLinks: clone(input.artifactLinks ?? previous?.artifactLinks ?? []),
284
+ resultAvailable: input.resultAvailable ?? previous?.resultAvailable ?? true, observedAt: timestamp,
285
+ ...(input.resultSummary !== undefined ? { resultSummary: input.resultSummary } : {}),
286
+ ...(input.structuredResultRef !== undefined ? { structuredResultRef: clone(input.structuredResultRef) } : {}),
287
+ ...(input.resultDigest !== undefined ? { resultDigest: input.resultDigest } : {}),
288
+ ...(input.resultRevision !== undefined ? { resultRevision: input.resultRevision } : {}) };
289
+ }
290
+ return conflict;
291
+ }
292
+ observe(attemptId, input) {
293
+ return this.mutate(state => {
294
+ const attempt = this.attempt(state, attemptId);
295
+ if (attempt.submissionStatus !== 'accepted')
296
+ throw new Error('Observe requires confirmed backend acceptance');
297
+ const previous = clone(attempt), conflict = this.applyObservation(attempt, input);
298
+ // Repeated polling with no changed facts updates checkedAt without growing the immutable event log.
299
+ const relevant = (item) => ({ status: item.executionStatus, providerState: item.providerState, phase: item.phase, stale: item.stale,
300
+ diagnostic: item.diagnostic, result: item.result ? { ...item.result, observedAt: undefined } : undefined });
301
+ if (canonical(relevant(previous)) !== canonical(relevant(attempt)))
302
+ this.event(state, state.jobs[attempt.jobId], attemptId, conflict ? 'attempt.observation_conflict' : previous.executionStatus !== attempt.executionStatus ? 'attempt.state_changed' : 'attempt.result_updated');
303
+ return attempt;
304
+ });
305
+ }
306
+ requestCancellation(attemptId) {
307
+ const existing = this.attempt(this.state, attemptId);
308
+ if (existing.cancellationRequestedAt)
309
+ return clone(existing);
310
+ return this.mutate(state => {
311
+ const attempt = this.attempt(state, attemptId);
312
+ attempt.cancellationRequestedAt ??= now();
313
+ attempt.updatedAt = now();
314
+ this.event(state, state.jobs[attempt.jobId], attemptId, 'attempt.cancellation_requested');
315
+ return attempt;
316
+ });
317
+ }
318
+ get(originSessionId, jobId) {
319
+ const job = this.job(this.state, originSessionId, jobId), current = this.state.attempts[job.currentAttemptId];
320
+ const history = this.state.acceptances[jobId] ?? [];
321
+ const acceptance = [...history].reverse().find(item => item.attemptId === current.attemptId
322
+ && item.resultRevision === current.result?.resultRevision && item.resultDigest === current.result?.resultDigest);
323
+ return clone({ ...job, attempts: Object.values(this.state.attempts).filter(item => item.jobId === jobId),
324
+ children: Object.values(this.state.jobs).filter(item => item.parentJobRef?.sourceId === this.sourceId && item.parentJobRef.jobId === jobId),
325
+ ...(current.result ? { result: current.result } : {}), ...(acceptance ? { businessAcceptance: acceptance } : {}), acceptanceHistory: history });
326
+ }
327
+ list(originSessionId) {
328
+ return Object.values(this.state.jobs).filter(job => job.originSessionId === originSessionId).map(job => this.get(originSessionId, job.jobId));
329
+ }
330
+ events(originSessionId, jobId, afterSequence = 0) {
331
+ if (jobId)
332
+ this.job(this.state, originSessionId, jobId);
333
+ return clone(this.state.events.filter(event => event.sequence > afterSequence && (!jobId || event.jobId === jobId)
334
+ && this.state.jobs[event.jobId]?.originSessionId === originSessionId));
335
+ }
336
+ findByBackend(originSessionId, ref) {
337
+ if (!ref.taskId && !ref.flowRunId)
338
+ throw new Error('Backend lookup requires a run ID');
339
+ const attempt = Object.values(this.state.attempts).find(item => this.state.jobs[item.jobId]?.originSessionId === originSessionId
340
+ && Object.entries(ref).every(([key, value]) => value === undefined || item.backendRunRef?.[key] === value));
341
+ return attempt ? clone({ job: this.state.jobs[attempt.jobId], attempt }) : undefined;
342
+ }
343
+ acceptance(originSessionId, jobId, input) {
344
+ return this.mutate(state => {
345
+ const job = this.job(state, originSessionId, jobId), attempt = this.attempt(state, input.attemptId);
346
+ if (attempt.jobId !== jobId || attempt.executionStatus !== 'completed')
347
+ throw new Error('Acceptance must reference a completed attempt of this job');
348
+ nonempty(input.resultRevision, 'resultRevision');
349
+ nonempty(input.resultDigest, 'resultDigest');
350
+ if (attempt.result?.resultRevision !== input.resultRevision || attempt.result?.resultDigest !== input.resultDigest)
351
+ throw new Error('Acceptance does not match the recorded result revision and digest');
352
+ if (!['pending', 'accepted', 'changes_requested'].includes(input.reviewStatus))
353
+ throw new Error('Unknown business acceptance status');
354
+ const record = { ...clone(input), recordedAt: now() };
355
+ (state.acceptances[jobId] ??= []).push(record);
356
+ this.event(state, job, input.attemptId, 'job.acceptance_recorded', record);
357
+ return record;
358
+ });
359
+ }
360
+ /** Each old Task gets one legacy Job; matching context IDs never merge jobs. */
361
+ migrateLegacy(records) {
362
+ return this.mutate(state => records.map(record => {
363
+ nonempty(record.originSessionId, 'originSessionId');
364
+ nonempty(record.remote, 'remote');
365
+ nonempty(record.taskId, 'taskId');
366
+ const existing = Object.values(state.attempts).find(item => state.jobs[item.jobId]?.originSessionId === record.originSessionId
367
+ && item.backendRunRef?.remote === record.remote && item.backendRunRef?.taskId === record.taskId);
368
+ if (existing)
369
+ return { remote: record.remote, taskId: record.taskId, jobId: existing.jobId, attemptId: existing.attemptId };
370
+ const timestamp = now(), jobId = randomUUID(), attemptId = randomUUID();
371
+ const snapshot = record.targetSnapshot ?? { targetId: `legacy:${record.remote}`, provider: 'a2a', remote: record.remote,
372
+ ...(record.cwd ? { cwd: record.cwd } : {}), ...(record.agentPreset ? { agentPreset: record.agentPreset } : {}) };
373
+ safeSnapshot(snapshot);
374
+ const executionStatus = record.executionStatus ?? 'unknown';
375
+ if (!statuses.has(executionStatus))
376
+ throw new Error('Invalid legacy execution status');
377
+ const attempt = { attemptId, jobId, operation: 'legacy_import', requestDigest: '', targetId: snapshot.targetId,
378
+ provider: 'a2a', targetSnapshot: clone(snapshot), input: null,
379
+ backendRunRef: { remote: record.remote, taskId: record.taskId, ...(record.contextId ? { contextId: record.contextId } : {}), ...(record.sessionId ? { sessionId: record.sessionId } : {}) },
380
+ submissionStatus: 'accepted', executionStatus, stale: record.stale ?? false, createdAt: record.createdAt ?? null,
381
+ updatedAt: record.checkedAt ?? timestamp, ...(record.checkedAt ? { checkedAt: record.checkedAt } : {}),
382
+ ...(record.providerState ? { providerState: record.providerState } : {}) };
383
+ if (record.resultSummary !== undefined || record.artifactLinks?.length)
384
+ attempt.result = { attemptId, resultSummary: record.resultSummary,
385
+ artifactLinks: clone(record.artifactLinks ?? []), resultAvailable: true, observedAt: record.checkedAt ?? timestamp };
386
+ const job = { sourceId: state.sourceId, jobId, originSessionId: record.originSessionId, accessScopeRef: record.originSessionId,
387
+ originKind: 'legacy', originRef: record.taskId, targetId: snapshot.targetId, title: record.title, currentAttemptId: attemptId,
388
+ executionStatus, inFlightAttemptIds: [], unresolvedAttemptIds: [], jobVersion: 0, createdAt: record.createdAt ?? null,
389
+ updatedAt: record.checkedAt ?? timestamp, provenance: 'legacy', migratedAt: timestamp };
390
+ state.attempts[attemptId] = attempt;
391
+ state.jobs[jobId] = job;
392
+ this.event(state, job, attemptId, 'job.migrated', { remote: record.remote, taskId: record.taskId });
393
+ return { remote: record.remote, taskId: record.taskId, jobId, attemptId };
394
+ }));
395
+ }
396
+ }
@@ -0,0 +1,231 @@
1
+ import { z } from 'zod';
2
+ export declare const pptDeliveryInputSchema: z.ZodObject<{
3
+ projectDirectory: z.ZodString;
4
+ projectName: z.ZodString;
5
+ instructions: z.ZodOptional<z.ZodString>;
6
+ slideCount: z.ZodDefault<z.ZodLiteral<6>>;
7
+ revisionRequest: z.ZodOptional<z.ZodString>;
8
+ }, z.core.$strict>;
9
+ export type PptDeliveryInput = z.infer<typeof pptDeliveryInputSchema>;
10
+ export declare const pptDeliveryPolicySchema: z.ZodObject<{
11
+ version: z.ZodDefault<z.ZodString>;
12
+ workspaceRoot: z.ZodString;
13
+ publicDirectory: z.ZodString;
14
+ publicBaseUrl: z.ZodString;
15
+ allowedProjectRoots: z.ZodArray<z.ZodString>;
16
+ summaryTargetId: z.ZodString;
17
+ makerTargetId: z.ZodString;
18
+ reviewTargetId: z.ZodString;
19
+ summaryAgentPreset: z.ZodDefault<z.ZodString>;
20
+ backupTargets: z.ZodOptional<z.ZodObject<{
21
+ project_script: z.ZodOptional<z.ZodString>;
22
+ ppt_production: z.ZodOptional<z.ZodString>;
23
+ independent_review: z.ZodOptional<z.ZodString>;
24
+ }, z.core.$strict>>;
25
+ maxTargetSwitches: z.ZodDefault<z.ZodNumber>;
26
+ runtimeDocument: z.ZodString;
27
+ designSkill: z.ZodString;
28
+ pythonExecutable: z.ZodString;
29
+ nodeExecutable: z.ZodOptional<z.ZodString>;
30
+ nodeModuleRoot: z.ZodOptional<z.ZodString>;
31
+ maxRevisionRounds: z.ZodDefault<z.ZodNumber>;
32
+ maxExecutionRetries: z.ZodDefault<z.ZodNumber>;
33
+ maxDurationMs: z.ZodDefault<z.ZodNumber>;
34
+ httpTimeoutMs: z.ZodDefault<z.ZodNumber>;
35
+ }, z.core.$strict>;
36
+ export type PptDeliveryPolicy = z.infer<typeof pptDeliveryPolicySchema>;
37
+ export interface PptDeliveryChild {
38
+ jobId: string;
39
+ attemptId: string;
40
+ executionStatus: string;
41
+ submissionStatus?: string;
42
+ targetId?: string;
43
+ resultSummary?: string;
44
+ artifactLinks?: unknown[];
45
+ resultMetadata?: Record<string, unknown>;
46
+ backendRunRef?: Record<string, unknown>;
47
+ sessionId?: string;
48
+ }
49
+ export interface PptDeliveryChildRequest {
50
+ targetId: string;
51
+ input: Record<string, unknown>;
52
+ clientRequestId: string;
53
+ parentJobRef: {
54
+ sourceId: string;
55
+ jobId: string;
56
+ };
57
+ parentAttemptId: string;
58
+ purpose: 'project_script' | 'ppt_production' | 'independent_review';
59
+ resultRevision: string;
60
+ originSessionId: string;
61
+ replacesJobRef?: {
62
+ sourceId: string;
63
+ jobId: string;
64
+ };
65
+ }
66
+ export interface PptDeliveryArtifact {
67
+ path: string;
68
+ url: string;
69
+ mediaType: string;
70
+ size: number;
71
+ sha256: string;
72
+ }
73
+ export interface PptDeliveryValidation {
74
+ status: 'passed';
75
+ artifactDigest: string;
76
+ checkedAt: string;
77
+ artifacts: PptDeliveryArtifact[];
78
+ structure: {
79
+ slideCount: number;
80
+ editableTextRuns: number;
81
+ shapes: number;
82
+ pictures: number;
83
+ aspectRatio: number;
84
+ };
85
+ checks: string[];
86
+ }
87
+ export interface PptDeliveryReview {
88
+ verdict: 'passed' | 'changes_requested';
89
+ artifactDigest: string;
90
+ factsChecked: boolean;
91
+ allSlidesViewed: boolean;
92
+ issues: string[];
93
+ limitations: string[];
94
+ evidence: string[];
95
+ }
96
+ export interface PptDeliveryRun {
97
+ version: 1;
98
+ sourceId: string;
99
+ jobId: string;
100
+ attemptId: string;
101
+ originSessionId: string;
102
+ input: PptDeliveryInput;
103
+ policy: PptDeliveryPolicy;
104
+ jobDirectory: string;
105
+ contractPath: string;
106
+ createdAt: string;
107
+ updatedAt: string;
108
+ executionStatus: 'working' | 'input_required' | 'completed' | 'failed' | 'canceled';
109
+ stage: 'summary' | 'make' | 'validate' | 'review' | 'finished';
110
+ phase: string;
111
+ revision: number;
112
+ revisionReasons: string[];
113
+ revisionExerciseApplied?: boolean;
114
+ executionRetries: Record<string, number>;
115
+ children: {
116
+ purpose: PptDeliveryChildRequest['purpose'];
117
+ revision: number;
118
+ targetId: string;
119
+ child: PptDeliveryChild;
120
+ acknowledged?: boolean;
121
+ }[];
122
+ activeTargets: Partial<Record<PptDeliveryChildRequest['purpose'], string>>;
123
+ targetSwitches: {
124
+ at: string;
125
+ purpose: PptDeliveryChildRequest['purpose'];
126
+ fromTargetId: string;
127
+ toTargetId: string;
128
+ replacesJobRef: {
129
+ sourceId: string;
130
+ jobId: string;
131
+ };
132
+ failedAttemptId: string;
133
+ reason: string;
134
+ policyVersion: string;
135
+ }[];
136
+ cancellationRequestedAt?: string;
137
+ artifactHistory?: {
138
+ revision: number;
139
+ validation: PptDeliveryValidation;
140
+ }[];
141
+ currentChild?: PptDeliveryChild;
142
+ validation?: PptDeliveryValidation;
143
+ review?: PptDeliveryReview;
144
+ /** Saved before submit. Stable request id survives a crash after remote acceptance. */
145
+ pending?: {
146
+ kind: 'submit' | 'continue';
147
+ request: PptDeliveryChildRequest;
148
+ child?: PptDeliveryChild;
149
+ };
150
+ diagnostics: string[];
151
+ transitions: {
152
+ at: string;
153
+ stage: string;
154
+ phase: string;
155
+ reason?: string;
156
+ }[];
157
+ metrics: {
158
+ submitCalls: number;
159
+ continueCalls: number;
160
+ queryCalls: number;
161
+ ackCalls: number;
162
+ machineChecks: number;
163
+ reviewRounds: number;
164
+ qualityRevisions: number;
165
+ acceptanceExerciseRevisions: number;
166
+ elapsedMs: number;
167
+ modelUsage: 'unknown';
168
+ modelUsageReason: string;
169
+ };
170
+ resultSummary?: string;
171
+ deliveryReceipt?: Record<string, unknown>;
172
+ parentUpdatePending?: PptDeliveryParentUpdate;
173
+ projectSnapshot?: {
174
+ gitHead: string;
175
+ gitStatus: string;
176
+ trackedDiffDigest: string;
177
+ };
178
+ scriptDigest?: string;
179
+ sourceManifestDigest?: string;
180
+ publicationCheckedAt?: string;
181
+ recovery?: {
182
+ fromAttemptId: string;
183
+ recoveredAt: string;
184
+ contractPath: string;
185
+ reusedChildren: {
186
+ jobId: string;
187
+ attemptId: string;
188
+ }[];
189
+ validationCheckedAt?: string;
190
+ };
191
+ }
192
+ export interface PptDeliveryParentUpdate {
193
+ executionStatus: PptDeliveryRun['executionStatus'];
194
+ phase: string;
195
+ resultSummary?: string;
196
+ artifactLinks?: PptDeliveryArtifact[];
197
+ deliveryReceipt?: Record<string, unknown>;
198
+ error?: string;
199
+ }
200
+ export interface PptDeliveryAdapter {
201
+ persist(run: PptDeliveryRun): Promise<void>;
202
+ submitChild(request: PptDeliveryChildRequest): Promise<PptDeliveryChild>;
203
+ continueChild(request: PptDeliveryChildRequest & {
204
+ child: PptDeliveryChild;
205
+ }): Promise<PptDeliveryChild>;
206
+ getChild(child: PptDeliveryChild): Promise<PptDeliveryChild>;
207
+ ackChild(child: PptDeliveryChild): Promise<void>;
208
+ updateParent(update: PptDeliveryParentUpdate): Promise<void>;
209
+ /** Injectable for transport fault tests. Production uses the real validator below. */
210
+ validateCandidate?(run: PptDeliveryRun): Promise<PptDeliveryValidation>;
211
+ preflightPublication?(run: PptDeliveryRun): Promise<void>;
212
+ now?(): number;
213
+ }
214
+ export declare function assertPptDeliveryRecoverable(previous: PptDeliveryRun): void;
215
+ /** Explicit new parent execution round at a verified review checkpoint; old rounds remain immutable. */
216
+ export declare function recoverPptDeliveryRun(previous: PptDeliveryRun, attemptId: string): Promise<PptDeliveryRun>;
217
+ export declare function createPptDeliveryRun(input: {
218
+ sourceId: string;
219
+ jobId: string;
220
+ attemptId: string;
221
+ originSessionId: string;
222
+ input: unknown;
223
+ policy: unknown;
224
+ }): Promise<PptDeliveryRun>;
225
+ /** Publication transport errors cannot be repaired by asking the model to redesign slides. */
226
+ export declare class PptPublicationError extends Error {
227
+ }
228
+ export declare function preflightPptPublication(run: PptDeliveryRun): Promise<void>;
229
+ export declare function validatePptDeliveryCandidate(run: PptDeliveryRun): Promise<PptDeliveryValidation>;
230
+ /** Called by the gateway's existing background reconcile. No main-session polling or long waits. */
231
+ export declare function advancePptDelivery(run: PptDeliveryRun, adapter: PptDeliveryAdapter): Promise<void>;