@qlairoslabs/acp-client 0.11.0 → 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 +311 -17
- 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/checkpoint-floor.ts +47 -0
- package/src/agent/adoption/index.ts +3 -1
- package/src/agent/adoption/replay.ts +15 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +223 -153
- 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 +537 -96
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/contracts.ts +28 -3
- package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
- package/src/checkpointing/recovery.ts +9 -2
- package/src/checkpointing/strategy.ts +27 -2
- package/src/client.ts +120 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/identity/checkpoint-backed.ts +2 -2
- 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 +146 -13
- 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,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
|
+
};
|
|
@@ -5,10 +5,13 @@ import type {
|
|
|
5
5
|
PersistenceBackend,
|
|
6
6
|
PersistenceJsonValue,
|
|
7
7
|
} from "./persistence/backend.ts";
|
|
8
|
+
import { contentText } from "./media/content.ts";
|
|
9
|
+
import { isMediaPart, type MessagePart, type ResolvedPart } from "./media/parts.ts";
|
|
8
10
|
|
|
9
11
|
/** Input for an assistant message a consumer appends without running a provider turn. */
|
|
10
12
|
export interface AppendAssistantMessageInput {
|
|
11
|
-
readonly text
|
|
13
|
+
readonly text?: string;
|
|
14
|
+
readonly parts?: readonly MessagePart[];
|
|
12
15
|
/** Opaque JSON stored on the record for the consumer's own use. */
|
|
13
16
|
readonly consumerMetadata?: PersistenceJsonValue;
|
|
14
17
|
}
|
|
@@ -42,6 +45,7 @@ export async function pendingOutOfBandMessages(
|
|
|
42
45
|
): Promise<readonly MessageRecord[]> {
|
|
43
46
|
const watermark = Math.max(
|
|
44
47
|
await recoveredThroughSequence(persistence, conversationId, targetProviderContextId),
|
|
48
|
+
await persistence.outOfBandDelivery?.get(conversationId, targetProviderContextId ?? "") ?? 0,
|
|
45
49
|
await lastCompletedTurnUserSequence(persistence, conversationId, currentUserSequence),
|
|
46
50
|
);
|
|
47
51
|
if (watermark >= currentUserSequence - 1) return [];
|
|
@@ -55,7 +59,7 @@ export async function pendingOutOfBandMessages(
|
|
|
55
59
|
...(cursor ? { cursor } : {}),
|
|
56
60
|
});
|
|
57
61
|
for (const message of page.messages) {
|
|
58
|
-
if (message.role === "assistant" && isOutOfBandMessage(message)
|
|
62
|
+
if (message.role === "assistant" && isOutOfBandMessage(message)) {
|
|
59
63
|
pending.push(message);
|
|
60
64
|
}
|
|
61
65
|
}
|
|
@@ -64,27 +68,13 @@ export async function pendingOutOfBandMessages(
|
|
|
64
68
|
return pending;
|
|
65
69
|
}
|
|
66
70
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
* own text. Only the user's text is persisted; everything else reaches the provider alone.
|
|
70
|
-
*/
|
|
71
|
-
export function composeProviderPrompt(
|
|
72
|
-
prompt: string,
|
|
73
|
-
identityPreamble: string | undefined,
|
|
74
|
-
outOfBand: readonly MessageRecord[],
|
|
75
|
-
): string {
|
|
76
|
-
const sections = [identityPreamble?.trim(), formatOutOfBandBlock(outOfBand)]
|
|
77
|
-
.filter((section): section is string => Boolean(section));
|
|
78
|
-
if (sections.length === 0) return prompt;
|
|
79
|
-
return `${sections.join("\n\n")}\n\n<current-message>\n${prompt}\n</current-message>`;
|
|
80
|
-
}
|
|
71
|
+
const OUT_OF_BAND_HEADER = "Messages you sent in this conversation through another channel since your last turn."
|
|
72
|
+
+ " The user has seen them; you have not.";
|
|
81
73
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const header = "Messages you sent in this conversation through another channel since your last turn."
|
|
85
|
-
+ " The user has seen them; you have not.";
|
|
74
|
+
/** The newest messages that fit the block's text budget, in order, and how many older ones were left out. */
|
|
75
|
+
function selectOutOfBandMessages(messages: readonly MessageRecord[]) {
|
|
86
76
|
const entries = messages.map((message) => `[${message.timestamp}] ${textOf(message)}`);
|
|
87
|
-
let budget = OUT_OF_BAND_PROMPT_MAX_CHARS -
|
|
77
|
+
let budget = OUT_OF_BAND_PROMPT_MAX_CHARS - OUT_OF_BAND_HEADER.length;
|
|
88
78
|
let kept = 0;
|
|
89
79
|
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
90
80
|
const cost = entries[index]!.length + 1;
|
|
@@ -92,12 +82,43 @@ function formatOutOfBandBlock(messages: readonly MessageRecord[]): string | unde
|
|
|
92
82
|
budget -= cost;
|
|
93
83
|
kept += 1;
|
|
94
84
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
85
|
+
return { omitted: entries.length - kept, selected: messages.slice(messages.length - kept) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The parts sent for one turn: identity preamble, then out-of-band messages, then the user's own
|
|
90
|
+
* parts. Everything but the user's parts is provider-only (`record: false`). An out-of-band message
|
|
91
|
+
* with media is wrapped in `<message id>`, so its media blocks are tied to it.
|
|
92
|
+
*/
|
|
93
|
+
export async function composeProviderParts(
|
|
94
|
+
current: readonly ResolvedPart[],
|
|
95
|
+
identityPreamble: string | undefined,
|
|
96
|
+
outOfBand: readonly MessageRecord[],
|
|
97
|
+
load: (message: MessageRecord) => Promise<readonly ResolvedPart[]>,
|
|
98
|
+
): Promise<readonly ResolvedPart[]> {
|
|
99
|
+
if (!identityPreamble?.trim() && outOfBand.length === 0) return current;
|
|
100
|
+
const result: ResolvedPart[] = [];
|
|
101
|
+
const text = (value: string) => result.push({ kind: "text", text: value, record: false });
|
|
102
|
+
if (identityPreamble?.trim()) text(`${identityPreamble.trim()}\n\n`);
|
|
103
|
+
if (outOfBand.length > 0) {
|
|
104
|
+
const { selected, omitted } = selectOutOfBandMessages(outOfBand);
|
|
105
|
+
text(`<messages-you-sent>\n${OUT_OF_BAND_HEADER}\n`);
|
|
106
|
+
if (omitted > 0) text(`(${omitted} earlier message${omitted === 1 ? "" : "s"} omitted)\n`);
|
|
107
|
+
for (const [index, message] of selected.entries()) {
|
|
108
|
+
const parts = await load(message);
|
|
109
|
+
const hasMedia = parts.some(isMediaPart);
|
|
110
|
+
if (hasMedia) text(`<message id="${message.recordId}">\n`);
|
|
111
|
+
text(`[${message.timestamp}] `);
|
|
112
|
+
result.push(...parts);
|
|
113
|
+
if (hasMedia) text("\n</message>");
|
|
114
|
+
if (index < selected.length - 1) text("\n");
|
|
115
|
+
}
|
|
116
|
+
text("\n</messages-you-sent>\n\n");
|
|
117
|
+
}
|
|
118
|
+
text("<current-message>\n");
|
|
119
|
+
result.push(...current);
|
|
120
|
+
text("\n</current-message>");
|
|
121
|
+
return result;
|
|
101
122
|
}
|
|
102
123
|
|
|
103
124
|
async function recoveredThroughSequence(
|
|
@@ -169,11 +190,7 @@ async function completedTurnUserSequence(
|
|
|
169
190
|
}
|
|
170
191
|
|
|
171
192
|
function textOf(message: MessageRecord): string {
|
|
172
|
-
|
|
173
|
-
return message.content
|
|
174
|
-
.map((block) => block.type === "text" ? block.text : "")
|
|
175
|
-
.join("")
|
|
176
|
-
.trim();
|
|
193
|
+
return contentText(message.content).trim();
|
|
177
194
|
}
|
|
178
195
|
|
|
179
196
|
function parseMetadata(metadata: string | undefined): Record<string, unknown> {
|
|
@@ -18,6 +18,7 @@ export interface AuditLogIdentity {
|
|
|
18
18
|
|
|
19
19
|
export class AuditPersistenceRuntime {
|
|
20
20
|
private failed = false;
|
|
21
|
+
private serial: Promise<unknown> = Promise.resolve();
|
|
21
22
|
|
|
22
23
|
private constructor(
|
|
23
24
|
private readonly writer: FileSessionLogWriter<"audit">,
|
|
@@ -68,7 +69,14 @@ export class AuditPersistenceRuntime {
|
|
|
68
69
|
|
|
69
70
|
get healthy(): boolean { return !this.failed; }
|
|
70
71
|
|
|
71
|
-
|
|
72
|
+
/** One write at a time: each takes its sequence number from the writer when it runs. */
|
|
73
|
+
append(event: NormalizedPersistenceEvent, durable = false, ts = Date.now()): Promise<boolean> {
|
|
74
|
+
const run = this.serial.then(() => this.appendNow(event, durable, ts));
|
|
75
|
+
this.serial = run.catch(() => undefined);
|
|
76
|
+
return run;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private async appendNow(event: NormalizedPersistenceEvent, durable: boolean, ts: number): Promise<boolean> {
|
|
72
80
|
const record = projectAuditEvent(event, {
|
|
73
81
|
auditLogId: this.identity.auditLogId,
|
|
74
82
|
generation: this.identity.generation,
|
|
@@ -88,7 +96,7 @@ export class AuditPersistenceRuntime {
|
|
|
88
96
|
}
|
|
89
97
|
|
|
90
98
|
async sync(): Promise<void> { await this.writer.sync(); }
|
|
91
|
-
async close(): Promise<void> { await this.writer.close(); }
|
|
99
|
+
async close(): Promise<void> { await this.serial; await this.writer.close(); }
|
|
92
100
|
}
|
|
93
101
|
|
|
94
102
|
/** Apply one normalized event stream to continuation state and its separate audit sink. */
|
|
@@ -134,6 +142,10 @@ export class AuditedPersistenceRuntime implements PersistenceStateRuntime {
|
|
|
134
142
|
return primary;
|
|
135
143
|
}
|
|
136
144
|
|
|
145
|
+
presentationStartedAt(presentationId: string): number | undefined {
|
|
146
|
+
return this.primary.presentationStartedAt?.(presentationId);
|
|
147
|
+
}
|
|
148
|
+
|
|
137
149
|
async appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options: { readonly durable?: boolean; readonly ts?: number } = {}): Promise<void> {
|
|
138
150
|
const ts = options.ts ?? Date.now();
|
|
139
151
|
await this.primary.appendTransitionEvent(event, options);
|