@1agents/acp-service 0.10.8 → 0.10.10

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 (94) hide show
  1. package/dist/bin/a2a.js +12 -1
  2. package/dist/src/a2a/gateway.d.ts +268 -2
  3. package/dist/src/a2a/gateway.js +337 -25
  4. package/dist/src/a2a/job-directory.d.ts +5 -0
  5. package/dist/src/a2a/job-directory.js +15 -0
  6. package/dist/src/a2a/preflight.d.ts +38 -0
  7. package/dist/src/a2a/preflight.js +56 -8
  8. package/dist/src/a2a/types.d.ts +8 -0
  9. package/dist/src/execution/case-view.d.ts +109 -0
  10. package/dist/src/execution/case-view.js +125 -0
  11. package/dist/src/execution/cases.d.ts +56 -0
  12. package/dist/src/execution/cases.js +77 -0
  13. package/dist/src/execution/externals.d.ts +83 -0
  14. package/dist/src/execution/externals.js +61 -0
  15. package/dist/src/execution/handoff.d.ts +54 -1
  16. package/dist/src/execution/handoff.js +80 -15
  17. package/dist/src/execution/ledger.d.ts +35 -2
  18. package/dist/src/execution/ledger.js +72 -2
  19. package/dist/src/execution/snapshots.d.ts +28 -0
  20. package/dist/src/execution/snapshots.js +64 -0
  21. package/dist/src/execution/targets.d.ts +63 -0
  22. package/dist/src/execution/targets.js +15 -1
  23. package/dist/src/execution/workbench.d.ts +5 -1
  24. package/dist/src/execution/workbench.js +13 -4
  25. package/dist/workbench-ui/app.css +18 -0
  26. package/dist/workbench-ui/app.js +13 -13
  27. package/package.json +12 -13
  28. package/vendor/dsh/a2a-executor.d.ts +2 -2
  29. package/vendor/dsh/adapter.d.ts +4 -4
  30. package/vendor/dsh/cordis.patch.yml +6 -5
  31. package/vendor/dsh/handoff-executor.d.ts +7 -0
  32. package/vendor/dsh/handoff-executor.js +28 -0
  33. package/vendor/dsh/handoff-spec.d.ts +26 -0
  34. package/vendor/dsh/handoff-spec.js +14 -0
  35. package/vendor/dsh/handoff-tools.d.ts +4 -0
  36. package/vendor/dsh/handoff-tools.js +20 -0
  37. package/vendor/dsh/index.js +8 -0
  38. package/vendor/dsh/review-mcp.js +6 -2
  39. package/vendor/dsh/review.d.ts +3 -0
  40. package/vendor/dsh/review.js +19 -0
  41. package/vendor/dsh/service-process.d.ts +9 -1
  42. package/vendor/dsh/service-process.js +69 -3
  43. package/vendor/dsh/ticket-tools.d.ts +1 -1
  44. package/vendor/runtime/dist/{cli-DXmYwv3U.js → cli-BwanDcOo.js} +4 -4
  45. package/vendor/runtime/dist/{cli-DXmYwv3U.js.map → cli-BwanDcOo.js.map} +1 -1
  46. package/vendor/runtime/dist/cli.js +8 -8
  47. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts → client-C5zneoBs.d.ts} +3 -1
  48. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts.map → client-C5zneoBs.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 +336 -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-DJ17ajbw.js → flows-CzLUHUTS.js} +4 -4
  75. package/vendor/runtime/dist/{flows-DJ17ajbw.js.map → flows-CzLUHUTS.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +1 -1
  77. package/vendor/runtime/dist/flows.js +1 -1
  78. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js → invocation-options-B6pIpdpR.js} +4 -4
  79. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js.map → invocation-options-B6pIpdpR.js.map} +1 -1
  80. package/vendor/runtime/dist/{ipc-BQQpcEdP.js → ipc-ivLtSAdL.js} +21 -3
  81. package/vendor/runtime/dist/ipc-ivLtSAdL.js.map +1 -0
  82. package/vendor/runtime/dist/{output-B3MDn7kv.js → output-BqKnXXb0.js} +3 -3
  83. package/vendor/runtime/dist/{output-B3MDn7kv.js.map → output-BqKnXXb0.js.map} +1 -1
  84. package/vendor/runtime/dist/{queue-owner-runtime-DXCVngwU.js → queue-owner-runtime-DXJND10J.js} +11 -2
  85. package/vendor/runtime/dist/queue-owner-runtime-DXJND10J.js.map +1 -0
  86. package/vendor/runtime/dist/runtime.d.ts +1 -1
  87. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  88. package/vendor/runtime/dist/runtime.js +3 -3
  89. package/vendor/runtime/dist/{session-watch-DURyCw31.js → session-watch-BHB3_PXm.js} +4 -4
  90. package/vendor/runtime/dist/{session-watch-DURyCw31.js.map → session-watch-BHB3_PXm.js.map} +1 -1
  91. package/vendor/runtime/dist/{watch-CIpoMaWD.js → watch-UjokHUfS.js} +2 -2
  92. package/vendor/runtime/dist/{watch-CIpoMaWD.js.map → watch-UjokHUfS.js.map} +1 -1
  93. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +0 -1
  94. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +0 -1
