@qlairoslabs/acp-client 0.12.1 → 0.13.1-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/CHANGELOG-consumer-fixes.md +17 -10
- package/CHANGELOG-controller-interface.md +258 -0
- package/CHANGELOG-metering.md +29 -0
- package/CHANGELOG-operation-lifecycle.md +15 -1
- package/CONSUMER_GUIDE.md +984 -6
- package/MIGRATION-0.10-to-0.12.md +4 -1
- package/MIGRATION-0.12-to-0.13.md +288 -0
- package/README.md +17 -16
- package/package.json +11 -2
- package/src/acp-client-handlers.ts +48 -0
- package/src/activity.ts +3 -0
- package/src/adapters.ts +25 -0
- package/src/agent/adoption/provider-attachment.ts +33 -0
- package/src/agent/adoption/provider-session-delete.ts +1 -1
- package/src/agent/adoption/provider-sessions.ts +3 -2
- package/src/agent/append-assistant-message.ts +91 -0
- package/src/agent/config.ts +54 -6
- package/src/agent/conversation-manager.ts +95 -158
- package/src/agent/manager-settings.ts +1 -0
- package/src/agent/native-channel-lifecycle.ts +111 -0
- package/src/agent/native-operations.ts +39 -0
- package/src/agent/persisted-lifecycle.ts +44 -4
- package/src/agent/persistence-policy/context.ts +13 -0
- package/src/agent/persistence-policy/resolver.ts +7 -0
- package/src/agent/persistence-policy/types.ts +1 -0
- package/src/agent/record-capture.ts +1 -0
- package/src/agent-adapter-registry.ts +33 -7
- package/src/agent-conversation-contracts.ts +14 -1
- package/src/agent-conversation-errors.ts +8 -0
- package/src/agent-conversation-owner.ts +9 -4
- package/src/agent-session-config.ts +137 -0
- package/src/agent-session.ts +440 -934
- package/src/agent.ts +168 -0
- package/src/capabilities.ts +2 -0
- package/src/checkpointing/recovery.ts +3 -0
- package/src/cli/index.ts +3 -3
- package/src/cli/managed.ts +2 -2
- package/src/client.ts +56 -96
- package/src/connection-attempt.ts +95 -0
- package/src/controller-connection.ts +115 -0
- package/src/controller.ts +158 -148
- package/src/conversation-controller/capabilities.ts +88 -0
- package/src/conversation-controller/contracts.ts +208 -0
- package/src/conversation-controller/factory.ts +39 -0
- package/src/conversation-controller/guards.ts +98 -0
- package/src/conversation-controller/index.ts +20 -0
- package/src/conversation-startup.ts +35 -0
- package/src/conversation-turns/backend-turns.ts +373 -0
- package/src/conversation-turns/clear-operations.ts +37 -0
- package/src/conversation-turns/context.ts +135 -0
- package/src/conversation-turns/index.ts +4 -0
- package/src/conversation-turns/record-helpers.ts +75 -0
- package/src/conversation-turns/recording.ts +235 -0
- package/src/conversation-turns/run-turn.ts +367 -0
- package/src/conversation-turns/turn-run.ts +57 -0
- package/src/errors.ts +41 -0
- package/src/handoff-options.ts +81 -0
- package/src/identity/checkpoint-backed.ts +1 -1
- package/src/index.ts +59 -3
- package/src/internal-inference/coordination/manager.ts +11 -0
- package/src/internal-inference/runtime/harness-runtime.ts +4 -4
- package/src/launcher.ts +37 -2
- package/src/media/parts.ts +5 -0
- package/src/message-status.ts +83 -0
- package/src/metering/engine.ts +39 -64
- package/src/metering/measurement-provenance.ts +36 -0
- package/src/metering/native/durability.ts +115 -0
- package/src/metering/native/ledger.ts +104 -0
- package/src/metering/native/operation.ts +85 -0
- package/src/metering/native/projection.ts +114 -0
- package/src/metering/native/proof.ts +51 -0
- package/src/metering/native/requirements.ts +10 -0
- package/src/metering/native/retirement.ts +92 -0
- package/src/metering/native/source.ts +90 -0
- package/src/metering/record.ts +38 -1
- package/src/metering/state.ts +13 -3
- package/src/native/approvals.ts +186 -0
- package/src/native/capabilities.ts +17 -0
- package/src/native/channel-changes.ts +211 -0
- package/src/native/connection.ts +56 -0
- package/src/native/controller.ts +592 -0
- package/src/native/delegation-sender.ts +26 -0
- package/src/native/errors.ts +35 -0
- package/src/native/functions.ts +156 -0
- package/src/native/host-config.ts +59 -0
- package/src/native/host.ts +978 -0
- package/src/native/item-receipts.ts +15 -0
- package/src/native/metering.ts +12 -0
- package/src/native/records.ts +166 -0
- package/src/native/recovery.ts +186 -0
- package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
- package/src/native/reminders/idle.ts +70 -0
- package/src/native/reminders/limits.ts +19 -0
- package/src/native/reminders/notifications.ts +29 -0
- package/src/native/reminders/routine-guard.ts +66 -0
- package/src/native/reminders/routine-schedule.ts +25 -0
- package/src/native/reminders/routine-wire.ts +21 -0
- package/src/native/reminders/schedule.ts +97 -0
- package/src/native/reminders/service.ts +280 -0
- package/src/native/reminders/supervisor.ts +91 -0
- package/src/native/reminders/sync.ts +301 -0
- package/src/native/reminders/wire.ts +197 -0
- package/src/native/submission-withdrawal.ts +65 -0
- package/src/native/usage.ts +15 -0
- package/src/native/worker-delivery.ts +61 -0
- package/src/native-harness/README.md +726 -0
- package/src/native-harness/package.json +24 -0
- package/src/native-harness/scripts/build-routine-zones.py +47 -0
- package/src/native-harness/src/capabilities/context/build.ts +59 -0
- package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
- package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
- package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
- package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
- package/src/native-harness/src/capabilities/context/session.ts +93 -0
- package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
- package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
- package/src/native-harness/src/capabilities/model/runner.ts +116 -0
- package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
- package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
- package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
- package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
- package/src/native-harness/src/capabilities/model/usage.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
- package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
- package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
- package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
- package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
- package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
- package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
- package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
- package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
- package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
- package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
- package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
- package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
- package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
- package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
- package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
- package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
- package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
- package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
- package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
- package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
- package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
- package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
- package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
- package/src/native-harness/src/client.ts +18 -0
- package/src/native-harness/src/contracts/agent.ts +105 -0
- package/src/native-harness/src/contracts/config-permissions.ts +49 -0
- package/src/native-harness/src/contracts/context.ts +112 -0
- package/src/native-harness/src/contracts/events.ts +47 -0
- package/src/native-harness/src/contracts/input-limits.ts +7 -0
- package/src/native-harness/src/contracts/inspection.ts +22 -0
- package/src/native-harness/src/contracts/loop.ts +31 -0
- package/src/native-harness/src/contracts/model-execution.ts +83 -0
- package/src/native-harness/src/contracts/operator-controls.ts +106 -0
- package/src/native-harness/src/contracts/output.ts +13 -0
- package/src/native-harness/src/contracts/protocol.ts +320 -0
- package/src/native-harness/src/contracts/reminders.ts +134 -0
- package/src/native-harness/src/contracts/routines.ts +20 -0
- package/src/native-harness/src/contracts/scenario.ts +42 -0
- package/src/native-harness/src/contracts/session-file.ts +20 -0
- package/src/native-harness/src/contracts/session.ts +184 -0
- package/src/native-harness/src/contracts/storage.ts +597 -0
- package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
- package/src/native-harness/src/contracts/tools.ts +133 -0
- package/src/native-harness/src/governance/permissions/gate.ts +129 -0
- package/src/native-harness/src/governance/policy/resolve.ts +32 -0
- package/src/native-harness/src/index.ts +322 -0
- package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
- package/src/native-harness/src/interfaces/cli/development.ts +145 -0
- package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
- package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
- package/src/native-harness/src/interfaces/cli/main.ts +47 -0
- package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
- package/src/native-harness/src/interfaces/cli/start.ts +106 -0
- package/src/native-harness/src/interfaces/client.ts +225 -0
- package/src/native-harness/src/interfaces/inspector/index.html +283 -0
- package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
- package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
- package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
- package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
- package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
- package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
- package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
- package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
- package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
- package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
- package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
- package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
- package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
- package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
- package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
- package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
- package/src/native-harness/src/kernel/channels.ts +409 -0
- package/src/native-harness/src/kernel/loop.ts +45 -0
- package/src/native-harness/src/runtime/config/development.ts +23 -0
- package/src/native-harness/src/runtime/config/managed.ts +2 -0
- package/src/native-harness/src/runtime/config/paths.ts +33 -0
- package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
- package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
- package/src/native-harness/src/runtime/reminders.ts +66 -0
- package/src/native-harness/src/state/storage/archive.ts +257 -0
- package/src/native-harness/src/state/storage/engine.ts +1204 -0
- package/src/native-harness/src/state/storage/inference.ts +124 -0
- package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
- package/src/native-harness/src/state/storage/memory.ts +354 -0
- package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
- package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
- package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
- package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
- package/src/native-harness/src/state/storage/retrieval.ts +122 -0
- package/src/native-harness/src/state/storage/routine-row.ts +25 -0
- package/src/native-harness/src/state/storage/script-identity.ts +7 -0
- package/src/native-harness/src/state/storage/session-file.ts +85 -0
- package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
- package/src/native-harness/src/state/storage/sqlite.ts +632 -0
- package/src/native-harness/src/testing.ts +190 -0
- package/src/native-harness/src/util/config.ts +66 -0
- package/src/native-harness/src/util/intake.ts +7 -0
- package/src/native-harness/src/util/json.ts +41 -0
- package/src/native-harness/src/util/message-position.ts +3 -0
- package/src/native-harness/src/util/reminder-schedule.ts +44 -0
- package/src/native-harness/src/util/schema.ts +40 -0
- package/src/native-harness/src/util/timeline-text.ts +72 -0
- package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
- package/src/native-harness/tsconfig.json +20 -0
- package/src/observation/agent-event-bus.ts +44 -18
- package/src/observation/index.ts +1 -0
- package/src/operations/contracts.ts +11 -3
- package/src/operations/errors.ts +5 -0
- package/src/operations/stale-policy.ts +1 -1
- package/src/operations/supervisor.ts +34 -10
- package/src/orchestrator/acp-delivery.ts +68 -0
- package/src/orchestrator/assignments.ts +27 -0
- package/src/orchestrator/busy.ts +15 -0
- package/src/orchestrator/config.ts +41 -0
- package/src/orchestrator/consumer-api.ts +24 -0
- package/src/orchestrator/contracts.ts +71 -0
- package/src/orchestrator/durable-assignments.ts +111 -0
- package/src/orchestrator/native-delegation.ts +103 -0
- package/src/orchestrator/orchestrator.ts +318 -0
- package/src/orchestrator/permissions.ts +28 -0
- package/src/orchestrator/policy.ts +44 -0
- package/src/orchestrator/pool.ts +123 -0
- package/src/orchestrator/tool-descriptions.ts +11 -0
- package/src/permissions/acp.ts +18 -0
- package/src/permissions/arrival.ts +13 -0
- package/src/permissions/consumer-config.ts +19 -0
- package/src/permissions/conversation.ts +288 -0
- package/src/permissions/matcher.ts +87 -0
- package/src/permissions/outcome.ts +26 -0
- package/src/permissions/policy.ts +86 -0
- package/src/permissions/request.ts +26 -0
- package/src/persistence/activity-projection.ts +1 -0
- package/src/persistence/backend.ts +34 -1
- package/src/persistence/channels.ts +23 -0
- package/src/persistence/index.ts +4 -0
- package/src/persistence/protocol-method.ts +5 -0
- package/src/persistence/reminder-wake.ts +49 -0
- package/src/persistence/reminders.ts +385 -0
- package/src/persistence/sqlite-backend.ts +84 -6
- package/src/persistence/sqlite-channels.ts +65 -0
- package/src/persistence/sqlite-reminders.ts +85 -0
- package/src/persistence/sqlite-schema.ts +108 -3
- package/src/persistence/sqlite-worker-delivery.ts +374 -0
- package/src/persistence/sqlite-workers.ts +59 -0
- package/src/persistence/worker-delivery-contract.ts +104 -0
- package/src/persistence/worker-terminal-reason.ts +29 -0
- package/src/persistence/workers.ts +19 -0
- package/src/provider-notices.ts +137 -0
- package/src/repl/commands.ts +2 -2
- package/src/steering/combine.ts +3 -1
- package/src/steering/contracts.ts +11 -2
- package/src/steering/controller.ts +3 -2
- package/src/terminals.ts +9 -6
- package/src/transport/acp-transport.ts +24 -14
- package/src/types.ts +15 -12
- package/src/updates.ts +14 -2
- package/src/wire-log.ts +1 -1
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { ContextLimits, ContextTurnOutcome, InferenceRead, InferenceStorageReads } from "../../contracts/context.ts";
|
|
2
|
+
import type { TimelineEntry } from "../../contracts/storage.ts";
|
|
3
|
+
|
|
4
|
+
/** Charge the serialized message, the UTF-8 bytes of variable entry fields,
|
|
5
|
+
* and a fixed allowance for scalar fields and record framing. */
|
|
6
|
+
export const entryOverhead = 128;
|
|
7
|
+
export const byteLength = (value: string) => Buffer.byteLength(value, "utf8");
|
|
8
|
+
|
|
9
|
+
export interface ContextRow {
|
|
10
|
+
seq: number;
|
|
11
|
+
bytes: number;
|
|
12
|
+
textBytes?: number;
|
|
13
|
+
kind: "input" | "assistant" | "other";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ContextRows {
|
|
17
|
+
contextTurnStart(channelId: string, turnId: number): number | undefined;
|
|
18
|
+
contextTrigger(turnId: number): ContextRow | undefined;
|
|
19
|
+
contextPreviousResponse(turnId: number): number;
|
|
20
|
+
contextInputs(turnId: number, after: number, limit: number): ContextRow[];
|
|
21
|
+
contextActive(turnId: number, limit: number): ContextRow[];
|
|
22
|
+
contextLocal(channelId: string, before: number, limit: number): ContextRow[];
|
|
23
|
+
contextRecent(before: number, limit: number, legacy?: boolean): ContextRow[];
|
|
24
|
+
contextShared(channelId: string, candidates: number): ContextRow[];
|
|
25
|
+
contextPolicies(turnId: number, limit: number, bytes: number): { names: string[]; bytes: number } | undefined;
|
|
26
|
+
contextUnfinished(turnId: number, maxBytes: number): { outcome: ContextTurnOutcome; bytes: number } | undefined;
|
|
27
|
+
contextEntry(seq: number): TimelineEntry;
|
|
28
|
+
contextHistoricalEntry(seq: number): TimelineEntry;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function validReadLimits(limits: ContextLimits): boolean {
|
|
32
|
+
return [limits.maxReadRecords, limits.maxReadBytes, limits.maxSharedCandidates, limits.maxInputBytes, limits.maxTakenTextBytes, limits.maxTakenItems]
|
|
33
|
+
.every(n => Number.isSafeInteger(n) && n > 0 && n < Number.MAX_SAFE_INTEGER);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Every adapter supplies headers first. Only rows charged to the same budget
|
|
37
|
+
* can cross the body-read boundary, including rows discarded after validation. */
|
|
38
|
+
export function readInference(rows: ContextRows, input: Parameters<InferenceStorageReads["readInferenceContext"]>[0],
|
|
39
|
+
turnStart: number): InferenceRead | { code: "context_limit" } {
|
|
40
|
+
const { channelId, turnId, limits } = input;
|
|
41
|
+
const { maxReadRecords, maxReadBytes, maxSharedCandidates } = limits;
|
|
42
|
+
const overflow = { code: "context_limit" } as const;
|
|
43
|
+
const trigger = rows.contextTrigger(turnId);
|
|
44
|
+
const taken = rows.contextInputs(turnId, rows.contextPreviousResponse(turnId), maxReadRecords + 1);
|
|
45
|
+
if (taken.length > limits.maxTakenItems ||
|
|
46
|
+
taken.reduce((total, row) => total + (row.textBytes ?? 0), 0) > limits.maxTakenTextBytes ||
|
|
47
|
+
(trigger?.textBytes ?? 0) > limits.maxInputBytes || taken.some(row => (row.textBytes ?? 0) > limits.maxInputBytes)) return overflow;
|
|
48
|
+
const requiredRows = trigger && trigger.seq !== taken[0]?.seq ? [trigger, ...taken] : taken;
|
|
49
|
+
const requiredBytes = requiredRows.reduce((total, row) => total + row.bytes, 0);
|
|
50
|
+
if (requiredRows.length > maxReadRecords || requiredBytes > maxReadBytes) return overflow;
|
|
51
|
+
const policies = rows.contextPolicies(turnId, maxReadRecords, maxReadBytes - requiredBytes);
|
|
52
|
+
if (!policies) return overflow;
|
|
53
|
+
|
|
54
|
+
let records = maxReadRecords - requiredRows.length;
|
|
55
|
+
let bytes = maxReadBytes - requiredBytes - policies.bytes;
|
|
56
|
+
function charge(group: readonly ContextRow[], reserveRecords = 0, reserveBytes = 0) {
|
|
57
|
+
const cost = group.reduce((total, row) => total + row.bytes, 0);
|
|
58
|
+
if (group.length > records - reserveRecords || cost > bytes - reserveBytes) return false;
|
|
59
|
+
records -= group.length;
|
|
60
|
+
bytes -= cost;
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
const required = requiredRows.map(row => rows.contextEntry(row.seq));
|
|
64
|
+
const takenItemIds = required.slice(required.length - taken.length).map(entry => entry.itemId!);
|
|
65
|
+
const requiredSeqs = new Set(requiredRows.map(row => row.seq));
|
|
66
|
+
|
|
67
|
+
// The newest bounded suffix can start with orphaned tool results. Start a
|
|
68
|
+
// group only at an assistant row and verify its entire result set after load.
|
|
69
|
+
const groups: ContextRow[][] = [];
|
|
70
|
+
let exchange: ContextRow[] | undefined;
|
|
71
|
+
if (records && bytes) for (const row of rows.contextActive(turnId, maxReadRecords).reverse()) {
|
|
72
|
+
if (row.kind === "assistant") { exchange = [row]; groups.push(exchange); }
|
|
73
|
+
else if (row.kind === "other") exchange?.push(row);
|
|
74
|
+
else if (!requiredSeqs.has(row.seq)) groups.push([row]);
|
|
75
|
+
}
|
|
76
|
+
const optionalTurn: TimelineEntry[] = [];
|
|
77
|
+
for (const group of groups.reverse()) {
|
|
78
|
+
if (!charge(group)) continue;
|
|
79
|
+
const entries = group.map(row => rows.contextEntry(row.seq));
|
|
80
|
+
const first = entries[0]!.message;
|
|
81
|
+
if (first.role === "assistant") {
|
|
82
|
+
const results = new Set(entries.slice(1).flatMap(({ message }) => message.role === "tool" ? [message.callId] : []));
|
|
83
|
+
if (results.size !== entries.length - 1 || results.size !== first.calls.length || first.calls.some(call => !results.has(call.id))) continue;
|
|
84
|
+
}
|
|
85
|
+
optionalTurn.push(...entries);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const localHistory: TimelineEntry[] = [], sharedHistory: TimelineEntry[] = [];
|
|
89
|
+
if (records && bytes) {
|
|
90
|
+
const local = rows.contextLocal(channelId, turnStart, maxReadRecords);
|
|
91
|
+
const shared = rows.contextShared(channelId, maxSharedCandidates).slice(0, maxReadRecords);
|
|
92
|
+
// Reserve room for a recent shared exchange even when a long local
|
|
93
|
+
// transcript can fill every record slot. Return unused space to local.
|
|
94
|
+
let reserveRecords = 0, reserveBytes = 0;
|
|
95
|
+
const sharedSlots = records > 1 ? Math.max(1, Math.floor(records / 3)) : 0;
|
|
96
|
+
for (const row of shared) {
|
|
97
|
+
if (reserveRecords === sharedSlots) break;
|
|
98
|
+
if (reserveBytes + row.bytes > Math.floor(bytes / 3)) continue;
|
|
99
|
+
reserveRecords++;
|
|
100
|
+
reserveBytes += row.bytes;
|
|
101
|
+
}
|
|
102
|
+
const deferred: ContextRow[] = [];
|
|
103
|
+
for (const row of local) {
|
|
104
|
+
if (charge([row], reserveRecords, reserveBytes))
|
|
105
|
+
localHistory.push(rows.contextHistoricalEntry(row.seq));
|
|
106
|
+
else deferred.push(row);
|
|
107
|
+
}
|
|
108
|
+
for (const row of shared) if (charge([row])) sharedHistory.push(rows.contextHistoricalEntry(row.seq));
|
|
109
|
+
for (const row of deferred) if (charge([row])) localHistory.push(rows.contextHistoricalEntry(row.seq));
|
|
110
|
+
}
|
|
111
|
+
const unfinished: ContextTurnOutcome[] = [];
|
|
112
|
+
const historicalTurns = new Set([...localHistory, ...sharedHistory].sort((a, b) => b.seq - a.seq).map(row => row.turnId));
|
|
113
|
+
for (const id of historicalTurns) {
|
|
114
|
+
if (!records || !bytes) break;
|
|
115
|
+
const record = rows.contextUnfinished(id, bytes);
|
|
116
|
+
if (!record) continue;
|
|
117
|
+
bytes -= record.bytes;
|
|
118
|
+
records--;
|
|
119
|
+
unfinished.push(record.outcome);
|
|
120
|
+
}
|
|
121
|
+
const order = (a: TimelineEntry, b: TimelineEntry) => a.seq - b.seq;
|
|
122
|
+
return { required, optionalTurn: optionalTurn.sort(order), localHistory: localHistory.sort(order),
|
|
123
|
+
sharedHistory: sharedHistory.sort(order), unfinished, takenItemIds, policyNames: policies.names };
|
|
124
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { ReminderArchiveState, ReminderWake } from "../../contracts/reminders.ts";
|
|
2
|
+
import type { ReminderReceipt } from "./reminder-change.ts";
|
|
3
|
+
import type { ReminderRow, ReminderTables } from "./reminder-tables.ts";
|
|
4
|
+
|
|
5
|
+
export interface MemoryReminderState {
|
|
6
|
+
guardLimit?: number;
|
|
7
|
+
dispositions: NonNullable<ReminderArchiveState["dispositions"]>;
|
|
8
|
+
guardCounters: Map<string, number>;
|
|
9
|
+
rows: Map<string, ReminderRow>;
|
|
10
|
+
creates: Map<string, ReminderReceipt>;
|
|
11
|
+
receipts: Map<string, Map<number, ReminderReceipt>>;
|
|
12
|
+
highWater: Map<string, number>;
|
|
13
|
+
listingRevision: number;
|
|
14
|
+
wake: ReminderWake;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const emptyMemoryReminders = (): MemoryReminderState => ({
|
|
18
|
+
dispositions: [], guardCounters: new Map(), rows: new Map(), creates: new Map(), receipts: new Map(), highWater: new Map(), listingRevision: 0,
|
|
19
|
+
wake: { nextDueAt: null, reminderRevision: 0 },
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export function memoryReminderTables(
|
|
23
|
+
state: MemoryReminderState, log: (undo: () => void) => void, eligible: (channel: string) => boolean,
|
|
24
|
+
): ReminderTables {
|
|
25
|
+
function put<K, V>(map: Map<K, V>, key: K, value: V) {
|
|
26
|
+
const previous = map.get(key);
|
|
27
|
+
log(() => { if (previous === undefined) map.delete(key); else map.set(key, previous); });
|
|
28
|
+
map.set(key, structuredClone(value));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
activate() {},
|
|
33
|
+
recordDisposition(event) {
|
|
34
|
+
const length = state.dispositions.length;
|
|
35
|
+
log(() => { state.dispositions.length = length; });
|
|
36
|
+
state.dispositions.push(structuredClone(event));
|
|
37
|
+
},
|
|
38
|
+
activeRoutines: channel => [...state.rows.values()].filter(({ reminder }) => reminder.channel === channel && reminder.state === "active" && reminder.missedRuns !== undefined).length,
|
|
39
|
+
guardLimit: () => state.guardLimit,
|
|
40
|
+
bindGuard(limit) {
|
|
41
|
+
const previous = state.guardLimit;
|
|
42
|
+
log(() => { state.guardLimit = previous; });
|
|
43
|
+
state.guardLimit = limit;
|
|
44
|
+
},
|
|
45
|
+
guardSpent: channel => state.guardCounters.get(channel) ?? 0,
|
|
46
|
+
setGuardSpent: (channel, spent) => put(state.guardCounters, channel, spent),
|
|
47
|
+
archive() {
|
|
48
|
+
return JSON.parse(JSON.stringify({ rows: [...state.rows.values()], receipts: [...state.receipts.values()].flatMap(rows => [...rows.values()]),
|
|
49
|
+
...(state.dispositions.length ? { dispositions: state.dispositions } : {}),
|
|
50
|
+
...(state.guardLimit === undefined ? {} : { guard: { limit: state.guardLimit,
|
|
51
|
+
counters: [...state.guardCounters].map(([channel, spent]) => ({ channel, spent })) } }),
|
|
52
|
+
listingRevision: state.listingRevision, wake: state.wake }));
|
|
53
|
+
},
|
|
54
|
+
restore(saved) {
|
|
55
|
+
for (const disposition of saved.dispositions ?? []) this.recordDisposition(disposition);
|
|
56
|
+
if (saved.guard) {
|
|
57
|
+
this.bindGuard(saved.guard.limit);
|
|
58
|
+
for (const { channel, spent } of saved.guard.counters) this.setGuardSpent(channel, spent);
|
|
59
|
+
}
|
|
60
|
+
for (const row of saved.rows) this.put(row);
|
|
61
|
+
for (const receipt of saved.receipts) this.saveReceipt(receipt);
|
|
62
|
+
this.setWake(saved.wake);
|
|
63
|
+
const before = state.listingRevision;
|
|
64
|
+
log(() => { state.listingRevision = before; });
|
|
65
|
+
state.listingRevision = saved.listingRevision;
|
|
66
|
+
},
|
|
67
|
+
get: id => structuredClone(state.rows.get(id)),
|
|
68
|
+
put(row) {
|
|
69
|
+
put(state.rows, row.reminder.id, row);
|
|
70
|
+
const before = state.listingRevision++;
|
|
71
|
+
log(() => { state.listingRevision = before; });
|
|
72
|
+
},
|
|
73
|
+
originalCreate: id => structuredClone(state.creates.get(id)),
|
|
74
|
+
receipt: (id, version) => structuredClone(state.receipts.get(id)?.get(version)),
|
|
75
|
+
highWater: id => state.highWater.get(id) ?? 0,
|
|
76
|
+
saveReceipt(receipt) {
|
|
77
|
+
const { reminderId, changeId } = receipt.result;
|
|
78
|
+
if (receipt.fingerprint.startsWith('["create",') && !state.creates.has(reminderId)) put(state.creates, reminderId, receipt);
|
|
79
|
+
const existing = state.receipts.get(reminderId);
|
|
80
|
+
if (existing) put(existing, changeId, receipt);
|
|
81
|
+
else put(state.receipts, reminderId, new Map([[changeId, receipt]]));
|
|
82
|
+
put(state.highWater, reminderId, Math.max(state.highWater.get(reminderId) ?? 0, changeId));
|
|
83
|
+
},
|
|
84
|
+
list: (channel, after, limit) => structuredClone([...state.rows.values()]
|
|
85
|
+
.filter(row => row.sequence > after && (channel === undefined || row.reminder.channel === channel))
|
|
86
|
+
.slice(0, limit)),
|
|
87
|
+
blocked: (channel, after, limit) => structuredClone([...state.rows.values()]
|
|
88
|
+
.filter(row => row.sequence > after && row.reminder.state === "blocked" && row.reminder.blockedReason === "invalid_policy"
|
|
89
|
+
&& (channel === undefined || row.reminder.channel === channel))
|
|
90
|
+
.slice(0, limit)),
|
|
91
|
+
eligible: (through, limit, heldChannels = []) => structuredClone([...state.rows.values()]
|
|
92
|
+
.filter(({ reminder }) => reminder.nextRunAt !== null && (through === null || reminder.nextRunAt <= through) && eligible(reminder.channel) && (reminder.missedRuns === undefined || !heldChannels.includes(reminder.channel)))
|
|
93
|
+
.sort((a, b) => a.reminder.nextRunAt!.localeCompare(b.reminder.nextRunAt!) || a.sequence - b.sequence)
|
|
94
|
+
.slice(0, limit)),
|
|
95
|
+
listingRevision: () => state.listingRevision,
|
|
96
|
+
wake: () => structuredClone(state.wake),
|
|
97
|
+
setWake(wake) {
|
|
98
|
+
const before = state.wake;
|
|
99
|
+
log(() => { state.wake = before; });
|
|
100
|
+
state.wake = structuredClone(wake);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
import { bindUnattendedGuard, checkUnattendedGuard } from "./engine.ts";
|
|
2
|
+
import { emptyMemoryReminders, memoryReminderTables, type MemoryReminderState } from "./memory-reminders.ts";
|
|
3
|
+
import { historicalCandidate, historicalRetrievalProjection, retrievalMessage, timelineTokens, timelineBytes } from "../../util/timeline-text.ts";
|
|
4
|
+
import { byteLength, entryOverhead, type ContextRow } from "./inference.ts";
|
|
5
|
+
import { checkScriptIdentity } from "./script-identity.ts";
|
|
6
|
+
import type { SessionStorageAdapter, StoredItem, TimelineEntry } from "../../contracts/storage.ts";
|
|
7
|
+
import { Fail, createEngine, failure, recover, referencesCompatible, type ChannelRow, type Meta, type Tables, type TurnRow, type ModelState } from "./engine.ts";
|
|
8
|
+
import { archiveMeta, restoreArchive, storedSession, validateArchive, validateSessionPayload } from "./archive.ts";
|
|
9
|
+
import { validateManagedConfig } from "../../util/config.ts";
|
|
10
|
+
|
|
11
|
+
type ContextEntry = ContextRow & { entry: TimelineEntry };
|
|
12
|
+
|
|
13
|
+
interface Data {
|
|
14
|
+
reminders: MemoryReminderState;
|
|
15
|
+
bySeq: Map<number, ContextEntry>;
|
|
16
|
+
retrievalReplies: Map<string, number>;
|
|
17
|
+
historicalCandidates: TimelineEntry[];
|
|
18
|
+
retrievalCalls: Map<number, Set<string>>;
|
|
19
|
+
retrievalIndex: Map<number, { bytes: number; words: Set<string> }>;
|
|
20
|
+
byTurn: Map<number, ContextEntry[]>;
|
|
21
|
+
inputs: Map<number, ContextEntry[]>;
|
|
22
|
+
assistants: Map<number, ContextEntry[]>;
|
|
23
|
+
turnPolicies: Map<number, Set<string>>;
|
|
24
|
+
revokedTools?: string[];
|
|
25
|
+
modelState?: ModelState;
|
|
26
|
+
config?: import("../../contracts/session-file.ts").PortableSessionConfig;
|
|
27
|
+
meta: Meta;
|
|
28
|
+
channels: Map<string, ChannelRow>; participants: Set<string>;
|
|
29
|
+
items: Map<string, StoredItem>; turns: Map<number, TurnRow>; entries: TimelineEntry[]; conversation: Map<string, TimelineEntry[]>; replies: Map<number, TimelineEntry[]>;
|
|
30
|
+
}
|
|
31
|
+
const empty = (meta: Meta): Data => ({ meta, reminders: emptyMemoryReminders(), channels: new Map(), participants: new Set(), items: new Map(), turns: new Map(), entries: [], bySeq: new Map(), retrievalReplies: new Map(), retrievalIndex: new Map(), historicalCandidates: [], retrievalCalls: new Map(), byTurn: new Map(), inputs: new Map(), assistants: new Map(), turnPolicies: new Map(), conversation: new Map(), replies: new Map() });
|
|
32
|
+
const copy = <T>(value: T): T => structuredClone(value);
|
|
33
|
+
const live = (turn: TurnRow) => turn.state.status === "running" || turn.state.status === "suspended";
|
|
34
|
+
|
|
35
|
+
/** Rows in maps. Each write records how to undo itself, so a throwing
|
|
36
|
+
* transaction leaves no partial change without copying the whole session. */
|
|
37
|
+
function memoryTables(data: Data): Tables {
|
|
38
|
+
let undo: (() => void)[] | undefined;
|
|
39
|
+
const log = (step: () => void) => { undo?.push(step); };
|
|
40
|
+
const before = (rows: readonly { seq: number }[], seq: number) => {
|
|
41
|
+
let low = 0, high = rows.length;
|
|
42
|
+
while (low < high) {
|
|
43
|
+
const mid = (low + high) >>> 1;
|
|
44
|
+
if (rows[mid]!.seq < seq) low = mid + 1; else high = mid;
|
|
45
|
+
}
|
|
46
|
+
return low;
|
|
47
|
+
};
|
|
48
|
+
const recent = <T>(rows: T[], limit: number, end = rows.length) => rows.slice(Math.max(0, end - limit), end).reverse();
|
|
49
|
+
const header = ({ seq, bytes, kind, entry }: ContextEntry): ContextRow => ({
|
|
50
|
+
seq, ...(entry.itemId === undefined ? {} : { textBytes: byteLength(data.items.get(entry.itemId)?.text ?? "") }),
|
|
51
|
+
bytes: bytes + byteLength(data.modelState?.entryIds[String(seq)] ?? entry.messageId ?? ""), kind,
|
|
52
|
+
});
|
|
53
|
+
const historicalHeader = (row: ContextEntry): ContextRow => {
|
|
54
|
+
const base = header(row), projected = historicalRetrievalProjection(row.entry.message);
|
|
55
|
+
return projected === row.entry.message ? base : { ...base,
|
|
56
|
+
bytes: base.bytes - byteLength(JSON.stringify(row.entry.message)) + byteLength(JSON.stringify(projected)) };
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
reminders: memoryReminderTables(data.reminders, log, channel => data.channels.get(channel)?.lifecycle === "open"),
|
|
60
|
+
contextTurnStart(channelId, turnId) {
|
|
61
|
+
const turn = data.turns.get(turnId);
|
|
62
|
+
return turn?.channelId === channelId ? turn.startedSeq : undefined;
|
|
63
|
+
},
|
|
64
|
+
contextTrigger(turnId) {
|
|
65
|
+
const first = data.inputs.get(turnId)?.[0];
|
|
66
|
+
return first && header(first);
|
|
67
|
+
},
|
|
68
|
+
contextPreviousResponse: turnId => data.assistants.get(turnId)?.at(-1)?.seq ?? 0,
|
|
69
|
+
contextInputs(turnId, after, limit) {
|
|
70
|
+
const rows = data.inputs.get(turnId) ?? [];
|
|
71
|
+
const start = before(rows, after + 1);
|
|
72
|
+
return rows.slice(start, start + limit).map(header);
|
|
73
|
+
},
|
|
74
|
+
contextActive: (turnId, limit) => recent(data.byTurn.get(turnId) ?? [], limit).map(header),
|
|
75
|
+
contextLocal(channelId, start, limit) {
|
|
76
|
+
const rows = data.conversation.get(channelId) ?? [];
|
|
77
|
+
return recent(rows, limit, before(rows, start)).map(row => historicalHeader(data.bySeq.get(row.seq)!));
|
|
78
|
+
},
|
|
79
|
+
contextRecent(cursor, limit) {
|
|
80
|
+
return recent(data.entries, limit, before(data.entries, cursor)).map(row => header(data.bySeq.get(row.seq)!));
|
|
81
|
+
},
|
|
82
|
+
contextShared(channelId, limit) {
|
|
83
|
+
return recent(data.historicalCandidates, limit).filter(row => row.channelId !== channelId &&
|
|
84
|
+
(row.kind === "participant_message" || (row.message.role === "assistant" && !!row.message.content)))
|
|
85
|
+
.map(row => historicalHeader(data.bySeq.get(row.seq)!));
|
|
86
|
+
},
|
|
87
|
+
contextPolicies(turnId, limit, budget) {
|
|
88
|
+
const names = data.turnPolicies.get(turnId);
|
|
89
|
+
if (!names) return { names: [], bytes: 0 };
|
|
90
|
+
if (names.size > limit) return undefined;
|
|
91
|
+
let bytes = 0;
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
bytes += byteLength(name) + 1;
|
|
94
|
+
if (bytes > budget) return undefined;
|
|
95
|
+
}
|
|
96
|
+
return { names: [...names].sort(), bytes };
|
|
97
|
+
},
|
|
98
|
+
contextUnfinished(turnId, budget) {
|
|
99
|
+
const turn = data.turns.get(turnId);
|
|
100
|
+
if (!turn || (turn.state.status !== "failed" && turn.state.status !== "interrupted")) return undefined;
|
|
101
|
+
const { channelId, state } = turn;
|
|
102
|
+
const bytes = entryOverhead + byteLength(channelId) + byteLength(JSON.stringify(state));
|
|
103
|
+
return bytes <= budget ? { outcome: { channelId, turnId, state }, bytes } : undefined;
|
|
104
|
+
},
|
|
105
|
+
retrievalCandidates(terms, channel, limit) {
|
|
106
|
+
const rows: { seq: number; bytes: number }[] = [];
|
|
107
|
+
const entries = channel === undefined ? data.entries : data.conversation.get(channel) ?? [];
|
|
108
|
+
for (let i = entries.length - 1; i >= 0 && rows.length < limit; i--) {
|
|
109
|
+
const seq = entries[i]!.seq, indexed = data.retrievalIndex.get(seq);
|
|
110
|
+
if (indexed && terms.every(term => indexed.words.has(term))) rows.push({ seq, bytes: indexed.bytes });
|
|
111
|
+
}
|
|
112
|
+
return rows;
|
|
113
|
+
},
|
|
114
|
+
retrievalEntry(seq) {
|
|
115
|
+
const entry = data.bySeq.get(seq)?.entry;
|
|
116
|
+
if (!entry) return;
|
|
117
|
+
const messageId = data.modelState?.entryIds[String(seq)] ?? entry.messageId;
|
|
118
|
+
return copy(messageId === undefined ? entry : { ...entry, messageId });
|
|
119
|
+
},
|
|
120
|
+
retrievalReplyId: id => data.retrievalReplies.get(id),
|
|
121
|
+
contextHistoricalEntry(seq) {
|
|
122
|
+
const saved = this.contextEntry(seq);
|
|
123
|
+
return { ...saved, message: historicalRetrievalProjection(saved.message) };
|
|
124
|
+
},
|
|
125
|
+
contextEntry(seq) {
|
|
126
|
+
const entry = data.bySeq.get(seq)!.entry;
|
|
127
|
+
const messageId = data.modelState?.entryIds[String(seq)] ?? entry.messageId;
|
|
128
|
+
// The engine detaches the selected values at the transaction boundary.
|
|
129
|
+
return messageId ? { ...entry, messageId } : entry;
|
|
130
|
+
},
|
|
131
|
+
modelCallPage(after, count) {
|
|
132
|
+
const calls = data.modelState?.calls ?? [];
|
|
133
|
+
if (after === undefined) return copy(calls.slice(0, count));
|
|
134
|
+
let lo = 0, hi = calls.length;
|
|
135
|
+
while (lo < hi) {
|
|
136
|
+
const mid = Math.floor((lo + hi) / 2);
|
|
137
|
+
if (Number(calls[mid]!.callId) < Number(after)) lo = mid + 1;
|
|
138
|
+
else hi = mid;
|
|
139
|
+
}
|
|
140
|
+
if (calls[lo]?.callId !== after) throw new Fail("not_found", "Unknown call cursor");
|
|
141
|
+
return copy(calls.slice(lo + 1, lo + 1 + count));
|
|
142
|
+
},
|
|
143
|
+
getModelState: () => copy(data.modelState),
|
|
144
|
+
setModelState(state) { const old = data.modelState; log(() => { data.modelState = old; }); data.modelState = copy(state); },
|
|
145
|
+
getRevokedTools: () => copy(data.revokedTools),
|
|
146
|
+
setRevokedTools(names) { const old = data.revokedTools; log(() => { data.revokedTools = old; }); data.revokedTools = [...names]; },
|
|
147
|
+
getConfig: () => copy(data.config),
|
|
148
|
+
setConfig(config) { const old = data.config; log(() => { data.config = old; }); data.config = copy(config); },
|
|
149
|
+
transaction(run) {
|
|
150
|
+
if (undo) return run();
|
|
151
|
+
undo = [];
|
|
152
|
+
try { return run(); }
|
|
153
|
+
catch (error) { for (const step of undo.reverse()) step(); throw error; }
|
|
154
|
+
finally { undo = undefined; }
|
|
155
|
+
},
|
|
156
|
+
getMeta: () => ({ ...data.meta }),
|
|
157
|
+
setMeta(meta) { const old = data.meta; log(() => { data.meta = old; }); data.meta = { ...meta }; },
|
|
158
|
+
channel: id => copy(data.channels.get(id)),
|
|
159
|
+
putChannel(channel) {
|
|
160
|
+
const old = data.channels.get(channel.channelId);
|
|
161
|
+
log(() => { if (old) data.channels.set(channel.channelId, old); else data.channels.delete(channel.channelId); });
|
|
162
|
+
data.channels.set(channel.channelId, copy(channel));
|
|
163
|
+
},
|
|
164
|
+
channels: () => copy([...data.channels.values()]),
|
|
165
|
+
addParticipant(id) { if (!data.participants.has(id)) { data.participants.add(id); log(() => data.participants.delete(id)); } },
|
|
166
|
+
participants: () => [...data.participants],
|
|
167
|
+
item: id => copy(data.items.get(id)),
|
|
168
|
+
putItem(item) {
|
|
169
|
+
const old = data.items.get(item.itemId);
|
|
170
|
+
log(() => { if (old) data.items.set(item.itemId, old); else data.items.delete(item.itemId); });
|
|
171
|
+
data.items.set(item.itemId, copy(item));
|
|
172
|
+
if (old?.turnId !== undefined || item.turnId === undefined) return;
|
|
173
|
+
const turnId = item.turnId;
|
|
174
|
+
let names = data.turnPolicies.get(turnId);
|
|
175
|
+
if (!names) {
|
|
176
|
+
names = new Set();
|
|
177
|
+
data.turnPolicies.set(turnId, names);
|
|
178
|
+
log(() => { data.turnPolicies.delete(turnId); });
|
|
179
|
+
}
|
|
180
|
+
const policy = item.policy;
|
|
181
|
+
for (const name of policy ? [policy.resolved, ...policy.inherited] : ["__legacy_allow"]) {
|
|
182
|
+
if (names.has(name)) continue;
|
|
183
|
+
const namesForUndo = names;
|
|
184
|
+
names.add(name);
|
|
185
|
+
log(() => { namesForUndo.delete(name); });
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
hasOpenRoutineNotice: (channelId, source) => [...data.items.values()].some(item => {
|
|
189
|
+
if (item.channelId !== channelId || item.externalSource !== source || item.kind !== "external_notice") return false;
|
|
190
|
+
const status = item.turnId === undefined ? undefined : data.turns.get(item.turnId)?.state.status;
|
|
191
|
+
return item.milestone === "received" || status === "running" || status === "suspended";
|
|
192
|
+
}),
|
|
193
|
+
pendingItems: (channelId, limit) => copy([...data.items.values()].filter(item => item.channelId === channelId && item.milestone === "received")
|
|
194
|
+
.sort((a, b) => a.acceptedSeq - b.acceptedSeq).slice(0, limit ?? Infinity)),
|
|
195
|
+
itemsOfTurn: turnId => copy([...data.items.values()].filter(item => item.turnId === turnId).sort((a, b) => a.entrySeq! - b.entrySeq!)),
|
|
196
|
+
items: () => copy([...data.items.values()].sort((a, b) => a.acceptedSeq - b.acceptedSeq)),
|
|
197
|
+
turn: id => copy(data.turns.get(id)),
|
|
198
|
+
putTurn(turn) {
|
|
199
|
+
const old = data.turns.get(turn.turnId);
|
|
200
|
+
// Same invariant the SQLite schema enforces with a partial unique index.
|
|
201
|
+
if (live(turn)) for (const other of data.turns.values())
|
|
202
|
+
if (other.turnId !== turn.turnId && other.channelId === turn.channelId && live(other)) throw new Error("Channel already has a live turn");
|
|
203
|
+
log(() => { if (old) data.turns.set(turn.turnId, old); else data.turns.delete(turn.turnId); });
|
|
204
|
+
data.turns.set(turn.turnId, copy(turn));
|
|
205
|
+
},
|
|
206
|
+
liveTurn: channelId => copy([...data.turns.values()].find(turn => turn.channelId === channelId && live(turn))),
|
|
207
|
+
turns: () => copy([...data.turns.values()].sort((a, b) => a.turnId - b.turnId)),
|
|
208
|
+
latestTurn: id => copy([...data.turns.values()].findLast(turn => turn.channelId === id)),
|
|
209
|
+
liveTurns: () => copy([...data.turns.values()].filter(live)),
|
|
210
|
+
policyNames: () => [...new Set([...data.channels.values()].flatMap(channel => channel.policy ? [channel.policy] : [])
|
|
211
|
+
.concat([...data.items.values()].flatMap(item => item.policy ? [item.policy.resolved, ...item.policy.inherited] : ["__legacy_allow"])))],
|
|
212
|
+
pendingCount: id => [...data.items.values()].filter(item => item.channelId === id && item.milestone === "received").length,
|
|
213
|
+
readRange(range) {
|
|
214
|
+
const older = range.direction === "older";
|
|
215
|
+
const select = (rows: TimelineEntry[]) => {
|
|
216
|
+
const before = (seq: number) => older ? seq <= range.throughRevision && seq < (range.exclusiveSeq ?? Infinity) : seq <= (range.exclusiveSeq ?? 0);
|
|
217
|
+
let low = 0, high = rows.length;
|
|
218
|
+
while (low < high) {
|
|
219
|
+
const mid = (low + high) >>> 1;
|
|
220
|
+
if (before(rows[mid]!.seq)) low = mid + 1; else high = mid;
|
|
221
|
+
}
|
|
222
|
+
return older ? rows.slice(Math.max(0, low - range.limit - 1), low).reverse()
|
|
223
|
+
: rows.slice(low, low + range.limit + 1).filter(row => row.seq <= range.throughRevision);
|
|
224
|
+
};
|
|
225
|
+
const rows = range.kind === "conversation" ? select(data.conversation.get(range.channel!) ?? [])
|
|
226
|
+
: range.kind === "replies" ? (range.turnIds ?? []).flatMap(id => select(data.replies.get(id) ?? []))
|
|
227
|
+
.filter(row => row.channelId === range.channel).sort((a, b) => older ? b.seq - a.seq : a.seq - b.seq).slice(0, range.limit + 1)
|
|
228
|
+
: select(data.entries);
|
|
229
|
+
return copy(rows.map(row => {
|
|
230
|
+
const messageId = data.modelState?.entryIds[String(row.seq)];
|
|
231
|
+
return messageId ? { ...row, messageId } : row;
|
|
232
|
+
}));
|
|
233
|
+
},
|
|
234
|
+
addEntry(entry) {
|
|
235
|
+
const saved = copy(entry);
|
|
236
|
+
if (saved.messageId !== undefined) {
|
|
237
|
+
const id = saved.messageId;
|
|
238
|
+
data.retrievalReplies.set(id, saved.seq);
|
|
239
|
+
log(() => { data.retrievalReplies.delete(id); });
|
|
240
|
+
}
|
|
241
|
+
const append = <T>(rows: T[], row: T) => { rows.push(row); log(() => { rows.pop(); }); };
|
|
242
|
+
const indexed = <K, T>(index: Map<K, T[]>, key: K, row: T) => {
|
|
243
|
+
let rows = index.get(key);
|
|
244
|
+
if (!rows) { rows = []; index.set(key, rows); log(() => { index.delete(key); }); }
|
|
245
|
+
append(rows, row);
|
|
246
|
+
};
|
|
247
|
+
const searchable = retrievalMessage(saved);
|
|
248
|
+
if (searchable) {
|
|
249
|
+
data.retrievalIndex.set(saved.seq, { bytes: timelineBytes(searchable.text),
|
|
250
|
+
words: new Set(timelineTokens(searchable.text).map(word => word.folded)) });
|
|
251
|
+
log(() => { data.retrievalIndex.delete(saved.seq); });
|
|
252
|
+
}
|
|
253
|
+
if (historicalCandidate(saved.message, id => {
|
|
254
|
+
let calls = data.retrievalCalls.get(saved.turnId);
|
|
255
|
+
if (!calls) {
|
|
256
|
+
calls = new Set();
|
|
257
|
+
data.retrievalCalls.set(saved.turnId, calls);
|
|
258
|
+
log(() => { data.retrievalCalls.delete(saved.turnId); });
|
|
259
|
+
}
|
|
260
|
+
if (!calls.has(id)) {
|
|
261
|
+
const registered = calls;
|
|
262
|
+
registered.add(id);
|
|
263
|
+
log(() => { registered.delete(id); });
|
|
264
|
+
}
|
|
265
|
+
}, id => data.retrievalCalls.get(saved.turnId)?.has(id) ?? false)) append(data.historicalCandidates, saved);
|
|
266
|
+
append(data.entries, saved);
|
|
267
|
+
const kind = saved.message.role === "assistant" ? "assistant" : saved.itemId !== undefined ? "input" : "other";
|
|
268
|
+
const bytes = entryOverhead + byteLength(JSON.stringify(saved.message)) +
|
|
269
|
+
byteLength(saved.at) + byteLength(saved.channelId) + byteLength(saved.from) + byteLength(saved.kind ?? "") +
|
|
270
|
+
byteLength(saved.sourceChannelId ?? "") + byteLength(saved.itemId ?? "") + byteLength(saved.externalSource ?? "");
|
|
271
|
+
const contextRow: ContextEntry = { entry: saved, seq: saved.seq, bytes, kind };
|
|
272
|
+
data.bySeq.set(saved.seq, contextRow);
|
|
273
|
+
log(() => { data.bySeq.delete(saved.seq); });
|
|
274
|
+
indexed(data.byTurn, saved.turnId, contextRow);
|
|
275
|
+
if (kind === "input") indexed(data.inputs, saved.turnId, contextRow);
|
|
276
|
+
if (kind === "assistant") indexed(data.assistants, saved.turnId, contextRow);
|
|
277
|
+
const reply = entry.message.role === "assistant" && !!entry.message.content;
|
|
278
|
+
if (reply || entry.kind === "participant_message") {
|
|
279
|
+
indexed(data.conversation, entry.channelId, saved);
|
|
280
|
+
}
|
|
281
|
+
if (reply) indexed(data.replies, entry.turnId, saved);
|
|
282
|
+
},
|
|
283
|
+
entriesOfTurn: turnId => copy(data.entries.filter(entry => entry.turnId === turnId)),
|
|
284
|
+
entries: () => copy(data.entries),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** One in-memory location with the same semantics as a database file: the
|
|
289
|
+
* session outlives its handle, so close and open behave like a restart within
|
|
290
|
+
* one process. Nothing survives the process itself. */
|
|
291
|
+
export function createMemoryStorageAdapter(): SessionStorageAdapter {
|
|
292
|
+
let data: Data | undefined;
|
|
293
|
+
let owned = false;
|
|
294
|
+
return {
|
|
295
|
+
readSavedConfig() {
|
|
296
|
+
if (!data) return failure(new Fail("not_found", "No session exists at this location"));
|
|
297
|
+
if (owned) return failure(new Fail("owner_conflict", "Session storage already has an owner"));
|
|
298
|
+
return { ok: true, value: copy(data.config), revision: data.meta.revision };
|
|
299
|
+
},
|
|
300
|
+
importSessionFile(payload, options) {
|
|
301
|
+
try {
|
|
302
|
+
const { archive, config } = validateSessionPayload(payload);
|
|
303
|
+
if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim())) throw new Fail("invalid_input", "sessionId must be a nonempty string");
|
|
304
|
+
if (data) throw new Fail("already_exists", "A session already exists at this location");
|
|
305
|
+
const next = empty(archiveMeta(copy(archive), options?.sessionId));
|
|
306
|
+
const tables = memoryTables(next); tables.transaction(() => { restoreArchive(tables, archive); tables.setConfig(config); });
|
|
307
|
+
data = next;
|
|
308
|
+
return { ok: true, value: storedSession(next.meta), revision: next.meta.revision };
|
|
309
|
+
} catch (error) { return failure(error); }
|
|
310
|
+
},
|
|
311
|
+
open(options) {
|
|
312
|
+
try {
|
|
313
|
+
const identity = options?.identity;
|
|
314
|
+
if (!identity || typeof identity.sessionId !== "string" || !identity.sessionId.trim() || typeof identity.compatibilityKey !== "string"
|
|
315
|
+
|| (options.mode !== "create" && options.mode !== "open")) throw new Fail("invalid_input", "Open needs a mode, sessionId and compatibilityKey");
|
|
316
|
+
let config; try { config = options.config === undefined ? undefined : validateManagedConfig(options.config); } catch (error) { throw new Fail("invalid_input", String(error)); }
|
|
317
|
+
if (owned) throw new Fail("owner_conflict", "Session storage already has an owner");
|
|
318
|
+
if (options.mode === "create") {
|
|
319
|
+
if (data) throw new Fail("already_exists", "A session already exists at this location");
|
|
320
|
+
checkScriptIdentity(identity.compatibilityKey, options.requiredScriptDigest);
|
|
321
|
+
data = empty({ sessionId: identity.sessionId, formatVersion: 6, createdAt: new Date().toISOString(),
|
|
322
|
+
compatibilityKey: identity.compatibilityKey, lifecycle: "running", revision: 0, nextTurnId: 1, nextItemNumber: 1 });
|
|
323
|
+
} else {
|
|
324
|
+
if (!data) throw new Fail("not_found", "No session exists at this location");
|
|
325
|
+
if (data.meta.sessionId !== identity.sessionId) throw new Fail("incompatible", "Location holds a different session");
|
|
326
|
+
checkScriptIdentity(data.meta.compatibilityKey, options.requiredScriptDigest);
|
|
327
|
+
}
|
|
328
|
+
const tables = memoryTables(data);
|
|
329
|
+
const reminderEvents: NonNullable<Parameters<typeof recover>[2]> = [];
|
|
330
|
+
tables.transaction(() => {
|
|
331
|
+
checkUnattendedGuard(tables, config?.limits?.unattendedTurns);
|
|
332
|
+
if (referencesCompatible(tables, config)) {
|
|
333
|
+
recover(tables, undefined, reminderEvents);
|
|
334
|
+
bindUnattendedGuard(tables, config?.limits?.unattendedTurns);
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
owned = true;
|
|
338
|
+
return { ok: true, value: createEngine(tables, identity.compatibilityKey, () => { owned = false; }, config, false, reminderEvents), revision: data.meta.revision };
|
|
339
|
+
} catch (error) { return failure(error); }
|
|
340
|
+
},
|
|
341
|
+
importArchive(raw, options) {
|
|
342
|
+
try {
|
|
343
|
+
const archive = validateArchive(raw);
|
|
344
|
+
if (options?.sessionId !== undefined && (typeof options.sessionId !== "string" || !options.sessionId.trim()))
|
|
345
|
+
throw new Fail("invalid_input", "sessionId must be a nonempty string");
|
|
346
|
+
if (data) throw new Fail("already_exists", "A session already exists at this location");
|
|
347
|
+
const next = empty(archiveMeta(copy(archive), options?.sessionId));
|
|
348
|
+
restoreArchive(memoryTables(next), archive);
|
|
349
|
+
data = next; // Published only after every row was written.
|
|
350
|
+
return { ok: true, value: storedSession(next.meta), revision: next.meta.revision };
|
|
351
|
+
} catch (error) { return failure(error); }
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ItemPolicy, ManagedConfig } from "../../contracts/config-permissions.ts";
|
|
3
|
+
|
|
4
|
+
/** Policy identity includes the caller's actual override, never the resolved
|
|
5
|
+
* policy: a channel edit must not change the signature of an accepted item. */
|
|
6
|
+
export interface PolicyInputIdentity {
|
|
7
|
+
kind: string; channelId: string; senderId: string; sourceChannelId?: string;
|
|
8
|
+
text: string; explicitPolicy?: string | null;
|
|
9
|
+
}
|
|
10
|
+
const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
11
|
+
export function legacyItemSignature(item: PolicyInputIdentity): string {
|
|
12
|
+
return digest([item.kind, item.channelId, item.senderId, item.sourceChannelId ?? null, item.text]);
|
|
13
|
+
}
|
|
14
|
+
export function policyItemSignature(item: PolicyInputIdentity): string {
|
|
15
|
+
return digest([item.kind, item.channelId, item.senderId, item.sourceChannelId ?? null, item.text, item.explicitPolicy ?? null]);
|
|
16
|
+
}
|
|
17
|
+
/** The references contributed by a source turn include every earlier notice's
|
|
18
|
+
* inherited restrictions. First occurrence order keeps the record stable. */
|
|
19
|
+
export function contributingPolicies(items: readonly ItemPolicy[]): string[] {
|
|
20
|
+
return [...new Set(items.flatMap(item => [item.resolved, ...item.inherited]))];
|
|
21
|
+
}
|
|
22
|
+
export function fingerprint(config: ManagedConfig, references: readonly string[]): string {
|
|
23
|
+
return JSON.stringify([...new Set(references)].sort().map(name => {
|
|
24
|
+
const policy = Object.hasOwn(config.policies, name) ? config.policies[name] : undefined;
|
|
25
|
+
if (!policy) throw new Error(`Unknown policy: ${name}`);
|
|
26
|
+
return [name, policy.fallback, Object.keys(policy.tools).sort().map(tool => [tool, policy.tools[tool]])];
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function externalNoticeSignature(channel: string, source: string | undefined, text: string, names: readonly string[]): string {
|
|
31
|
+
return digest(["external_notice", channel, source ?? null, text, [...new Set(names)].sort()]);
|
|
32
|
+
}
|