@1agents/acp-service 0.10.5 → 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.
@@ -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];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1agents/acp-service",
3
- "version": "0.10.5",
3
+ "version": "0.10.6",
4
4
  "description": "agent-workflow ACP runtime, CLI, HTTP/WebSocket service and DeepSeek Harness ACP/A2A plugins in one package. Part of 一芥天地 (DreamMate World).",
5
5
  "keywords": [
6
6
  "dreammate",
@@ -87,6 +87,14 @@
87
87
  "skills",
88
88
  "vendor"
89
89
  ],
90
+ "scripts": {
91
+ "build": "node ../../scripts/embed-runtime.mjs && tsc -p tsconfig.build.json && node workbench-ui/build.mjs",
92
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p workbench-ui/tsconfig.json",
93
+ "test": "npm run build && npm run test:only",
94
+ "prepack": "node ../../scripts/verify-package-build.mjs",
95
+ "start": "tsx bin/acp-service.ts",
96
+ "test:only": "node --import tsx --test test/*.test.ts"
97
+ },
90
98
  "engines": {
91
99
  "node": ">=22.13.0"
92
100
  },
@@ -105,9 +113,9 @@
105
113
  "zod": "^4.6.5"
106
114
  },
107
115
  "devDependencies": {
108
- "@1agents/chat-view": "0.1.0",
109
- "@1agents/file-preview": "0.1.0",
110
- "@scottzx/1acp": "0.16.0",
116
+ "@1agents/chat-view": "workspace:*",
117
+ "@1agents/file-preview": "workspace:*",
118
+ "@scottzx/1acp": "workspace:*",
111
119
  "@types/node": "^22.10.2",
112
120
  "@types/ws": "^8.5.14",
113
121
  "esbuild": "0.28.2",
@@ -132,12 +140,5 @@
132
140
  "@deepseek-ai/dsh-client-ui-workspace"
133
141
  ]
134
142
  }
135
- },
136
- "scripts": {
137
- "build": "node ../../scripts/embed-runtime.mjs && tsc -p tsconfig.build.json && node workbench-ui/build.mjs",
138
- "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p workbench-ui/tsconfig.json",
139
- "test": "npm run build && npm run test:only",
140
- "start": "tsx bin/acp-service.ts",
141
- "test:only": "node --import tsx --test test/*.test.ts"
142
143
  }
143
- }
144
+ }
@@ -99,7 +99,9 @@ preset 必须在执行宿主真实可用;要用普通 DSH 时显式选 `standa
99
99
 
100
100
  ## 账本、通知与处理
101
101
 
102
- 提交参数共同使用 `originSessionId/targetId/input`,建议稳定 `clientRequestId`;返回后保存 `sourceId/jobId/attemptId` 及可用的 `remote/taskId/contextId/sessionId`,立即结束本轮。受理未知不自动换编号重派。父子任务用 `parentJobRef:{sourceId,jobId}` 和可选 `parentAttemptId/purpose/resultRevision/replacesJobRef` 关联,不另造“外层任务”术语。
102
+ 提交参数共同使用 `originSessionId/targetId/input`,建议稳定 `clientRequestId`;返回后保存 `sourceId/jobId/attemptId` 及可用的 `remote/taskId/contextId/sessionId`,立即结束本轮。受理未知不自动换编号重派。父子任务用 `parentJobRef:{sourceId,jobId}` 和可选 `parentAttemptId/purpose/resultRevision/replacesJobRef` 关联,不另造“外层任务”术语。把产物交给另一个角色不是继续同一张任务:`handoff_propose` 只写提议,`handoff_decide` 接受后仍要用 `execution_submit` 带上 `handoffId` 才开下一张。约定用 `handoff_offer` 登记,达成后账本可以接受下一跳,但不会自己派单,也不会在多条约定同时成立时挑一条。
103
+
104
+ 同一件事的目录分成三处,不能混用。任务目录 `<cwd>/.1agents/jobs/<jobId>/` 只属于这一张任务。角色公开目录 `<cwd>/.1agents/roles/<roleId>/published/` 给其他角色看。共享产物空间用 `handoff_space` 按 `caseId` 登记一个已经存在的宿主目录,几张任务可以在那里读写要交接的文件;它不是角色目录,也不是某一张任务的私有目录。
103
105
 
104
106
  | 操作 | 方法与关键参数 |
105
107
  | --- | --- |
@@ -103,7 +103,7 @@ The bundle's `oneagents-acp` row accepts `serviceUrl`, `serviceMode`, `serviceSt
103
103
 