@@ -0,0 +1,61 @@
1
+ /**
2
+ * What the outside world says about one thing.
3
+ *
4
+ * A receipt is proof that a specific byte left through a specific channel. A fact is a number someone measured.
5
+ * Neither is a task status: publishing does not complete a job, and a number below a target is not a failure.
6
+ */
7
+ import { randomUUID } from 'node:crypto';
8
+ import { z } from 'zod';
9
+ import { CaseError, requireCase } from './cases.js';
10
+ const id = z.string().trim().min(1).max(512);
11
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
12
+ const instant = z.string().datetime({ offset: true });
13
+ export const receiptRecordSchema = z.object({ originSessionId: id, caseId: id, channel: id, remoteId: id,
14
+ artifactDigest: digest, artifactRevision: id.optional(), jobId: id.optional(), attemptId: id.optional(),
15
+ url: z.string().url().optional(), publishedAt: instant.optional(), recordedBy: z.lazy(() => writerSchema).optional() }).strict();
16
+ export const factRecordSchema = z.object({ originSessionId: id, caseId: id, metric: id, value: z.number().finite(),
17
+ unit: id.optional(), source: id, observedAt: instant.optional(), recordedBy: z.lazy(() => writerSchema).optional() }).strict();
18
+ /** Who may write an external fact or a receipt: a person on the page, an application with the credential, or a coach. */
19
+ const writerSchema = z.object({ kind: z.enum(['person', 'coach', 'application']), id: id.optional(),
20
+ agent: z.string().trim().min(1).max(512).optional(), sessionId: z.string().trim().min(1).max(512).optional() }).strict();
21
+ /**
22
+ * Record that these bytes went out. The channel and its own id are the key: the same key with the same digest
23
+ * is the same receipt, and the same key with another digest is a conflict, never an overwrite.
24
+ */
25
+ export function recordReceipt(ledger, raw) {
26
+ const input = receiptRecordSchema.parse(raw);
27
+ requireCase(ledger, input.originSessionId, input.caseId);
28
+ const prior = ledger.receiptsFor(input.originSessionId, input.caseId)
29
+ .find(item => item.channel === input.channel && item.remoteId === input.remoteId);
30
+ if (prior) {
31
+ if (prior.artifactDigest !== input.artifactDigest)
32
+ throw new CaseError('conflict', 'This channel id already has a receipt for another digest');
33
+ return prior;
34
+ }
35
+ const now = new Date().toISOString();
36
+ return ledger.commitReceipt({ receiptId: randomUUID(), caseId: input.caseId, originSessionId: input.originSessionId,
37
+ channel: input.channel, remoteId: input.remoteId, artifactDigest: input.artifactDigest,
38
+ ...(input.artifactRevision ? { artifactRevision: input.artifactRevision } : {}),
39
+ ...(input.jobId ? { jobId: input.jobId } : {}), ...(input.attemptId ? { attemptId: input.attemptId } : {}),
40
+ ...(input.url ? { url: input.url } : {}),
41
+ publishedAt: input.publishedAt ?? now, recordedAt: now, ...(input.recordedBy ? { recordedBy: input.recordedBy } : {}) });
42
+ }
43
+ /** Record one measured number. The platform stores it and does not say whether it is good. */
44
+ export function recordFact(ledger, raw) {
45
+ const input = factRecordSchema.parse(raw);
46
+ requireCase(ledger, input.originSessionId, input.caseId);
47
+ const now = new Date().toISOString();
48
+ return ledger.commitFact({ factId: randomUUID(), caseId: input.caseId, originSessionId: input.originSessionId,
49
+ metric: input.metric, value: input.value, ...(input.unit ? { unit: input.unit } : {}), source: input.source,
50
+ observedAt: input.observedAt ?? now, recordedAt: now, ...(input.recordedBy ? { recordedBy: input.recordedBy } : {}) });
51
+ }
52
+ /** Does this measurement satisfy the condition a convention stores? */
53
+ export function factSatisfied(value, operator, threshold) {
54
+ if (operator === 'gte')
55
+ return value >= threshold;
56
+ if (operator === 'lte')
57
+ return value <= threshold;
58
+ if (operator === 'gt')
59
+ return value > threshold;
60
+ return value < threshold;
61
+ }
@@ -1,12 +1,24 @@
1
1
  import { z } from 'zod';
2
2
  import type { LedgerActor } from './ledger.js';
3
3
  import { JobLedger } from './ledger.js';
4
+ import { type FactOperator } from './externals.js';
4
5
  export declare const handoffWhenSchema: z.ZodEnum<{
5
6
  acceptance_accepted: "acceptance_accepted";
6
7
  ticket_closed: "ticket_closed";
8
+ fact_reached: "fact_reached";
7
9
  }>;
8
10
  export type HandoffWhen = z.infer<typeof handoffWhenSchema>;
9
11
  export type HandoffStatus = 'proposed' | 'accepted' | 'taken' | 'rejected';
