@1agents/acp-service 0.10.4 → 0.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/src/a2a/gateway.d.ts +75 -0
  2. package/dist/src/a2a/gateway.js +54 -7
  3. package/dist/src/a2a/index.d.ts +1 -1
  4. package/dist/src/a2a/index.js +1 -1
  5. package/dist/src/a2a/job-directory.d.ts +9 -0
  6. package/dist/src/a2a/job-directory.js +14 -1
  7. package/dist/src/a2a/preflight.d.ts +6 -0
  8. package/dist/src/a2a/preflight.js +46 -0
  9. package/dist/src/a2a/result-metadata.js +18 -7
  10. package/dist/src/a2a/standalone.d.ts +4 -0
  11. package/dist/src/a2a/standalone.js +3 -0
  12. package/dist/src/a2a/types.d.ts +6 -0
  13. package/dist/src/a2a/workbench-ui.js +6 -2
  14. package/dist/src/execution/handoff.d.ts +141 -0
  15. package/dist/src/execution/handoff.js +193 -0
  16. package/dist/src/execution/ledger.d.ts +18 -0
  17. package/dist/src/execution/ledger.js +95 -3
  18. package/dist/src/execution/spaces.d.ts +13 -0
  19. package/dist/src/execution/spaces.js +32 -0
  20. package/dist/src/execution/workbench.d.ts +8 -2
  21. package/dist/src/execution/workbench.js +24 -3
  22. package/dist/workbench-ui/app.js +1 -1
  23. package/package.json +17 -12
  24. package/skills/acp-service/references/roles-and-tasks.md +3 -1
  25. package/vendor/dsh/a2a-executor.d.ts +2 -2
  26. package/vendor/dsh/adapter.d.ts +4 -4
  27. package/vendor/dsh/client.js +9 -33
  28. package/vendor/dsh/cordis.patch.yml +3 -1
  29. package/vendor/dsh/index.js +0 -3
  30. package/vendor/dsh/service-process.js +3 -1
  31. package/vendor/dsh/ticket-tools.d.ts +1 -1
  32. package/vendor/runtime/dist/{cli-BwanDcOo.js → cli-DXmYwv3U.js} +4 -4
  33. package/vendor/runtime/dist/{cli-BwanDcOo.js.map → cli-DXmYwv3U.js.map} +1 -1
  34. package/vendor/runtime/dist/cli.js +8 -8
  35. package/vendor/runtime/dist/{client-C5zneoBs.d.ts → client-VQsqcIOJ.d.ts} +1 -3
  36. package/vendor/runtime/dist/{client-C5zneoBs.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  37. package/vendor/runtime/dist/{flows-CzLUHUTS.js → flows-DJ17ajbw.js} +4 -4
  38. package/vendor/runtime/dist/{flows-CzLUHUTS.js.map → flows-DJ17ajbw.js.map} +1 -1
  39. package/vendor/runtime/dist/flows.d.ts +1 -1
  40. package/vendor/runtime/dist/flows.js +1 -1
  41. package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js → invocation-options-PBfCgrdi.js} +4 -4
  42. package/vendor/runtime/dist/{invocation-options-B6pIpdpR.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  43. package/vendor/runtime/dist/{ipc-ivLtSAdL.js → ipc-BQQpcEdP.js} +3 -21
  44. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  45. package/vendor/runtime/dist/{output-BqKnXXb0.js → output-B3MDn7kv.js} +3 -3
  46. package/vendor/runtime/dist/{output-BqKnXXb0.js.map → output-B3MDn7kv.js.map} +1 -1
  47. package/vendor/runtime/dist/{queue-owner-runtime-DXJND10J.js → queue-owner-runtime-DXCVngwU.js} +2 -11
  48. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  49. package/vendor/runtime/dist/runtime.d.ts +1 -1
  50. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  51. package/vendor/runtime/dist/runtime.js +3 -3
  52. package/vendor/runtime/dist/{session-watch-BHB3_PXm.js → session-watch-DURyCw31.js} +4 -4
  53. package/vendor/runtime/dist/{session-watch-BHB3_PXm.js.map → session-watch-DURyCw31.js.map} +1 -1
  54. package/vendor/runtime/dist/{watch-UjokHUfS.js → watch-CIpoMaWD.js} +2 -2
  55. package/vendor/runtime/dist/{watch-UjokHUfS.js.map → watch-CIpoMaWD.js.map} +1 -1
  56. package/vendor/dsh/workbench.d.ts +0 -18
  57. package/vendor/dsh/workbench.js +0 -91
  58. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  59. package/vendor/runtime/dist/docs-site/CLI.html +0 -833
  60. package/vendor/runtime/dist/docs-site/VISION.html +0 -415
  61. package/vendor/runtime/dist/docs-site/agents.html +0 -391
  62. package/vendor/runtime/dist/docs-site/compare.html +0 -359
  63. package/vendor/runtime/dist/docs-site/config.html +0 -450
  64. package/vendor/runtime/dist/docs-site/custom-agents.html +0 -408
  65. package/vendor/runtime/dist/docs-site/exit-codes.html +0 -347
  66. package/vendor/runtime/dist/docs-site/favicon.svg +0 -21
  67. package/vendor/runtime/dist/docs-site/flows.html +0 -498
  68. package/vendor/runtime/dist/docs-site/index.html +0 -367
  69. package/vendor/runtime/dist/docs-site/install.html +0 -386
  70. package/vendor/runtime/dist/docs-site/llms.txt +0 -36
  71. package/vendor/runtime/dist/docs-site/output-formats.html +0 -407
  72. package/vendor/runtime/dist/docs-site/permissions.html +0 -422
  73. package/vendor/runtime/dist/docs-site/prompting.html +0 -460
  74. package/vendor/runtime/dist/docs-site/quickstart.html +0 -382
  75. package/vendor/runtime/dist/docs-site/releasing.html +0 -341
  76. package/vendor/runtime/dist/docs-site/runtime-environment.html +0 -329
  77. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +0 -336
  78. package/vendor/runtime/dist/docs-site/safe-errors.html +0 -323
  79. package/vendor/runtime/dist/docs-site/session-control.html +0 -408
  80. package/vendor/runtime/dist/docs-site/session-watch.html +0 -354
  81. package/vendor/runtime/dist/docs-site/sessions.html +0 -488
  82. package/vendor/runtime/dist/docs-site/shared-sessions.html +0 -377
  83. package/vendor/runtime/dist/ipc-ivLtSAdL.js.map +0 -1
  84. package/vendor/runtime/dist/queue-owner-runtime-DXJND10J.js.map +0 -1
@@ -0,0 +1,193 @@
1
+ /**
2
+ * A handoff is a ledger edge, not a dispatch and not a drawn flow.
3
+ * An agent proposes one. A standing convention can accept one when its predicate is already true.
4
+ * Only an accepted handoff may be marked taken, and only by the submit that opens the next job.
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { z } from 'zod';
8
+ import { TicketError } from './ticket.js';
9
+ const id = z.string().trim().min(1).max(512);
10
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
11
+ const text = z.string().trim().min(1).max(4000);
12
+ export const handoffWhenSchema = z.enum(['acceptance_accepted', 'ticket_closed']);
13
+ export class HandoffError extends Error {
14
+ }
15
+ 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()
17
+ .refine(actor => actor.kind === 'coach' || (!actor.agent && !actor.sessionId), 'Only a coach names an agent session');
18
+ const proposeFields = {
19
+ caseId: id, toTargetId: id, purpose: id, artifactRevision: id, artifactDigest: digest, reason: text,
20
+ clientRequestId: id.optional(),
21
+ };
22
+ const proposeByOriginSchema = z.object({ originSessionId: id, jobId: id, attemptId: id, ...proposeFields }).strict();
23
+ const proposeByExecutorSchema = z.object({ jobId: id, attemptId: id, sessionId: id, via: z.enum(['dsh', 'mcp', 'cli']).optional(), ...proposeFields }).strict();
24
+ const decideSchema = z.object({ originSessionId: id, handoffId: id, decision: z.enum(['accept', 'reject']),
25
+ note: z.string().trim().max(4000).optional(), decidedBy: actorSchema }).strict();
26
+ 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();
28
+ const spaceSchema = z.object({ originSessionId: id, caseId: id,
29
+ 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
+ const readSchema = z.object({ originSessionId: id, jobId: id }).strict();
31
+ function applies(rule, job) {
32
+ return rule.originSessionId === job.originSessionId && rule.caseId === job.caseId
33
+ && (!rule.fromPurpose || rule.fromPurpose === job.purpose)
34
+ && (!rule.fromTargetId || rule.fromTargetId === job.targetId)
35
+ && rule.toTargetId !== job.targetId;
36
+ }
37
+ function ticketClosed(ledger, origin, jobId) {
38
+ try {
39
+ return ledger.ticket(origin, jobId).status === 'closed';
40
+ }
41
+ catch (error) {
42
+ if (error instanceof TicketError)
43
+ return false;
44
+ throw error;
45
+ }
46
+ }
47
+ function achieved(rule, view, closed) {
48
+ if (rule.when === 'ticket_closed')
49
+ return closed;
50
+ const acceptance = view.businessAcceptance;
51
+ return acceptance?.reviewStatus === 'accepted'
52
+ && acceptance.resultDigest === view.result?.resultDigest
53
+ && acceptance.resultRevision === view.result?.resultRevision
54
+ && view.result?.resultAvailable === true;
55
+ }
56
+ export function legalNextFor(ledger, originSessionId, jobId) {
57
+ const view = ledger.get(originSessionId, jobId);
58
+ if (!view.caseId)
59
+ return [];
60
+ const closed = ticketClosed(ledger, originSessionId, jobId);
61
+ return ledger.conventionsFor(originSessionId).filter(rule => applies(rule, view)).map(rule => ({
62
+ conventionId: rule.conventionId, toTargetId: rule.toTargetId, purpose: rule.toPurpose,
63
+ requireHuman: rule.requireHuman, when: rule.when, achieved: achieved(rule, view, closed),
64
+ }));
65
+ }
66
+ function sameProposal(existing, input) {
67
+ return existing.caseId === input.caseId && existing.toTargetId === input.toTargetId && existing.purpose === input.purpose
68
+ && existing.artifactRevision === input.artifactRevision && existing.artifactDigest === input.artifactDigest && existing.reason === input.reason;
69
+ }
70
+ /** Record a proposal. A single matching convention with requireHuman false accepts it. Nothing here opens a job. */
71
+ export function proposeHandoff(ledger, originSessionId, raw) {
72
+ const input = proposeByOriginSchema.parse({ ...raw, originSessionId });
73
+ const view = ledger.get(originSessionId, input.jobId);
74
+ const attempt = view.attempts.find(item => item.attemptId === input.attemptId) ?? fail('Attempt does not belong to this job');
75
+ if (attempt.attemptId !== view.currentAttemptId)
76
+ fail('Handoff must name the job\'s current attempt');
77
+ if (input.toTargetId === view.targetId)
78
+ fail('Handoff must name a different target; continue the same job to revise');
79
+ if (!attempt.result?.resultAvailable || attempt.result.resultDigest !== input.artifactDigest || attempt.result.resultRevision !== input.artifactRevision) {
80
+ fail('Handoff must name the current result revision and digest');
81
+ }
82
+ const existing = ledger.handoffsFor(originSessionId, input.jobId);
83
+ const replay = input.clientRequestId ? existing.find(item => item.clientRequestId === input.clientRequestId) : undefined;
84
+ if (replay)
85
+ return sameProposal(replay, input) ? replay : fail('clientRequestId conflicts with an existing handoff');
86
+ const open = existing.find(item => item.status !== 'rejected' && item.toTargetId === input.toTargetId && item.purpose === input.purpose && item.artifactDigest === input.artifactDigest);
87
+ if (open)
88
+ return open;
89
+ const closed = ticketClosed(ledger, originSessionId, input.jobId);
90
+ 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)
93
+ fail('More than one achieved convention matches this handoff; a person must choose');
94
+ const now = new Date().toISOString();
95
+ const handoff = {
96
+ handoffId: randomUUID(), caseId: input.caseId, fromJobId: input.jobId, fromAttemptId: input.attemptId,
97
+ toTargetId: input.toTargetId, purpose: input.purpose, artifactRevision: input.artifactRevision, artifactDigest: input.artifactDigest,
98
+ reason: input.reason, status: matches.some(rule => !rule.requireHuman) ? 'accepted' : 'proposed',
99
+ ...(input.clientRequestId ? { clientRequestId: input.clientRequestId } : {}),
100
+ ...(matches.some(rule => !rule.requireHuman) ? { conventionId: matches.find(rule => !rule.requireHuman).conventionId } : {}),
101
+ createdAt: now, updatedAt: now,
102
+ };
103
+ return ledger.commitHandoff(originSessionId, handoff, handoff.status === 'accepted' ? 'handoff.accepted' : 'handoff.proposed');
104
+ }
105
+ export function decideHandoff(ledger, raw) {
106
+ const input = decideSchema.parse(raw);
107
+ const current = ledger.findHandoff(input.originSessionId, input.handoffId) ?? fail('Handoff not found');
108
+ if (current.status === 'taken')
109
+ fail('A taken handoff already opened a job');
110
+ if (current.status === 'rejected')
111
+ return input.decision === 'reject' ? current : fail('A rejected handoff cannot be accepted');
112
+ if (current.status === 'accepted')
113
+ return input.decision === 'accept' ? current : fail('An accepted handoff cannot be rejected without a new proposal');
114
+ const now = new Date().toISOString();
115
+ const next = { ...current, status: input.decision === 'accept' ? 'accepted' : 'rejected', decidedBy: input.decidedBy,
116
+ ...(input.note ? { note: input.note } : {}), updatedAt: now };
117
+ return ledger.commitHandoff(input.originSessionId, next, input.decision === 'accept' ? 'handoff.accepted' : 'handoff.rejected');
118
+ }
119
+ /**
120
+ * When exactly one convention's predicate holds and it does not ask for a person, record an accepted handoff.
121
+ * Zero or several matches record nothing. This does not submit the next job.
122
+ */
123
+ export function continueByConvention(ledger, originSessionId, jobId) {
124
+ const view = ledger.get(originSessionId, jobId);
125
+ if (!view.caseId || !view.result?.resultAvailable || !view.result.resultDigest || !view.result.resultRevision)
126
+ return undefined;
127
+ const closed = ticketClosed(ledger, originSessionId, jobId);
128
+ const ready = ledger.conventionsFor(originSessionId).filter(rule => applies(rule, view) && !rule.requireHuman && achieved(rule, view, closed));
129
+ if (ready.length !== 1)
130
+ return undefined;
131
+ const rule = ready[0];
132
+ const digest = view.result.resultDigest;
133
+ const existing = ledger.handoffsFor(originSessionId, jobId);
134
+ if (existing.some(item => item.fromAttemptId === view.currentAttemptId && item.artifactDigest === digest && item.status !== 'rejected'))
135
+ return undefined;
136
+ const clientRequestId = `convention:${rule.conventionId}:${digest}`;
137
+ const now = new Date().toISOString();
138
+ return ledger.commitHandoff(originSessionId, {
139
+ handoffId: randomUUID(), caseId: view.caseId, fromJobId: jobId, fromAttemptId: view.currentAttemptId,
140
+ toTargetId: rule.toTargetId, purpose: rule.toPurpose, artifactRevision: view.result.resultRevision, artifactDigest: digest,
141
+ reason: '约定已达成', status: 'accepted', clientRequestId, conventionId: rule.conventionId, createdAt: now, updatedAt: now,
142
+ }, 'handoff.accepted');
143
+ }
144
+ export function offerConvention(ledger, raw) {
145
+ const input = offerSchema.parse(raw);
146
+ if (input.fromTargetId && input.fromTargetId === input.toTargetId)
147
+ fail('A convention must name a different target');
148
+ return ledger.commitConvention({
149
+ conventionId: randomUUID(), originSessionId: input.originSessionId, caseId: input.caseId,
150
+ ...(input.fromPurpose ? { fromPurpose: input.fromPurpose } : {}), ...(input.fromTargetId ? { fromTargetId: input.fromTargetId } : {}),
151
+ toTargetId: input.toTargetId, toPurpose: input.toPurpose, when: input.when, requireHuman: input.requireHuman ?? false,
152
+ ...(input.clientRequestId ? { clientRequestId: input.clientRequestId } : {}), recordedAt: new Date().toISOString(),
153
+ });
154
+ }
155
+ export function grantArtifactSpace(ledger, raw) {
156
+ const input = spaceSchema.parse(raw);
157
+ return ledger.commitArtifactSpace({ ...input, recordedAt: new Date().toISOString() });
158
+ }
159
+ export function readHandoff(ledger, raw) {
160
+ const input = readSchema.parse(raw);
161
+ const view = ledger.get(input.originSessionId, input.jobId);
162
+ const space = view.caseId ? ledger.artifactSpace(input.originSessionId, view.caseId) : undefined;
163
+ return {
164
+ caseId: view.caseId, handoffs: ledger.handoffsFor(input.originSessionId, input.jobId),
165
+ legalNext: legalNextFor(ledger, input.originSessionId, input.jobId),
166
+ ...(space ? { artifactSpace: space.root } : {}),
167
+ };
168
+ }
169
+ export const HANDOFF_METHODS = {
170
+ handoff_propose: { description: '提议把当前轮次已记录的产物交给另一个执行目标。只写账本,不派下一单。唯一匹配且不要求人确认的约定会直接接受;多条匹配则拒绝代选。', parameters: z.toJSONSchema(proposeByOriginSchema) },
171
+ handoff_decide: { description: '人或教练接受或拒绝一条提议。接受后仍要另调 execution_submit 并带上 handoffId,才会开下一张任务。', parameters: z.toJSONSchema(decideSchema) },
172
+ handoff_offer: { description: '登记一条约定:某件事在验收通过或任务单关闭后可以交给哪个目标。这不是流程图,多条同时成立时不会自动挑选。', parameters: z.toJSONSchema(offerSchema) },
173
+ handoff_space: { description: '把一个已有的宿主目录登记为这件事的共享产物空间。不创建目录,也不把它当成角色公开目录或某个任务的私有目录。', parameters: z.toJSONSchema(spaceSchema) },
174
+ handoff_get: { description: '读取这件事上的交接、当前允许的下一跳,以及已登记的共享产物空间。不派单。', parameters: z.toJSONSchema(readSchema) },
175
+ };
176
+ /** Gateway entry. An executor may omit originSessionId; the current attempt's session identifies the job. */
177
+ export function invokeHandoff(ledger, method, params) {
178
+ switch (method) {
179
+ case 'handoff_propose': {
180
+ const body = params && typeof params === 'object' ? params : {};
181
+ if (typeof body.originSessionId === 'string')
182
+ return proposeHandoff(ledger, body.originSessionId, params);
183
+ const executor = proposeByExecutorSchema.parse(params);
184
+ const origin = ledger.executorOrigin(executor.jobId, executor.attemptId, executor.sessionId);
185
+ return proposeHandoff(ledger, origin, { ...executor, originSessionId: origin });
186
+ }
187
+ case 'handoff_decide': return decideHandoff(ledger, params);
188
+ case 'handoff_offer': return offerConvention(ledger, params);
189
+ case 'handoff_space': return grantArtifactSpace(ledger, params);
190
+ case 'handoff_get': return readHandoff(ledger, params);
191
+ default: throw new Error(`Unknown handoff method: ${method}`);
192
+ }
193
+ }
@@ -1,3 +1,5 @@
1
+ import type { Handoff, HandoffConvention } from './handoff.js';
2
+ import type { ArtifactSpace } from './spaces.js';
1
3
  import { type Ticket, type TicketChange } from './ticket.js';
