pi-better-subagents 0.32.7 → 0.34.0

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 (67) hide show
  1. package/README.md +13 -0
  2. package/agent-catalog.mjs +24 -0
  3. package/agent-commands.ts +71 -4
  4. package/agent-inspection.ts +2 -1
  5. package/agents-catalog-tool.ts +8 -1
  6. package/assignment-outcomes.ts +14 -3
  7. package/assignment-projection.mjs +12 -4
  8. package/assignment-report.ts +92 -0
  9. package/catalog-host-admission.ts +69 -0
  10. package/catalog-overlay.ts +10 -0
  11. package/catalog-runtime.ts +10 -2
  12. package/catalog-store.ts +23 -0
  13. package/catalog-ui.ts +26 -10
  14. package/child-operations.ts +2 -0
  15. package/child-ownership.ts +1 -1
  16. package/docs/agent-catalog-operations.md +38 -0
  17. package/health-observation.ts +9 -4
  18. package/index.ts +154 -84
  19. package/launch-abort.ts +21 -0
  20. package/list.mjs +1 -1
  21. package/navigator.mjs +2 -1
  22. package/operation-bridge-types.ts +18 -1
  23. package/output-payload.ts +2 -0
  24. package/package.json +4 -2
  25. package/parse.ts +7 -6
  26. package/registry.ts +4 -2
  27. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  28. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  29. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  30. package/runtime-client/artifacts/darwin-x64.json +1 -0
  31. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  32. package/runtime-client/artifacts/linux-arm64.json +1 -0
  33. package/runtime-client/artifacts/linux-x64.gz +0 -0
  34. package/runtime-client/artifacts/linux-x64.json +1 -0
  35. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  36. package/runtime-client/src/daemon-owner.mjs +218 -0
  37. package/runtime-client/src/runtime/client.mjs +130 -0
  38. package/runtime-client/src/runtime/root.mjs +41 -0
  39. package/runtime-client/src/runtime/socket.mjs +9 -0
  40. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  41. package/runtime-client/src/runtime/work-client.mjs +102 -0
  42. package/runtime-client/src/startup/artifact.mjs +76 -0
  43. package/runtime-client/src/startup/install.mjs +184 -0
  44. package/runtime-client/src/startup/managed-types.mjs +1 -0
  45. package/runtime-client/src/startup/runtime.mjs +120 -0
  46. package/session-store.ts +85 -30
  47. package/shared-catalog.ts +69 -0
  48. package/shared-harness-settings.ts +4 -2
  49. package/shared-log-utils.ts +18 -7
  50. package/shared-navigator.ts +16 -4
  51. package/shared-operation-coordinator/assignment-observation.mjs +80 -3
  52. package/shared-operation-coordinator/index.ts +2 -0
  53. package/shared-operation-coordinator/src/discovery.ts +9 -0
  54. package/shared-operation-coordinator/src/errors.ts +2 -0
  55. package/shared-operation-coordinator/src/operations.ts +6 -4
  56. package/shared-operation-coordinator/src/result-supervision.ts +128 -0
  57. package/shared-operation-coordinator/src/schema.ts +39 -1
  58. package/shared-operation-coordinator/src/store.ts +55 -0
  59. package/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  60. package/shared-operation-coordinator/src/types.ts +6 -0
  61. package/shared-work-client.d.mts +12 -0
  62. package/shared-work-client.mjs +102 -0
  63. package/skill-picker.ts +6 -2
  64. package/tools.ts +39 -2
  65. package/work-observation.ts +177 -0
  66. package/worker-operations-host.ts +3 -0
  67. package/worker-waits.ts +50 -13