12
+ /** One frozen file: the bytes that were accepted, addressed by their digest. */
13
+ export interface HandoffSnapshot {
14
+ digest: string;
15
+ name: string;
16
+ size: number;
17
+ mediaType?: string;
18
+ /** Path inside the gateway's snapshot store, relative to its root. */
19
+ storedPath: string;
20
+ frozenAt: string;
21
+ }
10
22
  export interface Handoff {
11
23
  handoffId: string;
12
24
  caseId: string;
@@ -23,6 +35,8 @@ export interface Handoff {
23
35
  childJobId?: string;
24
36
  decidedBy?: LedgerActor;
25
37
  note?: string;
38
+ /** The accepted bytes, frozen by digest. Present once the handoff was accepted. */
39
+ snapshots?: HandoffSnapshot[];
26
40
  createdAt: string;
27
41
  updatedAt: string;
28
42
  }
@@ -37,6 +51,12 @@ export interface HandoffConvention {
37
51
  toPurpose: string;
38
52
  when: HandoffWhen;
39
53
  requireHuman: boolean;
54
+ /** The threshold a measured fact is compared against, when `when` is 'fact_reached'. */
55
+ condition?: {
56
+ metric: string;
57
+ operator: FactOperator;
58
+ value: number;
59
+ };
40
60
  clientRequestId?: string;
41
61
  recordedAt: string;
42
62
  }
@@ -51,18 +71,35 @@ export interface LegalNext {
51
71
  /** True when the convention's predicate already holds for the current result. */
52
72
  achieved: boolean;
53
73
  }
74
+ /** Who may record the decision, and as whom. */
75
+ export interface DecideOptions {
76
+ /** The workbench page records a person's decision. The A2A channel may not. */
77
+ allowPerson?: boolean;
78
+ /** The configured reviewer this decision belongs to. */
79
+ reviewerId?: string;
80
+ }
54
81
  export declare function legalNextFor(ledger: JobLedger, originSessionId: string, jobId: string): LegalNext[];
55
82
  /** Record a proposal. A single matching convention with requireHuman false accepts it. Nothing here opens a job. */
56
83
  export declare function proposeHandoff(ledger: JobLedger, originSessionId: string, raw: unknown): Handoff;
57
- export declare function decideHandoff(ledger: JobLedger, raw: unknown): Handoff;
84
+ /**
85
+ * Record a decision. A person's decision comes from the workbench page and carries the configured reviewer;
86
+ * this channel may record a coach's decision only, so an agent cannot write that a person agreed.
87
+ */
88
+ export declare function decideHandoff(ledger: JobLedger, raw: unknown, options?: DecideOptions): Handoff;
58
89
  /**
59
90
  * When exactly one convention's predicate holds and it does not ask for a person, record an accepted handoff.
60
91
  * Zero or several matches record nothing. This does not submit the next job.
61
92
  */
62
93
  export declare function continueByConvention(ledger: JobLedger, originSessionId: string, jobId: string): Handoff | undefined;
94
+ /**
95
+ * A measured fact reached a threshold. This only proposes the next hop; it never decides it and never dispatches.
96
+ */
97
+ export declare function proposeByFact(ledger: JobLedger, originSessionId: string, caseId: string, rule: HandoffConvention, reason: string): Handoff | undefined;
63
98
  export declare function offerConvention(ledger: JobLedger, raw: unknown): HandoffConvention;
64
99
  export declare function grantArtifactSpace(ledger: JobLedger, raw: unknown): import("./spaces.js").ArtifactSpace;
65
100
  export declare function readHandoff(ledger: JobLedger, raw: unknown): {
101
+ artifactRevision: string | undefined;
102
+ artifactDigest: string | undefined;
66
103
  artifactSpace?: string | undefined;
67
104
  caseId: string | undefined;
68
105
  handoffs: Handoff[];
@@ -99,8 +136,13 @@ export declare const HANDOFF_METHODS: {
99
136
  person: "person";
100
137
  coach: "coach";
101
138
  }>;
139
+ id: z.ZodOptional<z.ZodString>;
102
140
  agent: z.ZodOptional<z.ZodString>;
103
141
  sessionId: z.ZodOptional<z.ZodString>;
142
+ via: z.ZodOptional<z.ZodEnum<{
143
+ page: "page";
144
+ relay: "relay";
145
+ }>>;
104
146
  }, z.core.$strict>;
105
147
  }, z.core.$strict>>;
106
148
  };
@@ -116,9 +158,20 @@ export declare const HANDOFF_METHODS: {
116
158
  when: z.ZodEnum<{
117
159
  acceptance_accepted: "acceptance_accepted";
118
160
  ticket_closed: "ticket_closed";
161
+ fact_reached: "fact_reached";
119
162
  }>;
120
163
  requireHuman: z.ZodOptional<z.ZodBoolean>;
121
164
  clientRequestId: z.ZodOptional<z.ZodString>;
165
+ condition: z.ZodOptional<z.ZodObject<{
166
+ metric: z.ZodString;
167
+ operator: z.ZodEnum<{
168
+ gte: "gte";
169
+ lte: "lte";
170
+ gt: "gt";
171
+ lt: "lt";
172
+ }>;
173
+ value: z.ZodNumber;
174
+ }, z.core.$strict>>;
122
175
  }, z.core.$strict>>;
123
176
  };