104
104
  Explicitly authorized unattended work can declare `sessionPolicies`, with an exact absolute `cwd`, ACP registry `agent`, and optional `initialModeId`. A policy matches only that workspace and Agent; wildcards and duplicate scopes are rejected. New sessions select the advertised native mode before sending any prompt; an unavailable mode fails without prompting. A stored ACP 设置 record for the same workspace and Agent is applied on that new session, and its mode replaces `initialModeId`. Existing sessions keep their native mode and any ACP settings already selected or imported. `permissionMode` (`approve-reads`, `approve-all`, `deny-all`) may still appear in older configs and is ignored: the bridge does not apply that three-state shield. Mode and reasoning effort come from ACP 设置 (`session/set_mode`, `session/set_config_option`) or from the native session an import resumes. For example, an authorized Codex video workspace can use `initialModeId: "agent-full-access"` without changing the host's global model or other workspaces. Remove the declaration when the authorized batch ends; existing native sessions retain their own stored mode.
105
105
 
106
- Diagnostic storage defaults to `stateDirectory/diagnostics`; `diagnosticsDirectory` selects a separate explicit location. Keep this directory with the A2A state when moving a host. Its version is independent of DSH Session formats. The plugin privately mounts official storage components; it does not require a shared host storage-domain configuration. Only one plugin instance may write the directory at a time.
106
+ Diagnostic storage defaults to `stateDirectory/diagnostics`; `diagnosticsDirectory` selects a separate explicit location. Keep this directory with the A2A state when moving a host. Its version is independent of DSH Session formats. The plugin privately mounts official storage components; it does not require a shared host storage-domain configuration. Only one plugin instance may write the directory at a time. A second DSH process, such as desktop while web already holds the lock, starts instead of failing: A2A reads the owner's records and rejects mutations, and that follower's diagnostics stay in memory so a chat turn is not failed for lack of the lock. The follower does not mark the owner's in-flight tasks failed and does not release the owner's lock. Session binding files in `stateDirectory` are outside that lock.
107
107
 
108
108
  ### Local service lifecycle
109
109
 
@@ -1,7 +1,7 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { SessionId } from '@deepseek-ai/dsh-session';
3
3
  import { type A2ABackend, type A2AExecutionRef, type A2APreflightInput, type A2APrepareInput, type A2ARunResult, type A2ATarget } from '@1agents/acp-service/a2a';
4
- import type { Diagnostics } from './diagnostics.js';
4
+ import type { DiagnosticLog } from './diagnostics.js';
5
5
  export interface SessionControl {
6
6
  release(sessionId: string): Promise<{
7
7
  processReleased: true | 'pending';
@@ -36,7 +36,7 @@ export declare class DshA2ABackend implements A2ABackend {
36
36
  private readonly sessions?;
37
37
  private readonly executions;
38
38
  /** @param ctx DSH plugin context that owns session-controller and execution event registrations. */
39
- constructor(ctx: Context, diagnostics?: Diagnostics, sessions?: SessionControl);
39
+ constructor(ctx: Context, diagnostics?: DiagnosticLog, sessions?: SessionControl);
40
40
  close(target: A2ATarget): Promise<{
41
41
  processReleased: true | 'pending';
42
42
  acp?: boolean;
@@ -1,7 +1,7 @@
1
1
  /** Mount the shared A2A implementation on the current DSH web host. */
2
2
  import { createA2AServer, type A2AServerOptions } from '@1agents/acp-service/a2a';
3
3
  import type { Context } from '@deepseek-ai/cordis';
4
- import type { Diagnostics } from './diagnostics.js';
4
+ import type { DiagnosticLog } from './diagnostics.js';
5
5
  import { type SessionControl } from './a2a-executor.js';
6
6
  /** Optional host configuration; omitted configuration leaves A2A disabled. */
7
7
  export interface DshA2AOptions extends Omit<A2AServerOptions, 'backend' | 'token' | 'stateDirectory' | 'publicUrl'> {
@@ -23,4 +23,4 @@ export interface DshA2AOptions extends Omit<A2AServerOptions, 'backend' | 'token
23
23
  /** In-process takeover controls of the mounted host; absent while A2A is disabled or closed. */
24
24
  export type A2AHostControls = Pick<Awaited<ReturnType<typeof createA2AServer>>, 'sessionTask' | 'taskSession' | 'resubmit'>;
25
25
  /** Routes and in-flight turns are released with the owning Cordis plugin. */
26
- export declare function mountDshA2A(ctx: Context, options: DshA2AOptions, stateDirectory: string, diagnostics?: Diagnostics, sessions?: SessionControl, expose?: (host: A2AHostControls | undefined) => void): Promise<() => Promise<void>>;
26
+ export declare function mountDshA2A(ctx: Context, options: DshA2AOptions, stateDirectory: string, diagnostics?: DiagnosticLog, sessions?: SessionControl, expose?: (host: A2AHostControls | undefined) => void): Promise<() => Promise<void>>;