@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-alpha.1
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/CONSUMER_GUIDE.md +60 -26
- package/package.json +5 -1
- package/src/agent/config.ts +2 -0
- package/src/agent/native-operations.ts +1 -0
- package/src/agent-session.ts +11 -2
- package/src/agent.ts +4 -1
- package/src/index.ts +2 -0
- package/src/native/capabilities.ts +2 -2
- package/src/native/connection.ts +1 -1
- package/src/native/controller.ts +2 -1
- package/src/native/host-config.ts +2 -0
- package/src/native/host.ts +10 -0
- package/src/native/mcp.ts +47 -0
- package/src/native/recovery.ts +8 -7
- package/src/native/reminders/routine-guard.ts +4 -3
- package/src/native/reminders/routine-wire.ts +1 -1
- package/src/native-harness/README.md +58 -1
- package/src/native-harness/package.json +4 -0
- package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
- package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
- package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
- package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
- package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
- package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
- package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
- package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
- package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
- package/src/native-harness/src/capabilities/context/build.ts +5 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
- package/src/native-harness/src/capabilities/model/runner.ts +6 -3
- package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
- package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
- package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
- package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
- package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
- package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
- package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
- package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
- package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
- package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
- package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
- package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
- package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
- package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
- package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
- package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
- package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
- package/src/native-harness/src/contracts/agent.ts +3 -1
- package/src/native-harness/src/contracts/attachments.ts +62 -0
- package/src/native-harness/src/contracts/config-permissions.ts +13 -4
- package/src/native-harness/src/contracts/context.ts +1 -1
- package/src/native-harness/src/contracts/events.ts +2 -2
- package/src/native-harness/src/contracts/loop.ts +3 -3
- package/src/native-harness/src/contracts/mcp.ts +22 -0
- package/src/native-harness/src/contracts/model-execution.ts +2 -1
- package/src/native-harness/src/contracts/operator-controls.ts +8 -1
- package/src/native-harness/src/contracts/protocol.ts +20 -4
- package/src/native-harness/src/contracts/session-file.ts +2 -1
- package/src/native-harness/src/contracts/session.ts +6 -1
- package/src/native-harness/src/contracts/storage.ts +23 -5
- package/src/native-harness/src/contracts/tools.ts +2 -0
- package/src/native-harness/src/contracts/web.ts +16 -0
- package/src/native-harness/src/governance/permissions/gate.ts +9 -2
- package/src/native-harness/src/governance/policy/resolve.ts +6 -1
- package/src/native-harness/src/index.ts +43 -11
- package/src/native-harness/src/interfaces/cli/development.ts +108 -53
- package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
- package/src/native-harness/src/interfaces/cli/start.ts +22 -13
- package/src/native-harness/src/interfaces/client.ts +8 -2
- package/src/native-harness/src/interfaces/inspector/index.html +7 -1
- package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
- package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
- package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
- package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
- package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
- package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
- package/src/native-harness/src/kernel/channels.ts +19 -11
- package/src/native-harness/src/kernel/loop.ts +1 -1
- package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
- package/src/native-harness/src/runtime/config/managed.ts +1 -1
- package/src/native-harness/src/runtime/config/paths.ts +3 -2
- package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
- package/src/native-harness/src/state/storage/archive.ts +95 -12
- package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
- package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
- package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
- package/src/native-harness/src/state/storage/engine.ts +194 -34
- package/src/native-harness/src/state/storage/inference.ts +30 -2
- package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
- package/src/native-harness/src/state/storage/memory.ts +18 -3
- package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
- package/src/native-harness/src/state/storage/session-file.ts +22 -9
- package/src/native-harness/src/state/storage/sqlite.ts +51 -10
- package/src/native-harness/src/state/storage/web-tables.ts +47 -0
- package/src/native-harness/src/testing.ts +150 -55
- package/src/native-harness/src/util/attachment-input.ts +42 -0
- package/src/native-harness/src/util/config.ts +59 -12
- package/src/native-harness/src/util/mcp-config.ts +102 -0
- package/src/native-harness/src/util/web-config.ts +34 -0
- package/src/native-harness/src/util/web-usage.ts +33 -0
- package/src/steering/combine.ts +1 -0
- package/src/steering/contracts.ts +3 -0
|
@@ -2,7 +2,9 @@ import type { ContextLimits } from "../contracts/context.ts";
|
|
|
2
2
|
import type { ActiveTurn, ChannelInput, ChannelNotice, SendResult, SessionAgent, TurnExecutor, TurnPort } from "../contracts/agent.ts";
|
|
3
3
|
import type { EventSink, SessionEventSink } from "../contracts/events.ts";
|
|
4
4
|
import type { ChannelControls, ChannelStatus, ControlResult, LifecycleResult, SessionStatus } from "../contracts/session.ts";
|
|
5
|
-
import type { AcceptItem, SessionLifecycle, SessionStorage, StorageError, StorageResult, StorageSnapshot, StoredTurn } from "../contracts/storage.ts";
|
|
5
|
+
import type { AcceptItem, SessionLifecycle, SessionStorage, StorageError, StorageResult, StorageSnapshot, StoredTurn, TimelineEntry } from "../contracts/storage.ts";
|
|
6
|
+
import { attachmentFailureReason, parseAttachmentFailure } from "../contracts/attachments.ts";
|
|
7
|
+
import { attachmentView } from "../contracts/attachments.ts";
|
|
6
8
|
|
|
7
9
|
export interface ChannelScheduler {
|
|
8
10
|
wakeCommittedChannel(channelId: string): void;
|
|
@@ -48,7 +50,7 @@ export function sessionStatus(view: Pick<StorageSnapshot, "revision" | "session"
|
|
|
48
50
|
* publishes each one after it happens, and keeps the per-process handles
|
|
49
51
|
* (promises and abort controllers) that storage cannot hold. */
|
|
50
52
|
export function createChannelScheduler(
|
|
51
|
-
storage: SessionStorage, execute: TurnExecutor, emit: EventSink = () => {}, emitSession: SessionEventSink = () => {}, limits?: ContextLimits,
|
|
53
|
+
storage: SessionStorage, execute: TurnExecutor, emit: EventSink = () => {}, emitSession: SessionEventSink = () => {}, limits?: ContextLimits, imageInput = false,
|
|
52
54
|
): ChannelScheduler {
|
|
53
55
|
const live = new Map<string, { turnId: number; abort: AbortController; suspension: AbortController }>();
|
|
54
56
|
// Channels that may have pending input. Only an optimization and an idle
|
|
@@ -107,8 +109,15 @@ export function createChannelScheduler(
|
|
|
107
109
|
const ended = (turn: StoredTurn, revision: number) => {
|
|
108
110
|
if (turn.state.status !== "failed" && turn.state.status !== "interrupted") return;
|
|
109
111
|
emit({ channel: turn.channelId, revision, event: { type: "turn_ended", turnId: String(turn.turnId), outcome: turn.state.status,
|
|
110
|
-
error: turn.state.reason, ...(turn.state.
|
|
112
|
+
error: turn.state.reason, ...(parseAttachmentFailure(turn.state.reason) ? { attachmentFailure: parseAttachmentFailure(turn.state.reason) } : {}),
|
|
113
|
+
...(turn.state.uncertainCallIds.length ? { uncertainCalls: turn.state.uncertainCallIds } : {}) } });
|
|
111
114
|
};
|
|
115
|
+
const takenMessages = (entries: readonly TimelineEntry[]) => entries.flatMap(entry => {
|
|
116
|
+
if (entry.kind !== "participant_message" || !entry.itemId) return [];
|
|
117
|
+
const parts = entry.message.role === "user" ? entry.message.parts : undefined;
|
|
118
|
+
return [{ itemId: entry.itemId, messageId: `item:${entry.itemId}`, position: String(entry.seq),
|
|
119
|
+
...(parts ? { parts: attachmentView(parts, storage.readManagedAttachment, { timeline: true }) } : {}) }];
|
|
120
|
+
});
|
|
112
121
|
|
|
113
122
|
/** Start the channel's next turn if storage has one to start. */
|
|
114
123
|
function pump(channelId: string) {
|
|
@@ -120,8 +129,7 @@ export function createChannelScheduler(
|
|
|
120
129
|
if (!begun.ok || !begun.value) { if (begun.ok) waiting.delete(channelId); return; }
|
|
121
130
|
waiting.delete(channelId);
|
|
122
131
|
emit({ channel: channelId, revision: begun.revision, event: { type: "turn_started", turnId: String(begun.value.turn.turnId),
|
|
123
|
-
items: begun.value.items.map(item => item.itemId), messages: begun.value.entries
|
|
124
|
-
entry.kind === "participant_message" && entry.itemId ? [{ itemId: entry.itemId, messageId: `item:${entry.itemId}`, position: String(entry.seq) }] : []) } });
|
|
132
|
+
items: begun.value.items.map(item => item.itemId), messages: takenMessages(begun.value.entries) } });
|
|
125
133
|
run({ channelId, turnId: begun.value.turn.turnId, resumed: false });
|
|
126
134
|
}
|
|
127
135
|
|
|
@@ -141,8 +149,7 @@ export function createChannelScheduler(
|
|
|
141
149
|
if (!taken.ok) { if (taken.error.code !== "not_running" && taken.error.code !== "channel_suspended") fenced(taken.error.message); return; }
|
|
142
150
|
waiting.delete(channelId);
|
|
143
151
|
if (taken.value.items.length) emit({ channel: channelId, revision: taken.revision,
|
|
144
|
-
event: { type: "turn_took", turnId: String(turnId), items: taken.value.items.map(item => item.itemId), messages: taken.value.entries
|
|
145
|
-
entry.kind === "participant_message" && entry.itemId ? [{ itemId: entry.itemId, messageId: `item:${entry.itemId}`, position: String(entry.seq) }] : []) } });
|
|
152
|
+
event: { type: "turn_took", turnId: String(turnId), items: taken.value.items.map(item => item.itemId), messages: takenMessages(taken.value.entries) } });
|
|
146
153
|
},
|
|
147
154
|
confirm(milestone) {
|
|
148
155
|
const advanced = storage.confirmReceipts(turnId, milestone);
|
|
@@ -177,7 +184,8 @@ export function createChannelScheduler(
|
|
|
177
184
|
void Promise.resolve().then(() => execute(turn, port)).then(() => {}, error => {
|
|
178
185
|
// Record the failure unless stop already ended the turn; either way the
|
|
179
186
|
// channel stays usable.
|
|
180
|
-
const
|
|
187
|
+
const attachmentFailure = error && typeof error === "object" && "attachmentFailure" in error ? error.attachmentFailure as import("../contracts/attachments.ts").AttachmentFailure | undefined : undefined;
|
|
188
|
+
const outcome = attachmentFailure ? attachmentFailureReason(attachmentFailure) : error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? error.outcome : String(error);
|
|
181
189
|
const failed = storage.finishTurn(turnId, { status: "failed", reason: outcome });
|
|
182
190
|
release();
|
|
183
191
|
if (failed.ok && failed.value.finished) { ended(failed.value.turn, failed.revision); settleChannel(channelId, failed.revision); }
|
|
@@ -203,11 +211,11 @@ export function createChannelScheduler(
|
|
|
203
211
|
if (!known.ok || !known.value.items.some(stored => stored.itemId === item.itemId))
|
|
204
212
|
return { accepted: false, code: "stopped", error: "This process has stopped accepting work" };
|
|
205
213
|
}
|
|
206
|
-
const result = storage.acceptItem(item, limits?.maxInputBytes);
|
|
214
|
+
const result = storage.acceptItem(item, limits?.maxInputBytes, { imageInput });
|
|
207
215
|
if (!result.ok) {
|
|
208
216
|
const code = result.error.code;
|
|
209
217
|
return { accepted: false, error: result.error.message, code: code === "invalid_input" || code === "item_conflict"
|
|
210
|
-
|| code === "invalid_policy" || code === "incompatible" || code === "not_running" || code === "not_found" || code === "channel_suspended" || code === "channel_retired" ? code : "storage_failure" };
|
|
218
|
+
|| code === "invalid_policy" || code === "incompatible" || code === "not_running" || code === "not_found" || code === "channel_suspended" || code === "channel_retired" || code === "unsupported_image" || code === "transfer_limit" ? code : "storage_failure" };
|
|
211
219
|
}
|
|
212
220
|
const { item: stored, duplicate } = result.value;
|
|
213
221
|
if (!duplicate) {
|
|
@@ -330,7 +338,7 @@ export function createChannelScheduler(
|
|
|
330
338
|
agent: {
|
|
331
339
|
idle: () => live.size === 0 && (!compatible() || !started || stopped || lifecycle !== "running" || waiting.size === 0),
|
|
332
340
|
send: (input: ChannelInput) => accept({ kind: "participant_message", channelId: input?.channelId, senderId: input?.participantId,
|
|
333
|
-
text: input?.text, ...(input?.policy == null ? {} : { explicitPolicy: input.policy }), ...(input?.itemId === undefined ? {} : { itemId: input.itemId }) }),
|
|
341
|
+
text: input?.text, ...(input?.parts === undefined ? {} : { parts: input.parts }), ...(input?.policy == null ? {} : { explicitPolicy: input.policy }), ...(input?.itemId === undefined ? {} : { itemId: input.itemId }) }),
|
|
334
342
|
notifyExternal: notice => accept({ kind: "external_notice", itemId: notice.itemId, channelId: notice.channelId,
|
|
335
343
|
senderId: notice.source ?? "host", externalSource: notice.source, inheritedPolicyNames: notice.policyNames, text: notice.text }),
|
|
336
344
|
notify: (notice: ChannelNotice) => accept({ kind: "channel_notice", channelId: notice?.channelId,
|
|
@@ -29,7 +29,7 @@ export async function runTurn(
|
|
|
29
29
|
// A skip is already paired synchronously by the gate, so interruption
|
|
30
30
|
// cannot end a turn between its approval closure and its result commit.
|
|
31
31
|
if (result.dispatched) {
|
|
32
|
-
context.append({ role: "tool", callId: call.id, content: result.content, ...(result.outcome ? { outcome: result.outcome } : {}) });
|
|
32
|
+
context.append({ role: "tool", callId: call.id, content: result.content, ...(result.outcome ? { outcome: result.outcome } : {}), ...(result.usage ? { usage: result.usage } : {}) });
|
|
33
33
|
// A dispatched call whose executor reported a typed failure, or whose
|
|
34
34
|
// wait ended at its deadline, still has a paired result: the turn goes on.
|
|
35
35
|
const status = result.outcome?.status === "interrupted" ? "interrupted" : result.outcome?.status === "failed" ? "failed" : "completed";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ManagedModel } from "../../contracts/config-permissions.ts";
|
|
3
|
+
|
|
4
|
+
export function compatibleInferenceKey(model: Extract<ManagedModel, { protocol: "openai-compatible" }>,
|
|
5
|
+
system: string, tools: readonly string[]): string {
|
|
6
|
+
return createHash("sha256").update(JSON.stringify([model.protocol, model.providerId, model.baseUrl, model.model, system, tools])).digest("hex");
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** Runtime entry point for the shared, side-effect-free config validator. */
|
|
2
|
-
export { ConfigError, LEGACY_POLICY, resolveCredential, validateManagedConfig } from "../../util/config.ts";
|
|
2
|
+
export { ConfigError, LEGACY_POLICY, resolveCredential, resolveCompatibleCredential, validateManagedConfig } from "../../util/config.ts";
|
|
@@ -27,7 +27,8 @@ export function chooseManagedConfig(options: { mode: "create" | "open"; sidecar:
|
|
|
27
27
|
if (options.mode !== "open" || options.inline === undefined || raw === options.inline) return selected;
|
|
28
28
|
const requested = validateManagedConfig(options.inline).limits;
|
|
29
29
|
if (!requested) return selected;
|
|
30
|
-
if (selected.limits &&
|
|
30
|
+
if (selected.limits?.unattendedTurns !== undefined && requested.unattendedTurns !== undefined &&
|
|
31
|
+
selected.limits.unattendedTurns !== requested.unattendedTurns)
|
|
31
32
|
throw new ConfigError("config.limits.unattendedTurns", "inline and selected limits differ");
|
|
32
|
-
return { ...selected, limits: requested };
|
|
33
|
+
return { ...selected, limits: { ...selected.limits, ...requested } };
|
|
33
34
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface McpStdioLaunch {
|
|
2
|
+
command: string;
|
|
3
|
+
args: readonly string[];
|
|
4
|
+
cwd?: string;
|
|
5
|
+
env: Readonly<Record<string, string>>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// Stderr is drained without retaining remote output or mixing it with JSON-RPC.
|
|
9
|
+
export function spawnMcpStdio(config: McpStdioLaunch) {
|
|
10
|
+
const child = Bun.spawn([config.command, ...config.args], {
|
|
11
|
+
cwd: config.cwd, env: { ...config.env }, stdin: "pipe", stdout: "pipe", stderr: "pipe",
|
|
12
|
+
});
|
|
13
|
+
const stopDrain = new AbortController();
|
|
14
|
+
const drain = child.stderr.pipeTo(new WritableStream(), { signal: stopDrain.signal }).catch(() => {});
|
|
15
|
+
let closed: Promise<void> | undefined;
|
|
16
|
+
return {
|
|
17
|
+
stdout: child.stdout,
|
|
18
|
+
async write(frame: Uint8Array) {
|
|
19
|
+
child.stdin.write(frame);
|
|
20
|
+
await child.stdin.flush();
|
|
21
|
+
},
|
|
22
|
+
close() {
|
|
23
|
+
return closed ??= (async () => {
|
|
24
|
+
child.kill("SIGKILL");
|
|
25
|
+
await child.exited;
|
|
26
|
+
stopDrain.abort();
|
|
27
|
+
await drain;
|
|
28
|
+
})();
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { validWebDispatch, validCommittedWebUsage } from "../../util/web-usage.ts";
|
|
1
2
|
import { migrateImportedRoutines } from "./engine.ts";
|
|
2
3
|
import { validateReminderArchive } from "./reminder-archive.ts";
|
|
3
4
|
import type { SessionArchive, SessionArchiveV1, StoredSession } from "../../contracts/storage.ts";
|
|
4
5
|
import { Fail, isJson, signatureOf, type Meta, type Tables } from "./engine.ts";
|
|
5
6
|
import { validateConfig } from "./session-file.ts";
|
|
6
7
|
import { legacyItemSignature, policyItemSignature } from "./policy-metadata.ts";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { validateMixedParts } from "../../util/attachment-input.ts";
|
|
7
10
|
|
|
8
11
|
const bad = (message: string): never => { throw new Fail("invalid_archive", message); };
|
|
9
12
|
const str = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
@@ -16,7 +19,7 @@ const CHANNEL_STATES = ["open", "suspended", "retired"];
|
|
|
16
19
|
export function validateSessionPayload(value: unknown) {
|
|
17
20
|
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join() !== "archive,config") bad("Invalid session file payload");
|
|
18
21
|
const payload = value as { archive: SessionArchive; config: unknown };
|
|
19
|
-
if (![2, 3, 4, 5, 6, 7].includes((payload.archive as { archiveVersion?: number })?.archiveVersion ?? 0)) bad("Invalid session file archive version");
|
|
22
|
+
if (![2, 3, 4, 5, 6, 7, 8, 9].includes((payload.archive as { archiveVersion?: number })?.archiveVersion ?? 0)) bad("Invalid session file archive version");
|
|
20
23
|
const archive = validateArchive(payload.archive);
|
|
21
24
|
let config: ReturnType<typeof validateConfig>;
|
|
22
25
|
try { config = validateConfig(payload.config, (payload.archive as { archiveVersion: number }).archiveVersion === 2); } catch (error) { return bad(String(error)); }
|
|
@@ -30,9 +33,42 @@ export function validateSessionPayload(value: unknown) {
|
|
|
30
33
|
* running turn, a checkpoint nothing holds, or a live turn on a retired channel,
|
|
31
34
|
* which the next open would treat as an unclean exit or must never run. */
|
|
32
35
|
export function validateArchive(value: unknown): SessionArchive {
|
|
33
|
-
if (!
|
|
36
|
+
if (!value || typeof value !== "object") bad("Archive is not data");
|
|
34
37
|
const raw = value as any;
|
|
35
|
-
if (raw.format !== "harness-session" || ![1, 2, 3, 4, 5, 6, 7].includes(raw.archiveVersion)) bad("Unsupported archive format or version");
|
|
38
|
+
if (raw.format !== "harness-session" || ![1, 2, 3, 4, 5, 6, 7, 8, 9].includes(raw.archiveVersion)) bad("Unsupported archive format or version");
|
|
39
|
+
const files = new Map<string, { metadata: import("../../contracts/attachments.ts").AttachmentMetadata; readyAt: string; bytes: Uint8Array }>();
|
|
40
|
+
if (raw.archiveVersion === 8 || (raw.archiveVersion === 9 && raw.attachmentState !== undefined)) {
|
|
41
|
+
const state = raw.attachmentState;
|
|
42
|
+
if (!state || ![6, 7, 8].includes(state.baseFormat) || !Array.isArray(state.files) || !state.files.length) bad("Invalid attachment archive state");
|
|
43
|
+
let total = 0;
|
|
44
|
+
for (const file of state.files) {
|
|
45
|
+
const m = file?.metadata;
|
|
46
|
+
if (!file || Object.keys(file).sort().join() !== "bytes,metadata,readyAt" || !(file.bytes instanceof Uint8Array) || !m
|
|
47
|
+
|| Object.keys(m).sort().join() !== "bytes,channel,filename,id,mediaType,sha256"
|
|
48
|
+
|| typeof m.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(m.id)
|
|
49
|
+
|| files.has(m.id) || !nonblank(m.channel) || typeof m.filename !== "string" || !m.filename.length || !m.filename.isWellFormed() || Buffer.byteLength(m.filename) > 255
|
|
50
|
+
|| /[\u0000-\u001f\u007f-\u009f]/u.test(m.filename) || typeof m.mediaType !== "string" || m.mediaType.length > 127 || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(m.mediaType)
|
|
51
|
+
|| !Number.isSafeInteger(m.bytes) || m.bytes < 1 || m.bytes > 20 * 1024 * 1024 || file.bytes.length !== m.bytes
|
|
52
|
+
|| typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256) || createHash("sha256").update(file.bytes).digest("hex") !== m.sha256
|
|
53
|
+
|| typeof file.readyAt !== "string" || !Number.isFinite(Date.parse(file.readyAt))) bad("Invalid archived attachment");
|
|
54
|
+
total += m.bytes;
|
|
55
|
+
if (!Number.isSafeInteger(total) || total > 268435456) bad("Attachment archive exceeds limit");
|
|
56
|
+
if (m.mediaType.startsWith("image/")) {
|
|
57
|
+
const bytes = file.bytes as Uint8Array;
|
|
58
|
+
const png = m.mediaType === "image/png" && bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((n, i) => bytes[i] === n);
|
|
59
|
+
const jpeg = m.mediaType === "image/jpeg" && bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
|
|
60
|
+
const webp = m.mediaType === "image/webp" && bytes.length >= 12 && Buffer.from(bytes.subarray(0, 4)).toString("ascii") === "RIFF" && Buffer.from(bytes.subarray(8, 12)).toString("ascii") === "WEBP";
|
|
61
|
+
if (!png && !jpeg && !webp) bad("Archived image does not match its media type");
|
|
62
|
+
}
|
|
63
|
+
files.set(m.id, file);
|
|
64
|
+
}
|
|
65
|
+
const jsonPart = { ...raw, attachmentState: { ...state, files: state.files.map(({ bytes: _bytes, ...rest }: any) => rest) } };
|
|
66
|
+
if (!isJson(jsonPart)) bad("Archive is not JSON data");
|
|
67
|
+
} else if (!isJson(value) || raw.attachmentState !== undefined) bad("Archive is not JSON data");
|
|
68
|
+
if (raw.archiveVersion === 9) {
|
|
69
|
+
if (!raw.webState || Object.keys(raw.webState).join() !== "baseFormat" || ![6, 7, 8, 9].includes(raw.webState.baseFormat)
|
|
70
|
+
|| (raw.webState.baseFormat === 9) !== !!raw.attachmentState) bad("Invalid web archive base");
|
|
71
|
+
} else if (raw.webState !== undefined || raw.snapshot?.webDispatches !== undefined) bad("Unexpected web evidence");
|
|
36
72
|
const v1 = raw.archiveVersion === 1;
|
|
37
73
|
const legacy = raw.archiveVersion < 3;
|
|
38
74
|
if (!raw.snapshot || !raw.allocation || !raw.snapshot.session || !Array.isArray(raw.snapshot.channels)) bad("Archive is missing its snapshot or allocation state");
|
|
@@ -49,14 +85,14 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
49
85
|
const positions: Record<string, number> = {};
|
|
50
86
|
if (old && Array.isArray(policyArchive.snapshot.timeline)) for (const entry of policyArchive.snapshot.timeline)
|
|
51
87
|
if (entry.message?.role === "assistant") Object.defineProperty(positions, entry.channelId, { value: (Object.hasOwn(positions, entry.channelId) ? positions[entry.channelId]! : 0) + 1, writable: true, configurable: true, enumerable: true });
|
|
52
|
-
const previousFormat = [0, 2, 3, 4, 5, 6, 7, 8][raw.archiveVersion];
|
|
88
|
+
const previousFormat = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10][raw.archiveVersion];
|
|
53
89
|
if (raw.snapshot.session.formatVersion !== previousFormat) bad("Unsupported session format");
|
|
54
|
-
const archive: SessionArchive = { ...policyArchive, archiveVersion: raw.archiveVersion >= 7 ? 7 : raw.archiveVersion === 6 ? 6 : 5, snapshot: { ...policyArchive.snapshot,
|
|
55
|
-
session: { ...policyArchive.snapshot.session, formatVersion: raw.archiveVersion >= 7 ? 8 : raw.archiveVersion === 6 ? 7 : 6 },
|
|
90
|
+
const archive: SessionArchive = { ...policyArchive, archiveVersion: raw.archiveVersion >= 9 ? 9 : raw.archiveVersion >= 8 ? 8 : raw.archiveVersion >= 7 ? 7 : raw.archiveVersion === 6 ? 6 : 5, snapshot: { ...policyArchive.snapshot,
|
|
91
|
+
session: { ...policyArchive.snapshot.session, formatVersion: raw.archiveVersion >= 9 ? 10 : raw.archiveVersion >= 8 ? 9 : raw.archiveVersion >= 7 ? 8 : raw.archiveVersion === 6 ? 7 : 6 },
|
|
56
92
|
...(old ? { modelCalls: [], scriptPositions: positions } : {}) } };
|
|
57
93
|
const snapshot = archive.snapshot, allocation = archive.allocation;
|
|
58
94
|
const { session, revision } = snapshot;
|
|
59
|
-
if ((session.formatVersion !== 6 && session.formatVersion !== 7 && session.formatVersion !== 8) || !str(session.sessionId) || !str(session.createdAt) || typeof session.compatibilityKey !== "string")
|
|
95
|
+
if ((session.formatVersion !== 6 && session.formatVersion !== 7 && session.formatVersion !== 8 && session.formatVersion !== 9 && session.formatVersion !== 10) || !str(session.sessionId) || !str(session.createdAt) || typeof session.compatibilityKey !== "string")
|
|
60
96
|
bad("Unsupported session format");
|
|
61
97
|
if (session.lifecycle !== "running" && session.lifecycle !== "suspended") bad("Archive was not exported from an idle or suspended session");
|
|
62
98
|
if (!Number.isSafeInteger(revision) || revision < 0 || allocation.nextSeq !== revision + 1 || !int(allocation.nextTurnId) || !int(allocation.nextItemNumber))
|
|
@@ -126,6 +162,34 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
126
162
|
if (turn.state.status === "suspended" && outstanding.size) bad("Checkpoint has an unanswered tool call");
|
|
127
163
|
}
|
|
128
164
|
|
|
165
|
+
const records = snapshot.webDispatches;
|
|
166
|
+
if (archive.archiveVersion === 9) {
|
|
167
|
+
if (!Array.isArray(records)) bad("Missing web dispatch evidence");
|
|
168
|
+
const seen = new Set<string>();
|
|
169
|
+
for (const record of records!) {
|
|
170
|
+
if (!record || Object.keys(record).sort().join() !== "callId,evidence,turnId" || !int(record.turnId) || !str(record.callId) || !validWebDispatch(record.evidence)) bad("Invalid web dispatch evidence");
|
|
171
|
+
const identity = JSON.stringify([record.turnId, record.callId]);
|
|
172
|
+
if (seen.has(identity)) bad("Duplicate web dispatch evidence");
|
|
173
|
+
seen.add(identity);
|
|
174
|
+
const call = snapshot.timeline.flatMap(entry => entry.turnId === record.turnId && entry.message.role === "assistant" ? entry.message.calls : []).find(candidate => candidate.id === record.callId);
|
|
175
|
+
if (!call || call.name !== record.evidence.operation) bad("Web evidence does not match a call");
|
|
176
|
+
}
|
|
177
|
+
let refusals = 0;
|
|
178
|
+
for (const entry of snapshot.timeline) if (entry.message.role === "tool" && entry.message.webNoDispatch !== undefined) {
|
|
179
|
+
const message = entry.message;
|
|
180
|
+
const call = snapshot.timeline.flatMap(row => row.turnId === entry.turnId && row.message.role === "assistant" ? row.message.calls : []).find(candidate => candidate.id === message.callId);
|
|
181
|
+
if (message.webNoDispatch !== true || message.outcome?.status !== "skipped" || !call || !["web_search", "web_fetch"].includes(call.name)
|
|
182
|
+
|| records!.some(record => record.turnId === entry.turnId && record.callId === message.callId)) bad("Invalid web refusal evidence");
|
|
183
|
+
refusals++;
|
|
184
|
+
}
|
|
185
|
+
if (!records!.length && !refusals) bad("Empty web archive evidence");
|
|
186
|
+
for (const entry of snapshot.timeline) if (entry.message.role === "tool" && entry.message.usage !== undefined) {
|
|
187
|
+
const callId = entry.message.callId;
|
|
188
|
+
const record = records!.find(candidate => candidate.turnId === entry.turnId && candidate.callId === callId);
|
|
189
|
+
if (!record?.evidence.paid || !validCommittedWebUsage(entry.message.usage)) bad("Invalid paired web usage");
|
|
190
|
+
}
|
|
191
|
+
} else if (snapshot.timeline.some(entry => entry.message.role === "tool" && (entry.message.usage !== undefined || entry.message.webNoDispatch !== undefined))) bad("Unexpected paired web usage");
|
|
192
|
+
|
|
129
193
|
const revoked = (snapshot as { revokedTools?: unknown }).revokedTools;
|
|
130
194
|
if (revoked !== undefined && (!Array.isArray(revoked) || revoked.some(name => !str(name)) || new Set(revoked).size !== revoked.length
|
|
131
195
|
|| JSON.stringify([...revoked].sort()) !== JSON.stringify(revoked))) bad("Invalid revoked tools");
|
|
@@ -165,7 +229,7 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
165
229
|
}
|
|
166
230
|
for (const entry of snapshot.timeline) if (entry.messageId && !messageIds.has(entry.messageId)) bad("Unknown model message ID");
|
|
167
231
|
|
|
168
|
-
const ids = new Set<string>(), accepted = new Set<number>(), externalEntries = new Set<number>();
|
|
232
|
+
const ids = new Set<string>(), accepted = new Set<number>(), externalEntries = new Set<number>(), referencedFiles = new Set<string>();
|
|
169
233
|
for (const item of [...snapshot.items].sort((a, b) => (a?.entrySeq ?? 0) - (b?.entrySeq ?? 0))) {
|
|
170
234
|
if (!item || !str(item.itemId) || ids.has(item.itemId) || !channels.has(item.channelId) || !MILESTONES.includes(item.milestone)
|
|
171
235
|
|| !int(item.acceptedSeq) || item.acceptedSeq > revision || accepted.has(item.acceptedSeq) || !str(item.acceptedAt)
|
|
@@ -183,7 +247,17 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
183
247
|
|| JSON.stringify(names) !== JSON.stringify(item.policy?.inherited)) bad("Invalid external notice metadata");
|
|
184
248
|
} else if (!["participant_message", "channel_notice"].includes(item.kind)
|
|
185
249
|
|| item.externalSource !== undefined || item.inheritedPolicyNames !== undefined) bad("Invalid item kind or attribution");
|
|
186
|
-
if (
|
|
250
|
+
if (item.parts !== undefined) {
|
|
251
|
+
if (archive.archiveVersion < 8 || item.kind !== "participant_message") bad("Unexpected attachment parts");
|
|
252
|
+
try { validateMixedParts(item.parts); } catch { bad("Invalid attachment parts"); }
|
|
253
|
+
if (item.text !== item.parts.filter(part => part.type === "text").map(part => part.type === "text" ? part.text : "").join("\n")) bad("Attachment text projection differs");
|
|
254
|
+
for (const part of item.parts) if (part.type === "attachment") {
|
|
255
|
+
const file = files.get(part.id);
|
|
256
|
+
if (!file || file.metadata.channel !== item.channelId) bad("Unknown or mis-scoped archived attachment");
|
|
257
|
+
referencedFiles.add(part.id);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (![item.kind, item.senderId].every(str) || typeof item.text !== "string" || (item.parts === undefined && !str(item.text)) || item.signature !== signatureOf(item)) bad(`Item ${item.itemId} does not match its signature`);
|
|
187
261
|
if (!item.policy || !str(item.policy.resolved) || !Array.isArray(item.policy.inherited) || item.policy.inherited.some(name => !str(name))
|
|
188
262
|
|| (item.policy.explicit !== undefined && !str(item.policy.explicit)) || (item.policy.explicit ?? null) !== (item.explicitPolicy ?? null)) bad(`Item ${item.itemId} has invalid policy metadata`);
|
|
189
263
|
ids.add(item.itemId);
|
|
@@ -196,6 +270,7 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
196
270
|
} else {
|
|
197
271
|
const entry = entries.get(item.entrySeq as number), turn = turns.get(item.turnId as number);
|
|
198
272
|
if (!turn || !entry || entry.itemId !== item.itemId || entry.turnId !== item.turnId) bad(`Item ${item.itemId} has no matching timeline entry`);
|
|
273
|
+
if (item.parts && (entry!.message.role !== "user" || JSON.stringify(entry!.message.parts) !== JSON.stringify(item.parts))) bad("Attachment parts and timeline disagree");
|
|
199
274
|
if (item.kind === "external_notice" && (entry!.kind !== item.kind || entry!.externalSource !== item.externalSource
|
|
200
275
|
|| entry!.channelId !== item.channelId || entry!.message.content !== item.text)) bad("External notice and timeline disagree");
|
|
201
276
|
if (item.kind === "external_notice") externalEntries.add(entry!.seq);
|
|
@@ -206,10 +281,12 @@ export function validateArchive(value: unknown): SessionArchive {
|
|
|
206
281
|
if (entry.kind === "external_notice" && !externalEntries.has(entry.seq)) bad("External timeline entry has no inbox item");
|
|
207
282
|
for (const turn of snapshot.turns)
|
|
208
283
|
if (JSON.stringify(turn.itemIds) !== JSON.stringify(turns.get(turn.turnId)!.itemIds)) bad(`Turn ${turn.turnId} does not match its items`);
|
|
209
|
-
if (archive.archiveVersion >=
|
|
284
|
+
if (archive.archiveVersion >= 8 && (referencedFiles.size !== files.size || [...files.keys()].some(id => !referencedFiles.has(id)))) bad("Archive contains unreferenced attachment files");
|
|
285
|
+
const reminderFormat = archive.archiveVersion === 9 ? (archive.attachmentState?.baseFormat ?? archive.webState!.baseFormat) : archive.archiveVersion === 8 ? archive.attachmentState!.baseFormat : archive.archiveVersion >= 7 ? 8 : archive.archiveVersion === 6 ? 7 : 6;
|
|
286
|
+
if (reminderFormat >= 7) {
|
|
210
287
|
validateReminderArchive(archive.reminderState, snapshot);
|
|
211
288
|
const guard = archive.reminderState?.guard;
|
|
212
|
-
if (
|
|
289
|
+
if (reminderFormat >= 8) {
|
|
213
290
|
if (guard && (!Number.isSafeInteger(guard.limit) || guard.limit < 1 || !Array.isArray(guard.counters)))
|
|
214
291
|
bad("Invalid archived unattended guard");
|
|
215
292
|
const seen = new Set<string>();
|
|
@@ -240,7 +317,13 @@ export function restoreArchive(tables: Tables, archive: SessionArchive): void {
|
|
|
240
317
|
for (const participant of snapshot.participants) tables.addParticipant(participant.participantId);
|
|
241
318
|
for (const { itemIds: _derived, ...turn } of snapshot.turns) tables.putTurn(turn);
|
|
242
319
|
for (const entry of snapshot.timeline) tables.addEntry(entry);
|
|
320
|
+
if (archive.webState) { tables.web.activate(archive.webState.baseFormat); for (const record of snapshot.webDispatches ?? []) tables.web.add(record, archive.webState.baseFormat); }
|
|
321
|
+
if (archive.attachmentState) {
|
|
322
|
+
if (!tables.attachments) bad("Managed attachment storage is unavailable");
|
|
323
|
+
tables.attachments!.restore(archive.attachmentState.baseFormat, archive.attachmentState.files);
|
|
324
|
+
}
|
|
243
325
|
for (const item of snapshot.items) tables.putItem(item);
|
|
326
|
+
for (const item of snapshot.items) if (item.parts) tables.attachments!.saveParts(item.itemId, item.parts);
|
|
244
327
|
const entryIds = Object.fromEntries(snapshot.timeline.filter(entry => entry.messageId).map(entry => [String(entry.seq), entry.messageId!]));
|
|
245
328
|
const max = snapshot.modelCalls.reduce((n, call) => Math.max(n, Number(call.callId) || 0), 0);
|
|
246
329
|
tables.setModelState({ nextCall: max + 1, calls: snapshot.modelCalls, itemIds: {}, scriptPositions: snapshot.scriptPositions, entryIds });
|
|
@@ -253,5 +336,5 @@ export function restoreArchive(tables: Tables, archive: SessionArchive): void {
|
|
|
253
336
|
}
|
|
254
337
|
|
|
255
338
|
export function storedSession(meta: Meta): StoredSession {
|
|
256
|
-
return { sessionId: meta.sessionId, formatVersion: meta.formatVersion >= 8 ? 8 : meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt, lifecycle: meta.lifecycle, compatibilityKey: meta.compatibilityKey };
|
|
339
|
+
return { sessionId: meta.sessionId, formatVersion: meta.formatVersion >= 10 ? 10 : meta.formatVersion >= 9 ? 9 : meta.formatVersion >= 8 ? 8 : meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt, lifecycle: meta.lifecycle, compatibilityKey: meta.compatibilityKey };
|
|
257
340
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fsyncSync, fstatSync, mkdirSync, openSync, readSync, rmSync, writeSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { AttachmentMetadata } from "../../contracts/attachments.ts";
|
|
5
|
+
|
|
6
|
+
export class AttachmentArchiveError extends Error {
|
|
7
|
+
constructor(readonly code: "attachment_unavailable" | "transfer_limit", message: string) { super(message); }
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Memory-backed sessions have no durable publication to coordinate. Their
|
|
11
|
+
* fresh private root is removed on failure and becomes visible only when the
|
|
12
|
+
* caller publishes the in-memory session after this function returns. */
|
|
13
|
+
export function writeMemoryArchiveFiles(root: string, files: readonly { metadata: AttachmentMetadata; bytes: Uint8Array }[]): void {
|
|
14
|
+
mkdirSync(root, { mode: 0o700 });
|
|
15
|
+
try {
|
|
16
|
+
for (const file of files) {
|
|
17
|
+
if (!idPattern.test(file.metadata.id)) throw new AttachmentArchiveError("attachment_unavailable", "Invalid attachment ID");
|
|
18
|
+
const fd = openSync(join(root, file.metadata.id), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
19
|
+
try { let offset = 0; while (offset < file.bytes.length) { const n = writeSync(fd, file.bytes, offset, file.bytes.length - offset, offset); if (!n) throw Error("Unable to write attachment"); offset += n; } fsyncSync(fd); }
|
|
20
|
+
finally { closeSync(fd); }
|
|
21
|
+
}
|
|
22
|
+
const fd = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
23
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
24
|
+
} catch (error) { rmSync(root, { recursive: true, force: true }); throw error; }
|
|
25
|
+
}
|
|
26
|
+
const idPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
27
|
+
|
|
28
|
+
/** Preflight every retained file and the aggregate before allocating bytes.
|
|
29
|
+
* The owner holds the session fence for the entire consistent export. */
|
|
30
|
+
export function readArchiveFiles(root: string, records: readonly { metadata: AttachmentMetadata; readyAt: string }[], maxBytes: number) {
|
|
31
|
+
let total = 0;
|
|
32
|
+
for (const { metadata } of records) {
|
|
33
|
+
total += metadata.bytes;
|
|
34
|
+
if (!Number.isSafeInteger(total) || total > maxBytes) throw new AttachmentArchiveError("transfer_limit", "Retained attachment bytes exceed the export limit");
|
|
35
|
+
}
|
|
36
|
+
for (const record of records) {
|
|
37
|
+
const { metadata } = record;
|
|
38
|
+
if (!idPattern.test(metadata.id)) throw new AttachmentArchiveError("attachment_unavailable", "Invalid attachment ID");
|
|
39
|
+
let fd: number;
|
|
40
|
+
try { fd = openSync(join(root, metadata.id), constants.O_RDONLY | constants.O_NOFOLLOW); }
|
|
41
|
+
catch { throw new AttachmentArchiveError("attachment_unavailable", `Attachment unavailable: ${metadata.id}`); }
|
|
42
|
+
try { const stat = fstatSync(fd); if (!stat.isFile() || stat.size !== metadata.bytes) throw new AttachmentArchiveError("attachment_unavailable", `Attachment unavailable: ${metadata.id}`); }
|
|
43
|
+
finally { closeSync(fd); }
|
|
44
|
+
}
|
|
45
|
+
return records.map(({ metadata, readyAt }) => {
|
|
46
|
+
let fd: number;
|
|
47
|
+
try { fd = openSync(join(root, metadata.id), constants.O_RDONLY | constants.O_NOFOLLOW); }
|
|
48
|
+
catch { throw new AttachmentArchiveError("attachment_unavailable", `Attachment unavailable: ${metadata.id}`); }
|
|
49
|
+
try {
|
|
50
|
+
const stat = fstatSync(fd);
|
|
51
|
+
if (!stat.isFile() || stat.size !== metadata.bytes) throw new AttachmentArchiveError("attachment_unavailable", `Attachment unavailable: ${metadata.id}`);
|
|
52
|
+
const bytes = Buffer.alloc(metadata.bytes); let offset = 0;
|
|
53
|
+
while (offset < bytes.length) { const count = readSync(fd, bytes, offset, bytes.length - offset, offset); if (!count) throw new AttachmentArchiveError("attachment_unavailable", `Attachment unavailable: ${metadata.id}`); offset += count; }
|
|
54
|
+
if (createHash("sha256").update(bytes).digest("hex") !== metadata.sha256) throw new AttachmentArchiveError("attachment_unavailable", `Attachment corrupt: ${metadata.id}`);
|
|
55
|
+
return { metadata, readyAt, bytes };
|
|
56
|
+
} finally { closeSync(fd); }
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, writeFileSync, writeSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import type { SessionArchive } from "../../contracts/storage.ts";
|
|
7
|
+
import { Fail } from "./engine.ts";
|
|
8
|
+
|
|
9
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
10
|
+
const syncDirectory = (path: string) => { const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(fd); } finally { closeSync(fd); } };
|
|
11
|
+
|
|
12
|
+
/** A separate SQLite lock serializes create/open and import publication. It is
|
|
13
|
+
* released by the OS after process death, allowing the next owner to recover. */
|
|
14
|
+
export function acquireImportLease(path: string): () => void {
|
|
15
|
+
// Keep coordination files outside the session directory. Resolve the parent
|
|
16
|
+
// so equivalent local paths share one lock, independent of caller TMPDIR.
|
|
17
|
+
const key = createHash("sha256").update(join(realpathSync(dirname(path)), basename(path))).digest("hex");
|
|
18
|
+
const temp = process.platform === "win32" ? tmpdir() : "/tmp";
|
|
19
|
+
const lockDir = join(temp, `harness-attachment-locks-${process.getuid?.() ?? "user"}`);
|
|
20
|
+
mkdirSync(lockDir, { recursive: true, mode: 0o700 });
|
|
21
|
+
const dirFd = openSync(lockDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); closeSync(dirFd);
|
|
22
|
+
const lock = new Database(join(lockDir, key), { create: true, readwrite: true });
|
|
23
|
+
try { lock.exec("PRAGMA busy_timeout=0; BEGIN EXCLUSIVE"); }
|
|
24
|
+
catch (error) { lock.close(); const code = (error as { code?: string }).code; if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") throw new Fail("owner_conflict", "Session publication is in progress"); throw error; }
|
|
25
|
+
return () => { try { lock.exec("ROLLBACK"); } finally { lock.close(true); } };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type Marker = { token: string; ids: string[] };
|
|
29
|
+
function readMarker(path: string): Marker | undefined {
|
|
30
|
+
if (!existsSync(path)) return undefined;
|
|
31
|
+
try {
|
|
32
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
33
|
+
let marker: Marker;
|
|
34
|
+
try { marker = JSON.parse(readFileSync(fd, "utf8")); } finally { closeSync(fd); }
|
|
35
|
+
if (!marker || typeof marker.token !== "string" || !uuid.test(marker.token) || !Array.isArray(marker.ids)
|
|
36
|
+
|| marker.ids.some((id: unknown) => typeof id !== "string" || !uuid.test(id)) || new Set(marker.ids).size !== marker.ids.length) throw Error();
|
|
37
|
+
return marker;
|
|
38
|
+
} catch { throw new Fail("incompatible", "Invalid attachment import marker"); }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Recover only files named by our validated marker. Never recursively delete an
|
|
42
|
+
* existing directory, and never follow a root symlink. Caller holds the lease. */
|
|
43
|
+
export function recoverAttachmentImport(path: string, root: string): void {
|
|
44
|
+
const markerPath = `${path}.attachment-import`;
|
|
45
|
+
let marker: Marker | undefined;
|
|
46
|
+
try { marker = readMarker(markerPath); }
|
|
47
|
+
catch (error) {
|
|
48
|
+
// The root is created only after the marker is fully written and flushed.
|
|
49
|
+
// A truncated marker with no destination is an interrupted marker write.
|
|
50
|
+
if (!existsSync(path) && !existsSync(root)) { rmSync(markerPath, { force: true }); syncDirectory(dirname(path)); return; }
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
if (!marker) return;
|
|
54
|
+
const tokenPath = join(root, ".import-token");
|
|
55
|
+
let owned = false;
|
|
56
|
+
if (existsSync(root)) {
|
|
57
|
+
const rootFd = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
58
|
+
closeSync(rootFd);
|
|
59
|
+
try { const fd = openSync(tokenPath, constants.O_RDONLY | constants.O_NOFOLLOW); try { owned = readFileSync(fd, "utf8") === marker.token; } finally { closeSync(fd); } }
|
|
60
|
+
catch { /* No valid token means no file publication was completed. */ }
|
|
61
|
+
}
|
|
62
|
+
if (existsSync(path)) {
|
|
63
|
+
if (owned) { rmSync(tokenPath, { force: true }); syncDirectory(root); }
|
|
64
|
+
} else if (owned) {
|
|
65
|
+
const dir = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); closeSync(dir);
|
|
66
|
+
for (const id of marker.ids) rmSync(join(root, id), { force: true });
|
|
67
|
+
rmSync(tokenPath, { force: true });
|
|
68
|
+
try { rmdirSync(root); } catch { throw new Fail("already_exists", "Interrupted import directory contains other files"); }
|
|
69
|
+
} else if (existsSync(root)) {
|
|
70
|
+
const entries = readdirSync(root);
|
|
71
|
+
if (entries.length === 1 && entries[0] === ".import-token") rmSync(tokenPath, { force: true });
|
|
72
|
+
try { rmdirSync(root); } catch { throw new Fail("already_exists", "Attachment destination is occupied"); }
|
|
73
|
+
}
|
|
74
|
+
rmSync(markerPath, { force: true }); syncDirectory(dirname(path));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Publish files first and the SQLite database last. A marker and lease fence
|
|
78
|
+
* fresh-destination visibility; recovery removes only this import's files if
|
|
79
|
+
* publication did not commit. `publishDatabase` must fail if path is occupied. */
|
|
80
|
+
export function publishAttachmentImport(path: string, root: string, archive: SessionArchive, publishDatabase: () => void): void {
|
|
81
|
+
const state = archive.attachmentState;
|
|
82
|
+
if (!state) throw new Fail("invalid_archive", "Missing attachment state");
|
|
83
|
+
if (existsSync(path) || existsSync(root)) throw new Fail("already_exists", "Destination is occupied");
|
|
84
|
+
const markerPath = `${path}.attachment-import`, marker: Marker = { token: randomUUID(), ids: state.files.map(file => file.metadata.id) };
|
|
85
|
+
const markerFd = openSync(markerPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
86
|
+
try { writeFileSync(markerFd, JSON.stringify(marker)); fsyncSync(markerFd); } finally { closeSync(markerFd); }
|
|
87
|
+
syncDirectory(dirname(path));
|
|
88
|
+
try {
|
|
89
|
+
mkdirSync(root, { mode: 0o700 });
|
|
90
|
+
const tokenFd = openSync(join(root, ".import-token"), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
91
|
+
try { writeFileSync(tokenFd, marker.token); fsyncSync(tokenFd); } finally { closeSync(tokenFd); }
|
|
92
|
+
syncDirectory(root);
|
|
93
|
+
for (const file of state.files) {
|
|
94
|
+
const fd = openSync(join(root, file.metadata.id), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
95
|
+
try { let offset = 0; while (offset < file.bytes.length) { const count = writeSync(fd, file.bytes, offset, file.bytes.length - offset, offset); if (!count) throw Error("Unable to write attachment"); offset += count; } fsyncSync(fd); }
|
|
96
|
+
finally { closeSync(fd); }
|
|
97
|
+
}
|
|
98
|
+
syncDirectory(root);
|
|
99
|
+
publishDatabase();
|
|
100
|
+
syncDirectory(dirname(path));
|
|
101
|
+
recoverAttachmentImport(path, root);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
try { recoverAttachmentImport(path, root); } catch { /* Preserve the marker for the next owner. */ }
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|