@@ -0,0 +1,128 @@
1
+ // Generated from packages/operation-coordinator/src/result-supervision.ts. Do not edit directly.
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { getRow, run, type StoreContext } from "./sqlite.ts";
4
+ import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
5
+ import { requireId, requirePath } from "./validate.ts";
6
+ import type { RecordTerminalOutcomeInput } from "./types.ts";
7
+ import type { OwnerIdentity } from "./types.ts";
8
+
9
+ const PREFIX = "result-supervision-v1:";
10
+ export interface ResultSupervision {
11
+ operationId: string;
12
+ directory: string;
13
+ launchToken: string;
14
+ authorityRef: string | null;
15
+ hostId: string;
16
+ epoch: string;
17
+ owner: OwnerIdentity;
18
+ capability?: { adapter: string; captured: unknown; current: unknown };
19
+ }
20
+
21
+ export function resultSupervisions(ctx: StoreContext, activeOnly = false): ResultSupervision[] {
22
+ const rows = activeOnly
23
+ ? ctx.db.prepare("SELECT s.value FROM operations o JOIN coordinator_state s ON s.key = ? || o.operation_id WHERE o.phase = 'running'").all(PREFIX)
24
+ : ctx.db.prepare("SELECT value FROM coordinator_state WHERE key LIKE ?").all(`${PREFIX}%`);
25
+ return rows
26
+ .map(row => JSON.parse(String(row.value)));
27
+ }
28
+
29
+ export function resultSupervision(ctx: StoreContext, operationId: string): ResultSupervision | null {
30
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
31
+ return row ? JSON.parse(String(row.value)) : null;
32
+ }
33
+
34
+ /** The admitting host has stopped its local route before this exact-owner CAS. */
35
+ export function handoffResultSupervision(ctx: StoreContext, input: {
36
+ operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
37
+ capability?: ResultSupervision["capability"];
38
+ }): ResultSupervision {
39
+ const operationId = requireId("operationId", input.operationId);
40
+ const hostId = requireId("hostId", input.hostId);
41
+ const epoch = requireId("epoch", input.epoch);
42
+ const directory = requirePath("directory", input.directory);
43
+ return ctx.transaction(() => {
44
+ const previous = resultSupervision(ctx, operationId);
45
+ if (previous) {
46
+ if (previous.directory !== directory || previous.hostId !== hostId || previous.epoch !== epoch
47
+ || !isDeepStrictEqual(previous.capability, input.capability)) {
48
+ throw new Error("supervision-conflict: repeated handoff changed destination or captured authority");
49
+ }
50
+ return previous;
51
+ }
52
+ const operation = getOperation(ctx, operationId);
53
+ if (!operation || operation.supervision?.hostId !== input.expectedHostId) throw new Error("permission-unavailable: exact supervision owner changed");
54
+ const grant = { operationId, directory, hostId, epoch, launchToken: operation.launchToken,
55
+ authorityRef: operation.authorityRef, owner: operation.owner, ...(input.capability ? { capability: input.capability } : {}) };
56
+ recordSupervision(ctx, { operationId, owner: operation.owner, expectedHostId: input.expectedHostId,
57
+ supervision: { hostId }, health: "active" });
58
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?)", PREFIX + operationId, JSON.stringify(grant));
59
+ return grant;
60
+ });
61
+ }
62
+
63
+ /** A wait's dependency set transfers together, or none of it does. */
64
+ export function handoffResultSupervisions(ctx: StoreContext, inputs: Parameters<typeof handoffResultSupervision>[1][]): ResultSupervision[] {
65
+ return ctx.transaction(() => inputs.map(input => handoffResultSupervision(ctx, input)));
66
+ }
67
+
68
+ export function resultScopeManaged(ctx: StoreContext, scope: string): boolean {
69
+ return !!getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + requireId("scope", scope));
70
+ }
71
+
72
+ export function handoffResultScope(ctx: StoreContext, input: {
73
+ scope: string;
74
+ expectedDiscovery: { hostId: string; token: string } | null;
75
+ grants: Parameters<typeof handoffResultSupervision>[1][];
76
+ }): ResultSupervision[] {
77
+ return ctx.transaction(() => {
78
+ const claim = getRow(ctx, "SELECT host_id, token FROM discovery_claims WHERE scope = ?", requireId("scope", input.scope));
79
+ if (claim ? !input.expectedDiscovery || claim.host_id !== input.expectedDiscovery.hostId || claim.token !== input.expectedDiscovery.token : input.expectedDiscovery !== null) {
80
+ throw new Error("supervision-conflict: discovery owner changed during handoff");
81
+ }
82
+ const grants = handoffResultSupervisions(ctx, input.grants);
83
+ // Registration precedes sidecar creation. Check durable records inside
84
+ // this transaction, including old records whose scope is unknown.
85
+ const stranded = getRow(ctx, `SELECT operation_id FROM operations o
86
+ WHERE phase = 'running' AND observer_kind = 'local-supervisor'
87
+ AND COALESCE(json_extract(supervision_json, '$.resultAdapter'), 0) != 1
88
+ AND (json_extract(supervision_json, '$.resultScope') IS NULL
89
+ OR json_extract(supervision_json, '$.resultScope') = ?)
90
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = ? || o.operation_id)
91
+ LIMIT 1`, input.scope, PREFIX);
92
+ if (stranded) throw new Error("permission-unavailable: untransferred legacy operation prevents scope handoff");
93
+ run(ctx, "DELETE FROM discovery_claims WHERE scope = ?", input.scope);
94
+ run(ctx, "INSERT OR IGNORE INTO coordinator_state (key, value) VALUES (?, 'managed')", "result-scope-v1:" + input.scope);
95
+ return grants;
96
+ });
97
+ }
98
+
99
+ /** Called by the singleton server after proving the preceding server has exited. */
100
+ export function recoverResultSupervision(ctx: StoreContext, input: ResultSupervision): void {
101
+ ctx.transaction(() => {
102
+ const previous = resultSupervision(ctx, input.operationId);
103
+ if (!previous || previous.launchToken !== input.launchToken || previous.directory !== input.directory
104
+ || previous.authorityRef !== input.authorityRef || JSON.stringify(previous.owner) !== JSON.stringify(input.owner)
105
+ || JSON.stringify(previous.capability) !== JSON.stringify(input.capability)) {
106
+ throw new Error("supervision-conflict: execution or captured authority changed");
107
+ }
108
+ const operation = getOperation(ctx, input.operationId)!;
109
+ if (operation.terminalRevision > 0) return;
110
+ recordSupervision(ctx, { operationId: input.operationId, owner: operation.owner,
111
+ expectedHostId: previous.hostId, supervision: { hostId: input.hostId }, health: "active" });
112
+ run(ctx, "UPDATE coordinator_state SET value = ? WHERE key = ?", JSON.stringify(input), PREFIX + input.operationId);
113
+ });
114
+ }
115
+
116
+ export function publishSupervisedResult(ctx: StoreContext, input: {
117
+ operationId: string; epoch: string; publication: RecordTerminalOutcomeInput;
118
+ }) {
119
+ return ctx.transaction(() => {
120
+ const grant = resultSupervision(ctx, input.operationId);
121
+ const operation = getOperation(ctx, input.operationId);
122
+ if (!grant || grant.epoch !== input.epoch || operation?.supervision?.hostId !== grant.hostId
123
+ || operation.launchToken !== grant.launchToken || input.publication.operationId !== input.operationId) {
124
+ throw new Error("stale-runtime-epoch: result supervision changed");
125
+ }
126
+ return recordTerminalOutcome(ctx, input.publication);
127
+ });
128
+ }
@@ -18,7 +18,33 @@ import { SCHEMA_VERSION } from "./types.ts";
18
18
  import { StoreError } from "./errors.ts";