124
177
  handoff_space: {
@@ -6,14 +6,17 @@
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { z } from 'zod';
8
8
  import { TicketError } from './ticket.js';
9
+ import { requireCase } from './cases.js';
10
+ import { factSatisfied } from './externals.js';
9
11
  const id = z.string().trim().min(1).max(512);
10
12
  const digest = z.string().regex(/^[a-f0-9]{64}$/);
11
13
  const text = z.string().trim().min(1).max(4000);
12
- export const handoffWhenSchema = z.enum(['acceptance_accepted', 'ticket_closed']);
14
+ export const handoffWhenSchema = z.enum(['acceptance_accepted', 'ticket_closed', 'fact_reached']);
13
15
  export class HandoffError extends Error {
14
16
  }
15
17
  const fail = (message) => { throw new HandoffError(message); };
16
- const actorSchema = z.object({ kind: z.enum(['person', 'coach']), agent: z.string().optional(), sessionId: z.string().optional() }).strict()
18
+ const actorSchema = z.object({ kind: z.enum(['person', 'coach']), id: id.optional(), agent: z.string().optional(), sessionId: z.string().optional(),
19
+ via: z.enum(['page', 'relay']).optional() }).strict()
17
20
  .refine(actor => actor.kind === 'coach' || (!actor.agent && !actor.sessionId), 'Only a coach names an agent session');
18
21
  const proposeFields = {
19
22
  caseId: id, toTargetId: id, purpose: id, artifactRevision: id, artifactDigest: digest, reason: text,
@@ -24,10 +27,12 @@ const proposeByExecutorSchema = z.object({ jobId: id, attemptId: id, sessionId:
24
27
  const decideSchema = z.object({ originSessionId: id, handoffId: id, decision: z.enum(['accept', 'reject']),
25
28
  note: z.string().trim().max(4000).optional(), decidedBy: actorSchema }).strict();
26
29
  const offerSchema = z.object({ originSessionId: id, caseId: id, fromPurpose: id.optional(), fromTargetId: id.optional(),
27
- toTargetId: id, toPurpose: id, when: handoffWhenSchema, requireHuman: z.boolean().optional(), clientRequestId: id.optional() }).strict();
30
+ toTargetId: id, toPurpose: id, when: handoffWhenSchema, requireHuman: z.boolean().optional(), clientRequestId: id.optional(),
31
+ condition: z.object({ metric: id, operator: z.enum(['gte', 'lte', 'gt', 'lt']), value: z.number().finite() }).strict().optional() }).strict();
28
32
  const spaceSchema = z.object({ originSessionId: id, caseId: id,
29
33
  root: z.string().min(1).max(4096).refine(value => value.startsWith('/') && !value.includes('\0') && !value.split('/').includes('..'), 'artifact space must be an absolute remote path') }).strict();
30
34
  const readSchema = z.object({ originSessionId: id, jobId: id }).strict();
35
+ const readByExecutorSchema = z.object({ jobId: id, attemptId: id, sessionId: id }).strict();
31
36
  function applies(rule, job) {
32
37
  return rule.originSessionId === job.originSessionId && rule.caseId === job.caseId
33
38
  && (!rule.fromPurpose || rule.fromPurpose === job.purpose)
@@ -44,9 +49,14 @@ function ticketClosed(ledger, origin, jobId) {
44
49
  throw error;
45
50
  }
46
51
  }
47
- function achieved(rule, view, closed) {
52
+ function achieved(rule, view, closed, facts) {
48
53
  if (rule.when === 'ticket_closed')
49
54
  return closed;
55
+ if (rule.when === 'fact_reached') {
56
+ if (!rule.condition)
57
+ return false;
58
+ return facts.some(fact => fact.metric === rule.condition.metric && factSatisfied(fact.value, rule.condition.operator, rule.condition.value));
59
+ }
50
60
  const acceptance = view.businessAcceptance;
51
61
  return acceptance?.reviewStatus === 'accepted'
52
62
  && acceptance.resultDigest === view.result?.resultDigest
@@ -58,9 +68,10 @@ export function legalNextFor(ledger, originSessionId, jobId) {
58
68
  if (!view.caseId)
59
69
  return [];
60
70
  const closed = ticketClosed(ledger, originSessionId, jobId);
71
+ const facts = ledger.factsFor(originSessionId, view.caseId).map(fact => ({ metric: fact.metric, value: fact.value }));
61
72
  return ledger.conventionsFor(originSessionId).filter(rule => applies(rule, view)).map(rule => ({
62
73
  conventionId: rule.conventionId, toTargetId: rule.toTargetId, purpose: rule.toPurpose,
63
- requireHuman: rule.requireHuman, when: rule.when, achieved: achieved(rule, view, closed),
74
+ requireHuman: rule.requireHuman, when: rule.when, achieved: achieved(rule, view, closed, facts),
64
75
  }));
65
76
  }
66
77
  function sameProposal(existing, input) {
@@ -69,8 +80,15 @@ function sameProposal(existing, input) {
69
80
  }
70
81
  /** Record a proposal. A single matching convention with requireHuman false accepts it. Nothing here opens a job. */
71
82
  export function proposeHandoff(ledger, originSessionId, raw) {
72
- const input = proposeByOriginSchema.parse({ ...raw, originSessionId });
83
+ const body = raw && typeof raw === 'object' ? { ...raw } : {};
84
+ // The executor's own fields name who is calling; they are not part of the proposal.
85
+ delete body.via;
86
+ delete body.sessionId;
87
+ const input = proposeByOriginSchema.parse({ ...body, originSessionId });
73
88
  const view = ledger.get(originSessionId, input.jobId);
89
+ if (view.caseId && view.caseId !== input.caseId)
90
+ fail('Handoff must name the case of its job');
91
+ requireCase(ledger, originSessionId, input.caseId);
74
92
  const attempt = view.attempts.find(item => item.attemptId === input.attemptId) ?? fail('Attempt does not belong to this job');
75
93
  if (attempt.attemptId !== view.currentAttemptId)
76
94
  fail('Handoff must name the job\'s current attempt');
@@ -87,23 +105,36 @@ export function proposeHandoff(ledger, originSessionId, raw) {
87
105
  if (open)
88
106
  return open;
89
107
  const closed = ticketClosed(ledger, originSessionId, input.jobId);
108
+ const facts = ledger.factsFor(originSessionId, input.caseId).map(fact => ({ metric: fact.metric, value: fact.value }));
90
109
  const matches = ledger.conventionsFor(originSessionId).filter(rule => applies(rule, { ...view, caseId: input.caseId })
91
- && rule.toTargetId === input.toTargetId && rule.toPurpose === input.purpose && achieved(rule, { ...view, caseId: input.caseId }, closed));
92
- if (matches.filter(rule => !rule.requireHuman).length > 1)
110
+ && rule.toTargetId === input.toTargetId && rule.toPurpose === input.purpose && achieved(rule, { ...view, caseId: input.caseId }, closed, facts));
111
+ // A threshold that has been reached only proposes: it never decides that work moves on by itself.
112
+ const automatic = matches.filter(rule => !rule.requireHuman && rule.when !== 'fact_reached');
113
+ if (automatic.length > 1)
93
114
  fail('More than one achieved convention matches this handoff; a person must choose');
94
115
  const now = new Date().toISOString();
95
116
  const handoff = {
96
117
  handoffId: randomUUID(), caseId: input.caseId, fromJobId: input.jobId, fromAttemptId: input.attemptId,
97
118
  toTargetId: input.toTargetId, purpose: input.purpose, artifactRevision: input.artifactRevision, artifactDigest: input.artifactDigest,
98
- reason: input.reason, status: matches.some(rule => !rule.requireHuman) ? 'accepted' : 'proposed',
119
+ reason: input.reason, status: automatic.length ? 'accepted' : 'proposed',
99
120
  ...(input.clientRequestId ? { clientRequestId: input.clientRequestId } : {}),
100
- ...(matches.some(rule => !rule.requireHuman) ? { conventionId: matches.find(rule => !rule.requireHuman).conventionId } : {}),
121
+ ...(automatic.length ? { conventionId: automatic[0].conventionId } : {}),
101
122
  createdAt: now, updatedAt: now,
102
123
  };
103
124
  return ledger.commitHandoff(originSessionId, handoff, handoff.status === 'accepted' ? 'handoff.accepted' : 'handoff.proposed');
104
125
  }
105
- export function decideHandoff(ledger, raw) {
126
+ /**
127
+ * Record a decision. A person's decision comes from the workbench page and carries the configured reviewer;
128
+ * this channel may record a coach's decision only, so an agent cannot write that a person agreed.
129
+ */
130
+ export function decideHandoff(ledger, raw, options = {}) {
106
131
  const input = decideSchema.parse(raw);
132
+ if (input.decidedBy.kind === 'person') {
133
+ if (!options.allowPerson)
134
+ fail('A person decides on the workbench page, not through this channel');
135
+ if (options.reviewerId && input.decidedBy.id !== options.reviewerId)
136
+ fail('This decision belongs to another reviewer');
137
+ }
107
138
  const current = ledger.findHandoff(input.originSessionId, input.handoffId) ?? fail('Handoff not found');
108
139
  if (current.status === 'taken')
109
140
  fail('A taken handoff already opened a job');
@@ -125,7 +156,9 @@ export function continueByConvention(ledger, originSessionId, jobId) {
125
156
  if (!view.caseId || !view.result?.resultAvailable || !view.result.resultDigest || !view.result.resultRevision)
126
157
  return undefined;
127
158
  const closed = ticketClosed(ledger, originSessionId, jobId);
128
- const ready = ledger.conventionsFor(originSessionId).filter(rule => applies(rule, view) && !rule.requireHuman && achieved(rule, view, closed));
159
+ const facts = ledger.factsFor(originSessionId, view.caseId).map(fact => ({ metric: fact.metric, value: fact.value }));
160
+ const ready = ledger.conventionsFor(originSessionId).filter(rule => applies(rule, view) && !rule.requireHuman
161
+ && rule.when !== 'fact_reached' && achieved(rule, view, closed, facts));
129
162
  if (ready.length !== 1)
130
163
  return undefined;
131
164
  const rule = ready[0];
@@ -141,19 +174,43 @@ export function continueByConvention(ledger, originSessionId, jobId) {
141
174
  reason: '约定已达成', status: 'accepted', clientRequestId, conventionId: rule.conventionId, createdAt: now, updatedAt: now,
142
175
  }, 'handoff.accepted');
143
176
  }
177
+ /**
178
+ * A measured fact reached a threshold. This only proposes the next hop; it never decides it and never dispatches.
179
+ */
180
+ export function proposeByFact(ledger, originSessionId, caseId, rule, reason) {
181
+ const view = ledger.list(originSessionId).find(job => job.caseId === caseId);
182
+ if (!view || !view.result?.resultAvailable || !view.result.resultDigest || !view.result.resultRevision)
183
+ return undefined;
184
+ const existing = ledger.handoffsFor(originSessionId, view.jobId);
185
+ if (existing.some(item => item.conventionId === rule.conventionId && item.status !== 'rejected'))
186
+ return undefined;
187
+ const now = new Date().toISOString();
188
+ return ledger.commitHandoff(originSessionId, {
189
+ handoffId: randomUUID(), caseId, fromJobId: view.jobId, fromAttemptId: view.currentAttemptId,
190
+ toTargetId: rule.toTargetId, purpose: rule.toPurpose, artifactRevision: view.result.resultRevision, artifactDigest: view.result.resultDigest,
191
+ reason, status: 'proposed', conventionId: rule.conventionId, createdAt: now, updatedAt: now,
192
+ }, 'handoff.proposed');
193
+ }
144
194
  export function offerConvention(ledger, raw) {
145
195
  const input = offerSchema.parse(raw);
146
196
  if (input.fromTargetId && input.fromTargetId === input.toTargetId)
147
197
  fail('A convention must name a different target');
198
+ if (input.when === 'fact_reached' && !input.condition)
199
+ fail('A fact threshold needs a condition');
200
+ if (input.when !== 'fact_reached' && input.condition)
201
+ fail('Only a fact threshold carries a condition');
202
+ requireCase(ledger, input.originSessionId, input.caseId);
148
203
  return ledger.commitConvention({
149
204
  conventionId: randomUUID(), originSessionId: input.originSessionId, caseId: input.caseId,
150
205
  ...(input.fromPurpose ? { fromPurpose: input.fromPurpose } : {}), ...(input.fromTargetId ? { fromTargetId: input.fromTargetId } : {}),
151
206
  toTargetId: input.toTargetId, toPurpose: input.toPurpose, when: input.when, requireHuman: input.requireHuman ?? false,
207
+ ...(input.condition ? { condition: input.condition } : {}),
152
208
  ...(input.clientRequestId ? { clientRequestId: input.clientRequestId } : {}), recordedAt: new Date().toISOString(),
153
209
  });
154
210
  }
155
211
  export function grantArtifactSpace(ledger, raw) {
156
212
  const input = spaceSchema.parse(raw);
213
+ requireCase(ledger, input.originSessionId, input.caseId);
157
214
  return ledger.commitArtifactSpace({ ...input, recordedAt: new Date().toISOString() });
158
215
  }
159
216
  export function readHandoff(ledger, raw) {
@@ -164,11 +221,12 @@ export function readHandoff(ledger, raw) {
164
221
  caseId: view.caseId, handoffs: ledger.handoffsFor(input.originSessionId, input.jobId),
165
222
  legalNext: legalNextFor(ledger, input.originSessionId, input.jobId),
166
223
  ...(space ? { artifactSpace: space.root } : {}),
224
+ artifactRevision: view.result?.resultRevision, artifactDigest: view.result?.resultDigest,
167
225
  };
168
226
  }
169
227
  export const HANDOFF_METHODS = {
170
228
  handoff_propose: { description: '提议把当前轮次已记录的产物交给另一个执行目标。只写账本,不派下一单。唯一匹配且不要求人确认的约定会直接接受;多条匹配则拒绝代选。', parameters: z.toJSONSchema(proposeByOriginSchema) },
171
- handoff_decide: { description: '人或教练接受或拒绝一条提议。接受后仍要另调 execution_submit 并带上 handoffId,才会开下一张任务。', parameters: z.toJSONSchema(decideSchema) },
229
+ handoff_decide: { description: '人或教练接受或拒绝一条提议。接受后仍要另调 execution_submit 并带上 handoffId,才会开下一张任务。本通道不能代写人的决定:kind 只能是 coach,人的决定在工作台页面上做。', parameters: z.toJSONSchema(decideSchema) },
172
230
  handoff_offer: { description: '登记一条约定:某件事在验收通过或任务单关闭后可以交给哪个目标。这不是流程图,多条同时成立时不会自动挑选。', parameters: z.toJSONSchema(offerSchema) },
173
231
  handoff_space: { description: '把一个已有的宿主目录登记为这件事的共享产物空间。不创建目录,也不把它当成角色公开目录或某个任务的私有目录。', parameters: z.toJSONSchema(spaceSchema) },
174
232
  handoff_get: { description: '读取这件事上的交接、当前允许的下一跳,以及已登记的共享产物空间。不派单。', parameters: z.toJSONSchema(readSchema) },
@@ -181,13 +239,20 @@ export function invokeHandoff(ledger, method, params) {
181
239
  if (typeof body.originSessionId === 'string')
182
240
  return proposeHandoff(ledger, body.originSessionId, params);
183
241
  const executor = proposeByExecutorSchema.parse(params);
184
- const origin = ledger.executorOrigin(executor.jobId, executor.attemptId, executor.sessionId);
242
+ const origin = ledger.executorHandoffOrigin(executor.jobId, executor.attemptId, executor.sessionId);
185
243
  return proposeHandoff(ledger, origin, { ...executor, originSessionId: origin });
186
244
  }
187
245
  case 'handoff_decide': return decideHandoff(ledger, params);
188
246
  case 'handoff_offer': return offerConvention(ledger, params);
189
247
  case 'handoff_space': return grantArtifactSpace(ledger, params);
190
- case 'handoff_get': return readHandoff(ledger, params);
248
+ case 'handoff_get': {
249
+ const body = params && typeof params === 'object' ? params : {};
250
+ if (typeof body.originSessionId === 'string')
251
+ return readHandoff(ledger, params);
252
+ const executor = readByExecutorSchema.parse(params);
253
+ const origin = ledger.executorHandoffOrigin(executor.jobId, executor.attemptId, executor.sessionId);
254
+ return readHandoff(ledger, { originSessionId: origin, jobId: executor.jobId });
255
+ }
191
256
  default: throw new Error(`Unknown handoff method: ${method}`);
192
257
  }
193
258
  }
@@ -1,5 +1,7 @@
1
1
  import type { Handoff, HandoffConvention } from './handoff.js';
2
2
  import type { ArtifactSpace } from './spaces.js';
3
+ import type { CaseRecord } from './cases.js';
4
+ import type { CaseFact, CaseReceipt } from './externals.js';
3
5
  import { type Ticket, type TicketChange } from './ticket.js';
4
6
  export type ExecutionStatus = 'not_started' | 'submitted' | 'working' | 'input_required' | 'auth_required' | 'completed' | 'failed' | 'canceled' | 'rejected' | 'unknown';
5
7
  export type SubmissionStatus = 'prepared' | 'dispatching' | 'accepted' | 'known_not_submitted' | 'submission_unknown';
@@ -38,11 +40,19 @@ export interface LedgerResult {
38
40
  resultAvailable: boolean;
39
41
  observedAt: string;
40
42
  }
41
- /** Who acted: a person, or a coach agent naming its session. */
43
+ /** Who acted: a person, a coach agent naming its session, or an application holding the workbench credential. */
42
44
  export interface LedgerActor {
43
- kind: 'person' | 'coach';
45
+ kind: 'person' | 'coach' | 'application';
46
+ id?: string;
44
47
  agent?: string;
45
48
  sessionId?: string;
49
+ /**
50
+ * How this claim reached the ledger. `page` is the gateway's own page session; `relay` is a host
51
+ * forwarding for its page with the shared secret. The two are indistinguishable to the gateway when
52
+ * the caller runs as the same OS user, so the record says which one it was instead of implying both
53
+ * are the same proof.
54
+ */
55
+ via?: 'page' | 'relay';
46
56
  }
47
57
  export interface BusinessAcceptance {
48
58
  attemptId: string;
@@ -149,6 +159,12 @@ export interface LedgerState {
149
159
  handoffs?: Handoff[];
150
160
  conventions?: HandoffConvention[];
151
161
  artifactSpaces?: ArtifactSpace[];
162
+ /** One thing, by (originSessionId, caseId). Absent in state written before cases existed. */
163
+ cases?: Record<string, CaseRecord>;
164
+ /** External receipts, one per (channel, remote id). */
165
+ receipts?: CaseReceipt[];
166
+ /** External facts. The platform stores the number; it does not judge it. */
167
+ facts?: CaseFact[];
152
168
  }
153
169
  export interface LedgerPrepareInput {
154
170
  originSessionId: string;
@@ -272,11 +288,22 @@ export declare class JobLedger {
272
288
  conventionsFor(originSessionId: string): HandoffConvention[];
273
289
  artifactSpace(originSessionId: string, caseId: string): ArtifactSpace | undefined;
274
290
  findHandoff(originSessionId: string, handoffId: string): Handoff | undefined;
291
+ /** The scope a job belongs to. */
292
+ originOf(jobId: string): string | undefined;
275
293
  /** Trusted handoff module: append or replace one edge and record it on the from-job. Binds caseId if the job has none. */
276
294
  commitHandoff(originSessionId: string, handoff: Handoff, event: string): Handoff;
277
295
  markHandoffTaken(originSessionId: string, handoffId: string, childJobId: string): Handoff;
278
296
  commitConvention(convention: HandoffConvention): HandoffConvention;
279
297
  commitArtifactSpace(space: ArtifactSpace): ArtifactSpace;
298
+ /** One thing. The record is written once; a second write with the same id keeps the first. */
299
+ commitCase(record: CaseRecord): CaseRecord;
300
+ findCase(originSessionId: string, caseId: string): CaseRecord | undefined;
301
+ casesFor(originSessionId?: string): CaseRecord[];
302
+ /** One external receipt per (channel, remote id). A different digest for the same key is a conflict. */
303
+ commitReceipt(receipt: CaseReceipt): CaseReceipt;
304
+ receiptsFor(originSessionId: string, caseId: string): CaseReceipt[];
305
+ commitFact(fact: CaseFact): CaseFact;
306
+ factsFor(originSessionId: string, caseId: string): CaseFact[];
280
307
  ticket(originSessionId: string, jobId: string): Ticket;
281
308
  /**
282
309
  * One ticket operation: it gets the job's ticket (undefined before one is opened) to change in place and reports
@@ -299,6 +326,12 @@ export declare class JobLedger {
299
326
  attemptId: string;
300
327
  sessionId?: string;
301
328
  };
329
+ /**
330
+ * The origin of the job whose current attempt `attemptId` is, for a caller that only names the attempt and its
331
+ * session. Unlike a ticket operation this accepts a finished round: handing over the result of a completed round
332
+ * is exactly what a handoff proposal is for.
333
+ */
334
+ executorHandoffOrigin(jobId: string, attemptId: string, sessionId: string): string;
302
335
  /** Each old Task gets one legacy Job; matching context IDs never merge jobs. */
303
336
  migrateLegacy(records: LegacyLedgerRecord[]): Array<{
304
337
  remote: string;
@@ -1,5 +1,6 @@
1
1
  /** Durable Job/Attempt facts. This module does not execute or schedule work. */
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
+ import { caseKey } from './cases.js';
3
4
  import { TicketError } from './ticket.js';
4
5
  const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
5
6
  const statuses = new Set(['not_started', 'submitted', 'working', 'input_required', 'auth_required', 'completed', 'failed', 'canceled', 'rejected', 'unknown']);
@@ -50,11 +51,12 @@ export class JobLedger {
50
51
  || !Number.isSafeInteger(initial.nextSequence) || !initial.acceptances)
51
52
  throw new Error('Invalid execution ledger state');
52
53
  this.state = { ...clone(initial), tickets: clone(initial.tickets ?? {}), handoffs: clone(initial.handoffs ?? []),
53
- conventions: clone(initial.conventions ?? []), artifactSpaces: clone(initial.artifactSpaces ?? []) };
54
+ conventions: clone(initial.conventions ?? []), artifactSpaces: clone(initial.artifactSpaces ?? []),
55
+ cases: clone(initial.cases ?? {}), receipts: clone(initial.receipts ?? []), facts: clone(initial.facts ?? []) };
54
56
  }
55
57
  else {
56
58
  this.state = { version: 1, sourceId: randomUUID(), jobs: {}, attempts: {}, requests: {}, events: [], nextSequence: 1, acceptances: {}, tickets: {},
57
- handoffs: [], conventions: [], artifactSpaces: [] };
59
+ handoffs: [], conventions: [], artifactSpaces: [], cases: {}, receipts: [], facts: [] };
58
60
  }
59
61
  }
60
62
  snapshot() { return clone(this.state); }
@@ -445,6 +447,10 @@ export class JobLedger {
445
447
  return undefined;
446
448
  return clone(handoff);
447
449
  }
450
+ /** The scope a job belongs to. */
451
+ originOf(jobId) {
452
+ return this.state.jobs[jobId]?.originSessionId;
453
+ }
448
454
  /** Trusted handoff module: append or replace one edge and record it on the from-job. Binds caseId if the job has none. */
449
455
  commitHandoff(originSessionId, handoff, event) {
450
456
  return this.mutate(state => {
@@ -513,6 +519,55 @@ export class JobLedger {
513
519
  return space;
514
520
  });
515
521
  }
522
+ /** One thing. The record is written once; a second write with the same id keeps the first. */
523
+ commitCase(record) {
524
+ return this.mutate(state => {
525
+ const list = state.cases ??= {};
526
+ const key = caseKey(record.originSessionId, record.caseId);
527
+ const prior = list[key];
528
+ if (prior)
529
+ return clone(prior);
530
+ list[key] = clone(record);
531
+ return record;
532
+ });
533
+ }
534
+ findCase(originSessionId, caseId) {
535
+ const record = this.state.cases?.[caseKey(originSessionId, caseId)];
536
+ return record ? clone(record) : undefined;
537
+ }
538
+ casesFor(originSessionId) {
539
+ return Object.values(this.state.cases ?? {})
540
+ .filter(record => !originSessionId || record.originSessionId === originSessionId)
541
+ .map(record => clone(record));
542
+ }
543
+ /** One external receipt per (channel, remote id). A different digest for the same key is a conflict. */
544
+ commitReceipt(receipt) {
545
+ return this.mutate(state => {
546
+ const list = state.receipts ??= [];
547
+ const prior = list.find(item => item.originSessionId === receipt.originSessionId && item.caseId === receipt.caseId
548
+ && item.channel === receipt.channel && item.remoteId === receipt.remoteId);
549
+ if (prior) {
550
+ if (prior.artifactDigest !== receipt.artifactDigest)
551
+ throw new Error('Receipt key already holds another digest');
552
+ return clone(prior);
553
+ }
554
+ list.push(clone(receipt));
555
+ return receipt;
556
+ });
557
+ }
558
+ receiptsFor(originSessionId, caseId) {
559
+ return clone((this.state.receipts ?? []).filter(item => item.originSessionId === originSessionId && item.caseId === caseId));
560
+ }
561
+ commitFact(fact) {
562
+ return this.mutate(state => {
563
+ const list = state.facts ??= [];
564
+ list.push(clone(fact));
565
+ return fact;
566
+ });
567
+ }
568
+ factsFor(originSessionId, caseId) {
569
+ return clone((this.state.facts ?? []).filter(item => item.originSessionId === originSessionId && item.caseId === caseId));
570
+ }
516
571
  ticket(originSessionId, jobId) {
517
572
  this.job(this.state, originSessionId, jobId);
518
573
  const ticket = this.state.tickets[jobId];
@@ -558,6 +613,21 @@ export class JobLedger {
558
613
  throw new TicketError('没有这个任务');
559
614
  return { attemptId: attempt.attemptId, ...(attempt.backendRunRef?.sessionId !== undefined ? { sessionId: attempt.backendRunRef.sessionId } : {}) };
560
615
  }
616
+ /**
617
+ * The origin of the job whose current attempt `attemptId` is, for a caller that only names the attempt and its
618
+ * session. Unlike a ticket operation this accepts a finished round: handing over the result of a completed round
619
+ * is exactly what a handoff proposal is for.
620
+ */
621
+ executorHandoffOrigin(jobId, attemptId, sessionId) {
622
+ const job = Object.hasOwn(this.state.jobs, jobId) ? this.state.jobs[jobId] : undefined;
623
+ const attempt = Object.hasOwn(this.state.attempts, attemptId) ? this.state.attempts[attemptId] : undefined;
624
+ if (!job || !attempt || attempt.jobId !== jobId || job.currentAttemptId !== attemptId)
625
+ throw new TicketError('这一轮执行不是该任务的当前轮次');
626
+ const recorded = attempt.backendRunRef?.sessionId;
627
+ if (recorded !== undefined && recorded !== sessionId)
628
+ throw new TicketError('调用的会话不是执行这一轮的会话');
629
+ return job.originSessionId;
630
+ }
561
631
  /** Each old Task gets one legacy Job; matching context IDs never merge jobs. */
562
632
  migrateLegacy(records) {
563
633
  return this.mutate(state => records.map(record => {
@@ -0,0 +1,28 @@
1
+ import type { HandoffSnapshot } from './handoff.js';
2
+ export declare class SnapshotError extends Error {
3
+ readonly code: 'not_found' | 'changed';
4
+ constructor(code: 'not_found' | 'changed', message: string);
5
+ }
6
+ export interface SnapshotInput {
7
+ caseId: string;
8
+ handoffId: string;
9
+ files: {
10
+ digest: string;
11
+ name: string;
12
+ mediaType?: string;
13
+ bytes: Buffer;
14
+ }[];
15
+ }
16
+ export declare class SnapshotStore {
17
+ private readonly root;
18
+ constructor(root: string);
19
+ /** The path a frozen file is stored at, relative to the store's root. */
20
+ storedPath(caseId: string, handoffId: string, digest: string): string;
21
+ private absolute;
22
+ /** Copy the bytes in. A file that is already frozen with the same digest is left alone. */
23
+ freeze(input: SnapshotInput): Promise<HandoffSnapshot[]>;
24
+ /** Read the frozen bytes back. The digest is checked again on every read. */
25
+ read(storedPath: string, expectedDigest: string): Promise<Buffer>;
26
+ /** The absolute path a frozen file lives at on this host. */
27
+ absolutePath(storedPath: string): string;
28
+ }