@qlairoslabs/acp-client 0.11.1 → 0.12.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/CHANGELOG-consumer-fixes.md +55 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +287 -12
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +3 -1
- package/src/agent/adoption/replay.ts +1 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +178 -150
- package/src/agent/error-record-writer.ts +77 -0
- package/src/agent/persisted-lifecycle.ts +152 -35
- package/src/agent/record-capture.ts +18 -18
- package/src/agent-adapter-registry.ts +2 -0
- package/src/agent-client.ts +9 -3
- package/src/agent-conversation-contracts.ts +6 -0
- package/src/agent-conversation-owner.ts +31 -6
- package/src/agent-conversation-presentation.ts +12 -1
- package/src/agent-conversation-queue.ts +3 -2
- package/src/agent-session.ts +535 -94
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/recovery.ts +5 -0
- package/src/checkpointing/strategy.ts +2 -0
- package/src/client.ts +120 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/index.ts +17 -0
- package/src/internal-inference/config.ts +7 -0
- package/src/internal-inference/contracts.ts +3 -0
- package/src/internal-inference/coordination/handles.ts +11 -2
- package/src/internal-inference/coordination/manager.ts +20 -3
- package/src/internal-inference/index.ts +2 -0
- package/src/internal-inference/persistence/records.ts +3 -1
- package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
- package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
- package/src/internal-inference/runtime/harness-runtime.ts +19 -2
- package/src/media/acp.ts +118 -0
- package/src/media/capture.ts +15 -0
- package/src/media/content.ts +142 -0
- package/src/media/files.ts +28 -0
- package/src/media/parts.ts +145 -0
- package/src/media/pending.ts +51 -0
- package/src/media/redact.ts +14 -0
- package/src/media/store.ts +127 -0
- package/src/metering/provider.ts +8 -1
- package/src/operations/activity-tracker.ts +31 -0
- package/src/operations/contracts.ts +63 -0
- package/src/operations/errors.ts +31 -0
- package/src/operations/index.ts +6 -0
- package/src/operations/stale-policy.ts +51 -0
- package/src/operations/supervisor.ts +209 -0
- package/src/operations/timers.ts +12 -0
- package/src/out-of-band-messages.ts +49 -32
- package/src/persistence/audit-runtime.ts +14 -2
- package/src/persistence/backend.ts +108 -12
- package/src/persistence/error-records.ts +27 -0
- package/src/persistence/index.ts +8 -0
- package/src/persistence/presentation.ts +9 -1
- package/src/persistence/projection.ts +20 -0
- package/src/persistence/records.ts +45 -6
- package/src/persistence/sqlite-backend.ts +207 -16
- package/src/persistence/sqlite-conversation-records.ts +31 -4
- package/src/persistence/sqlite-files.ts +95 -0
- package/src/persistence/sqlite-media-store.ts +67 -0
- package/src/persistence/sqlite-schema.ts +86 -10
- package/src/persistence/state-runtime.ts +2 -0
- package/src/persistence/timeline-reconcile.ts +21 -4
- package/src/persistence/transcript-reader.ts +11 -4
- package/src/persistence/transcript-runtime.ts +105 -12
- package/src/repl/repl.ts +1 -1
- package/src/response.ts +40 -8
- package/src/steering/combine.ts +11 -4
- package/src/steering/contracts.ts +14 -4
- package/src/steering/controller.ts +96 -21
- package/src/steering/index.ts +1 -0
- package/src/transport/acp-transport.ts +18 -7
- package/src/types.ts +7 -0
- package/src/updates.ts +4 -4
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { basename, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import { hashBytes, supportsCopy, type MediaCapabilities } from "./acp.ts";
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_MEDIA_THRESHOLDS,
|
|
7
|
+
isMediaPart,
|
|
8
|
+
normalizeParts,
|
|
9
|
+
type MediaKind,
|
|
10
|
+
type MessagePart,
|
|
11
|
+
type MediaThresholds,
|
|
12
|
+
type ResolvedPart,
|
|
13
|
+
} from "./parts.ts";
|
|
14
|
+
|
|
15
|
+
export interface MediaInfo {
|
|
16
|
+
/** The conversation the copy belongs to. */
|
|
17
|
+
readonly owner: string;
|
|
18
|
+
readonly kind: MediaKind;
|
|
19
|
+
readonly mimeType: string;
|
|
20
|
+
readonly name?: string;
|
|
21
|
+
readonly size: number;
|
|
22
|
+
readonly sha256: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface StoredMedia {
|
|
26
|
+
readonly ref: string;
|
|
27
|
+
readonly info: MediaInfo;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Where kept copies live. The SQLite backend provides one; a consumer can pass its own. */
|
|
31
|
+
export interface MediaStore {
|
|
32
|
+
put(bytes: Uint8Array, info: MediaInfo): Promise<string>;
|
|
33
|
+
get(ref: string): Promise<(StoredMedia & { readonly data: Uint8Array }) | null>;
|
|
34
|
+
delete(ref: string): Promise<void>;
|
|
35
|
+
/** Every copy of one conversation, so a cleanup pass can find bytes a failed write left behind. */
|
|
36
|
+
list(owner: string): Promise<readonly StoredMedia[]>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface MediaConfig {
|
|
40
|
+
/** Replaces the persistence backend's own store. */
|
|
41
|
+
readonly store?: MediaStore;
|
|
42
|
+
readonly thresholds?: MediaThresholds;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ResolvePartsOptions {
|
|
46
|
+
/** Relative paths resolve against it. */
|
|
47
|
+
cwd: string;
|
|
48
|
+
/** The conversation sending the parts: a ref it owns is reused, another one is copied. */
|
|
49
|
+
owner?: string;
|
|
50
|
+
store?: MediaStore;
|
|
51
|
+
thresholds?: MediaThresholds;
|
|
52
|
+
capabilities?: MediaCapabilities;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read each part's source and decide its mode. A `path` part with no `mode` goes as a link above its
|
|
57
|
+
* kind's threshold, or when the agent cannot take a copy of its kind. An explicit copy the agent cannot
|
|
58
|
+
* take is refused.
|
|
59
|
+
*/
|
|
60
|
+
export async function resolveParts(
|
|
61
|
+
parts: readonly MessagePart[],
|
|
62
|
+
options: ResolvePartsOptions,
|
|
63
|
+
): Promise<readonly ResolvedPart[]> {
|
|
64
|
+
for (const [kind, threshold] of Object.entries(options.thresholds ?? {})) {
|
|
65
|
+
if (!["image", "audio", "file"].includes(kind) || !Number.isSafeInteger(threshold) || threshold < 0) {
|
|
66
|
+
throw new Error(`invalid media threshold for ${kind}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const result: ResolvedPart[] = [];
|
|
70
|
+
for (const part of normalizeParts(parts)) {
|
|
71
|
+
if (!isMediaPart(part)) {
|
|
72
|
+
result.push(part);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (part.ref) {
|
|
76
|
+
const stored = await options.store?.get(part.ref);
|
|
77
|
+
if (!stored) throw new Error(`media ref is missing or removed: ${part.ref}`);
|
|
78
|
+
if (!supportsCopy(part.kind, options.capabilities)) throw new Error(`agent does not support ${part.kind} copies`);
|
|
79
|
+
result.push({
|
|
80
|
+
kind: part.kind,
|
|
81
|
+
mode: "copy",
|
|
82
|
+
mimeType: part.mimeType ?? stored.info.mimeType,
|
|
83
|
+
name: part.name ?? stored.info.name,
|
|
84
|
+
size: stored.data.byteLength,
|
|
85
|
+
sha256: stored.info.sha256,
|
|
86
|
+
data: new Uint8Array(stored.data),
|
|
87
|
+
// Another conversation's copy is stored again, so each conversation owns its copies.
|
|
88
|
+
...(stored.info.owner === options.owner ? { ref: stored.ref } : {}),
|
|
89
|
+
...(part.keep === undefined ? {} : { keep: part.keep }),
|
|
90
|
+
...(part.record === false ? { record: false as const } : {}),
|
|
91
|
+
});
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const path = part.path === undefined
|
|
95
|
+
? undefined
|
|
96
|
+
: resolve(options.cwd, part.path.startsWith("file:") ? fileURLToPath(part.path) : part.path);
|
|
97
|
+
const mimeType = part.mimeType ?? ((path ? Bun.file(path).type : "") || "application/octet-stream");
|
|
98
|
+
const kind = mimeType === "image/svg+xml" ? "file" : part.kind;
|
|
99
|
+
// A link is not opened by the library: a file it cannot read is the agent's to report.
|
|
100
|
+
const size = path
|
|
101
|
+
? await stat(path).then((info) => info.size, (error) => {
|
|
102
|
+
if (part.mode === "link") return undefined;
|
|
103
|
+
throw error;
|
|
104
|
+
})
|
|
105
|
+
: part.data!.byteLength;
|
|
106
|
+
const threshold = options.thresholds?.[kind] ?? DEFAULT_MEDIA_THRESHOLDS[kind];
|
|
107
|
+
let mode = part.mode ?? (path && size! > threshold ? "link" : "copy");
|
|
108
|
+
if (mode === "copy" && !supportsCopy(kind, options.capabilities)) {
|
|
109
|
+
if (part.mode === undefined && path) mode = "link";
|
|
110
|
+
else throw new Error(`agent does not support ${part.kind} copies`);
|
|
111
|
+
}
|
|
112
|
+
if (mode === "link" && part.keep !== undefined) throw new Error("keep is only valid for copies");
|
|
113
|
+
let data: Uint8Array | undefined;
|
|
114
|
+
if (mode === "copy") data = path ? new Uint8Array(await readFile(path)) : new Uint8Array(part.data!);
|
|
115
|
+
result.push({
|
|
116
|
+
kind,
|
|
117
|
+
mode,
|
|
118
|
+
mimeType,
|
|
119
|
+
name: part.name ?? (path ? basename(path) : undefined),
|
|
120
|
+
...(data ? { size: data.byteLength } : size !== undefined ? { size } : {}),
|
|
121
|
+
...(data ? { data, sha256: hashBytes(data) } : { uri: pathToFileURL(path!).href }),
|
|
122
|
+
...(part.record === false ? { record: false as const } : {}),
|
|
123
|
+
...(part.keep === undefined ? {} : { keep: part.keep }),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
}
|
package/src/metering/provider.ts
CHANGED
|
@@ -106,8 +106,15 @@ export type CounterInterpretation = "cumulative" | "per_turn";
|
|
|
106
106
|
* (every turn re-reads the same cached context), which is why comparing totals is not a
|
|
107
107
|
* valid test and reported "cumulative" until the components were checked.
|
|
108
108
|
* See .res/somelogs.md/9-5+/9-6-harness-matrix-findings.md, Finding 5.
|
|
109
|
+
*
|
|
110
|
+
* Codex: two plain turns of one session (no cancel, no steering) reported
|
|
111
|
+
* total/input/output/cachedRead of 17948/782/14/17152 and then 18080/7059/13/11008. Each report
|
|
112
|
+
* satisfies `total === input + output + cachedRead` on its own, and input, output and cachedRead
|
|
113
|
+
* move both ways between turns, which no cumulative counter can do; read as cumulative the second
|
|
114
|
+
* turn was a `counter_reset` ("outputTokens decreased from 14 to 13").
|
|
115
|
+
* See .res/somelogs.md/9-22+/10-4-LOG-adopt-provider-session.md, "Real-harness pass".
|
|
109
116
|
*/
|
|
110
|
-
const PER_TURN_ADAPTERS: ReadonlySet<string> = new Set(["opencode"]);
|
|
117
|
+
const PER_TURN_ADAPTERS: ReadonlySet<string> = new Set(["opencode", "codex"]);
|
|
111
118
|
|
|
112
119
|
/**
|
|
113
120
|
* The interpretation to apply for an adapter.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ActivityEvent } from "../types.ts";
|
|
2
|
+
|
|
3
|
+
const terminal = new Set(["completed", "failed"]);
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Which tool calls are in flight, and since when. Timing state only; tool content stays in the
|
|
7
|
+
* presentation aggregator.
|
|
8
|
+
*/
|
|
9
|
+
export class ToolTracker {
|
|
10
|
+
private readonly tools = new Map<string, { status: string; startedAt: number }>();
|
|
11
|
+
|
|
12
|
+
get inFlight(): number {
|
|
13
|
+
return [...this.tools.values()].filter((tool) => !terminal.has(tool.status)).length;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
get oldestStartedAt(): number | null {
|
|
17
|
+
const starts = [...this.tools.values()]
|
|
18
|
+
.filter((tool) => !terminal.has(tool.status))
|
|
19
|
+
.map((tool) => tool.startedAt);
|
|
20
|
+
return starts.length ? Math.min(...starts) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** True when this update settles a previously unsettled tool. */
|
|
24
|
+
observe(event: ActivityEvent, now = Date.now()): boolean {
|
|
25
|
+
if (event.kind !== "tool" && event.kind !== "tool_update") return false;
|
|
26
|
+
const previous = this.tools.get(event.toolCallId);
|
|
27
|
+
const status = event.status ?? previous?.status ?? "pending";
|
|
28
|
+
this.tools.set(event.toolCallId, { status, startedAt: previous?.startedAt ?? now });
|
|
29
|
+
return terminal.has(status) && !terminal.has(previous?.status ?? "pending");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Shared types for the operation lifecycle: what a supervised provider request looks like from the
|
|
2
|
+
// outside (its stage and timestamps) and what the provider is observed to send while it runs.
|
|
3
|
+
// Spec: .res/somelogs.md/9-22+/10-17-SPEC-operation-lifecycle.md.
|
|
4
|
+
|
|
5
|
+
import type { ActivityEvent } from "../types.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Anything the provider sent for a session: a `session/update`, or a request from the agent to the
|
|
9
|
+
* client. Permission requests are reported when they start and when they are answered.
|
|
10
|
+
*/
|
|
11
|
+
export type ProviderOutput =
|
|
12
|
+
| { readonly kind: "update"; readonly sessionId: string | null; readonly activity?: ActivityEvent }
|
|
13
|
+
| { readonly kind: "request" | "permission_started" | "permission_ended"; readonly sessionId: string | null };
|
|
14
|
+
|
|
15
|
+
export type OutputListener = (output: ProviderOutput) => void;
|
|
16
|
+
|
|
17
|
+
/** What a running operation is waiting on. */
|
|
18
|
+
export type OperationStage = "waiting" | "streaming" | "tool_running" | "awaiting_permission" | "cancelling";
|
|
19
|
+
|
|
20
|
+
export type SupervisedOperationKind = "turn" | "internal_inference" | "recap";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Why a cancel was requested. The persisted copies (JSONL validation, SQLite CHECK) derive from or
|
|
24
|
+
* are tested against these lists.
|
|
25
|
+
*/
|
|
26
|
+
export const CANCEL_REASONS = ["interrupt", "steer", "stalled", "stop", "abort"] as const;
|
|
27
|
+
export type CancelReason = typeof CANCEL_REASONS[number];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* How a requested cancel ended: the provider stopped (`acknowledged`), the process was killed
|
|
31
|
+
* (`forced`), the operation finished on its own first (`too_late`), or it ended in an error, thrown or
|
|
32
|
+
* reported as an `error` result (`failed`).
|
|
33
|
+
*/
|
|
34
|
+
export const CANCEL_OUTCOMES = ["acknowledged", "forced", "too_late", "failed"] as const;
|
|
35
|
+
export type CancelOutcome = typeof CANCEL_OUTCOMES[number];
|
|
36
|
+
|
|
37
|
+
/** The readable state of one running operation. Contains no content. */
|
|
38
|
+
export interface OperationActivity {
|
|
39
|
+
readonly operationId: string;
|
|
40
|
+
readonly kind: SupervisedOperationKind;
|
|
41
|
+
readonly stage: OperationStage;
|
|
42
|
+
readonly startedAt: number;
|
|
43
|
+
readonly lastOutputAt: number | null;
|
|
44
|
+
readonly toolsInFlight: number;
|
|
45
|
+
readonly cancel?: { readonly reason: CancelReason; readonly requestedAt: number };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** When an operation counts as stale. `false` disables a condition. */
|
|
49
|
+
export interface StaleLimits {
|
|
50
|
+
/** No output at all since the request was sent. Default 120 000. */
|
|
51
|
+
readonly firstOutputMs?: number | false;
|
|
52
|
+
/** No output since the last one, with no tool or permission explaining it. Default 180 000. */
|
|
53
|
+
readonly nextOutputMs?: number | false;
|
|
54
|
+
/** One tool running longer than this. Off by default. */
|
|
55
|
+
readonly toolMs?: number | false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Stale limits per operation kind. */
|
|
59
|
+
export interface OperationLifecycleConfig {
|
|
60
|
+
readonly turns?: StaleLimits;
|
|
61
|
+
readonly internalInference?: StaleLimits;
|
|
62
|
+
readonly recap?: StaleLimits;
|
|
63
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ResponseMessage } from "../types.ts";
|
|
2
|
+
import type { OperationMeteringRecord } from "../metering/record.ts";
|
|
3
|
+
import type { StallPhase } from "./stale-policy.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The provider stopped producing output and the request was cancelled. `phase` says whether
|
|
7
|
+
* anything had arrived; `messages` holds what did.
|
|
8
|
+
*/
|
|
9
|
+
export class OperationStalledError extends Error {
|
|
10
|
+
readonly code = "stalled";
|
|
11
|
+
readonly data: { providerCode: string; phase: StallPhase };
|
|
12
|
+
messages: readonly ResponseMessage[] = Object.freeze([]);
|
|
13
|
+
/** Steers delivered right after this turn, as the recovery prompt. */
|
|
14
|
+
followedBy?: readonly string[];
|
|
15
|
+
metering?: OperationMeteringRecord;
|
|
16
|
+
cancel?: "acknowledged" | "forced";
|
|
17
|
+
|
|
18
|
+
constructor(readonly operationId: string, readonly phase: StallPhase) {
|
|
19
|
+
super(`Provider operation stalled (${phase}).`);
|
|
20
|
+
this.name = "OperationStalledError";
|
|
21
|
+
this.data = { providerCode: "stalled", phase };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The in-flight request ended because its provider process was killed. */
|
|
26
|
+
export class ForcedStopError extends Error {
|
|
27
|
+
constructor() {
|
|
28
|
+
super("Provider process was forcibly stopped.");
|
|
29
|
+
this.name = "ForcedStopError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { OperationActivity, StaleLimits } from "./contracts.ts";
|
|
2
|
+
|
|
3
|
+
/** Whether anything had arrived when the operation went stale. */
|
|
4
|
+
export type StallPhase = "no_response" | "incomplete_response";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_STALE_LIMITS = Object.freeze({ firstOutputMs: 120_000, nextOutputMs: 180_000 });
|
|
7
|
+
|
|
8
|
+
export interface StaleDecision {
|
|
9
|
+
readonly deadline: number;
|
|
10
|
+
readonly phase: StallPhase;
|
|
11
|
+
readonly stale: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* When the operation becomes stale if nothing else arrives, or null when no deadline applies. No
|
|
16
|
+
* deadline is owed while an identified tool or permission explains the silence.
|
|
17
|
+
*/
|
|
18
|
+
export function stalePolicy(
|
|
19
|
+
activity: OperationActivity,
|
|
20
|
+
permissions: number,
|
|
21
|
+
oldestToolAt: number | null,
|
|
22
|
+
limits: StaleLimits,
|
|
23
|
+
now: number,
|
|
24
|
+
): StaleDecision | null {
|
|
25
|
+
if (activity.stage === "cancelling" || permissions > 0) return null;
|
|
26
|
+
const phase = activity.lastOutputAt === null ? "no_response" : "incomplete_response";
|
|
27
|
+
let duration: number | false;
|
|
28
|
+
let since: number;
|
|
29
|
+
if (activity.toolsInFlight) {
|
|
30
|
+
duration = limits.toolMs ?? false;
|
|
31
|
+
since = oldestToolAt ?? now;
|
|
32
|
+
} else if (activity.lastOutputAt === null) {
|
|
33
|
+
duration = limits.firstOutputMs ?? DEFAULT_STALE_LIMITS.firstOutputMs;
|
|
34
|
+
since = activity.startedAt;
|
|
35
|
+
} else {
|
|
36
|
+
duration = limits.nextOutputMs ?? DEFAULT_STALE_LIMITS.nextOutputMs;
|
|
37
|
+
since = activity.lastOutputAt;
|
|
38
|
+
}
|
|
39
|
+
if (duration === false) return null;
|
|
40
|
+
const deadline = since + duration;
|
|
41
|
+
return { deadline, phase, stale: now >= deadline };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function validateStaleLimits(limits: StaleLimits): void {
|
|
45
|
+
for (const [key, value] of Object.entries(limits)) {
|
|
46
|
+
if (value === undefined || value === false) continue;
|
|
47
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
48
|
+
throw new Error(`${key} must be a positive finite number or false`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// OperationSupervisor — owns timing and cancellation for exactly one provider request: its stage,
|
|
2
|
+
// the stale conditions, the cancel escalation (cancel, cancel again, then kill the process) and the
|
|
3
|
+
// reason it ended. It never holds or rewrites content; updates keep their own path to the
|
|
4
|
+
// conversation, and the supervisor is one more observer of them.
|
|
5
|
+
|
|
6
|
+
import { stalePolicy, validateStaleLimits, type StallPhase } from "./stale-policy.ts";
|
|
7
|
+
import { OperationStalledError } from "./errors.ts";
|
|
8
|
+
import type { PromptResult } from "../types.ts";
|
|
9
|
+
import type {
|
|
10
|
+
CancelOutcome,
|
|
11
|
+
CancelReason,
|
|
12
|
+
OperationActivity,
|
|
13
|
+
OutputListener,
|
|
14
|
+
ProviderOutput,
|
|
15
|
+
StaleLimits,
|
|
16
|
+
SupervisedOperationKind,
|
|
17
|
+
} from "./contracts.ts";
|
|
18
|
+
import { ToolTracker } from "./activity-tracker.ts";
|
|
19
|
+
import { realTimers, type Timers } from "./timers.ts";
|
|
20
|
+
|
|
21
|
+
/** The narrow view of a provider the supervisor needs. */
|
|
22
|
+
export interface SupervisedProvider {
|
|
23
|
+
prompt(): Promise<PromptResult>;
|
|
24
|
+
subscribeOutput(listener: OutputListener): () => void;
|
|
25
|
+
cancel(): void;
|
|
26
|
+
forceStop(): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SupervisorOptions {
|
|
30
|
+
readonly operationId: string;
|
|
31
|
+
readonly kind: SupervisedOperationKind;
|
|
32
|
+
/** Output for another session is ignored. */
|
|
33
|
+
readonly sessionId?: string | null;
|
|
34
|
+
/** How long a cancel may take before the process is killed. Default 30 000. */
|
|
35
|
+
readonly cancelGraceMs?: number;
|
|
36
|
+
readonly timers?: Timers;
|
|
37
|
+
readonly limits?: StaleLimits;
|
|
38
|
+
readonly onStageChanged?: (activity: OperationActivity) => void;
|
|
39
|
+
/** The last running tool settled. */
|
|
40
|
+
readonly onToolBoundary?: () => void;
|
|
41
|
+
/** A cancel was requested, once per operation. */
|
|
42
|
+
readonly onCancelRequested?: (reason: CancelReason) => void;
|
|
43
|
+
/** The operation ended after a cancel was requested, and how. */
|
|
44
|
+
readonly onCancelResolved?: (reason: CancelReason, outcome: CancelOutcome) => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const forcedResult = (): PromptResult => ({
|
|
48
|
+
text: "",
|
|
49
|
+
messages: Object.freeze([]),
|
|
50
|
+
stopReason: "cancelled",
|
|
51
|
+
status: "cancelled",
|
|
52
|
+
usage: null,
|
|
53
|
+
cancel: "forced",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export class OperationSupervisor {
|
|
57
|
+
readonly tools = new ToolTracker();
|
|
58
|
+
private readonly timers: Timers;
|
|
59
|
+
private readonly startedAt: number;
|
|
60
|
+
private lastOutputAt: number | null = null;
|
|
61
|
+
private permissions = 0;
|
|
62
|
+
private cancellation?: { reason: CancelReason; requestedAt: number };
|
|
63
|
+
private stage: OperationActivity["stage"] = "waiting";
|
|
64
|
+
private handles: unknown[] = [];
|
|
65
|
+
private staleHandle: unknown;
|
|
66
|
+
private stallPhase?: StallPhase;
|
|
67
|
+
private finished = false;
|
|
68
|
+
private started = false;
|
|
69
|
+
private forced = false;
|
|
70
|
+
private finishForced?: (result: PromptResult) => void;
|
|
71
|
+
|
|
72
|
+
constructor(private readonly provider: SupervisedProvider, private readonly options: SupervisorOptions) {
|
|
73
|
+
validateStaleLimits(options.limits ?? {});
|
|
74
|
+
const grace = options.cancelGraceMs;
|
|
75
|
+
if (grace !== undefined && (!Number.isFinite(grace) || grace <= 0)) {
|
|
76
|
+
throw new Error("cancelGraceMs must be positive and finite");
|
|
77
|
+
}
|
|
78
|
+
this.timers = options.timers ?? realTimers;
|
|
79
|
+
this.startedAt = this.timers.now();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
get activity(): OperationActivity {
|
|
83
|
+
return Object.freeze({
|
|
84
|
+
operationId: this.options.operationId,
|
|
85
|
+
kind: this.options.kind,
|
|
86
|
+
stage: this.stage,
|
|
87
|
+
startedAt: this.startedAt,
|
|
88
|
+
lastOutputAt: this.lastOutputAt,
|
|
89
|
+
toolsInFlight: this.tools.inFlight,
|
|
90
|
+
...(this.cancellation ? { cancel: Object.freeze({ ...this.cancellation }) } : {}),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Ask the provider to stop. Ends within the cancel grace whatever the provider does. */
|
|
95
|
+
cancel(reason: CancelReason): void {
|
|
96
|
+
if (this.finished || this.cancellation) return;
|
|
97
|
+
this.timers.clearTimeout(this.staleHandle);
|
|
98
|
+
this.cancellation = { reason, requestedAt: this.timers.now() };
|
|
99
|
+
this.options.onCancelRequested?.(reason);
|
|
100
|
+
this.publishStage();
|
|
101
|
+
this.sendCancel();
|
|
102
|
+
const grace = this.options.cancelGraceMs ?? 30_000;
|
|
103
|
+
this.handles.push(this.timers.setTimeout(() => {
|
|
104
|
+
if (!this.finished) this.sendCancel();
|
|
105
|
+
}, grace / 2));
|
|
106
|
+
this.handles.push(this.timers.setTimeout(() => {
|
|
107
|
+
if (this.finished) return;
|
|
108
|
+
this.forced = true;
|
|
109
|
+
// Start teardown before releasing the queue; reconnect waits for teardown in the controller.
|
|
110
|
+
void Promise.resolve().then(() => this.provider.forceStop()).catch(() => {});
|
|
111
|
+
this.finishForced?.(forcedResult());
|
|
112
|
+
}, grace));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async run(): Promise<PromptResult> {
|
|
116
|
+
if (this.started) throw new Error("operation supervisor can only run once");
|
|
117
|
+
this.started = true;
|
|
118
|
+
const detach = this.provider.subscribeOutput((output) => this.observe(output));
|
|
119
|
+
this.options.onStageChanged?.(this.activity);
|
|
120
|
+
this.armStaleTimer();
|
|
121
|
+
// How a requested cancel ended; a stall is a cancel the provider either honoured or not.
|
|
122
|
+
let outcome: CancelOutcome = "failed";
|
|
123
|
+
try {
|
|
124
|
+
const forced = new Promise<PromptResult>((resolve) => { this.finishForced = resolve; });
|
|
125
|
+
const result = await Promise.race([Promise.resolve().then(() => this.provider.prompt()), forced]);
|
|
126
|
+
outcome = this.forced ? "forced"
|
|
127
|
+
: result.status === "cancelled" ? "acknowledged"
|
|
128
|
+
: result.status === "error" ? "failed" : "too_late";
|
|
129
|
+
// A cancel can lose the race with a normal ending: the turn is then complete, even when the
|
|
130
|
+
// stall policy asked for the cancel.
|
|
131
|
+
if (this.stallPhase && result.status === "cancelled") throw this.stalled();
|
|
132
|
+
if (this.cancellation && result.status === "cancelled") {
|
|
133
|
+
return { ...result, cancel: this.forced ? "forced" : "acknowledged" };
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (this.stallPhase) {
|
|
138
|
+
const stalled = error instanceof OperationStalledError ? this.markCancel(error) : this.stalled();
|
|
139
|
+
outcome = stalled.cancel ?? outcome;
|
|
140
|
+
throw stalled;
|
|
141
|
+
}
|
|
142
|
+
if (this.forced) {
|
|
143
|
+
outcome = "forced";
|
|
144
|
+
return forcedResult();
|
|
145
|
+
}
|
|
146
|
+
throw error;
|
|
147
|
+
} finally {
|
|
148
|
+
this.finished = true;
|
|
149
|
+
if (this.cancellation) this.options.onCancelResolved?.(this.cancellation.reason, outcome);
|
|
150
|
+
this.timers.clearTimeout(this.staleHandle);
|
|
151
|
+
detach();
|
|
152
|
+
for (const handle of this.handles) this.timers.clearTimeout(handle);
|
|
153
|
+
this.handles = [];
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private stalled(): OperationStalledError {
|
|
158
|
+
return this.markCancel(new OperationStalledError(this.options.operationId, this.stallPhase!));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private markCancel(error: OperationStalledError): OperationStalledError {
|
|
162
|
+
error.cancel = this.forced ? "forced" : "acknowledged";
|
|
163
|
+
return error;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private publishStage(): void {
|
|
167
|
+
const stage = this.cancellation ? "cancelling"
|
|
168
|
+
: this.permissions ? "awaiting_permission"
|
|
169
|
+
: this.tools.inFlight ? "tool_running"
|
|
170
|
+
: this.lastOutputAt === null ? "waiting"
|
|
171
|
+
: "streaming";
|
|
172
|
+
if (stage === this.stage) return;
|
|
173
|
+
this.stage = stage;
|
|
174
|
+
this.options.onStageChanged?.(this.activity);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private observe(output: ProviderOutput): void {
|
|
178
|
+
if (this.finished) return;
|
|
179
|
+
if (output.sessionId && this.options.sessionId && output.sessionId !== this.options.sessionId) return;
|
|
180
|
+
this.lastOutputAt = this.timers.now();
|
|
181
|
+
if (output.kind === "permission_started") this.permissions++;
|
|
182
|
+
if (output.kind === "permission_ended") this.permissions = Math.max(0, this.permissions - 1);
|
|
183
|
+
if (output.kind === "update" && output.activity) {
|
|
184
|
+
const settled = this.tools.observe(output.activity, this.lastOutputAt);
|
|
185
|
+
if (settled && !this.tools.inFlight) this.options.onToolBoundary?.();
|
|
186
|
+
}
|
|
187
|
+
this.publishStage();
|
|
188
|
+
this.armStaleTimer();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private armStaleTimer(): void {
|
|
192
|
+
this.timers.clearTimeout(this.staleHandle);
|
|
193
|
+
const limits = this.options.limits ?? {};
|
|
194
|
+
const decision = stalePolicy(this.activity, this.permissions, this.tools.oldestStartedAt, limits, this.timers.now());
|
|
195
|
+
if (!decision || this.finished) return;
|
|
196
|
+
this.staleHandle = this.timers.setTimeout(() => {
|
|
197
|
+
this.stallPhase = decision.phase;
|
|
198
|
+
this.cancel("stalled");
|
|
199
|
+
}, Math.max(0, decision.deadline - this.timers.now()));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private sendCancel(): void {
|
|
203
|
+
try {
|
|
204
|
+
this.provider.cancel();
|
|
205
|
+
} catch {
|
|
206
|
+
// Escalation still bounds a broken notification transport.
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Injectable wall clock and scheduler for operation deadlines. */
|
|
2
|
+
export interface Timers {
|
|
3
|
+
now(): number;
|
|
4
|
+
setTimeout(callback: () => void, delayMs: number): unknown;
|
|
5
|
+
clearTimeout(handle: unknown): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const realTimers: Timers = {
|
|
9
|
+
now: () => Date.now(),
|
|
10
|
+
setTimeout: (callback, delay) => setTimeout(callback, delay),
|
|
11
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
12
|
+
};
|