19
19
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
20
20
 
21
+ // Enforce the handoff even for an older process still using its bundled store.
22
+ // Unknown legacy scopes conservatively conflict with any managed root scope.
23
+ const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admission_v1
24
+ BEFORE INSERT ON operations
25
+ WHEN NEW.observer_kind = 'local-supervisor'
26
+ AND COALESCE(json_extract(NEW.supervision_json, '$.resultAdapter'), 0) != 1
27
+ AND EXISTS (SELECT 1 FROM coordinator_state
28
+ WHERE key LIKE 'result-scope-v1:%'
29
+ AND (json_extract(NEW.supervision_json, '$.resultScope') IS NULL
30
+ OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
31
+ BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
32
+
21
33
  const DDL: readonly string[] = [
34
+ `CREATE TABLE task_cancellation_authorities (
35
+ credential_hash TEXT PRIMARY KEY,
36
+ request_json TEXT NOT NULL,
37
+ directory TEXT NOT NULL
38
+ )`,
39
+ `CREATE TABLE task_cancellation_requests (
40
+ owner_key TEXT NOT NULL,
41
+ request_key TEXT NOT NULL,
42
+ operation_id TEXT NOT NULL REFERENCES operations (operation_id),
43
+ intent_json TEXT NOT NULL,
44
+ result_json TEXT,
45
+ state TEXT NOT NULL CHECK (state IN ('accepted', 'stop-requested')),
46
+ PRIMARY KEY (owner_key, request_key)
47
+ )`,
22
48
  `CREATE TABLE assignment_repairs (
23
49
  fault_key TEXT PRIMARY KEY,
24
50
  assignment_id TEXT NOT NULL,
@@ -224,6 +250,7 @@ const DDL: readonly string[] = [
224
250
  generation INTEGER NOT NULL,
225
251
  PRIMARY KEY (wait_id, generation)
226
252
  )`,
253
+ RESULT_ADMISSION_FENCE,
227
254
  ];
228
255
 
229
256
  const SCHEMA_VERSION_KEY = "schema_version";
@@ -280,6 +307,7 @@ export function ensureSchema(ctx: StoreContext): void {
280
307
  if (recorded < SCHEMA_VERSION) {
281
308
  if (recorded === 3) {
282
309
  ctx.transaction(() => {
310
+ ensureAdditiveSchema(ctx);
283
311
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
284
312
  run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
285
313
  });
@@ -323,9 +351,18 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
323
351
  && hasIndex()
324
352
  && hasTable("discovery_claims")
325
353
  && hasTable("coordinator_state")
326
- ) return;
354
+ && hasTable("task_cancellation_requests")
355
+ && hasTable("task_cancellation_authorities")
356
+ && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")
357
+ ) {
358
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
359
+ return;
360
+ }
327
361
 
328
362
  ctx.transaction(() => {
363
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
364
+ if (!getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")) ctx.db.exec("ALTER TABLE task_cancellation_requests ADD COLUMN result_json TEXT");
365
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_authorities"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
329
366
  if (!hasColumn()) {
330
367
  ctx.db.exec("ALTER TABLE operations ADD COLUMN supervision_host_id TEXT");
331
368
  ctx.db.exec(`UPDATE operations
@@ -346,6 +383,7 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
346
383
  key TEXT PRIMARY KEY,
347
384
  value TEXT NOT NULL
348
385
  )`);
386
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
349
387
  });
350
388
  }
351
389
 
@@ -8,6 +8,9 @@
8
8
  * and leaves no partial record.
9
9
  */
10
10
  import { StoreError } from "./errors.ts";
11
+ import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
12
+ import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
13
+ import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
11
14
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
12
15
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.ts";
13
16
  import type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./assignment-outcomes.ts";
@@ -32,6 +35,7 @@ import {
32
35
  import {
33
36
  getChangeRevision as readChangeRevision,
34
37
  readDiscoveryClaim as readClaim,
38
+ readDiscoveryState,
35
39
  releaseDiscoveryClaim as deleteDiscoveryClaim,
36
40
  tryClaimDiscovery as writeDiscoveryClaim,
37
41
  } from "./discovery.ts";
@@ -116,6 +120,26 @@ import {
116
120
  } from "./types.ts";
117
121
 
118
122
  export interface Store {
123
+ resultScopeManaged(scope: string): boolean;
124
+ handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
125
+ resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
126
+ resultSupervisions(activeOnly?: boolean): ReturnType<typeof resultSupervisions>;
127
+ handoffResultSupervision(input: Parameters<typeof handoffResultSupervision>[1]): ReturnType<typeof handoffResultSupervision>;
128
+ handoffResultSupervisions(input: Parameters<typeof handoffResultSupervisions>[1]): ReturnType<typeof handoffResultSupervisions>;
129
+ recoverResultSupervision(input: Parameters<typeof recoverResultSupervision>[1]): void;
130
+ publishSupervisedResult(input: Parameters<typeof publishSupervisedResult>[1]): ReturnType<typeof publishSupervisedResult>;
131
+ unknownTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
132
+ taskCancellationManaged(operationId: string): boolean;
133
+ pendingTaskCancellations(): ReturnType<typeof pendingTaskCancellations>;
134
+ finishTaskCancellationIntent(input: Parameters<typeof finishTaskCancellationIntent>[1]): TaskCancellationIntent;
135
+ cancellationRuntimeEpoch(instanceId?: string): number;
136
+ acceptAuthorizedTaskCancellation(input: { credential: string; runtimeEpoch: number }): TaskCancellationIntent;
137
+ admitTaskCancellation(input: Parameters<typeof admitTaskCancellation>[1]): void;
138
+ authorizedTaskCancellation(credential: string): ReturnType<typeof authorizedTaskCancellation>;
139
+ finishTaskCancellation(input: Parameters<typeof finishTaskCancellation>[1]): TaskCancellationIntent;
140
+ acceptTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
141
+ getTaskCancellation(input: { owner: OwnerIdentity; idempotencyKey: string }): TaskCancellationIntent | null;
142
+ recordTaskStopRequested(input: TaskCancellationRequest): TaskCancellationIntent;
119
143
  registerAssignment(input: Parameters<typeof registerAssignment>[1]): void;
120
144
  receiptAssignmentOutcome(input: Parameters<typeof receiptAssignmentOutcome>[1]): AssignmentOutcomeRecord;
121
145
  recordAssignmentOutcome(input: AssignmentOutcomeInput): AssignmentOutcomeRecord;
@@ -169,6 +193,7 @@ export interface Store {
169
193
 
170
194
  /** The shared discovery leader for this store/supervisor scope, if recorded. */
171
195
  readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
196
+ readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
172
197
  /**
173
198
  * Compare-and-swap a discovery claim. The caller must name the exact claim it
174
199
  * observed, or null for none; a stale contender receives null and must not
@@ -311,6 +336,23 @@ export function openStore(options: StoreOptions): Store {
311
336
  };
312
337
 
313
338
  const store: Store = {
339
+ resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
340
+ handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
341
+ resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
342
+ resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
343
+ handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
344
+ handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
345
+ recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
346
+ publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
347
+ unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
348
+ taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
349
+ pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
350
+ finishTaskCancellationIntent(input) { alive(); return finishTaskCancellationIntent(ctx, input); },
351
+ cancellationRuntimeEpoch(instanceId) { alive(); return cancellationRuntimeEpoch(ctx, instanceId); },
352
+ acceptAuthorizedTaskCancellation(input) { alive(); return acceptAuthorizedTaskCancellation(ctx, input); },
353
+ admitTaskCancellation(input) { alive(); admitTaskCancellation(ctx, input); },
354
+ authorizedTaskCancellation(credential) { alive(); return authorizedTaskCancellation(ctx, credential); },
355
+ finishTaskCancellation(input) { alive(); return finishTaskCancellation(ctx, input); },
314
356
  registerAssignment(input) { alive(); registerAssignment(ctx, input); },
315
357
  receiptAssignmentOutcome(input) { alive(); return receiptAssignmentOutcome(ctx, input); },
316
358
  recordAssignmentOutcome(input) { alive(); return recordAssignmentOutcome(ctx, input); },
@@ -360,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
360
402
  terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
361
403
  );
362
404
  },
405
+ readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
363
406
  readDiscoveryClaim(scope) {
364
407
  alive();
365
408
  return readClaim(ctx, scope);
@@ -380,6 +423,18 @@ export function openStore(options: StoreOptions): Store {
380
423
  alive();
381
424
  return writeWait(ctx, input);
382
425
  },
426
+ acceptTaskCancellation(input) {
427
+ alive();
428
+ return acceptTaskCancellation(ctx, input);
429
+ },
430
+ getTaskCancellation(input) {
431
+ alive();
432
+ return getTaskCancellation(ctx, input);
433
+ },
434
+ recordTaskStopRequested(input) {
435
+ alive();
436
+ return recordTaskStopRequested(ctx, input);
437
+ },
383
438
  transitionWaitPhase(input) {
384
439
  alive();
385
440
  return writePhase(ctx, input);
@@ -0,0 +1,224 @@
1
+ // Generated from packages/operation-coordinator/src/task-cancellation.ts. Do not edit directly.
2
+ /**
3
+ * Durable intent for the fixed cancel_task operation. Admission and process
4
+ * identity checks remain the host's responsibility. An accepted intent is not
5
+ * evidence that a process stopped; recovery must use its original launch token.
6
+ */
7
+ import { StoreError } from "./errors.ts";
8
+ import { createHash, randomBytes } from "node:crypto";
9
+ import { getOperation, recordTerminalOutcome } from "./operations.ts";
10
+ import { columnText, getRow, run, type StoreContext } from "./sqlite.ts";
11
+ import type { OwnerIdentity, RecordTerminalOutcomeInput } from "./types.ts";
12
+ import { normalizeOwner, requireCounter, requireId, requireText, sameOwner } from "./validate.ts";
13
+
14
+ export interface TaskCancellationRequest {
15
+ owner: OwnerIdentity;
16
+ idempotencyKey: string;
17
+ operationId: string;
18
+ expectedLaunchToken: string;
19
+ expectedTerminalRevision: number;
20
+ expectedHostId: string;
21
+ reason: string;
22
+ }
23
+
24
+ export interface TaskCancellationIntent extends TaskCancellationRequest {
25
+ operation: "cancel_task";
26
+ taskId: string;
27
+ state: "accepted" | "stop-requested";
28
+ acceptedAt: number;
29
+ result?: { status: string; terminal: boolean };
30
+ }
31
+
32
+ export interface CancellationAdmission {
33
+ credentialHash: string;
34
+ request: TaskCancellationRequest;
35
+ directory: string;
36
+ runtimeEpoch?: number;
37
+ cancelEpoch?: number;
38
+ revision?: string;
39
+ }
40
+
41
+ export function cancellationRuntimeEpoch(ctx: StoreContext, instanceId?: string): number {
42
+ return ctx.transaction(() => {
43
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = 'cancellation-runtime'");
44
+ const current = row ? JSON.parse(columnText(row, "value")) : { epoch: 0 };
45
+ if (!instanceId || current.instanceId === instanceId) return current.epoch;
46
+ const epoch = current.epoch + 1;
47
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES ('cancellation-runtime', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", JSON.stringify({ instanceId, epoch }));
48
+ return epoch;
49
+ });
50
+ }
51
+
52
+ function cancelEpoch(ctx: StoreContext, operationId: string): number {
53
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", `cancel:${operationId}`);
54
+ return row ? Number(columnText(row, "value")) : 0;
55
+ }
56
+
57
+ function revision(operation: unknown, epoch: number): string {
58
+ const op = operation as ReturnType<typeof getOperation>;
59
+ return createHash("sha256").update(JSON.stringify([op && {
60
+ operationId: op.operationId, owner: op.owner, launchToken: op.launchToken,
61
+ terminalRevision: op.terminalRevision, phase: op.phase, authorityRef: op.authorityRef,
62
+ hostId: op.supervision?.hostId,
63
+ }, epoch])).digest("hex");
64
+ }
65
+
66
+ export function taskCancellationManaged(ctx: StoreContext, operationId: string): boolean {
67
+ return !!getRow(ctx, "SELECT credential_hash FROM task_cancellation_authorities WHERE json_extract(request_json, '$.request.operationId') = ? LIMIT 1", requireId("operationId", operationId));
68
+ }
69
+
70
+ export function pendingTaskCancellations(ctx: StoreContext): CancellationAdmission[] {
71
+ return ctx.db.prepare("SELECT a.* FROM task_cancellation_authorities a JOIN task_cancellation_requests r ON json_extract(a.request_json, '$.request.operationId') = r.operation_id AND json_extract(a.request_json, '$.request.idempotencyKey') = r.request_key WHERE r.result_json IS NULL").all()
72
+ .map(row => ({ credentialHash: columnText(row, "credential_hash"), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") }));
73
+ }
74
+
75
+ export function acceptAuthorizedTaskCancellation(ctx: StoreContext, input: { credential: string; runtimeEpoch: number }): TaskCancellationIntent {
76
+ return ctx.transaction(() => {
77
+ const admission = authorizedTaskCancellation(ctx, input.credential);
78
+ const previous = getTaskCancellation(ctx, admission.request);
79
+ if (previous) return acceptTaskCancellation(ctx, admission.request);
80
+ if (input.runtimeEpoch !== cancellationRuntimeEpoch(ctx) || input.runtimeEpoch !== admission.runtimeEpoch) throw new StoreError("supervision-conflict", "not_accepted: stale-runtime-epoch; query journal before new admission");
81
+ const operation = getOperation(ctx, admission.request.operationId);
82
+ const epoch = cancelEpoch(ctx, admission.request.operationId);
83
+ if (epoch !== admission.cancelEpoch || revision(operation, epoch) !== admission.revision) throw new StoreError("operation-conflict", "not_accepted: stale-revision or cancellation epoch");
84
+ const intent = acceptTaskCancellation(ctx, admission.request);
85
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", `cancel:${intent.operationId}`, String(epoch + 1));
86
+ return intent;
87
+ });
88
+ }
89
+
90
+ export function cancellationCredential(): { credential: string; hash: string } {
91
+ const credential = randomBytes(32).toString("hex");
92
+ return { credential, hash: credentialHash(credential) };
93
+ }
94
+
95
+ function credentialHash(credential: string): string {
96
+ return createHash("sha256").update(requireText("credential", credential, 128)).digest("hex");
97
+ }
98
+
99
+ /** Called only by the existing admitted domain host, never by a socket command. */
100
+ export function admitTaskCancellation(ctx: StoreContext, input: CancellationAdmission): void {
101
+ const normalized = request(input.request);
102
+ const hash = requireId("credentialHash", input.credentialHash);
103
+ const directory = requireText("directory", input.directory, 4096);
104
+ ctx.transaction(() => {
105
+ const operation = getOperation(ctx, normalized.operationId);
106
+ if (!operation || !sameOwner(operation.owner, normalized.owner)) throw new StoreError("foreign-owner", "Cancellation admission requires the recorded owner.");
107
+ const previous = getTaskCancellation(ctx, normalized);
108
+ if (operation.launchToken !== normalized.expectedLaunchToken || (!previous && operation.supervision?.hostId !== normalized.expectedHostId)) {
109
+ throw new StoreError("supervision-conflict", "Cancellation admission requires the current exact launch and host.");
110
+ }
111
+ if (previous && JSON.stringify(request(previous)) !== JSON.stringify(normalized)) throw new StoreError("request-conflict", "Cancellation key is bound to different request content.");
112
+ const original = previous ? request(previous) : normalized;
113
+ const epoch = cancelEpoch(ctx, normalized.operationId);
114
+ run(ctx, "INSERT INTO task_cancellation_authorities (credential_hash, request_json, directory) VALUES (?, ?, ?)", hash,
115
+ JSON.stringify({ request: original, runtimeEpoch: cancellationRuntimeEpoch(ctx), cancelEpoch: epoch, revision: revision(operation, epoch) }), directory);
116
+ });
117
+ }
118
+
119
+ /** A credential binds an already-admitted exact request, not a claimed session ID. */
120
+ export function authorizedTaskCancellation(ctx: StoreContext, credential: string): CancellationAdmission {
121
+ const row = getRow(ctx, "SELECT * FROM task_cancellation_authorities WHERE credential_hash = ?", credentialHash(credential));
122
+ if (!row) throw new StoreError("foreign-owner", "permission-unavailable: cancellation authority is not registered.");
123
+ return { credentialHash: credentialHash(credential), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") };
124
+ }
125
+
126
+ export function finishTaskCancellation(ctx: StoreContext, input: { credential: string; status: string; terminal: boolean }): TaskCancellationIntent {
127
+ const admission = authorizedTaskCancellation(ctx, input.credential);
128
+ return finishTaskCancellationIntent(ctx, { request: admission.request, status: input.status, terminal: input.terminal });
129
+ }
130
+
131
+ export function finishTaskCancellationIntent(ctx: StoreContext, input: { request: TaskCancellationRequest; status: string; terminal: boolean; publication?: RecordTerminalOutcomeInput }): TaskCancellationIntent {
132
+ return ctx.transaction(() => {
133
+ const intent = recordTaskStopRequested(ctx, input.request);
134
+ if (intent.result) return intent;
135
+ if (input.publication) {
136
+ if (input.publication.operationId !== intent.operationId || !sameOwner(input.publication.owner, intent.owner)) throw new StoreError("foreign-owner", "Terminal publication does not match the cancellation intent.");
137
+ recordTerminalOutcome(ctx, input.publication);
138
+ }
139
+ const result = { status: requireText("status", input.status, 64), terminal: input.terminal === true };
140
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
141
+ return { ...intent, result };
142
+ });
143
+ }
144
+
145
+ export function unknownTaskCancellation(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
146
+ return ctx.transaction(() => {
147
+ const intent = getTaskCancellation(ctx, input);
148
+ if (!intent) throw new StoreError("request-conflict", "Cannot record an unknown outcome without an accepted intent.");
149
+ if (intent.result) return intent;
150
+ const result = { status: "outcome_unknown", terminal: false };
151
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
152
+ return { ...intent, result };
153
+ });
154
+ }
155
+
156
+ function ownerKey(owner: OwnerIdentity): string {
157
+ return JSON.stringify([owner.kind, owner.sessionId, owner.workspace, owner.branchId, owner.goalId]);
158
+ }
159
+
160
+ function request(input: TaskCancellationRequest): TaskCancellationRequest {
161
+ return {
162
+ owner: normalizeOwner("owner", input.owner),
163
+ idempotencyKey: requireText("idempotencyKey", input.idempotencyKey, 512),
164
+ operationId: requireId("operationId", input.operationId),
165
+ expectedLaunchToken: requireId("launchToken", input.expectedLaunchToken),
166
+ expectedTerminalRevision: requireCounter("terminalRevision", input.expectedTerminalRevision),
167
+ expectedHostId: requireId("hostId", input.expectedHostId),
168
+ reason: requireText("reason", input.reason, 1024),
169
+ };
170
+ }
171
+
172
+ export function getTaskCancellation(
173
+ ctx: StoreContext,
174
+ input: { owner: OwnerIdentity; idempotencyKey: string },
175
+ ): TaskCancellationIntent | null {
176
+ const owner = normalizeOwner("owner", input.owner);
177
+ const key = requireText("idempotencyKey", input.idempotencyKey, 512);
178
+ const row = getRow(ctx, "SELECT intent_json, state, result_json FROM task_cancellation_requests WHERE owner_key = ? AND request_key = ?", ownerKey(owner), key);
179
+ if (!row) return null;
180
+ return { ...JSON.parse(columnText(row, "intent_json")), state: columnText(row, "state"), ...(row.result_json ? { result: JSON.parse(columnText(row, "result_json")) } : {}) };
181
+ }
182
+
183
+ export function acceptTaskCancellation(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
184
+ const normalized = request(input);
185
+ return ctx.transaction(() => {
186
+ // Journal lookup precedes current object checks: a retry after terminal
187
+ // publication must recover the original receipt, not become a new stop.
188
+ const previous = getTaskCancellation(ctx, normalized);
189
+ if (previous) {
190
+ const { operation: _operation, taskId: _taskId, state: _state, acceptedAt: _at, result: _result, ...original } = previous;
191
+ if (JSON.stringify(original) !== JSON.stringify(normalized)) {
192
+ throw new StoreError("request-conflict", "Cancellation key is already bound to different request content.");
193
+ }
194
+ return previous;
195
+ }
196
+ const operation = getOperation(ctx, normalized.operationId);
197
+ if (!operation) throw new StoreError("unknown-operation", "Cancellation operation does not exist.");
198
+ if (!sameOwner(operation.owner, normalized.owner)) throw new StoreError("foreign-owner", "Cancellation requires the recorded execution owner.");
199
+ if (operation.launchToken !== normalized.expectedLaunchToken || operation.terminalRevision !== normalized.expectedTerminalRevision) {
200
+ throw new StoreError("operation-conflict", "Cancellation launch token or terminal revision changed.");
201
+ }
202
+ if (operation.supervision?.hostId !== normalized.expectedHostId) {
203
+ throw new StoreError("supervision-conflict", "Cancellation supervision host changed.");
204
+ }
205
+ const intent: TaskCancellationIntent = {
206
+ ...normalized, operation: "cancel_task", taskId: operation.taskId, state: "accepted", acceptedAt: ctx.now(),
207
+ };
208
+ run(ctx, "INSERT INTO task_cancellation_requests (owner_key, request_key, operation_id, intent_json, state) VALUES (?, ?, ?, ?, 'accepted')",
209
+ ownerKey(normalized.owner), normalized.idempotencyKey, operation.operationId, JSON.stringify(intent));
210
+ return intent;
211
+ });
212
+ }
213
+
214
+ /** Record durable stop-file publication, never process exit or a terminal verdict. */
215
+ export function recordTaskStopRequested(ctx: StoreContext, input: TaskCancellationRequest): TaskCancellationIntent {
216
+ return ctx.transaction(() => {
217
+ const normalized = request(input);
218
+ if (!getTaskCancellation(ctx, normalized)) throw new StoreError("request-conflict", "Cancellation intent must commit before the stop action.");
219
+ const intent = acceptTaskCancellation(ctx, normalized);
220
+ run(ctx, "UPDATE task_cancellation_requests SET state = 'stop-requested' WHERE owner_key = ? AND request_key = ?",
221
+ ownerKey(normalized.owner), normalized.idempotencyKey);
222
+ return { ...intent, state: "stop-requested" };
223
+ });
224
+ }
@@ -83,6 +83,10 @@ export interface ObserverIdentity {
83
83
  * (a replacement host takes over on reload) while launch identity is not.
84
84
  */
85
85
  export interface SupervisionIdentity {
86
+ /** Durable discovery scope, recorded before sidecar creation or runner start. */
87
+ resultScope?: string;
88
+ /** The host uses grant-before-runner result admission and performs no global discovery. */
89
+ resultAdapter?: 1;
86
90
  /** Host that owns supervision, e.g. the Pi process id plus a start token. */
87
91
  hostId: string;
88
92
  /** Runner process identity, when a separate runner owns the operation. */
@@ -112,6 +116,8 @@ export interface RegisterOperationInput {
112
116
  }
113
117
 
114
118
  export interface OperationRecord {
119
+ /** Grant presence in the same snapshot as a bulk operation read. */
120
+ resultManaged?: boolean;
115
121
  operationId: string;
116
122
  taskId: string;
117
123
  launchToken: string;
@@ -0,0 +1,12 @@
1
+ export class WorkClient {
2
+ constructor(socketPath: string, agentDir: string, requiredCapabilities?: string[]);
3
+ ready: Promise<any>;
4
+ request(type: string, params?: object): Promise<any>;
5
+ snapshot?: any;
6
+ readonly closed: boolean;
7
+ onChange(listener: (...args: any[]) => void): () => void;
8
+ onCatalog(listener: (...args: any[]) => void): () => void;
9
+ subscribe(scope: object): Promise<any>;
10
+ get(scope: object): Promise<any>;
11
+ close(): void;
12
+ }