@1agents/acp-service 0.10.9 → 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 (92) 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 -7
  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/ticket-tools.d.ts +1 -1
  42. package/vendor/runtime/dist/{cli-DXmYwv3U.js → cli-BwanDcOo.js} +4 -4
  43. package/vendor/runtime/dist/{cli-DXmYwv3U.js.map → cli-BwanDcOo.js.map} +1 -1
  44. package/vendor/runtime/dist/cli.js +8 -8
  45. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts → client-C5zneoBs.d.ts} +3 -1
  46. package/vendor/runtime/dist/{client-VQsqcIOJ.d.ts.map → client-C5zneoBs.d.ts.map} +1 -1
  47. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  48. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  49. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  50. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  51. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  52. package/vendor/runtime/dist/docs-site/config.html +450 -0
  53. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  54. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  55. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  56. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  57. package/vendor/runtime/dist/docs-site/index.html +367 -0
  58. package/vendor/runtime/dist/docs-site/install.html +386 -0
  59. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  60. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  61. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  62. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  63. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  64. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  65. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  66. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +336 -0
  67. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  68. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  69. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  70. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  71. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  72. package/vendor/runtime/dist/{flows-DJ17ajbw.js → flows-CzLUHUTS.js} +4 -4
  73. package/vendor/runtime/dist/{flows-DJ17ajbw.js.map → flows-CzLUHUTS.js.map} +1 -1
  74. package/vendor/runtime/dist/flows.d.ts +1 -1
  75. package/vendor/runtime/dist/flows.js +1 -1
  76. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js → invocation-options-B6pIpdpR.js} +4 -4
  77. package/vendor/runtime/dist/{invocation-options-PBfCgrdi.js.map → invocation-options-B6pIpdpR.js.map} +1 -1
  78. package/vendor/runtime/dist/{ipc-BQQpcEdP.js → ipc-ivLtSAdL.js} +21 -3
  79. package/vendor/runtime/dist/ipc-ivLtSAdL.js.map +1 -0
  80. package/vendor/runtime/dist/{output-B3MDn7kv.js → output-BqKnXXb0.js} +3 -3
  81. package/vendor/runtime/dist/{output-B3MDn7kv.js.map → output-BqKnXXb0.js.map} +1 -1
  82. package/vendor/runtime/dist/{queue-owner-runtime-DXCVngwU.js → queue-owner-runtime-DXJND10J.js} +11 -2
  83. package/vendor/runtime/dist/queue-owner-runtime-DXJND10J.js.map +1 -0
  84. package/vendor/runtime/dist/runtime.d.ts +1 -1
  85. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  86. package/vendor/runtime/dist/runtime.js +3 -3
  87. package/vendor/runtime/dist/{session-watch-DURyCw31.js → session-watch-BHB3_PXm.js} +4 -4
  88. package/vendor/runtime/dist/{session-watch-DURyCw31.js.map → session-watch-BHB3_PXm.js.map} +1 -1
  89. package/vendor/runtime/dist/{watch-CIpoMaWD.js → watch-UjokHUfS.js} +2 -2
  90. package/vendor/runtime/dist/{watch-CIpoMaWD.js.map → watch-UjokHUfS.js.map} +1 -1
  91. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +0 -1
  92. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +0 -1
@@ -1,5 +1,23 @@
1
1
  import { z } from 'zod';
2
2
  import type { A2APreflightInput, A2APreflightReport } from './types.js';
3
+ /**
4
+ * The sandbox profile of an execution target. It is configuration, not a workbench shape: only a target that runs
5
+ * commands (ffmpeg, downloads) needs one. The profile names what the environment may reach; it never names host
6
+ * credentials or the container socket.
7
+ */
8
+ export declare const sandboxProfileSchema: z.ZodObject<{
9
+ name: z.ZodString;
10
+ image: z.ZodOptional<z.ZodString>;
11
+ network: z.ZodDefault<z.ZodEnum<{
12
+ bridge: "bridge";
13
+ none: "none";
14
+ }>>;
15
+ writableRoots: z.ZodOptional<z.ZodArray<z.ZodString>>;
16
+ env: z.ZodOptional<z.ZodArray<z.ZodString>>;
17
+ }, z.core.$strict>;
18
+ export type SandboxProfile = z.infer<typeof sandboxProfileSchema>;
19
+ /** True when this profile would hand the sandbox something it must not have. */
20
+ export declare function sandboxViolation(profile: SandboxProfile): string | undefined;
3
21
  export declare const a2aPreflightRequirementsSchema: z.ZodObject<{
4
22
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
5
23
  jobDirectory: z.ZodOptional<z.ZodString>;
@@ -15,6 +33,16 @@ export declare const a2aPreflightRequirementsSchema: z.ZodObject<{
15
33
  modules: z.ZodOptional<z.ZodArray<z.ZodString>>;
16
34
  moduleRoot: z.ZodOptional<z.ZodString>;
17
35
  }, z.core.$strict>>;
36
+ sandbox: z.ZodOptional<z.ZodObject<{
37
+ name: z.ZodString;
38
+ image: z.ZodOptional<z.ZodString>;
39
+ network: z.ZodDefault<z.ZodEnum<{
40
+ bridge: "bridge";
41
+ none: "none";
42
+ }>>;
43
+ writableRoots: z.ZodOptional<z.ZodArray<z.ZodString>>;
44
+ env: z.ZodOptional<z.ZodArray<z.ZodString>>;
45
+ }, z.core.$strict>>;
18
46
  }, z.core.$strict>;
