pi-better-background-tasks 0.17.0 → 0.18.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.
- package/package.json +4 -2
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/src/failures.ts +4 -2
- package/src/index.ts +6 -31
- package/src/managed-authority.ts +28 -0
- package/src/managed-client.ts +60 -0
- package/src/managed-frontend.ts +131 -0
- package/src/navigator-provider.ts +14 -6
- package/src/observed-waits.ts +118 -36
- package/src/output.ts +12 -0
- package/src/registry.ts +18 -1
- package/src/runtime.ts +8 -2
- package/src/sandbox.ts +7 -0
- package/src/shared-callback-batcher.ts +4 -1
- package/src/shared-failure-observations.ts +3 -0
- package/src/shared-navigator.ts +23 -5
- package/src/shared-operation-coordinator/assignment-observation.mjs +30 -0
- package/src/shared-operation-coordinator/index.ts +2 -0
- package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
- package/src/shared-operation-coordinator/src/schema.ts +31 -0
- package/src/shared-operation-coordinator/src/store.ts +18 -0
- package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
- package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/src/tools.ts +21 -5
|
@@ -65,6 +65,8 @@ export function createAssignmentReader(path) {
|
|
|
65
65
|
db ??= new DatabaseSync(path, { readOnly: true });
|
|
66
66
|
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
67
67
|
},
|
|
68
|
+
connection(refresh = true) { if (refresh) this.revision(); return db; },
|
|
69
|
+
|
|
68
70
|
beginSnapshot() {
|
|
69
71
|
this.revision();
|
|
70
72
|
if (snapshot) throw new Error("Coordinator snapshot already open");
|
|
@@ -80,6 +82,7 @@ export function createAssignmentReader(path) {
|
|
|
80
82
|
return { revision: this.revision(), release };
|
|
81
83
|
} catch (error) { release(); throw error; }
|
|
82
84
|
},
|
|
85
|
+
|
|
83
86
|
read(owner) {
|
|
84
87
|
try {
|
|
85
88
|
this.revision();
|
|
@@ -115,6 +118,33 @@ export function createAssignmentReader(path) {
|
|
|
115
118
|
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
116
119
|
} catch { return undefined; }
|
|
117
120
|
},
|
|
121
|
+
upgradeObligations() {
|
|
122
|
+
try { this.revision(); } catch (error) {
|
|
123
|
+
if (error.code === "ENOENT") return [];
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
const version = db.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
|
|
127
|
+
if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema during upgrade");
|
|
128
|
+
const obligations = db.prepare("SELECT operation_id, task_id, observer_kind FROM operations WHERE phase='running' AND terminal_revision=0").all()
|
|
129
|
+
.map(row => ({ kind: "unsettled-operation", id: row.task_id, operationId: row.operation_id, observer: row.observer_kind }));
|
|
130
|
+
const reasons = db.prepare("SELECT claim_id AS id, state FROM resume_claims WHERE state IN ('claimed', 'published')").all()
|
|
131
|
+
.map(row => ({ kind: "resume-claim", id: row.id, state: row.state }));
|
|
132
|
+
for (const row of db.prepare("SELECT wait_id, generation, phase FROM waits WHERE owner_kind='worker-conversation' AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed=0").all()) {
|
|
133
|
+
reasons.push({ kind: "worker-wait", id: row.wait_id, generation: row.generation, phase: row.phase });
|
|
134
|
+
}
|
|
135
|
+
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_launch_intents'").get()) {
|
|
136
|
+
for (const row of db.prepare("SELECT owner, request_key, attempts FROM subagent_launch_intents WHERE state='accepted'").all()) {
|
|
137
|
+
reasons.push({ kind: "launch-intent", id: row.request_key, owner: row.owner, attempts: JSON.parse(row.attempts).map(attempt => attempt.id) });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
for (const row of db.prepare("SELECT value FROM coordinator_state WHERE key LIKE 'background-request-v1:%'").all()) {
|
|
141
|
+
const request = JSON.parse(row.value);
|
|
142
|
+
if (request.state !== 'returned') reasons.push({kind:'background-request', id:request.key, owner:request.owner});
|
|
143
|
+
}
|
|
144
|
+
return [...obligations, ...reasons];
|
|
145
|
+
},
|
|
146
|
+
|
|
118
147
|
close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
148
|
+
|
|
119
149
|
};
|
|
120
150
|
}
|
|
@@ -118,3 +118,5 @@ export { StoreError, isStoreError } from "./src/errors.ts";
|
|
|
118
118
|
export type { StoreErrorCode } from "./src/errors.ts";
|
|
119
119
|
export { openStore, ownerDiff } from "./src/store.ts";
|
|
120
120
|
export type { Store } from "./src/store.ts";
|
|
121
|
+
|
|
122
|
+
export type { ParentCallbackScope, ParentCallbackPage, RecentBackgroundTerminalPage } from './src/background-parent-callbacks.ts';
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/background-parent-callbacks.ts. Do not edit directly.
|
|
2
|
+
/** Pending parent notifications are obligations, independent of UI retention. */
|
|
3
|
+
import { bumpChangeRevision } from './discovery.ts';
|
|
4
|
+
import { mapOperation } from './rows.ts';
|
|
5
|
+
import { getRow, getRows, run, type StoreContext } from './sqlite.ts';
|
|
6
|
+
import { requireBoolean, requireCounter, requireId, requirePath } from './validate.ts';
|
|
7
|
+
import type { OperationRecord } from './types.ts';
|
|
8
|
+
|
|
9
|
+
export interface ParentCallbackScope { sessionId: string; workspace: string }
|
|
10
|
+
export interface ParentCallbackPage { after?: string; limit?: number }
|
|
11
|
+
export interface RecentBackgroundTerminalPage {
|
|
12
|
+
since: number;
|
|
13
|
+
after?: { terminalAt: number; operationId: string };
|
|
14
|
+
limit?: number;
|
|
15
|
+
owner?: ParentCallbackScope;
|
|
16
|
+
}
|
|
17
|
+
const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
|
|
18
|
+
const scopeValues = (scope: ParentCallbackScope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)] as const;
|
|
19
|
+
|
|
20
|
+
export function setParentCallbackPending(ctx: StoreContext, taskId: string, pending: boolean): boolean {
|
|
21
|
+
taskId = requireId('taskId', taskId);
|
|
22
|
+
pending = requireBoolean('pending', pending);
|
|
23
|
+
return ctx.transaction(() => {
|
|
24
|
+
const operation = getRow(ctx, "SELECT operation_id, owner_workspace, owner_session_id FROM operations WHERE task_id=? AND owner_kind='parent-session' AND observer_kind='local-supervisor'", taskId);
|
|
25
|
+
if (!operation) return false;
|
|
26
|
+
const changed = pending
|
|
27
|
+
? run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
|
|
28
|
+
VALUES (?,'parent-session',?,?)`, String(operation.operation_id), String(operation.owner_workspace), String(operation.owner_session_id))
|
|
29
|
+
: run(ctx, 'DELETE FROM background_parent_callbacks WHERE operation_id=?', String(operation.operation_id));
|
|
30
|
+
if (changed > 0) bumpChangeRevision(ctx);
|
|
31
|
+
return changed > 0;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function listPendingParentCallbacks(ctx: StoreContext, scope: ParentCallbackScope, options: ParentCallbackPage = {}): OperationRecord[] {
|
|
36
|
+
return getRows(ctx, `SELECT o.* FROM background_parent_callbacks p JOIN operations o ON o.operation_id=p.operation_id
|
|
37
|
+
WHERE p.owner_kind='parent-session' AND p.owner_workspace=? AND p.owner_session_id=? AND p.operation_id>? AND o.terminal_revision>0
|
|
38
|
+
ORDER BY p.operation_id LIMIT ?`, ...scopeValues(scope), options.after === undefined ? '' : requireId('after', options.after), pageSize(options.limit)).map(mapOperation);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function listRecentBackgroundTerminals(ctx: StoreContext, options: RecentBackgroundTerminalPage): OperationRecord[] {
|
|
42
|
+
const params: Array<string|number> = [requireCounter('since', options.since)];
|
|
43
|
+
let where = "observer_kind='local-supervisor' AND terminal_revision>0 AND terminal_at>=?";
|
|
44
|
+
if (options.owner) { where += " AND owner_kind='parent-session' AND owner_workspace=? AND owner_session_id=?"; params.push(...scopeValues(options.owner)); }
|
|
45
|
+
if (options.after) { where += ' AND (terminal_at,operation_id)>(?,?)'; params.push(requireCounter('after.terminalAt', options.after.terminalAt), requireId('after.operationId', options.after.operationId)); }
|
|
46
|
+
params.push(pageSize(options.limit));
|
|
47
|
+
return getRows(ctx, `SELECT * FROM operations WHERE ${where} ORDER BY terminal_at,operation_id LIMIT ?`, ...params).map(mapOperation);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Call from the canonical manager in bounded batches, yielding between pages. */
|
|
51
|
+
export function seedPendingParentCallbacks(ctx: StoreContext, options: { limit?: number } = {}): { done: boolean; seeded: number } {
|
|
52
|
+
return ctx.transaction(() => {
|
|
53
|
+
const migration = getRow(ctx, 'SELECT * FROM background_parent_callback_migration WHERE singleton=1')!;
|
|
54
|
+
if (Number(migration.done)) return { done: true, seeded: 0 };
|
|
55
|
+
const limit = pageSize(options.limit);
|
|
56
|
+
const rows = getRows(ctx, `SELECT operation_id,owner_workspace,owner_session_id FROM operations
|
|
57
|
+
WHERE owner_kind='parent-session' AND observer_kind='local-supervisor' AND operation_id>? AND operation_id<=?
|
|
58
|
+
ORDER BY operation_id LIMIT ?`, String(migration.after_operation_id), String(migration.through_operation_id), limit);
|
|
59
|
+
let seeded = 0;
|
|
60
|
+
for (const row of rows) seeded += Number(run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
|
|
61
|
+
VALUES (?,'parent-session',?,?)`, String(row.operation_id), String(row.owner_workspace), String(row.owner_session_id)));
|
|
62
|
+
const after = rows.length ? String(rows.at(-1)!.operation_id) : String(migration.after_operation_id);
|
|
63
|
+
const done = rows.length < limit || after === migration.through_operation_id;
|
|
64
|
+
run(ctx, 'UPDATE background_parent_callback_migration SET after_operation_id=?,done=? WHERE singleton=1', after, done ? 1 : 0);
|
|
65
|
+
if (seeded) bumpChangeRevision(ctx);
|
|
66
|
+
return { done, seeded };
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/background-requests.ts. Do not edit directly.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import type { StoreContext } from './sqlite.ts';
|
|
4
|
+
export interface BackgroundRequest {
|
|
5
|
+
owner: string;
|
|
6
|
+
key: string;
|
|
7
|
+
digest: string;
|
|
8
|
+
state: 'accepted' | 'dispatching' | 'returned';
|
|
9
|
+
operations: Array<{
|
|
10
|
+
operationId: string;
|
|
11
|
+
taskId: string;
|
|
12
|
+
token: string;
|
|
13
|
+
}>;
|
|
14
|
+
result?: unknown;
|
|
15
|
+
}
|
|
16
|
+
const prefix = 'background-request-v1:';
|
|
17
|
+
// A partial index excludes returned history. CASE protects other coordinator
|
|
18
|
+
// records and makes corrupt request rows visible to recovery rather than hiding them.
|
|
19
|
+
const pendingPredicate = "key GLOB 'background-request-v1:*' AND CASE WHEN json_valid(value) THEN COALESCE(json_extract(value, '$.state'), '') != 'returned' ELSE 1 END";
|
|
20
|
+
export const BACKGROUND_PENDING_QUERY = `SELECT value FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} ORDER BY key LIMIT ?`;
|
|
21
|
+
function storageKey(owner: string, key: string) { return prefix + createHash('sha256').update(JSON.stringify([owner, key])).digest('hex'); }
|
|
22
|
+
export class BackgroundRequests {
|
|
23
|
+
private context: StoreContext;
|
|
24
|
+
private alive: () => void;
|
|
25
|
+
constructor(context: StoreContext, alive: () => void) {
|
|
26
|
+
this.context = context;
|
|
27
|
+
this.alive = alive;
|
|
28
|
+
alive();
|
|
29
|
+
context.db.exec(`CREATE INDEX IF NOT EXISTS background_requests_pending ON coordinator_state(key) WHERE ${pendingPredicate}`);
|
|
30
|
+
}
|
|
31
|
+
read(owner: string, key: string): BackgroundRequest | undefined {
|
|
32
|
+
this.alive();
|
|
33
|
+
const row = this.context.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(storageKey(owner, key));
|
|
34
|
+
return row ? JSON.parse(String(row.value)) : undefined;
|
|
35
|
+
}
|
|
36
|
+
private write(value: BackgroundRequest) {
|
|
37
|
+
this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
|
|
38
|
+
}
|
|
39
|
+
accept(owner: string, key: string, digest: string) {
|
|
40
|
+
this.alive();
|
|
41
|
+
return this.context.transaction(() => {
|
|
42
|
+
const prior = this.read(owner, key);
|
|
43
|
+
if (prior) {
|
|
44
|
+
if (prior.digest !== digest)
|
|
45
|
+
throw new Error('request-conflict: Background request key changed content');
|
|
46
|
+
return { prior: true, record: prior };
|
|
47
|
+
}
|
|
48
|
+
const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [] };
|
|
49
|
+
this.write(record);
|
|
50
|
+
return { prior: false, record };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
dispatch(owner: string, key: string) { this.update(owner, key, value => { if (value.state !== 'accepted')
|
|
54
|
+
throw new Error('Background request already dispatched'); value.state = 'dispatching'; }); }
|
|
55
|
+
operation(owner: string, key: string, operation: BackgroundRequest['operations'][number]) {
|
|
56
|
+
this.update(owner, key, value => {
|
|
57
|
+
if (value.state !== 'dispatching')
|
|
58
|
+
throw new Error('Background request is not dispatching');
|
|
59
|
+
if (value.operations.some(prior => prior.operationId === operation.operationId))
|
|
60
|
+
throw new Error('Background operation already prepared');
|
|
61
|
+
value.operations.push(operation);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
finish(owner: string, key: string, result: unknown) { this.update(owner, key, value => { value.result = result; value.state = 'returned'; }); }
|
|
65
|
+
private update(owner: string, key: string, change: (value: BackgroundRequest) => void) {
|
|
66
|
+
this.alive();
|
|
67
|
+
this.context.transaction(() => { const value = this.read(owner, key); if (!value)
|
|
68
|
+
throw new Error('Background request not admitted'); change(value); this.write(value); });
|
|
69
|
+
}
|
|
70
|
+
hasPending(): boolean {
|
|
71
|
+
this.alive();
|
|
72
|
+
return Boolean(this.context.db.prepare(`SELECT 1 FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} LIMIT 1`).get());
|
|
73
|
+
}
|
|
74
|
+
pending(limit = 128): BackgroundRequest[] {
|
|
75
|
+
this.alive();
|
|
76
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 128) throw new Error('Background recovery batch limit must be 1..128');
|
|
77
|
+
return this.context.db.prepare(BACKGROUND_PENDING_QUERY).all(limit).map(row => JSON.parse(String(row.value)));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -30,6 +30,33 @@ const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admiss
|
|
|
30
30
|
OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
|
|
31
31
|
BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
|
|
32
32
|
|
|
33
|
+
const BACKGROUND_CALLBACK_DDL = [
|
|
34
|
+
`CREATE TABLE IF NOT EXISTS background_parent_callbacks (
|
|
35
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
36
|
+
owner_kind TEXT NOT NULL CHECK(owner_kind='parent-session'),
|
|
37
|
+
owner_workspace TEXT NOT NULL,
|
|
38
|
+
owner_session_id TEXT NOT NULL
|
|
39
|
+
)`,
|
|
40
|
+
`CREATE TRIGGER IF NOT EXISTS background_parent_callback_registration
|
|
41
|
+
AFTER INSERT ON operations
|
|
42
|
+
WHEN NEW.owner_kind='parent-session' AND NEW.observer_kind='local-supervisor'
|
|
43
|
+
BEGIN INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
|
|
44
|
+
VALUES(NEW.operation_id,NEW.owner_kind,NEW.owner_workspace,NEW.owner_session_id); END`,
|
|
45
|
+
`CREATE INDEX IF NOT EXISTS background_parent_callbacks_owner ON background_parent_callbacks(owner_kind,owner_workspace,owner_session_id,operation_id)`,
|
|
46
|
+
`CREATE INDEX IF NOT EXISTS operations_background_recent ON operations(terminal_at,operation_id) WHERE observer_kind='local-supervisor' AND terminal_revision>0`,
|
|
47
|
+
`CREATE INDEX IF NOT EXISTS operations_background_owner_recent ON operations(owner_kind,owner_workspace,owner_session_id,terminal_at,operation_id) WHERE observer_kind='local-supervisor' AND terminal_revision>0`,
|
|
48
|
+
`CREATE INDEX IF NOT EXISTS operations_background_parent_seed ON operations(operation_id) WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
|
|
49
|
+
`CREATE TABLE IF NOT EXISTS background_parent_callback_migration (
|
|
50
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
|
51
|
+
after_operation_id TEXT NOT NULL,
|
|
52
|
+
through_operation_id TEXT NOT NULL,
|
|
53
|
+
done INTEGER NOT NULL CHECK(done IN (0,1))
|
|
54
|
+
)`,
|
|
55
|
+
`INSERT OR IGNORE INTO background_parent_callback_migration(singleton,after_operation_id,through_operation_id,done)
|
|
56
|
+
SELECT 1,'',COALESCE(MAX(operation_id),''),CASE WHEN MAX(operation_id) IS NULL THEN 1 ELSE 0 END
|
|
57
|
+
FROM operations WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
|
|
58
|
+
];
|
|
59
|
+
|
|
33
60
|
const DDL: readonly string[] = [
|
|
34
61
|
`CREATE TABLE task_cancellation_authorities (
|
|
35
62
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -84,6 +111,7 @@ const DDL: readonly string[] = [
|
|
|
84
111
|
updated_at INTEGER NOT NULL,
|
|
85
112
|
terminal_at INTEGER
|
|
86
113
|
)`,
|
|
114
|
+
...BACKGROUND_CALLBACK_DDL,
|
|
87
115
|
`CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
|
|
88
116
|
`CREATE INDEX operations_phase ON operations (phase)`,
|
|
89
117
|
`CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
|
|
@@ -341,6 +369,9 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
341
369
|
* records during a rolling upgrade. Missing additions are created once on open.
|
|
342
370
|
*/
|
|
343
371
|
function ensureAdditiveSchema(ctx: StoreContext): void {
|
|
372
|
+
// Schema/index creation is atomic; legacy obligation seeding is performed
|
|
373
|
+
// separately in bounded batches by the canonical manager.
|
|
374
|
+
ctx.transaction(() => { for (const statement of BACKGROUND_CALLBACK_DDL) ctx.db.exec(statement); });
|
|
344
375
|
const hasColumn = (): boolean =>
|
|
345
376
|
getRows(ctx, "PRAGMA table_info(operations)").some((row) => columnText(row, "name") === "supervision_host_id");
|
|
346
377
|
const hasIndex = (): boolean =>
|
|
@@ -7,7 +7,11 @@
|
|
|
7
7
|
* synchronous and transactional; a refusal throws `StoreError` with a typed code
|
|
8
8
|
* and leaves no partial record.
|
|
9
9
|
*/
|
|
10
|
+
import { setUpgradeFence } from "./upgrade.ts";
|
|
11
|
+
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
|
|
12
|
+
import { BackgroundRequests } from "./background-requests.ts";
|
|
10
13
|
import { StoreError } from "./errors.ts";
|
|
14
|
+
import { SubagentLaunchJournal } from "./subagent-launch.ts";
|
|
11
15
|
import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
|
|
12
16
|
import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
|
|
13
17
|
import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
|
|
@@ -120,6 +124,7 @@ import {
|
|
|
120
124
|
} from "./types.ts";
|
|
121
125
|
|
|
122
126
|
export interface Store {
|
|
127
|
+
subagentLaunchJournal(): SubagentLaunchJournal;
|
|
123
128
|
resultScopeManaged(scope: string): boolean;
|
|
124
129
|
handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
|
|
125
130
|
resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
|
|
@@ -161,6 +166,12 @@ export interface Store {
|
|
|
161
166
|
* returns `created: false`, and any difference is refused with
|
|
162
167
|
* `operation-conflict` or `task-ownership`.
|
|
163
168
|
*/
|
|
169
|
+
backgroundRequests(): BackgroundRequests;
|
|
170
|
+
setParentCallbackPending(taskId: string, pending: boolean): boolean;
|
|
171
|
+
listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
|
|
172
|
+
listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
|
|
173
|
+
seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
|
|
174
|
+
setUpgradeFence(epoch: string | null): void;
|
|
164
175
|
registerOperation(input: RegisterOperationInput): RegisterOperationResult;
|
|
165
176
|
/**
|
|
166
177
|
* Replace supervision identity and/or report observer health
|
|
@@ -336,6 +347,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
336
347
|
};
|
|
337
348
|
|
|
338
349
|
const store: Store = {
|
|
350
|
+
subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
|
|
339
351
|
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
340
352
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
341
353
|
resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
|
|
@@ -366,6 +378,12 @@ export function openStore(options: StoreOptions): Store {
|
|
|
366
378
|
closed = true;
|
|
367
379
|
db.close();
|
|
368
380
|
},
|
|
381
|
+
setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
|
|
382
|
+
listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
|
|
383
|
+
listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
|
|
384
|
+
seedPendingParentCallbacks(options) { alive(); return seedPendingParentCallbacks(ctx, options); },
|
|
385
|
+
backgroundRequests() { alive(); return new BackgroundRequests(ctx, alive); },
|
|
386
|
+
setUpgradeFence(epoch) { alive(); setUpgradeFence(ctx, epoch); },
|
|
369
387
|
registerOperation(input) {
|
|
370
388
|
alive();
|
|
371
389
|
return writeOperation(ctx, input);
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import type { StoreContext } from "./sqlite.ts";
|
|
4
|
+
|
|
5
|
+
export interface LaunchAttempt {
|
|
6
|
+
id: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
lease: string;
|
|
9
|
+
leasePath: string;
|
|
10
|
+
preflightPath: string;
|
|
11
|
+
preflightDigest: string;
|
|
12
|
+
policyPath?: string;
|
|
13
|
+
policyDigest?: string;
|
|
14
|
+
capacityOwner: { pid: number; start: string };
|
|
15
|
+
launchAuthority?: unknown;
|
|
16
|
+
recipe: unknown;
|
|
17
|
+
permissions: unknown;
|
|
18
|
+
token: string;
|
|
19
|
+
state: "prepared" | "spawned";
|
|
20
|
+
pid?: number;
|
|
21
|
+
writerPid?: number;
|
|
22
|
+
writerStartTime?: string;
|
|
23
|
+
pidStartTime?: string;
|
|
24
|
+
recoveryMeta?: unknown;
|
|
25
|
+
bootstrapped?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface LaunchIntent {
|
|
28
|
+
owner: string; request_key: string; digest: string; epoch: number;
|
|
29
|
+
state: "accepted" | "returned"; attempts: string; result: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Fixed launch journal on the coordinator's existing connection and transaction. */
|
|
33
|
+
export class SubagentLaunchJournal {
|
|
34
|
+
private context: StoreContext;
|
|
35
|
+
private alive: () => void;
|
|
36
|
+
constructor(context: StoreContext, alive: () => void) {
|
|
37
|
+
this.context = context;
|
|
38
|
+
this.alive = alive;
|
|
39
|
+
this.transaction(() => this.db.exec(`CREATE TABLE IF NOT EXISTS subagent_launch_intents (
|
|
40
|
+
owner TEXT NOT NULL, request_key TEXT NOT NULL, digest TEXT NOT NULL,
|
|
41
|
+
epoch INTEGER NOT NULL, state TEXT NOT NULL, attempts TEXT NOT NULL, result TEXT,
|
|
42
|
+
PRIMARY KEY(owner, request_key));
|
|
43
|
+
CREATE TABLE IF NOT EXISTS subagent_management (singleton INTEGER PRIMARY KEY CHECK(singleton=1), instance TEXT NOT NULL, epoch INTEGER NOT NULL);`));
|
|
44
|
+
}
|
|
45
|
+
private get db() { this.alive(); return this.context.db; }
|
|
46
|
+
private transaction<T>(run: () => T): T { this.alive(); return this.context.transaction(run); }
|
|
47
|
+
epoch(instance: string) {
|
|
48
|
+
return this.transaction(() => {
|
|
49
|
+
const previous = this.db.prepare("SELECT * FROM subagent_management WHERE singleton=1").get();
|
|
50
|
+
if (previous?.instance === instance) return Number(previous.epoch);
|
|
51
|
+
const epoch = (Number(previous?.epoch ?? 0)) + 1;
|
|
52
|
+
this.db.prepare("INSERT OR REPLACE INTO subagent_management VALUES (1, ?, ?)").run(instance, epoch);
|
|
53
|
+
return epoch;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
current(epoch: number) {
|
|
57
|
+
if (this.db.prepare("SELECT epoch FROM subagent_management WHERE singleton=1").get()?.epoch !== epoch) throw new Error("stale-runtime-epoch");
|
|
58
|
+
}
|
|
59
|
+
read(owner: string, key: string): LaunchIntent | undefined { return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE owner=? AND request_key=?").get(owner, key) as unknown as LaunchIntent | undefined; }
|
|
60
|
+
attempt(id: string): LaunchAttempt | undefined {
|
|
61
|
+
const row = this.db.prepare("SELECT j.value AS attempt FROM subagent_launch_intents, json_each(subagent_launch_intents.attempts) j WHERE json_extract(j.value, '$.id')=? LIMIT 1").get(id);
|
|
62
|
+
return row ? JSON.parse(String(row.attempt)) : undefined;
|
|
63
|
+
}
|
|
64
|
+
unresolvedAttempts() {
|
|
65
|
+
return this.db.prepare("SELECT j.value AS attempt FROM subagent_launch_intents, json_each(subagent_launch_intents.attempts) j WHERE subagent_launch_intents.state='accepted'").all().map(row => JSON.parse(String(row.attempt)));
|
|
66
|
+
}
|
|
67
|
+
pendingIntents(): LaunchIntent[] {
|
|
68
|
+
return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all() as unknown as LaunchIntent[];
|
|
69
|
+
}
|
|
70
|
+
finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
|
|
71
|
+
this.transaction(() => {
|
|
72
|
+
this.current(epoch);
|
|
73
|
+
this.db.prepare("UPDATE subagent_launch_intents SET state='returned', result=? WHERE owner=? AND request_key=? AND state='accepted' AND epoch<?")
|
|
74
|
+
.run(JSON.stringify(result), owner, key, epoch);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
accept(owner: string, key: string, digest: string, epoch: number) {
|
|
78
|
+
return this.transaction(() => {
|
|
79
|
+
this.current(epoch);
|
|
80
|
+
const prior = this.read(owner, key);
|
|
81
|
+
if (prior) {
|
|
82
|
+
if (prior.digest !== digest) throw new Error("request-conflict: launch key has different content");
|
|
83
|
+
return { prior: true, ...prior };
|
|
84
|
+
}
|
|
85
|
+
this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
|
|
86
|
+
return this.read(owner, key);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
prepare(owner: string, key: string, epoch: number, input: Omit<LaunchAttempt, "token" | "state">) {
|
|
90
|
+
return this.transaction(() => {
|
|
91
|
+
this.current(epoch);
|
|
92
|
+
const row = this.read(owner, key);
|
|
93
|
+
if (!row || row.epoch !== epoch || row.state !== "accepted") throw new Error("Launch intent is not admitted");
|
|
94
|
+
const attempts: LaunchAttempt[] = JSON.parse(row.attempts);
|
|
95
|
+
if (attempts.some(attempt => attempt.id === input.id)) throw new Error("Attempt already dispatched; reconcile exact identity");
|
|
96
|
+
const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
|
|
97
|
+
attempts.push(attempt);
|
|
98
|
+
this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
|
|
99
|
+
return attempt;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
spawned(owner: string, key: string, epoch: number, id: string, pid: number, pidStartTime?: string) {
|
|
103
|
+
this.transaction(() => {
|
|
104
|
+
this.current(epoch);
|
|
105
|
+
const attempts = JSON.parse(this.read(owner, key)!.attempts) as LaunchAttempt[];
|
|
106
|
+
const attempt = attempts.find(value => value.id === id);
|
|
107
|
+
if (!attempt || attempt.state !== "prepared") throw new Error("Launch publication is ambiguous");
|
|
108
|
+
if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
|
|
109
|
+
Object.assign(attempt, { state: "spawned", pid, pidStartTime });
|
|
110
|
+
this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
finish(owner: string, key: string, epoch: number, result: unknown) {
|
|
114
|
+
this.transaction(() => {
|
|
115
|
+
this.current(epoch);
|
|
116
|
+
this.db.prepare("UPDATE subagent_launch_intents SET state='returned', result=? WHERE owner=? AND request_key=? AND epoch=?").run(JSON.stringify(result), owner, key, epoch);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/upgrade.ts. Do not edit directly.
|
|
2
|
+
import type { StoreContext } from "./sqlite.ts";
|
|
3
|
+
|
|
4
|
+
/** Persistent admission fence also enforced against older bundled writers. */
|
|
5
|
+
export function setUpgradeFence(ctx: StoreContext, epoch: string | null) {
|
|
6
|
+
ctx.transaction(() => {
|
|
7
|
+
ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS runtime_upgrade_admission_v1 BEFORE INSERT ON operations
|
|
8
|
+
WHEN EXISTS (SELECT 1 FROM coordinator_state WHERE key='runtime-upgrade-fence-v1')
|
|
9
|
+
AND NOT EXISTS (SELECT 1 FROM operations WHERE operation_id=NEW.operation_id)
|
|
10
|
+
AND NOT (NEW.owner_kind='worker-conversation' AND EXISTS (
|
|
11
|
+
SELECT 1 FROM assignment_bindings b JOIN assignment_attempts a USING(assignment_id)
|
|
12
|
+
WHERE json_extract(b.owner_json, '$.kind')=NEW.owner_kind
|
|
13
|
+
AND json_extract(b.owner_json, '$.sessionId')=NEW.owner_session_id
|
|
14
|
+
AND json_extract(b.owner_json, '$.workspace')=NEW.owner_workspace
|
|
15
|
+
AND json_extract(b.owner_json, '$.branchId') IS NEW.owner_branch_id
|
|
16
|
+
AND json_extract(b.owner_json, '$.goalId') IS NEW.owner_goal_id
|
|
17
|
+
AND NOT EXISTS (SELECT 1 FROM assignment_outcomes o WHERE o.assignment_id=b.assignment_id)))
|
|
18
|
+
BEGIN SELECT RAISE(ABORT, 'runtime-draining: new execution deferred for upgrade'); END`);
|
|
19
|
+
if (epoch === null) ctx.db.prepare("DELETE FROM coordinator_state WHERE key='runtime-upgrade-fence-v1'").run();
|
|
20
|
+
else ctx.db.prepare("INSERT OR REPLACE INTO coordinator_state VALUES ('runtime-upgrade-fence-v1', ?)").run(epoch);
|
|
21
|
+
});
|
|
22
|
+
}
|
package/src/tools.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
formatMissingTask,
|
|
12
12
|
formatMutationRefusal,
|
|
13
13
|
formatStatus,
|
|
14
|
+
formatDurableStatusMetadata,
|
|
14
15
|
formatStopResult,
|
|
15
16
|
type OutputOptions,
|
|
16
17
|
} from "./output.js";
|
|
@@ -298,7 +299,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
|
|
|
298
299
|
"Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
|
|
299
300
|
];
|
|
300
301
|
|
|
301
|
-
export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator): void {
|
|
302
|
+
export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
|
|
302
303
|
const { resumeRunningTask, spawnTask } = runtime;
|
|
303
304
|
let activeSession: BackgroundTaskCallbackOrigin | undefined;
|
|
304
305
|
const getActiveSession = () => activeSession;
|
|
@@ -314,12 +315,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
314
315
|
pi.on("session_start", async (_event, ctx) => {
|
|
315
316
|
setCallbackBatchContext(pi, ctx);
|
|
316
317
|
activeSession = getCallbackOrigin(ctx);
|
|
318
|
+
if (options.resumeLocal !== false) {
|
|
317
319
|
for (const meta of listMetasForOrigin(activeSession)) {
|
|
318
320
|
if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
|
|
319
321
|
resumeRunningTask(pi, meta, getActiveSession);
|
|
320
322
|
}
|
|
321
323
|
}
|
|
322
324
|
runTaskMaintenance({ activeOrigin: activeSession });
|
|
325
|
+
}
|
|
323
326
|
});
|
|
324
327
|
pi.on("agent_start", (_event, ctx) => {
|
|
325
328
|
setCallbackBatchContext(pi, ctx);
|
|
@@ -417,7 +420,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
417
420
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
418
421
|
const origin = getCallbackOrigin(ctx);
|
|
419
422
|
activeSession = origin;
|
|
420
|
-
const durable = await durableStatusText(pi, params.id, ctx);
|
|
423
|
+
const durable = await durableStatusText(pi, params.id, ctx, params);
|
|
421
424
|
if (durable !== undefined) return text(durable);
|
|
422
425
|
return text(taskStatus(pi, params.id, params, statusOptions(params, origin)));
|
|
423
426
|
},
|
|
@@ -710,7 +713,7 @@ async function runAction(
|
|
|
710
713
|
return durableAwareList(pi, params, callbackOrigin, ctx);
|
|
711
714
|
case "status": {
|
|
712
715
|
if (!params.id) return "Invalid parameters: status requires id.";
|
|
713
|
-
const durable = await durableStatusText(pi, String(params.id), ctx);
|
|
716
|
+
const durable = await durableStatusText(pi, String(params.id), ctx, params);
|
|
714
717
|
if (durable !== undefined) return durable;
|
|
715
718
|
return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
|
|
716
719
|
}
|
|
@@ -840,11 +843,24 @@ async function durableLaunchText(
|
|
|
840
843
|
}
|
|
841
844
|
}
|
|
842
845
|
|
|
843
|
-
async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): Promise<string | undefined> {
|
|
846
|
+
async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, params: Record<string, unknown>): Promise<string | undefined> {
|
|
844
847
|
const host = getObservedWaitHost(pi);
|
|
845
848
|
if (!host || !host.isDurableTask(id)) return undefined;
|
|
846
849
|
try {
|
|
847
|
-
|
|
850
|
+
const view = await host.settledStatusForParent(ctx, id);
|
|
851
|
+
if (params.verbose === true || cursorKind(typeof params.cursor === "string" ? params.cursor : undefined) === "t") {
|
|
852
|
+
const origin = { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() };
|
|
853
|
+
const task = host.readDurableTask(origin, id);
|
|
854
|
+
if (!task) return `Background task ${id} is outside the current session scope.`;
|
|
855
|
+
const meta = {
|
|
856
|
+
...task, kind: task.kind === "watch" ? "command_watch" : "process", status: view.status,
|
|
857
|
+
argv: task.argv ? [...task.argv] : undefined,
|
|
858
|
+
logPath: task.logPaths.stdout, callbackOrigin: origin,
|
|
859
|
+
lastExitCode: view.exitCode, result: task.terminal ? { exitCode: view.exitCode, signal: view.signal } : undefined,
|
|
860
|
+
};
|
|
861
|
+
return formatDurableStatusMetadata(meta, statusOptions(params, origin));
|
|
862
|
+
}
|
|
863
|
+
return host.formatStatus(view);
|
|
848
864
|
} catch (error) {
|
|
849
865
|
return readableError(error);
|
|
850
866
|
}
|