2
4
  export type ExecutionStatus = 'not_started' | 'submitted' | 'working' | 'input_required' | 'auth_required' | 'completed' | 'failed' | 'canceled' | 'rejected' | 'unknown';
3
5
  export type SubmissionStatus = 'prepared' | 'dispatching' | 'accepted' | 'known_not_submitted' | 'submission_unknown';
@@ -106,6 +108,8 @@ export interface LedgerJob {
106
108
  purpose?: string;
107
109
  resultRevision?: string;
108
110
  replacesJobRef?: JobRef;
111
+ /** Set when the job is part of a case that can share an artifact space and handoffs. Absent on older jobs. */
112
+ caseId?: string;
109
113
  jobVersion: number;
110
114
  createdAt: string | null;
111
115
  updatedAt: string;
@@ -141,6 +145,10 @@ export interface LedgerState {
141
145
  acceptances: Record<string, BusinessAcceptance[]>;
142
146
  /** Task tickets by executor jobId; absent in state written before tickets existed. */
143
147
  tickets?: Record<string, Ticket>;
148
+ /** Absent in state written before handoffs existed. */
149
+ handoffs?: Handoff[];
150
+ conventions?: HandoffConvention[];
151
+ artifactSpaces?: ArtifactSpace[];
144
152
  }
145
153
  export interface LedgerPrepareInput {
146
154
  originSessionId: string;
@@ -154,6 +162,7 @@ export interface LedgerPrepareInput {
154
162
  parentAttemptId?: string;
155
163
  purpose?: string;
156
164
  title?: string;
165
+ caseId?: string;
157
166
  operation?: string;
158
167
  resultRevision?: string;
159
168
  replacesJobRef?: JobRef;
@@ -259,6 +268,15 @@ export declare class JobLedger {
259
268
  processEvent(jobId: string, attemptId: string, type: string, data: unknown): void;
260
269
  /** The originator waits on the job again, so it is no longer listed as abandoned. */
261
270
  rewatch(originSessionId: string, jobId: string): LedgerAttempt;
271
+ handoffsFor(originSessionId: string, jobId: string): Handoff[];
272
+ conventionsFor(originSessionId: string): HandoffConvention[];
273
+ artifactSpace(originSessionId: string, caseId: string): ArtifactSpace | undefined;
274
+ findHandoff(originSessionId: string, handoffId: string): Handoff | undefined;
275
+ /** Trusted handoff module: append or replace one edge and record it on the from-job. Binds caseId if the job has none. */
276
+ commitHandoff(originSessionId: string, handoff: Handoff, event: string): Handoff;
277
+ markHandoffTaken(originSessionId: string, handoffId: string, childJobId: string): Handoff;
278
+ commitConvention(convention: HandoffConvention): HandoffConvention;
279
+ commitArtifactSpace(space: ArtifactSpace): ArtifactSpace;
262
280
  ticket(originSessionId: string, jobId: string): Ticket;
263
281
  /**
264
282
  * One ticket operation: it gets the job's ticket (undefined before one is opened) to change in place and reports
@@ -49,10 +49,12 @@ export class JobLedger {
49
49
  if (initial.version !== 1 || !initial.sourceId || !initial.jobs || !initial.attempts || !initial.requests || !Array.isArray(initial.events)
50
50
  || !Number.isSafeInteger(initial.nextSequence) || !initial.acceptances)
51
51
  throw new Error('Invalid execution ledger state');
52
- this.state = { ...clone(initial), tickets: clone(initial.tickets ?? {}) };
52
+ this.state = { ...clone(initial), tickets: clone(initial.tickets ?? {}), handoffs: clone(initial.handoffs ?? []),
53
+ conventions: clone(initial.conventions ?? []), artifactSpaces: clone(initial.artifactSpaces ?? []) };
53
54
  }
54
55
  else {
55
- this.state = { version: 1, sourceId: randomUUID(), jobs: {}, attempts: {}, requests: {}, events: [], nextSequence: 1, acceptances: {}, tickets: {} };
56
+ this.state = { version: 1, sourceId: randomUUID(), jobs: {}, attempts: {}, requests: {}, events: [], nextSequence: 1, acceptances: {}, tickets: {},
57
+ handoffs: [], conventions: [], artifactSpaces: [] };
56
58
  }
57
59
  }
58
60
  snapshot() { return clone(this.state); }
@@ -124,7 +126,7 @@ export class JobLedger {
124
126
  const request = { operation, targetId: input.targetSnapshot.targetId,
125
127
  input: input.requestDigestInput === undefined ? input.input : input.requestDigestInput, jobId: input.jobId,
126
128
  parentJobRef: input.parentJobRef, parentAttemptId: input.parentAttemptId, purpose: input.purpose,
127
- title: input.title, resultRevision: input.resultRevision, replacesJobRef: input.replacesJobRef };
129
+ title: input.title, resultRevision: input.resultRevision, replacesJobRef: input.replacesJobRef, caseId: input.caseId };
128
130
  const digest = createHash('sha256').update(canonical(request)).digest('hex');
129
131
  const requestKey = input.clientRequestId === undefined ? undefined : canonical([this.state.sourceId, input.originSessionId, operation, input.clientRequestId]);
130
132
  return { operation, digest, requestKey };
@@ -159,6 +161,10 @@ export class JobLedger {
159
161
  if (input.parentJobRef && canonical(input.parentJobRef) !== canonical(job.parentJobRef ?? null)
160
162
  || input.parentAttemptId && input.parentAttemptId !== job.parentAttemptId)
161
163
  throw new Error('A job cannot change its parent');
164
+ if (input.caseId && job.caseId && input.caseId !== job.caseId)
165
+ throw new Error('A job cannot change its case');
166
+ if (input.caseId && !job.caseId)
167
+ job.caseId = input.caseId;
162
168
  }
163
169
  else {
164
170
  if (Boolean(input.parentJobRef) !== Boolean(input.parentAttemptId))
@@ -178,6 +184,7 @@ export class JobLedger {
178
184
  ...(input.parentJobRef ? { parentJobRef: clone(input.parentJobRef), parentAttemptId: input.parentAttemptId } : {}),
179
185
  ...(input.purpose ? { purpose: input.purpose } : {}), ...(input.resultRevision ? { resultRevision: input.resultRevision } : {}),
180
186
  ...(input.replacesJobRef ? { replacesJobRef: clone(input.replacesJobRef) } : {}),
187
+ ...(input.caseId ? { caseId: input.caseId } : {}),
181
188
  ...(input.initiatedBy ? { initiatedBy: clone(input.initiatedBy) } : {}) };
182
189
  state.jobs[job.jobId] = job;
183
190
  }
@@ -421,6 +428,91 @@ export class JobLedger {
421
428
  return clone(attempt);
422
429
  });
423
430
  }
431
+ handoffsFor(originSessionId, jobId) {
432
+ this.job(this.state, originSessionId, jobId);
433
+ return clone((this.state.handoffs ?? []).filter(item => item.fromJobId === jobId || item.childJobId === jobId));
434
+ }
435
+ conventionsFor(originSessionId) {
436
+ return clone((this.state.conventions ?? []).filter(item => item.originSessionId === originSessionId));
437
+ }
438
+ artifactSpace(originSessionId, caseId) {
439
+ return clone((this.state.artifactSpaces ?? []).find(item => item.originSessionId === originSessionId && item.caseId === caseId));
440
+ }
441
+ findHandoff(originSessionId, handoffId) {
442
+ const handoff = (this.state.handoffs ?? []).find(item => item.handoffId === handoffId);
443
+ const job = handoff ? this.state.jobs[handoff.fromJobId] : undefined;
444
+ if (!handoff || !job || job.originSessionId !== originSessionId)
445
+ return undefined;
446
+ return clone(handoff);
447
+ }
448
+ /** Trusted handoff module: append or replace one edge and record it on the from-job. Binds caseId if the job has none. */
449
+ commitHandoff(originSessionId, handoff, event) {
450
+ return this.mutate(state => {
451
+ const job = this.job(state, originSessionId, handoff.fromJobId);
452
+ if (job.caseId && job.caseId !== handoff.caseId)
453
+ throw new Error('Job is already bound to another case');
454
+ job.caseId ??= handoff.caseId;
455
+ const list = state.handoffs ??= [];
456
+ const index = list.findIndex(item => item.handoffId === handoff.handoffId);
457
+ if (index >= 0)
458
+ list[index] = clone(handoff);
459
+ else
460
+ list.push(clone(handoff));
461
+ this.event(state, job, handoff.fromAttemptId, event, { handoffId: handoff.handoffId, status: handoff.status,
462
+ toTargetId: handoff.toTargetId, purpose: handoff.purpose, caseId: handoff.caseId, artifactRevision: handoff.artifactRevision,
463
+ artifactDigest: handoff.artifactDigest, ...(handoff.childJobId ? { childJobId: handoff.childJobId } : {}),
464
+ ...(handoff.conventionId ? { conventionId: handoff.conventionId } : {}) });
465
+ return handoff;
466
+ });
467
+ }
468
+ markHandoffTaken(originSessionId, handoffId, childJobId) {
469
+ return this.mutate(state => {
470
+ const handoff = (state.handoffs ?? []).find(item => item.handoffId === handoffId);
471
+ if (!handoff)
472
+ throw new Error('Handoff not found');
473
+ const job = this.job(state, originSessionId, handoff.fromJobId);
474
+ if (handoff.status === 'taken') {
475
+ if (handoff.childJobId !== childJobId)
476
+ throw new Error('Handoff already opened a different job');
477
+ return clone(handoff);
478
+ }
479
+ if (handoff.status !== 'accepted')
480
+ throw new Error('Only an accepted handoff opens a job');
481
+ const child = this.job(state, originSessionId, childJobId);
482
+ if (child.parentJobRef?.jobId !== handoff.fromJobId || child.parentAttemptId !== handoff.fromAttemptId
483
+ || child.targetId !== handoff.toTargetId || child.purpose !== handoff.purpose || child.caseId !== handoff.caseId) {
484
+ throw new Error('Child job does not match the handoff');
485
+ }
486
+ handoff.status = 'taken';
487
+ handoff.childJobId = childJobId;
488
+ handoff.updatedAt = now();
489
+ this.event(state, job, handoff.fromAttemptId, 'handoff.taken', { handoffId, childJobId, toTargetId: handoff.toTargetId, purpose: handoff.purpose });
490
+ return clone(handoff);
491
+ });
492
+ }
493
+ commitConvention(convention) {
494
+ return this.mutate(state => {
495
+ const list = state.conventions ??= [];
496
+ const prior = convention.clientRequestId ? list.find(item => item.originSessionId === convention.originSessionId && item.clientRequestId === convention.clientRequestId) : undefined;
497
+ if (prior)
498
+ return clone(prior);
499
+ list.push(clone(convention));
500
+ return convention;
501
+ });
502
+ }
503
+ commitArtifactSpace(space) {
504
+ return this.mutate(state => {
505
+ const list = state.artifactSpaces ??= [];
506
+ const prior = list.find(item => item.originSessionId === space.originSessionId && item.caseId === space.caseId);
507
+ if (prior) {
508
+ if (prior.root !== space.root)
509
+ throw new Error('Artifact space for this case already has a different root');
510
+ return clone(prior);
511
+ }
512
+ list.push(clone(space));
513
+ return space;
514
+ });
515
+ }
424
516
  ticket(originSessionId, jobId) {
425
517
  this.job(this.state, originSessionId, jobId);
426
518
  const ticket = this.state.tickets[jobId];
@@ -0,0 +1,13 @@
1
+ export interface ArtifactSpace {
2
+ originSessionId: string;
3
+ caseId: string;
4
+ /** Absolute path on the execution host. The gateway does not create it. */
5
+ root: string;
6
+ recordedAt: string;
7
+ }
8
+ export declare function rolePublicationDirectory(cwd: string, roleId: string): string | undefined;
9
+ /** The role id named by `<cwd>/.1agents/roles/<roleId>/published`, if the path is exactly that. */
10
+ export declare function roleIdFromPublication(cwd: string, directory: string): string | undefined;
11
+ export type SpaceKind = 'role_publication' | 'job' | 'artifact_space' | 'outside';
12
+ /** Classify an announced path. Realpath containment is the host's job; this only separates the three contracts. */
13
+ export declare function classifySpace(cwd: string, directory: string, jobDirectory?: string, artifactSpace?: string): SpaceKind;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Three directories, and they are not interchangeable.
3
+ * A role publication is readable by other roles. A job directory belongs to one task.
4
+ * An artifact space is the shared place where several tasks of one case write deliverables.
5
+ * Path checks here are POSIX spellings announced to a remote host; the host still realpath-checks them.
6
+ */
7
+ import { posix } from 'node:path';
8
+ const ROLE_ID = /^[A-Za-z0-9._-]{1,200}$/;
9
+ export function rolePublicationDirectory(cwd, roleId) {
10
+ if (!ROLE_ID.test(roleId))
11
+ return undefined;
12
+ return posix.join(cwd, '.1agents', 'roles', roleId, 'published');
13
+ }
14
+ /** The role id named by `<cwd>/.1agents/roles/<roleId>/published`, if the path is exactly that. */
15
+ export function roleIdFromPublication(cwd, directory) {
16
+ const tail = posix.relative(posix.join(cwd, '.1agents', 'roles'), directory);
17
+ const match = /^([A-Za-z0-9._-]+)\/published$/.exec(tail);
18
+ return match?.[1];
19
+ }
20
+ /** Classify an announced path. Realpath containment is the host's job; this only separates the three contracts. */
21
+ export function classifySpace(cwd, directory, jobDirectory, artifactSpace) {
22
+ if (roleIdFromPublication(cwd, directory))
23
+ return 'role_publication';
24
+ if (jobDirectory && directory === jobDirectory)
25
+ return 'job';
26
+ if (artifactSpace) {
27
+ const tail = posix.relative(artifactSpace, directory);
28
+ if (tail === '' || (tail !== '..' && !tail.startsWith('../') && !posix.isAbsolute(tail)))
29
+ return 'artifact_space';
30
+ }
31
+ return 'outside';
32
+ }
@@ -6,6 +6,7 @@ import { deliveryProgress } from './delivery-progress.js';
6
6
  import type { HumanReviewRequest, HumanReviewStatus } from './human-review.js';
7
7
  import { type ProcessRequest } from './process-request.js';
8
8
  import { type AgentDraft, type AgentRelease, type ResidentAgentRef, type WorkbenchAgentRow } from './agent-registry.js';
9
+ import type { Handoff, LegalNext } from './handoff.js';
9
10
  export interface WorkbenchServiceInfo {
10
11
  kind: 'a2a' | 'gateway_workflow' | 'activepieces' | 'unknown';
11
12
  source: 'backend_run' | 'target_snapshot' | 'workflow_run' | 'unrecorded';
@@ -31,6 +32,7 @@ export interface AcpTaskSummary {
31
32
  jobId: string;
32
33
  title: string;
33
34
  originSessionId: string;
35
+ caseId?: string;
34
36
  parentJobRef?: JobRef;
35
37
  parentAttemptId?: string;
36
38
  purpose?: string;
@@ -84,10 +86,12 @@ export interface WorkbenchProgress {
84
86
  }
85
87
  export interface WorkbenchDependency {
86
88
  from: string;
87
- to: string;
88
- kind: 'parent' | 'depends_on' | 'replaces';
89
+ to?: string;
90
+ kind: 'parent' | 'depends_on' | 'replaces' | 'handoff';
89
91
  label: string;
90
92
  parentAttemptId?: string;
93
+ handoffId?: string;
94
+ status?: Handoff['status'];
91
95
  }
92
96
  export type WorkbenchReview = HumanReviewRequest & {
93
97
  canReview: boolean;
@@ -112,6 +116,8 @@ export interface AcpTaskDetail extends AcpTaskSummary {
112
116
  processRequests: WorkbenchProcessRequest[];
113
117
  events: LedgerEvent[];
114
118
  dependencies: WorkbenchDependency[];
119
+ /** Conventions that apply to this job. Unachieved ones are not drawn as edges. */
120
+ legalNext?: LegalNext[];
115
121
  artifacts: {
116
122
  revision: string;
117
123
  digest?: string;
@@ -15,6 +15,19 @@ function runDescription(run) {
15
15
  return ({ summary: '文稿作者正在生成或修订文字稿。', make: '制作角色正在根据确认的文字稿设计 PPT。', validate: '正在检查制作产物的文件与结构。',
16
16
  review: '独立验收角色正在核对事实和页面效果。', finished: '交付已完成,可查看最终产物。' })[run.stage];
17
17
  }
18
+ function legalNext(ledger, job) {
19
+ if (!job.caseId)
20
+ return [];
21
+ const attempt = ledger.attempts[job.currentAttemptId];
22
+ const acceptance = [...(ledger.acceptances[job.jobId] ?? [])].reverse().find(item => item.attemptId === job.currentAttemptId && item.resultDigest === attempt?.result?.resultDigest && item.resultRevision === attempt?.result?.resultRevision);
23
+ const closed = ledger.tickets?.[job.jobId]?.status === 'closed';
24
+ const applies = (rule) => rule.originSessionId === job.originSessionId && rule.caseId === job.caseId
25
+ && (!rule.fromPurpose || rule.fromPurpose === job.purpose) && (!rule.fromTargetId || rule.fromTargetId === job.targetId) && rule.toTargetId !== job.targetId;
26
+ return (ledger.conventions ?? []).filter(applies).map(rule => ({
27
+ conventionId: rule.conventionId, toTargetId: rule.toTargetId, purpose: rule.toPurpose, requireHuman: rule.requireHuman, when: rule.when,
28
+ achieved: rule.when === 'ticket_closed' ? Boolean(closed) : acceptance?.reviewStatus === 'accepted' && attempt?.result?.resultAvailable === true,
29
+ }));
30
+ }
18
31
  function byNewest(items) { return items.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); }
19
32
  function latestReview(reviews, job) {
20
33
  return byNewest(reviews.filter(r => r.jobId === job.jobId && r.attemptId === job.currentAttemptId).map(r => structuredClone(r)).reverse())[0];
@@ -205,7 +218,7 @@ function summary(job, run, reviews, ledger, actorId, requests, now) {
205
218
  const development = describeTaskDevelopment(attempt?.targetSnapshot?.development, { targetId: job.targetId, resident: execution.kind === 'resident', residentName: execution.targetName });
206
219
  return { sourceId: job.sourceId, jobId: job.jobId, title: job.title ?? `${purposeNames[job.purpose ?? ''] ?? '执行任务'} ${job.jobId.slice(0, 8)}`,
207
220
  channel: development.channel, ...(development.agentId ? { agentId: development.agentId, agentName: development.name, agentPhase: development.phase } : {}),
208
- originSessionId: job.originSessionId, ...(job.parentJobRef ? { parentJobRef: job.parentJobRef } : {}), ...(job.parentAttemptId ? { parentAttemptId: job.parentAttemptId } : {}),
221
+ originSessionId: job.originSessionId, ...(job.caseId ? { caseId: job.caseId } : {}), ...(job.parentJobRef ? { parentJobRef: job.parentJobRef } : {}), ...(job.parentAttemptId ? { parentAttemptId: job.parentAttemptId } : {}),
209
222
  ...(job.purpose ? { purpose: job.purpose } : {}), targetId: job.targetId, currentAttemptId: job.currentAttemptId, executionStatus: job.executionStatus, displayStatus, phase,
210
223
  createdAt: job.createdAt, updatedAt: [job.updatedAt, review?.updatedAt, pendingRequest?.updatedAt].filter((value) => Boolean(value)).sort().at(-1), stale: attempt?.stale ?? true,
211
224
  inFlightAttemptIds: [...job.inFlightAttemptIds], unresolvedAttemptIds: [...job.unresolvedAttemptIds], execution,
@@ -265,7 +278,15 @@ export function workbenchSnapshot(source) {
265
278
  if (related.replacesJobRef?.sourceId === ledger.sourceId && visible.has(related.replacesJobRef.jobId))
266
279
  dependencies.push({ from: related.replacesJobRef.jobId, to: related.jobId, kind: 'replaces', label: '接替执行' });
267
280
  }
268
- // Only this explicit domain workflow supplies ordering. Parent refs alone never imply dependencies.
281
+ // Parent refs are not handoff order. A handoff edge exists only after one was proposed, accepted or taken.
282
+ for (const handoff of (ledger.handoffs ?? []).filter(item => item.fromJobId === job.jobId && item.status !== 'rejected')) {
283
+ const taken = handoff.status === 'taken' && handoff.childJobId && visible.has(handoff.childJobId);
284
+ dependencies.push({ from: job.jobId, ...(taken ? { to: handoff.childJobId } : {}), kind: 'handoff',
285
+ label: handoff.status === 'taken' ? '已交接' : handoff.status === 'accepted' ? '待开下一单' : '提议交接',
286
+ handoffId: handoff.handoffId, status: handoff.status });
287
+ }
288
+ const next = legalNext(ledger, job);
289
+ // Only this explicit domain workflow supplies its own stage ordering. Parent refs alone never imply dependencies.
269
290
  if (run) {
270
291
  const last = (purpose) => [...run.children].reverse().find(item => item.purpose === purpose)?.child.jobId;
271
292
  const chain = [last('project_script'), last('ppt_production'), last('independent_review')].filter((id) => Boolean(id && visible.has(id)));
@@ -292,7 +313,7 @@ export function workbenchSnapshot(source) {
292
313
  const asked = Object.values(ledger.attempts).filter(attempt => attempt.jobId === job.jobId)
293
314
  .sort((a, b) => (a.createdAt ?? '').localeCompare(b.createdAt ?? ''))[0]?.input;
294
315
  const description = typeof asked?.prompt === 'string' && asked.prompt.trim() ? asked.prompt.slice(0, 20_000) : undefined;
295
- details[job.jobId] = { ...summaries.get(job.jobId), ...(description ? { description } : {}), attempts, children, ancestors, progress: progress(job, run, source.reviews, ledger.attempts[job.currentAttemptId], source.now ?? Date.now()),
316
+ details[job.jobId] = { ...summaries.get(job.jobId), ...(description ? { description } : {}), attempts, children, ancestors, ...(next.length ? { legalNext: next } : {}), progress: progress(job, run, source.reviews, ledger.attempts[job.currentAttemptId], source.now ?? Date.now()),
296
317
  processRequests: (source.processRequests ?? []).filter(request => request.jobId === job.jobId || children.some(child => child.jobId === request.jobId)).map(request => {
297
318
  const projected = projectProcessRequest(request, now);
298
319
  const owner = ledger.jobs[request.jobId];