19
47
  export declare const a2aPreflightInputSchema: z.ZodObject<{
20
48
  allowedDirectories: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -31,6 +59,16 @@ export declare const a2aPreflightInputSchema: z.ZodObject<{
31
59
  modules: z.ZodOptional<z.ZodArray<z.ZodString>>;
32
60
  moduleRoot: z.ZodOptional<z.ZodString>;
33
61
  }, z.core.$strict>>;
62
+ sandbox: z.ZodOptional<z.ZodObject<{
63
+ name: z.ZodString;
64
+ image: z.ZodOptional<z.ZodString>;
65
+ network: z.ZodDefault<z.ZodEnum<{
66
+ bridge: "bridge";
67
+ none: "none";
68
+ }>>;
69
+ writableRoots: z.ZodOptional<z.ZodArray<z.ZodString>>;
70
+ env: z.ZodOptional<z.ZodArray<z.ZodString>>;
71
+ }, z.core.$strict>>;
34
72
  cwd: z.ZodString;
35
73
  }, z.core.$strict>;
36
74
  export declare const a2aPreflightReportSchema: z.ZodObject<{
@@ -12,6 +12,37 @@ import { roleIdFromPublication } from '../execution/spaces.js';
12
12
  const absolutePath = z.string().min(1).max(4096).refine(value => isAbsolute(value) && !value.includes('\0'), 'Expected an absolute host path');
13
13
  const pythonModule = z.string().regex(/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/).max(200);
14
14
  const nodeModule = z.string().regex(/^(?:@[A-Za-z0-9_.-]+\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/).max(200);
15
+ /**
16
+ * The sandbox profile of an execution target. It is configuration, not a workbench shape: only a target that runs
17
+ * commands (ffmpeg, downloads) needs one. The profile names what the environment may reach; it never names host
18
+ * credentials or the container socket.
19
+ */
20
+ export const sandboxProfileSchema = z.object({
21
+ name: z.string().trim().min(1).max(200),
22
+ image: z.string().trim().min(1).max(500).optional(),
23
+ network: z.enum(['none', 'bridge']).default('none'),
24
+ /** Paths inside the sandbox the task may write. They must live inside the admitted roots. */
25
+ writableRoots: z.array(absolutePath).max(20).optional(),
26
+ /** Environment variable names the sandbox may pass through. A credential-shaped name is refused. */
27
+ env: z.array(z.string().trim().min(1).max(200)).max(50).optional(),
28
+ }).strict();
29
+ /** Host paths a sandbox must never see: the container socket, private keys and the host credential stores. */
30
+ const FORBIDDEN_SANDBOX_PATHS = ['/var/run/docker.sock', '/run/docker.sock', '/var/run/containerd', '/etc/ssh', '/root/.ssh', '/Users'];
31
+ const FORBIDDEN_ENV = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE_KEY|APIKEY|API_KEY|SESSION)/i;
32
+ /** True when this profile would hand the sandbox something it must not have. */
33
+ export function sandboxViolation(profile) {
34
+ if (profile.network !== 'none' && profile.network !== 'bridge')
35
+ return 'sandbox network must be none or bridge';
36
+ for (const root of profile.writableRoots ?? []) {
37
+ if (FORBIDDEN_SANDBOX_PATHS.some(forbidden => root === forbidden || root.startsWith(`${forbidden}/`))) {
38
+ return `sandbox may not write to ${root}`;
39
+ }
40
+ }
41
+ for (const name of profile.env ?? [])
42
+ if (FORBIDDEN_ENV.test(name))
43
+ return `sandbox may not receive ${name}`;
44
+ return undefined;
45
+ }
15
46
  export const a2aPreflightRequirementsSchema = z.object({
16
47
  allowedDirectories: z.array(absolutePath).min(1).max(100).optional(),
17
48
  jobDirectory: absolutePath.optional(),
@@ -20,6 +51,8 @@ export const a2aPreflightRequirementsSchema = z.object({
20
51
  requiredFiles: z.array(absolutePath).max(64).optional(),
21
52
  python: z.object({ executable: absolutePath, modules: z.array(pythonModule).max(32) }).strict().optional(),
22
53
  node: z.object({ executable: absolutePath, modules: z.array(nodeModule).max(32).optional(), moduleRoot: absolutePath.optional() }).strict().optional(),
54
+ /** The sandbox this target runs in, when it runs commands. */
55
+ sandbox: sandboxProfileSchema.optional(),
23
56
  }).strict();
24
57
  export const a2aPreflightInputSchema = a2aPreflightRequirementsSchema.extend({ cwd: absolutePath }).strict();
25
58
  export const a2aPreflightReportSchema = z.object({
@@ -176,14 +209,29 @@ export async function runA2APreflight(raw) {
176
209
  report.artifactSpace = directory;
177
210
  return directory;
178
211
  });
179
- for (const [index, file] of (input.requiredFiles ?? []).entries())
180
- await check(`requiredFile.${index}`, async () => {
181
- const actual = await realpath(file);
182
- if (!(await stat(actual)).isFile())
183
- throw new Error('Required input is not a regular file');
184
- const handle = await open(actual, 'r');
185
- await handle.close();
186
- return actual;
212
+ if (input.requiredFiles)
213
+ for (const [index, file] of (input.requiredFiles ?? []).entries())
214
+ await check(`requiredFile.${index}`, async () => {
215
+ const actual = await realpath(file);
216
+ if (!(await stat(actual)).isFile())
217
+ throw new Error('Required input is not a regular file');
218
+ const handle = await open(actual, 'r');
219
+ await handle.close();
220
+ return actual;
221
+ });
222
+ if (input.sandbox)
223
+ await check('sandbox', async () => {
224
+ const violation = sandboxViolation(input.sandbox);
225
+ if (violation)
226
+ throw new Error(violation);
227
+ // Every path the sandbox may write must live inside the admitted roots, so the sandbox cannot reach the host.
228
+ const admitted = [report.cwd, report.jobDirectory, report.artifactSpace, ...(input.allowedDirectories ?? [])].filter((value) => Boolean(value));
229
+ for (const root of input.sandbox.writableRoots ?? []) {
230
+ const actual = await realpath(root).catch(() => root);
231
+ if (!admitted.some(base => within(base, actual)))
232
+ throw new Error(`sandbox root ${root} is outside the admitted roots`);
233
+ }
234
+ return `sandbox ${input.sandbox.name}; network=${input.sandbox.network}`;
187
235
  });
188
236
  if (input.python)
189
237
  await check('python', async () => {
@@ -34,6 +34,14 @@ export interface A2APreflightRequirements {
34
34
  modules?: string[];
35
35
  moduleRoot?: string;
36
36
  };
37
+ /** The sandbox this target runs commands in, when it has one. */
38
+ sandbox?: {
39
+ name: string;
40
+ image?: string;
41
+ network: 'none' | 'bridge';
42
+ writableRoots?: string[];
43
+ env?: string[];
44
+ };
37
45
  }
38
46
  export interface A2APreflightInput extends A2APreflightRequirements {
39
47
  cwd: string;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * What one thing looks like on the workbench page.
3
+ *
4
+ * The page projects the ledger: it draws the edges that happened, the proposals that are open, and the conventions
5
+ * that are still waiting for their condition. It never invents an endpoint, and it never decides anything.
6
+ */
7
+ import type { LedgerActor } from './ledger.js';
8
+ import type { HandoffStatus, HandoffWhen, HandoffSnapshot } from './handoff.js';
9
+ import type { CaseFact, CaseReceipt } from './externals.js';
10
+ import type { AcpTaskSummary, WorkbenchSnapshot, WorkbenchSource } from './workbench.js';
11
+ export interface WorkbenchCaseSummary {
12
+ caseId: string;
13
+ originSessionId: string;
14
+ goal: string;
15
+ title?: string;
16
+ createdAt: string;
17
+ createdBy?: LedgerActor;
18
+ updatedAt: string;
19
+ /** True when the case is projected from older jobs that only carried a case id. */
20
+ legacy?: boolean;
21
+ taskCount: number;
22
+ /** How many things on this case wait for a person. */
23
+ pendingCount: number;
24
+ artifactSpace?: string;
25
+ lastActivityAt: string;
26
+ }
27
+ export interface WorkbenchCaseEdge {
28
+ handoffId: string;
29
+ fromJobId: string;
30
+ fromAttemptId: string;
31
+ toTargetId: string;
32
+ purpose: string;
33
+ status: HandoffStatus;
34
+ /** True once the edge really happened; a proposal is drawn dashed and names no destination job. */
35
+ happened: boolean;
36
+ artifactRevision: string;
37
+ artifactDigest: string;
38
+ reason: string;
39
+ note?: string;
40
+ decidedBy?: LedgerActor;
41
+ childJobId?: string;
42
+ snapshots?: HandoffSnapshot[];
43
+ createdAt: string;
44
+ updatedAt: string;
45
+ }
46
+ export interface WorkbenchCaseConvention {
47
+ conventionId: string;
48
+ fromPurpose?: string;
49
+ fromTargetId?: string;
50
+ toTargetId: string;
51
+ toPurpose: string;
52
+ when: HandoffWhen;
53
+ requireHuman: boolean;
54
+ /** True when the condition already holds for the case's current job. */
55
+ achieved: boolean;
56
+ condition?: {
57
+ metric: string;
58
+ operator: string;
59
+ value: number;
60
+ };
61
+ recordedAt: string;
62
+ }
63
+ export interface WorkbenchCaseArtifact {
64
+ revision: string;
65
+ digest?: string;
66
+ jobId: string;
67
+ artifacts: unknown[];
68
+ }
69
+ export interface WorkbenchInboxItem {
70
+ kind: 'review' | 'process_request' | 'handoff';
71
+ id: string;
72
+ caseId?: string;
73
+ jobId: string;
74
+ title: string;
75
+ summary: string;
76
+ revision?: string;
77
+ digest?: string;
78
+ createdAt: string;
79
+ /** True when the person on this page may answer it. */
80
+ canDecide: boolean;
81
+ }
82
+ export interface WorkbenchCaseDetail extends WorkbenchCaseSummary {
83
+ tasks: AcpTaskSummary[];
84
+ edges: WorkbenchCaseEdge[];
85
+ conventions: WorkbenchCaseConvention[];
86
+ artifacts: WorkbenchCaseArtifact[];
87
+ receipts: CaseReceipt[];
88
+ facts: CaseFact[];
89
+ inbox: WorkbenchInboxItem[];
90
+ }
91
+ export interface WorkbenchCaseList {
92
+ items: WorkbenchCaseSummary[];
93
+ total: number;
94
+ counts: {
95
+ all: number;
96
+ pending: number;
97
+ };
98
+ }
99
+ declare const terminal: Set<string>;
100
+ /** Every case this scope can see, opened ones and the compatibility projections of older jobs. */
101
+ export declare function workbenchCases(source: WorkbenchSource, snapshot: WorkbenchSnapshot): {
102
+ list: WorkbenchCaseList;
103
+ details: Record<string, WorkbenchCaseDetail>;
104
+ };
105
+ /** One case, or nothing when this scope cannot see it. */
106
+ export declare function getWorkbenchCase(details: Record<string, WorkbenchCaseDetail>, originSessionId: string, caseId: string): WorkbenchCaseDetail;
107
+ /** The case a job belongs to, in the same scope. */
108
+ export declare function caseOfJob(details: Record<string, WorkbenchCaseDetail>, originSessionId: string, jobId: string): WorkbenchCaseDetail | undefined;
109
+ export { terminal as terminalStatuses };
@@ -0,0 +1,125 @@
1
+ import { legalNextForJob } from './workbench.js';
2
+ import { projectProcessRequest } from './process-request.js';
3
+ const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
4
+ function caseKey(originSessionId, caseId) { return `${originSessionId}\u0000${caseId}`; }
5
+ function edgeOf(handoff) {
6
+ return { handoffId: handoff.handoffId, fromJobId: handoff.fromJobId, fromAttemptId: handoff.fromAttemptId,
7
+ toTargetId: handoff.toTargetId, purpose: handoff.purpose, status: handoff.status,
8
+ happened: handoff.status === 'taken', artifactRevision: handoff.artifactRevision, artifactDigest: handoff.artifactDigest,
9
+ reason: handoff.reason, ...(handoff.note ? { note: handoff.note } : {}), ...(handoff.decidedBy ? { decidedBy: handoff.decidedBy } : {}),
10
+ ...(handoff.childJobId ? { childJobId: handoff.childJobId } : {}), ...(handoff.snapshots ? { snapshots: handoff.snapshots } : {}),
11
+ createdAt: handoff.createdAt, updatedAt: handoff.updatedAt };
12
+ }
13
+ /** Every case this scope can see, opened ones and the compatibility projections of older jobs. */
14
+ export function workbenchCases(source, snapshot) {
15
+ const { ledger, actorId } = source;
16
+ const allowed = source.allowedOrigins ? new Set(source.allowedOrigins) : undefined;
17
+ const visible = snapshot.tasks;
18
+ const visibleJobs = new Set(visible.map(job => job.jobId));
19
+ const jobsByCase = new Map();
20
+ for (const job of Object.values(ledger.jobs)) {
21
+ if (!job.caseId)
22
+ continue;
23
+ if (allowed && !allowed.has(job.originSessionId))
24
+ continue;
25
+ const key = caseKey(job.originSessionId, job.caseId);
26
+ jobsByCase.set(key, [...(jobsByCase.get(key) ?? []), job]);
27
+ }
28
+ const opened = Object.values(ledger.cases ?? {});
29
+ const records = new Map();
30
+ for (const record of opened) {
31
+ if (allowed && !allowed.has(record.originSessionId))
32
+ continue;
33
+ records.set(caseKey(record.originSessionId, record.caseId), { ...record });
34
+ }
35
+ for (const [key, jobs] of jobsByCase) {
36
+ if (records.has(key))
37
+ continue;
38
+ const oldest = jobs.reduce((first, job) => ((first.createdAt ?? '') <= (job.createdAt ?? '') ? first : job));
39
+ records.set(key, { caseId: oldest.caseId, originSessionId: oldest.originSessionId, goal: oldest.title ?? '',
40
+ createdAt: oldest.createdAt ?? new Date(0).toISOString(), updatedAt: oldest.updatedAt, legacy: true });
41
+ }
42
+ const details = {};
43
+ const items = [];
44
+ for (const [key, record] of records) {
45
+ const jobs = jobsByCase.get(key) ?? [];
46
+ const jobIds = new Set(jobs.map(job => job.jobId));
47
+ const tasks = visible.filter(task => jobIds.has(task.jobId));
48
+ const edges = (ledger.handoffs ?? []).filter(handoff => handoff.caseId === record.caseId
49
+ && handoff.fromJobId && jobIds.has(handoff.fromJobId)).map(edgeOf);
50
+ const conventions = (ledger.conventions ?? [])
51
+ .filter(rule => rule.originSessionId === record.originSessionId && rule.caseId === record.caseId)
52
+ .map(rule => {
53
+ const target = jobs.map(job => legalNextForJob(ledger, job).find(item => item.conventionId === rule.conventionId)).find(Boolean);
54
+ return { conventionId: rule.conventionId, ...(rule.fromPurpose ? { fromPurpose: rule.fromPurpose } : {}),
55
+ ...(rule.fromTargetId ? { fromTargetId: rule.fromTargetId } : {}), toTargetId: rule.toTargetId, toPurpose: rule.toPurpose,
56
+ when: rule.when, requireHuman: rule.requireHuman, achieved: Boolean(target?.achieved),
57
+ ...(rule.condition ? { condition: rule.condition } : {}), recordedAt: rule.recordedAt };
58
+ });
59
+ const artifacts = [];
60
+ for (const task of tasks) {
61
+ for (const entry of snapshot.details[task.jobId]?.artifacts ?? []) {
62
+ artifacts.push({ revision: entry.revision, ...(entry.digest ? { digest: entry.digest } : {}), jobId: task.jobId, artifacts: entry.artifacts });
63
+ }
64
+ }
65
+ const receipts = (ledger.receipts ?? []).filter(item => item.originSessionId === record.originSessionId && item.caseId === record.caseId);
66
+ const facts = (ledger.facts ?? []).filter(item => item.originSessionId === record.originSessionId && item.caseId === record.caseId);
67
+ const space = (ledger.artifactSpaces ?? []).find(item => item.originSessionId === record.originSessionId && item.caseId === record.caseId);
68
+ const inbox = inboxFor(source, record.caseId, jobIds, actorId);
69
+ const lastActivityAt = [...edges.map(edge => edge.updatedAt), ...tasks.map(task => task.updatedAt), record.updatedAt]
70
+ .filter(Boolean).sort().at(-1) ?? record.updatedAt;
71
+ const summary = { caseId: record.caseId, originSessionId: record.originSessionId, goal: record.goal,
72
+ ...(record.title ? { title: record.title } : {}), createdAt: record.createdAt, updatedAt: record.updatedAt,
73
+ ...(record.createdBy ? { createdBy: record.createdBy } : {}), ...(record.legacy ? { legacy: true } : {}),
74
+ taskCount: tasks.length, pendingCount: inbox.filter(item => item.canDecide).length,
75
+ ...(space ? { artifactSpace: space.root } : {}), lastActivityAt };
76
+ items.push(summary);
77
+ details[key] = { ...summary, tasks, edges, conventions, artifacts, receipts, facts, inbox };
78
+ }
79
+ items.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt));
80
+ const list = { items, total: items.length, counts: { all: items.length, pending: items.filter(item => item.pendingCount > 0).length } };
81
+ return { list, details };
82
+ }
83
+ /** Reviews, questions and handoff proposals of one case, in one column. */
84
+ function inboxFor(source, caseId, jobIds, actorId) {
85
+ const items = [];
86
+ for (const review of source.reviews) {
87
+ if (!jobIds.has(review.jobId) || review.status !== 'pending')
88
+ continue;
89
+ items.push({ kind: 'review', id: review.reviewId, caseId, jobId: review.jobId, title: review.title,
90
+ summary: `确认 ${review.revision}`, revision: review.revision, digest: review.digest, createdAt: review.createdAt,
91
+ canDecide: review.reviewerId === actorId });
92
+ }
93
+ const now = source.now ?? Date.now();
94
+ for (const request of source.processRequests ?? []) {
95
+ if (!jobIds.has(request.jobId))
96
+ continue;
97
+ const projected = projectProcessRequest(request, now);
98
+ if (projected.status !== 'pending')
99
+ continue;
100
+ items.push({ kind: 'process_request', id: projected.requestId, caseId, jobId: request.jobId,
101
+ title: projected.kind === 'plan' ? '计划待批准' : projected.kind === 'permission' ? `工具「${projected.toolTitle ?? ''}」待批准` : '有待回答的问题',
102
+ summary: projected.kind === 'plan' ? projected.planContent ?? '' : projected.kind === 'permission' ? projected.toolTitle ?? '' : projected.questions?.[0]?.question ?? '',
103
+ createdAt: projected.createdAt, canDecide: true });
104
+ }
105
+ for (const handoff of source.ledger.handoffs ?? []) {
106
+ if (!jobIds.has(handoff.fromJobId) || handoff.status !== 'proposed')
107
+ continue;
108
+ items.push({ kind: 'handoff', id: handoff.handoffId, caseId, jobId: handoff.fromJobId, title: '交接提议',
109
+ summary: `${handoff.reason}(交给 ${handoff.toTargetId})`, revision: handoff.artifactRevision,
110
+ digest: handoff.artifactDigest, createdAt: handoff.createdAt, canDecide: true });
111
+ }
112
+ return items.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
113
+ }
114
+ /** One case, or nothing when this scope cannot see it. */
115
+ export function getWorkbenchCase(details, originSessionId, caseId) {
116
+ const detail = details[caseKey(originSessionId, caseId)];
117
+ if (!detail)
118
+ throw new Error('Case not found in authorized scope');
119
+ return structuredClone(detail);
120
+ }
121
+ /** The case a job belongs to, in the same scope. */
122
+ export function caseOfJob(details, originSessionId, jobId) {
123
+ return Object.values(details).find(detail => detail.originSessionId === originSessionId && detail.tasks.some(task => task.jobId === jobId));
124
+ }
125
+ export { terminal as terminalStatuses };
@@ -0,0 +1,56 @@
1
+ import { z } from 'zod';
2
+ import type { JobLedger, LedgerActor } from './ledger.js';
3
+ export interface CaseRecord {
4
+ caseId: string;
5
+ originSessionId: string;
6
+ /** What this thing is for, in the owner's words. */
7
+ goal: string;
8
+ title?: string;
9
+ createdAt: string;
10
+ /** Absent on a compatibility projection of an older job that only carried a case id. */
11
+ createdBy?: LedgerActor;
12
+ updatedAt: string;
13
+ /** True when the record is projected from older jobs instead of opened through case_open. */
14
+ legacy?: boolean;
15
+ }
16
+ export declare class CaseError extends Error {
17
+ readonly code: 'not_found' | 'conflict' | 'invalid';
18
+ constructor(code: 'not_found' | 'conflict' | 'invalid', message: string);
19
+ }
20
+ export declare const caseActorSchema: z.ZodObject<{
21
+ kind: z.ZodEnum<{
22
+ person: "person";
23
+ coach: "coach";
24
+ }>;
25
+ id: z.ZodOptional<z.ZodString>;
26
+ agent: z.ZodOptional<z.ZodString>;
27
+ sessionId: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strict>;
29
+ export declare const caseOpenSchema: z.ZodObject<{
30
+ originSessionId: z.ZodString;
31
+ caseId: z.ZodOptional<z.ZodString>;
32
+ goal: z.ZodString;
33
+ title: z.ZodOptional<z.ZodString>;
34
+ createdBy: z.ZodOptional<z.ZodObject<{
35
+ kind: z.ZodEnum<{
36
+ person: "person";
37
+ coach: "coach";
38
+ }>;
39
+ id: z.ZodOptional<z.ZodString>;
40
+ agent: z.ZodOptional<z.ZodString>;
41
+ sessionId: z.ZodOptional<z.ZodString>;
42
+ }, z.core.$strict>>;
43
+ }, z.core.$strict>;
44
+ /** The ledger keys cases by origin and id together; the page never shows one origin's case to another. */
45
+ export declare const caseKey: (originSessionId: string, caseId: string) => string;
46
+ /**
47
+ * Open a case. The id is chosen by the caller or minted here; a repeated id with the same goal returns the
48
+ * same case instead of a second one.
49
+ */
50
+ export declare function openCase(ledger: JobLedger, raw: unknown): CaseRecord;
51
+ /** The opened case, or a compatibility projection of an older job that only carried a case id. */
52
+ export declare function projectCase(ledger: JobLedger, originSessionId: string, caseId: string): CaseRecord | undefined;
53
+ /** A case must exist before a convention, a shared space or a task may name it. */
54
+ export declare function requireCase(ledger: JobLedger, originSessionId: string, caseId: string): CaseRecord;
55
+ /** Every case this origin owns, opened ones first and compatibility projections last. */
56
+ export declare function listCases(ledger: JobLedger, originSessionId?: string): CaseRecord[];
@@ -0,0 +1,77 @@
1
+ /**
2
+ * One thing. A case owns its tasks, its handoffs, its shared artifact space, its receipts and its facts.
3
+ * The ledger keeps the record. Nothing here dispatches work, judges a result or accepts a handoff.
4
+ */
5
+ import { randomUUID } from 'node:crypto';
6
+ import { z } from 'zod';
7
+ export class CaseError extends Error {
8
+ code;
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.code = code;
12
+ this.name = 'CaseError';
13
+ }
14
+ }
15
+ const id = z.string().trim().min(1).max(512);
16
+ export const caseActorSchema = z.object({ kind: z.enum(['person', 'coach']), id: id.optional(),
17
+ agent: z.string().trim().min(1).max(512).optional(), sessionId: z.string().trim().min(1).max(512).optional() }).strict();
18
+ export const caseOpenSchema = z.object({ originSessionId: id, caseId: id.optional(),
19
+ goal: z.string().trim().min(1).max(4000), title: z.string().trim().min(1).max(200).optional(),
20
+ createdBy: caseActorSchema.optional() }).strict();
21
+ /** The ledger keys cases by origin and id together; the page never shows one origin's case to another. */
22
+ export const caseKey = (originSessionId, caseId) => `${originSessionId}\u0000${caseId}`;
23
+ /**
24
+ * Open a case. The id is chosen by the caller or minted here; a repeated id with the same goal returns the
25
+ * same case instead of a second one.
26
+ */
27
+ export function openCase(ledger, raw) {
28
+ const input = caseOpenSchema.parse(raw);
29
+ const caseId = input.caseId ?? `case-${randomUUID()}`;
30
+ const existing = ledger.findCase(input.originSessionId, caseId);
31
+ if (existing) {
32
+ if (existing.goal !== input.goal)
33
+ throw new CaseError('conflict', 'This case already exists with another goal');
34
+ return existing;
35
+ }
36
+ const now = new Date().toISOString();
37
+ return ledger.commitCase({ caseId, originSessionId: input.originSessionId, goal: input.goal,
38
+ ...(input.title ? { title: input.title } : {}), createdAt: now, updatedAt: now,
39
+ ...(input.createdBy ? { createdBy: input.createdBy } : {}) });
40
+ }
41
+ /** The opened case, or a compatibility projection of an older job that only carried a case id. */
42
+ export function projectCase(ledger, originSessionId, caseId) {
43
+ const record = ledger.findCase(originSessionId, caseId);
44
+ if (record)
45
+ return record;
46
+ const jobs = Object.values(ledger.snapshot().jobs)
47
+ .filter(job => job.originSessionId === originSessionId && job.caseId === caseId);
48
+ if (!jobs.length)
49
+ return undefined;
50
+ const oldest = jobs.reduce((first, job) => ((first.createdAt ?? '') <= (job.createdAt ?? '') ? first : job));
51
+ return { caseId, originSessionId, goal: oldest.title ?? '', createdAt: oldest.createdAt ?? new Date(0).toISOString(),
52
+ updatedAt: oldest.updatedAt, legacy: true };
53
+ }
54
+ /** A case must exist before a convention, a shared space or a task may name it. */
55
+ export function requireCase(ledger, originSessionId, caseId) {
56
+ const record = projectCase(ledger, originSessionId, caseId);
57
+ if (!record)
58
+ throw new CaseError('not_found', 'No such case; open it first');
59
+ return record;
60
+ }
61
+ /** Every case this origin owns, opened ones first and compatibility projections last. */
62
+ export function listCases(ledger, originSessionId) {
63
+ const opened = ledger.casesFor(originSessionId);
64
+ const projected = new Map();
65
+ for (const job of Object.values(ledger.snapshot().jobs)) {
66
+ if (!job.caseId || (originSessionId && job.originSessionId !== originSessionId))
67
+ continue;
68
+ const key = caseKey(job.originSessionId, job.caseId);
69
+ if (projected.has(key) || opened.some(item => caseKey(item.originSessionId, item.caseId) === key))
70
+ continue;
71
+ const record = projectCase(ledger, job.originSessionId, job.caseId);
72
+ if (record)
73
+ projected.set(key, record);
74
+ }
75
+ return [...opened, ...projected.values()]
76
+ .sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
77
+ }
@@ -0,0 +1,83 @@
1
+ import { z } from 'zod';
2
+ import type { JobLedger, LedgerActor } from './ledger.js';
3
+ export interface CaseReceipt {
4
+ receiptId: string;
5
+ caseId: string;
6
+ originSessionId: string;
7
+ /** The channel this went out through, e.g. a public account. */
8
+ channel: string;
9
+ /** The channel's own id for the published item. Together with the channel it is the receipt's key. */
10
+ remoteId: string;
11
+ /** The exact bytes that were published. */
12
+ artifactDigest: string;
13
+ artifactRevision?: string;
14
+ jobId?: string;
15
+ attemptId?: string;
16
+ url?: string;
17
+ publishedAt: string;
18
+ recordedAt: string;
19
+ recordedBy?: LedgerActor;
20
+ }
21
+ export interface CaseFact {
22
+ factId: string;
23
+ caseId: string;
24
+ originSessionId: string;
25
+ metric: string;
26
+ value: number;
27
+ unit?: string;
28
+ /** Who measured it. A pull from a channel, or a person. */
29
+ source: string;
30
+ observedAt: string;
31
+ recordedAt: string;
32
+ }
33
+ export type FactOperator = 'gte' | 'lte' | 'gt' | 'lt';
34
+ export declare const receiptRecordSchema: z.ZodObject<{
35
+ originSessionId: z.ZodString;
36
+ caseId: z.ZodString;
37
+ channel: z.ZodString;
38
+ remoteId: z.ZodString;
39
+ artifactDigest: z.ZodString;
40
+ artifactRevision: z.ZodOptional<z.ZodString>;
41
+ jobId: z.ZodOptional<z.ZodString>;
42
+ attemptId: z.ZodOptional<z.ZodString>;
43
+ url: z.ZodOptional<z.ZodString>;
44
+ publishedAt: z.ZodOptional<z.ZodString>;
45
+ recordedBy: z.ZodOptional<z.ZodLazy<z.ZodObject<{
46
+ kind: z.ZodEnum<{
47
+ person: "person";
48
+ coach: "coach";
49
+ application: "application";
50
+ }>;
51
+ id: z.ZodOptional<z.ZodString>;
52
+ agent: z.ZodOptional<z.ZodString>;
53
+ sessionId: z.ZodOptional<z.ZodString>;
54
+ }, z.core.$strict>>>;
55
+ }, z.core.$strict>;
56
+ export declare const factRecordSchema: z.ZodObject<{
57
+ originSessionId: z.ZodString;
58
+ caseId: z.ZodString;
59
+ metric: z.ZodString;
60
+ value: z.ZodNumber;
61
+ unit: z.ZodOptional<z.ZodString>;
62
+ source: z.ZodString;
63
+ observedAt: z.ZodOptional<z.ZodString>;
64
+ recordedBy: z.ZodOptional<z.ZodLazy<z.ZodObject<{
65
+ kind: z.ZodEnum<{
66
+ person: "person";
67
+ coach: "coach";
68
+ application: "application";
69
+ }>;
70
+ id: z.ZodOptional<z.ZodString>;
71
+ agent: z.ZodOptional<z.ZodString>;
72
+ sessionId: z.ZodOptional<z.ZodString>;
73
+ }, z.core.$strict>>>;
74
+ }, z.core.$strict>;
75
+ /**
76
+ * Record that these bytes went out. The channel and its own id are the key: the same key with the same digest
77
+ * is the same receipt, and the same key with another digest is a conflict, never an overwrite.
78
+ */
79
+ export declare function recordReceipt(ledger: JobLedger, raw: unknown): CaseReceipt;
80
+ /** Record one measured number. The platform stores it and does not say whether it is good. */
81
+ export declare function recordFact(ledger: JobLedger, raw: unknown): CaseFact;
82
+ /** Does this measurement satisfy the condition a convention stores? */
83
+ export declare function factSatisfied(value: number, operator: FactOperator, threshold: number): boolean;