@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,104 @@
|
|
|
1
|
+
import { isRoutine } from "./routine-row.ts";
|
|
2
|
+
import type { Reminder, ReminderArchiveState } from "../../contracts/reminders.ts";
|
|
3
|
+
import type { StorageSnapshot } from "../../contracts/storage.ts";
|
|
4
|
+
import { normalizeReminderSchedule, reminderInstant } from "../../util/reminder-schedule.ts";
|
|
5
|
+
import { Fail, initialIntakeHasParticipant } from "./engine.ts";
|
|
6
|
+
|
|
7
|
+
const bad = (): never => { throw new Fail("invalid_archive", "Invalid archived reminder state"); };
|
|
8
|
+
const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
|
|
9
|
+
const integer = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;
|
|
10
|
+
const iso = (value: unknown): boolean => typeof value === "string" &&
|
|
11
|
+
reminderInstant(value) !== undefined && new Date(Date.parse(value)).toISOString() === value;
|
|
12
|
+
|
|
13
|
+
export function validateReminderArchive(state: ReminderArchiveState | undefined, snapshot: StorageSnapshot): void {
|
|
14
|
+
if (!state || !Array.isArray(state.rows) || !Array.isArray(state.receipts) || !integer(state.listingRevision) ||
|
|
15
|
+
(state.guard !== undefined && !Array.isArray(state.guard.counters)) || !state.wake || !integer(state.wake.reminderRevision) ||
|
|
16
|
+
(state.wake.nextDueAt !== null && !iso(state.wake.nextDueAt))) return bad();
|
|
17
|
+
const channels = new Map(snapshot.channels.map(channel => [channel.channelId, channel.lifecycle]));
|
|
18
|
+
const items = new Map(snapshot.items.map(item => [item.itemId, item]));
|
|
19
|
+
const ids = new Set<string>(), receipts = new Set<string>();
|
|
20
|
+
const validRow = (row: Reminder): boolean => {
|
|
21
|
+
if (!row || !text(row.id) || !channels.has(row.channel) || !text(row.text) ||
|
|
22
|
+
(row.createdBy !== "host" && row.createdBy !== "agent") || !Array.isArray(row.policyNames) ||
|
|
23
|
+
!row.policyNames.every(text) || new Set(row.policyNames).size !== row.policyNames.length ||
|
|
24
|
+
!row.schedule || !iso(row.acceptedAt) ||
|
|
25
|
+
!["active", "paused", "blocked", "done", "cancelled", "expired"].includes(row.state)) return false;
|
|
26
|
+
if (isRoutine(row)) {
|
|
27
|
+
if (snapshot.session.formatVersion !== 8 || !state.guard ||
|
|
28
|
+
!["coalesce", "skip", "each"].includes(row.missedRuns) || !["skip", "queue"].includes(row.overlap) ||
|
|
29
|
+
(row.remainingCount !== undefined && !integer(row.remainingCount)) ||
|
|
30
|
+
(row.state === "active" ? !iso(row.nextRunAt) : row.nextRunAt !== null)) return false;
|
|
31
|
+
if ("every" in row.schedule && row.schedule.every !== undefined)
|
|
32
|
+
return integer(row.schedule.every) && row.schedule.every >= 600_000 && iso(row.schedule.startAt);
|
|
33
|
+
return "cron" in row.schedule && text(row.schedule.cron) && text(row.schedule.timezone) &&
|
|
34
|
+
typeof row.timezoneVersion === "string" && /^\d{4}[a-z]+$/.test(row.timezoneVersion);
|
|
35
|
+
}
|
|
36
|
+
if (!iso(row.schedule.at)) return false;
|
|
37
|
+
const schedule = normalizeReminderSchedule(row.schedule.at!, row.acceptedAt, row.expiresAfter, Date.parse(row.acceptedAt));
|
|
38
|
+
return !!schedule && row.expiresAfter === schedule.expiresAfter && row.expiresAt === schedule.expiresAt &&
|
|
39
|
+
row.nextRunAt === (row.state === "active" ? row.schedule.at : null);
|
|
40
|
+
};
|
|
41
|
+
let sequence = 0, nextDueAt: string | null = null;
|
|
42
|
+
for (const entry of state.rows) {
|
|
43
|
+
if (!entry || !integer(entry.sequence) || entry.sequence <= sequence || entry.sequence > snapshot.revision ||
|
|
44
|
+
typeof entry.defaultedExpiry !== "boolean" || !validRow(entry.reminder) || ids.has(entry.reminder.id) || (entry.original !== undefined && !text(entry.original))) return bad();
|
|
45
|
+
const row = entry.reminder;
|
|
46
|
+
if (entry.defaultedExpiry && !isRoutine(row)) {
|
|
47
|
+
const defaulted = normalizeReminderSchedule(row.schedule.at!, row.acceptedAt, undefined, Date.parse(row.acceptedAt));
|
|
48
|
+
if (defaulted?.expiresAfter !== row.expiresAfter) return bad();
|
|
49
|
+
}
|
|
50
|
+
sequence = entry.sequence;
|
|
51
|
+
ids.add(row.id);
|
|
52
|
+
if (isRoutine(row)) {
|
|
53
|
+
if (entry.processedThrough !== undefined && !Number.isSafeInteger(entry.processedThrough)) return bad();
|
|
54
|
+
if (entry.episodeCutoff !== undefined && !Number.isSafeInteger(entry.episodeCutoff)) return bad();
|
|
55
|
+
if (entry.coalescedPending !== undefined && !integer(entry.coalescedPending)) return bad();
|
|
56
|
+
if (row.noticeId !== undefined) {
|
|
57
|
+
const notice = items.get(row.noticeId);
|
|
58
|
+
if (notice?.kind !== "external_notice" || notice.channelId !== row.channel ||
|
|
59
|
+
notice.externalSource !== `reminder:${row.id}` || !iso(row.lastRunAt)) return bad();
|
|
60
|
+
}
|
|
61
|
+
} else if (row.state === "done") {
|
|
62
|
+
const notice = items.get(row.noticeId ?? "");
|
|
63
|
+
if (row.noticeId !== `reminder-notice:${row.id}:${row.schedule.at}` ||
|
|
64
|
+
row.lastOccurrenceId !== `reminder:${row.id}:${row.schedule.at}` || !iso(row.lastRunAt) ||
|
|
65
|
+
notice?.kind !== "external_notice" || notice.channelId !== row.channel || notice.text !== row.text ||
|
|
66
|
+
notice.externalSource !== `reminder:${row.id}`) return bad();
|
|
67
|
+
} else if (row.noticeId !== undefined || row.lastRunAt !== undefined) return bad();
|
|
68
|
+
const isHeld = isRoutine(row) && !!state.guard && (state.guard.counters.find(counter => counter.channel === row.channel)?.spent ?? 0) >= state.guard.limit
|
|
69
|
+
&& !hasRunnableParticipant(snapshot, row.channel);
|
|
70
|
+
if (!isHeld && snapshot.session.lifecycle === "running" && channels.get(row.channel) === "open" && row.nextRunAt !== null &&
|
|
71
|
+
(nextDueAt === null || row.nextRunAt < nextDueAt)) nextDueAt = row.nextRunAt;
|
|
72
|
+
}
|
|
73
|
+
if ((!state.rows.length && !state.receipts.length && !state.guard) || state.listingRevision < state.rows.length ||
|
|
74
|
+
state.wake.nextDueAt !== nextDueAt || (nextDueAt !== null && !state.wake.reminderRevision)) return bad();
|
|
75
|
+
if (state.dispositions !== undefined) {
|
|
76
|
+
if (snapshot.session.formatVersion !== 8 || !Array.isArray(state.dispositions)) return bad();
|
|
77
|
+
for (const entry of state.dispositions) {
|
|
78
|
+
if (!entry || !ids.has(entry.reminderId)) return bad();
|
|
79
|
+
if (entry.type === "routine_disposition") {
|
|
80
|
+
if (!integer(entry.count) || !entry.count || !iso(entry.firstScheduledAt) || !iso(entry.lastScheduledAt) ||
|
|
81
|
+
entry.lastScheduledAt < entry.firstScheduledAt || !["missed", "catch_up_limit", "overlap", "expired", "coalesced"].includes(entry.reason)) return bad();
|
|
82
|
+
} else if (entry.type !== "routine_migration_blocked" || !text(entry.fromVersion) || !text(entry.targetVersion) ||
|
|
83
|
+
!["invalid_schedule", "proof_budget"].includes(entry.cause)) return bad();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const receipt of state.receipts) {
|
|
87
|
+
const result = receipt?.result;
|
|
88
|
+
if (!result || !text(receipt.fingerprint) || !text(result.reminderId) || !integer(result.changeId) || !result.changeId) return bad();
|
|
89
|
+
const key = JSON.stringify([result.reminderId, result.changeId]);
|
|
90
|
+
if (receipts.has(key)) return bad();
|
|
91
|
+
receipts.add(key);
|
|
92
|
+
if (result.outcome === "applied") {
|
|
93
|
+
if (!validRow(result.reminder) || result.reminder.id !== result.reminderId || !ids.has(result.reminderId)) return bad();
|
|
94
|
+
} else if (result.outcome !== "blocked" || !["invalid_policy", "channel_missing", "channel_retired", "invalid_schedule",
|
|
95
|
+
"limit_exceeded", "unattended_guard_required", "conflict", "not_found", "stale", "invalid_state"].includes(result.reason)) return bad();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
function hasRunnableParticipant(snapshot: StorageSnapshot, channel: string): boolean {
|
|
101
|
+
const items = snapshot.items.filter(item => item.channelId === channel && item.milestone === "received")
|
|
102
|
+
.sort((left, right) => left.acceptedSeq - right.acceptedSeq);
|
|
103
|
+
return initialIntakeHasParticipant(items);
|
|
104
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { isRoutine, prepareRoutineRow } from "./routine-row.ts";
|
|
2
|
+
import type { Reminder, ReminderBlockReason, ReminderChange, ReminderChangeResult } from "../../contracts/reminders.ts";
|
|
3
|
+
import { normalizeReminderSchedule } from "../../util/reminder-schedule.ts";
|
|
4
|
+
|
|
5
|
+
export interface ReminderReceipt {
|
|
6
|
+
fingerprint: string;
|
|
7
|
+
result: ReminderChangeResult;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface ReminderChanges {
|
|
11
|
+
receipt(reminderId: string, changeId: number): ReminderReceipt | undefined;
|
|
12
|
+
highWater(reminderId: string): number;
|
|
13
|
+
originalCreate(reminderId: string): ReminderReceipt | undefined;
|
|
14
|
+
defaultedExpiry(reminderId: string): boolean;
|
|
15
|
+
get(reminderId: string): Reminder | undefined;
|
|
16
|
+
put(reminder: Reminder, defaultedExpiry?: boolean, original?: string): void;
|
|
17
|
+
saveReceipt(receipt: ReminderReceipt): void;
|
|
18
|
+
channelStatus(channel: string): "open" | "suspended" | "suspending" | "retired" | undefined;
|
|
19
|
+
guardEnabled(): boolean;
|
|
20
|
+
activeRoutines(channel: string): number;
|
|
21
|
+
processedThrough(id: string): number | undefined;
|
|
22
|
+
proofExhausted(): never;
|
|
23
|
+
validPolicies(names: readonly string[]): boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const terminal = (row: Reminder) => row.state === "done" || row.state === "cancelled" || row.state === "expired";
|
|
27
|
+
|
|
28
|
+
function serialize(value: unknown): string {
|
|
29
|
+
return JSON.stringify(value, (_key, input) => input && typeof input === "object" && !Array.isArray(input)
|
|
30
|
+
? Object.fromEntries(Object.keys(input).sort().map(key => [key, input[key]]))
|
|
31
|
+
: input);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The caller owns the transaction, including first-write activation and wake reconciliation. */
|
|
35
|
+
export function applyReminderChange(store: ReminderChanges, change: ReminderChange, now: number): ReminderChangeResult {
|
|
36
|
+
const { reminderId, changeId, op, payload } = change;
|
|
37
|
+
const id = { reminderId, changeId };
|
|
38
|
+
const block = (reason: ReminderBlockReason): ReminderChangeResult => ({ ...id, outcome: "blocked", reason });
|
|
39
|
+
const accept = (reminder: Reminder, alreadyQueued?: boolean): ReminderChangeResult => ({
|
|
40
|
+
...id, outcome: "applied", reminder, ...(alreadyQueued === undefined ? {} : { alreadyQueued }),
|
|
41
|
+
});
|
|
42
|
+
const fingerprint = serialize([op, payload]);
|
|
43
|
+
const prior = store.receipt(reminderId, changeId);
|
|
44
|
+
if (prior) return prior.fingerprint === fingerprint ? prior.result : block("conflict");
|
|
45
|
+
if (changeId <= store.highWater(reminderId)) return block("stale");
|
|
46
|
+
const persist = (result: ReminderChangeResult) => {
|
|
47
|
+
store.saveReceipt({ fingerprint, result });
|
|
48
|
+
return result;
|
|
49
|
+
};
|
|
50
|
+
const row = store.get(reminderId);
|
|
51
|
+
if (change.op === "create") {
|
|
52
|
+
if (reminderId.startsWith("agent-reminder:")) return persist(block("conflict"));
|
|
53
|
+
const original = store.originalCreate(reminderId);
|
|
54
|
+
if (original) {
|
|
55
|
+
if (original.fingerprint !== fingerprint) return persist(block("conflict"));
|
|
56
|
+
return persist(row ? accept(row) : { ...original.result, ...id });
|
|
57
|
+
}
|
|
58
|
+
if (row) return persist(block("conflict"));
|
|
59
|
+
const fields = change.payload;
|
|
60
|
+
const oneOff = fields.schedule.at === undefined ? undefined : normalizeReminderSchedule(fields.schedule.at, fields.acceptedAt, fields.expiresAfter, now);
|
|
61
|
+
if (fields.schedule.at !== undefined && (!oneOff || fields.missedRuns !== undefined || fields.overlap !== undefined))
|
|
62
|
+
return persist(block("invalid_schedule"));
|
|
63
|
+
const channel = store.channelStatus(fields.channel);
|
|
64
|
+
if (!channel || channel === "retired") return persist(block(channel === "retired" ? "channel_retired" : "channel_missing"));
|
|
65
|
+
const policyNames = [...new Set(fields.policyNames ?? [])].sort();
|
|
66
|
+
if (!store.validPolicies(policyNames)) return persist(block("invalid_policy"));
|
|
67
|
+
if (fields.schedule.at === undefined) {
|
|
68
|
+
if (!store.guardEnabled()) return persist(block("unattended_guard_required"));
|
|
69
|
+
if (store.activeRoutines(fields.channel) >= 20) return persist(block("limit_exceeded"));
|
|
70
|
+
const prepared = prepareRoutineRow(fields.schedule, fields.acceptedAt, now, fields.expiresAfter);
|
|
71
|
+
if (prepared.kind === "proof_budget") return store.proofExhausted();
|
|
72
|
+
if (prepared.kind !== "valid") return persist(block("invalid_schedule"));
|
|
73
|
+
const reminder = { ...prepared.fields, id: reminderId, channel: fields.channel, createdBy: "host",
|
|
74
|
+
policyNames, text: fields.text, state: "active", missedRuns: fields.missedRuns ?? "coalesce", overlap: fields.overlap ?? "skip" } as const;
|
|
75
|
+
store.put(reminder as Reminder, fields.expiresAfter === undefined, fingerprint);
|
|
76
|
+
return persist(accept(reminder as Reminder));
|
|
77
|
+
}
|
|
78
|
+
const schedule = oneOff!;
|
|
79
|
+
const reminder: Reminder = { ...schedule, id: reminderId, channel: fields.channel, createdBy: "host",
|
|
80
|
+
policyNames, text: fields.text, state: "active", nextRunAt: schedule.schedule.at };
|
|
81
|
+
store.put(reminder, fields.expiresAfter === undefined, fingerprint);
|
|
82
|
+
return persist(accept(reminder));
|
|
83
|
+
}
|
|
84
|
+
if (!row) return persist(block("not_found"));
|
|
85
|
+
if (op === "cancel") {
|
|
86
|
+
const reminder: Reminder = terminal(row) ? row : { ...row, state: "cancelled", nextRunAt: null };
|
|
87
|
+
if (reminder !== row) store.put(reminder);
|
|
88
|
+
return persist(accept(reminder, row.noticeId !== undefined));
|
|
89
|
+
}
|
|
90
|
+
if (terminal(row)) return persist(block("invalid_state"));
|
|
91
|
+
const fields = change.payload;
|
|
92
|
+
const channel = store.channelStatus(row.channel);
|
|
93
|
+
if (!channel || channel === "retired") return persist(block(channel === "retired" ? "channel_retired" : "channel_missing"));
|
|
94
|
+
if (!store.validPolicies(row.policyNames)) return persist(block("invalid_policy"));
|
|
95
|
+
const defaulted = fields.expiresAfter === undefined && store.defaultedExpiry(reminderId);
|
|
96
|
+
const grace = fields.expiresAfter !== undefined ? fields.expiresAfter : defaulted ? undefined : row.expiresAfter;
|
|
97
|
+
if (isRoutine(row)) {
|
|
98
|
+
if (fields.schedule && (fields.schedule.at !== undefined ||
|
|
99
|
+
(fields.schedule.every !== undefined) !== (row.schedule.every !== undefined)))
|
|
100
|
+
return persist(block("invalid_schedule"));
|
|
101
|
+
const state = fields.state ?? (row.state === "blocked" ? "active" : row.state);
|
|
102
|
+
if (state === "active" && row.state !== "active" && store.activeRoutines(row.channel) >= 20)
|
|
103
|
+
return persist(block("limit_exceeded"));
|
|
104
|
+
if (row.timezoneMigration && !fields.schedule && state === "active") return persist(block("invalid_schedule"));
|
|
105
|
+
if (!fields.schedule && fields.expiresAfter === undefined && (row.state === "active" || state !== "active")) {
|
|
106
|
+
const reminder = { ...row, state, text: fields.text ?? row.text, missedRuns: fields.missedRuns ?? row.missedRuns,
|
|
107
|
+
overlap: fields.overlap ?? row.overlap, nextRunAt: state === "active" ? row.nextRunAt : null };
|
|
108
|
+
store.put(reminder);
|
|
109
|
+
return persist(accept(reminder));
|
|
110
|
+
}
|
|
111
|
+
const acceptedAt = fields.acceptedAt ?? row.acceptedAt;
|
|
112
|
+
const schedule = fields.schedule ?? (row.remainingCount === undefined ? row.schedule
|
|
113
|
+
: { ...row.schedule, count: row.remainingCount, until: undefined });
|
|
114
|
+
const prepared = prepareRoutineRow(schedule, acceptedAt, fields.acceptedAt === undefined ? Math.max(now, Date.parse(row.acceptedAt)) : now, grace, store.processedThrough(row.id));
|
|
115
|
+
if (prepared.kind === "proof_budget") return store.proofExhausted();
|
|
116
|
+
if (prepared.kind !== "valid") return persist(block("invalid_schedule"));
|
|
117
|
+
const reminder = { ...row, ...prepared.fields, ...(fields.schedule ? { timezoneMigration: undefined } : { schedule: row.schedule, remainingCount: row.remainingCount }),
|
|
118
|
+
text: fields.text ?? row.text, missedRuns: fields.missedRuns ?? row.missedRuns, overlap: fields.overlap ?? row.overlap,
|
|
119
|
+
blockedReason: undefined, state, nextRunAt: state === "active" ? prepared.fields.nextRunAt : null } as Reminder;
|
|
120
|
+
store.put(reminder, defaulted);
|
|
121
|
+
return persist(accept(reminder));
|
|
122
|
+
}
|
|
123
|
+
if ((fields.schedule && fields.schedule.at === undefined) || fields.missedRuns !== undefined || fields.overlap !== undefined)
|
|
124
|
+
return persist(block("invalid_schedule"));
|
|
125
|
+
const schedule = fields.schedule !== undefined || fields.expiresAfter !== undefined
|
|
126
|
+
? normalizeReminderSchedule(fields.schedule?.at ?? row.schedule.at, fields.acceptedAt ?? row.acceptedAt, grace, fields.acceptedAt === undefined ? Math.max(now, Date.parse(row.acceptedAt)) : now)
|
|
127
|
+
: row;
|
|
128
|
+
if (!schedule) return persist(block("invalid_schedule"));
|
|
129
|
+
const state = fields.state ?? (row.state === "blocked" ? "active" : row.state);
|
|
130
|
+
const reminder: Reminder = {
|
|
131
|
+
...row, schedule: schedule.schedule, acceptedAt: schedule.acceptedAt, expiresAfter: schedule.expiresAfter,
|
|
132
|
+
expiresAt: schedule.expiresAt, text: fields.text ?? row.text, state,
|
|
133
|
+
nextRunAt: state === "active" ? schedule.schedule.at : null,
|
|
134
|
+
};
|
|
135
|
+
delete reminder.blockedReason;
|
|
136
|
+
store.put(reminder, defaulted);
|
|
137
|
+
return persist(accept(reminder));
|
|
138
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Reminder, ReminderArchiveState, ReminderWake } from "../../contracts/reminders.ts";
|
|
2
|
+
import type { ReminderReceipt } from "./reminder-change.ts";
|
|
3
|
+
|
|
4
|
+
export interface ReminderRow {
|
|
5
|
+
sequence: number;
|
|
6
|
+
reminder: Reminder;
|
|
7
|
+
original?: string;
|
|
8
|
+
defaultedExpiry: boolean;
|
|
9
|
+
processedThrough?: number;
|
|
10
|
+
episodeCutoff?: number; coalescedPending?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ReminderTables {
|
|
14
|
+
activate(): void;
|
|
15
|
+
recordDisposition(event: NonNullable<ReminderArchiveState["dispositions"]>[number]): void;
|
|
16
|
+
activeRoutines(channel: string): number;
|
|
17
|
+
guardLimit(): number | undefined;
|
|
18
|
+
bindGuard(limit: number): void;
|
|
19
|
+
guardSpent(channel: string): number;
|
|
20
|
+
setGuardSpent(channel: string, spent: number): void;
|
|
21
|
+
archive(): ReminderArchiveState;
|
|
22
|
+
restore(state: ReminderArchiveState): void;
|
|
23
|
+
get(id: string): ReminderRow | undefined;
|
|
24
|
+
put(row: ReminderRow): void;
|
|
25
|
+
originalCreate(id: string): ReminderReceipt | undefined;
|
|
26
|
+
receipt(id: string, changeId: number): ReminderReceipt | undefined;
|
|
27
|
+
highWater(id: string): number;
|
|
28
|
+
saveReceipt(receipt: ReminderReceipt): void;
|
|
29
|
+
list(channel: string | undefined, after: number, limit: number): ReminderRow[];
|
|
30
|
+
blocked(channel: string | undefined, after: number, limit: number): ReminderRow[];
|
|
31
|
+
eligible(through: string | null, limit: number, heldChannels?: readonly string[]): ReminderRow[];
|
|
32
|
+
listingRevision(): number;
|
|
33
|
+
wake(): ReminderWake;
|
|
34
|
+
setWake(wake: ReminderWake): void;
|
|
35
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { RetrievedMessage, TimelineSearch, TimelineSearchResult, TimelineWindow, TimelineWindowResult } from "../../contracts/timeline-retrieval.ts";
|
|
2
|
+
import { retrievalMessage, scoreTimeline, timelineBytes, timelineQuery, timelineTokens } from "../../util/timeline-text.ts";
|
|
3
|
+
import { Fail, type Meta, type Tables } from "./engine.ts";
|
|
4
|
+
|
|
5
|
+
const maxResponseBudget = 32 * 1024;
|
|
6
|
+
const candidateCap = 1000;
|
|
7
|
+
const verificationBudget = 2 * 1024 * 1024;
|
|
8
|
+
const byteSize = (value: unknown) => timelineBytes(JSON.stringify(value));
|
|
9
|
+
|
|
10
|
+
function excerpt(text: string, first: number): string {
|
|
11
|
+
// NFC changes token spelling but not the boundaries of ordinary combining
|
|
12
|
+
// sequences. Use the original offsets so the excerpt retains attribution.
|
|
13
|
+
const token = Array.from(text.matchAll(/[\p{L}\p{M}\p{N}]+/gu))[first];
|
|
14
|
+
const before = Array.from(text.slice(0, token?.index ?? 0)).slice(-40).join("");
|
|
15
|
+
const after = text.slice(token?.index ?? 0);
|
|
16
|
+
let result = before, bytes = timelineBytes(before);
|
|
17
|
+
for (const scalar of after) {
|
|
18
|
+
bytes += timelineBytes(scalar);
|
|
19
|
+
if (bytes > 512) break;
|
|
20
|
+
result += scalar;
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function searchTimeline(tables: Tables, input: TimelineSearch, maxBytes = maxResponseBudget): TimelineSearchResult {
|
|
26
|
+
const responseBudget = Math.min(maxResponseBudget, maxBytes);
|
|
27
|
+
const tokens = timelineQuery(input);
|
|
28
|
+
if (!tokens) throw new Fail("invalid_input", "Query requires searchable words within timeline limits");
|
|
29
|
+
const candidates = tables.retrievalCandidates([...new Set(tokens.map(word => word.folded))], input.channel, candidateCap + 1);
|
|
30
|
+
const form = input.case_sensitive ? "exact" : "folded";
|
|
31
|
+
const wanted = tokens.map(word => word[form]);
|
|
32
|
+
const matches: Array<{ score: number; hit: TimelineSearchResult["hits"][number] }> = [];
|
|
33
|
+
let budget = verificationBudget, partial = candidates.length > candidateCap;
|
|
34
|
+
for (const row of candidates.slice(0, candidateCap)) {
|
|
35
|
+
if (row.bytes > budget) { partial = true; break; }
|
|
36
|
+
budget -= row.bytes;
|
|
37
|
+
const entry = tables.retrievalEntry(row.seq);
|
|
38
|
+
const message = entry && retrievalMessage(entry);
|
|
39
|
+
if (!message || (input.channel !== undefined && message.channel !== input.channel)) continue;
|
|
40
|
+
const { text, ...origin } = message;
|
|
41
|
+
const { score, first } = scoreTimeline(timelineTokens(text).map(word => word[form]), wanted, input.match === "phrase");
|
|
42
|
+
if (score) matches.push({ score, hit: { ...origin, excerpt: excerpt(text, first) } });
|
|
43
|
+
}
|
|
44
|
+
matches.sort((a, b) => b.score - a.score || b.hit.seq - a.hit.seq);
|
|
45
|
+
const hits: TimelineSearchResult["hits"] = [];
|
|
46
|
+
for (const { hit } of matches.slice(0, 20)) {
|
|
47
|
+
if (byteSize({ hits: [...hits, hit], partial: false }) > responseBudget) { partial = true; break; }
|
|
48
|
+
hits.push(hit);
|
|
49
|
+
}
|
|
50
|
+
return { hits, partial };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type Cursor = [1, string, string, number, string, number, number, number, number, number, number, number];
|
|
54
|
+
const encode = (cursor: Cursor) => Buffer.from(JSON.stringify(cursor)).toString("base64url");
|
|
55
|
+
const natural = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;
|
|
56
|
+
const invalid = () => new Fail("invalid_input", "Invalid timeline window cursor");
|
|
57
|
+
|
|
58
|
+
function decode(cursor: string): Cursor {
|
|
59
|
+
try {
|
|
60
|
+
const data = JSON.parse(Buffer.from(cursor, "base64url").toString());
|
|
61
|
+
if (Array.isArray(data) && data.length === 12 && data[0] === 1 &&
|
|
62
|
+
[data[1], data[2], data[4]].every(value => typeof value === "string") &&
|
|
63
|
+
[data[3], ...data.slice(5)].every(natural) && encode(data as Cursor) === cursor) return data as Cursor;
|
|
64
|
+
} catch { /* invalid below */ }
|
|
65
|
+
throw invalid();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function pointRead(tables: Tables, id: string): RetrievedMessage {
|
|
69
|
+
const seq = id.startsWith("item:") ? tables.item(id.slice(5))?.entrySeq :
|
|
70
|
+
/^[1-9]\d*$/.test(id) && Number.isSafeInteger(Number(id)) ? Number(id) : tables.retrievalReplyId(id);
|
|
71
|
+
const entry = seq === undefined ? undefined : tables.retrievalEntry(seq);
|
|
72
|
+
const message = entry && retrievalMessage(entry);
|
|
73
|
+
if (!message || message.message_id !== id) throw new Fail("not_found", "Unknown timeline message");
|
|
74
|
+
return message;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function readMessageWindow(tables: Tables, meta: Meta, input: TimelineWindow, maxBytes = maxResponseBudget): TimelineWindowResult {
|
|
78
|
+
const responseBudget = Math.min(maxResponseBudget, maxBytes);
|
|
79
|
+
const saved = input.cursor === undefined ? undefined : decode(input.cursor);
|
|
80
|
+
const target = pointRead(tables, input.message_id);
|
|
81
|
+
const before = input.before ?? saved?.[6] ?? 0, after = input.after ?? saved?.[7] ?? 0;
|
|
82
|
+
const revision = saved?.[5] ?? meta.revision;
|
|
83
|
+
if (!natural(before) || before > 20 || !natural(after) || after > 20 || revision > meta.revision || target.seq > revision ||
|
|
84
|
+
(saved && (saved[1] !== meta.sessionId || saved[2] !== target.message_id || saved[3] !== target.seq ||
|
|
85
|
+
saved[4] !== target.channel || saved[6] !== before || saved[7] !== after))) throw invalid();
|
|
86
|
+
const nearby = (direction: "older" | "newer", limit: number) => limit ? tables.readRange({
|
|
87
|
+
kind: "conversation", direction, limit, channel: target.channel, throughRevision: revision, exclusiveSeq: target.seq,
|
|
88
|
+
}).slice(0, limit).flatMap(entry => { const message = retrievalMessage(entry); return message ? [message] : []; }) : [];
|
|
89
|
+
const window = [...nearby("older", before).reverse(), target, ...nearby("newer", after)];
|
|
90
|
+
const first = window[0]!.seq, last = window.at(-1)!.seq;
|
|
91
|
+
const start = saved ? window.findIndex(message => message.seq === saved[10]) : 0;
|
|
92
|
+
if (start < 0 || (saved && (saved[8] !== first || saved[9] !== last))) throw invalid();
|
|
93
|
+
const result: TimelineWindowResult = { target: target.message_id, sequence: target.seq, revision, messages: [] };
|
|
94
|
+
const next = (seq: number, offset: number) => encode([1, meta.sessionId, target.message_id, target.seq, target.channel,
|
|
95
|
+
revision, before, after, first, last, seq, offset]);
|
|
96
|
+
for (let index = start; index < window.length; index++) {
|
|
97
|
+
const { text, ...origin } = window[index]!;
|
|
98
|
+
const offset = index === start ? saved?.[11] ?? 0 : 0;
|
|
99
|
+
const body = Buffer.from(text);
|
|
100
|
+
if (offset > body.length || (offset > 0 && (offset === body.length || (body[offset]! & 0xc0) === 0x80))) throw invalid();
|
|
101
|
+
const rest = body.subarray(offset), following = window[index + 1];
|
|
102
|
+
const fragment = (end: number) => {
|
|
103
|
+
const cursor = end < rest.length ? next(origin.seq, offset + end) : following && next(following.seq, 0);
|
|
104
|
+
return { ...result, messages: [...result.messages, { ...origin, offset, text: rest.subarray(0, end).toString() }],
|
|
105
|
+
...(cursor === undefined ? {} : { next: cursor }) };
|
|
106
|
+
};
|
|
107
|
+
if (result.messages.length === 20) return { ...result, next: next(origin.seq, offset) };
|
|
108
|
+
const full = rest.length <= responseBudget ? fragment(rest.length) : undefined;
|
|
109
|
+
if (full && byteSize(full) <= responseBudget) { result.messages = full.messages; continue; }
|
|
110
|
+
if (result.messages.length) return { ...result, next: next(origin.seq, offset) };
|
|
111
|
+
let lo = 0, hi = Math.min(rest.length, responseBudget);
|
|
112
|
+
while (lo < hi) {
|
|
113
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
114
|
+
if (byteSize(fragment(mid)) <= responseBudget) lo = mid;
|
|
115
|
+
else hi = mid - 1;
|
|
116
|
+
}
|
|
117
|
+
while (lo > 0 && lo < rest.length && (rest[lo]! & 0xc0) === 0x80) lo--;
|
|
118
|
+
if (!lo) throw new Fail("transfer_limit", "Timeline message identity exceeds the response budget");
|
|
119
|
+
return fragment(lo);
|
|
120
|
+
}
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Reminder, ReminderSchedule } from "../../contracts/reminders.ts";
|
|
2
|
+
import type { RoutineReminder } from "../../capabilities/reminders/routine-advance.ts";
|
|
3
|
+
import { prepareRoutineSchedule } from "../../capabilities/reminders/routine-schedule.ts";
|
|
4
|
+
import { routineExpiry } from "../../capabilities/reminders/routine-expiry.ts";
|
|
5
|
+
|
|
6
|
+
export function isRoutine(row: Reminder): row is RoutineReminder {
|
|
7
|
+
return row.missedRuns !== undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function prepareRoutineRow(schedule: ReminderSchedule, acceptedAt: string, now: number,
|
|
11
|
+
grace: number | null | undefined, fence?: number) {
|
|
12
|
+
if (schedule.at !== undefined) return { kind: "invalid_schedule" } as const;
|
|
13
|
+
const prepared = prepareRoutineSchedule(schedule, acceptedAt, now, fence);
|
|
14
|
+
if (prepared.kind !== "valid") return prepared;
|
|
15
|
+
const next = prepared.calendar.at(0)!;
|
|
16
|
+
try {
|
|
17
|
+
const expiry = routineExpiry(prepared.calendar, next, grace);
|
|
18
|
+
return { kind: "valid", fields: { schedule: prepared.schedule, timezoneVersion: prepared.timezoneVersion,
|
|
19
|
+
remainingCount: schedule.count, acceptedAt, nextRunAt: new Date(next).toISOString(),
|
|
20
|
+
expiresAfter: expiry.expiresAfter, expiresAt: expiry.expiresAt === null ? null : new Date(expiry.expiresAt).toISOString() } } as const;
|
|
21
|
+
} catch (error) {
|
|
22
|
+
if (error instanceof RangeError) return { kind: "invalid_schedule" } as const;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Fail } from "./engine.ts";
|
|
2
|
+
|
|
3
|
+
export function checkScriptIdentity(key: string, required: string | undefined): void {
|
|
4
|
+
if (required === undefined) return;
|
|
5
|
+
const tagged = /^scripted-jsonl-v1:([a-f0-9]{64}):[a-f0-9]{64}$/.exec(key);
|
|
6
|
+
if (tagged?.[0] !== key || tagged[1] !== required) throw new Fail("incompatible", "Scripted model sequences differ or the stored script identity is missing");
|
|
7
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { PortableSessionConfig } from "../../contracts/session-file.ts";
|
|
2
|
+
import { validateManagedConfig } from "../../util/config.ts";
|
|
3
|
+
|
|
4
|
+
/** Narrow, definite-length CBOR profile for JSON-compatible session data. */
|
|
5
|
+
export class SessionFileError extends Error {
|
|
6
|
+
constructor(readonly code: "invalid_archive" | "transfer_limit" | "serialization_error", message: string) { super(message); }
|
|
7
|
+
}
|
|
8
|
+
const bad = (message: string): never => { throw new Error(message); };
|
|
9
|
+
export function validateConfig(value: unknown, legacy = false): PortableSessionConfig {
|
|
10
|
+
return validateManagedConfig(value, legacy);
|
|
11
|
+
}
|
|
12
|
+
function cborEncode(value: unknown): Uint8Array {
|
|
13
|
+
const chunks: Uint8Array[] = [];
|
|
14
|
+
const head = (major: number, n: number) => {
|
|
15
|
+
if (!Number.isSafeInteger(n) || n < 0) bad("Invalid CBOR length");
|
|
16
|
+
if (n < 24) { chunks.push(Uint8Array.of(major * 32 + n)); return; }
|
|
17
|
+
const size = n <= 255 ? 1 : n <= 65535 ? 2 : n <= 0xffffffff ? 4 : 8;
|
|
18
|
+
const bytes = new Uint8Array(1 + size), view = new DataView(bytes.buffer);
|
|
19
|
+
bytes[0] = major * 32 + ({ 1: 24, 2: 25, 4: 26, 8: 27 } as Record<number, number>)[size]!;
|
|
20
|
+
if (size === 1) view.setUint8(1, n); else if (size === 2) view.setUint16(1, n); else if (size === 4) view.setUint32(1, n); else view.setBigUint64(1, BigInt(n));
|
|
21
|
+
chunks.push(bytes);
|
|
22
|
+
};
|
|
23
|
+
const visit = (v: unknown, depth: number) => {
|
|
24
|
+
if (v === null) { chunks.push(Uint8Array.of(0xf6)); return; }
|
|
25
|
+
if (typeof v === "boolean") { chunks.push(Uint8Array.of(v ? 0xf5 : 0xf4)); return; }
|
|
26
|
+
if (typeof v === "number") {
|
|
27
|
+
if (!Number.isFinite(v) || (Number.isInteger(v) && !Number.isSafeInteger(v))) bad("Invalid number");
|
|
28
|
+
if (Number.isSafeInteger(v) && !Object.is(v, -0)) { head(v >= 0 ? 0 : 1, v >= 0 ? v : -1 - v); return; }
|
|
29
|
+
const bytes = new Uint8Array(9); bytes[0] = 0xfb; new DataView(bytes.buffer).setFloat64(1, v); chunks.push(bytes); return;
|
|
30
|
+
}
|
|
31
|
+
if (typeof v === "string") { const bytes = new TextEncoder().encode(v); if (new TextDecoder("utf-8", { fatal: true }).decode(bytes) !== v) bad("Invalid text"); head(3, bytes.length); chunks.push(bytes); return; }
|
|
32
|
+
if (!v || typeof v !== "object" || depth >= 128) bad("Invalid value or nesting");
|
|
33
|
+
if (Array.isArray(v)) { head(4, v.length); for (const x of v) visit(x, depth + 1); return; }
|
|
34
|
+
if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) bad("Invalid map");
|
|
35
|
+
const entries = Object.entries(v as object); head(5, entries.length); for (const [k, x] of entries) { visit(k, depth + 1); visit(x, depth + 1); }
|
|
36
|
+
};
|
|
37
|
+
visit(value, 0);
|
|
38
|
+
return Buffer.concat(chunks);
|
|
39
|
+
}
|
|
40
|
+
function cborDecode(bytes: Uint8Array): unknown {
|
|
41
|
+
let pos = 0; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
42
|
+
const take = (n: number) => { if (!Number.isSafeInteger(n) || n < 0 || n > bytes.length - pos) bad("Truncated CBOR"); const p = pos; pos += n; return p; };
|
|
43
|
+
const arg = (a: number): number => {
|
|
44
|
+
if (a < 24) return a;
|
|
45
|
+
if (a === 24) return view.getUint8(take(1));
|
|
46
|
+
if (a === 25) return view.getUint16(take(2));
|
|
47
|
+
if (a === 26) return view.getUint32(take(4));
|
|
48
|
+
if (a === 27) { const n = view.getBigUint64(take(8)); if (n > BigInt(Number.MAX_SAFE_INTEGER)) bad("Unsafe integer"); return Number(n); }
|
|
49
|
+
return bad("Invalid or indefinite CBOR argument");
|
|
50
|
+
};
|
|
51
|
+
const visit = (depth: number): unknown => {
|
|
52
|
+
const b = view.getUint8(take(1)), major = b >> 5, a = b & 31;
|
|
53
|
+
if (major === 0 || major === 1) { const n = arg(a); const v = major === 0 ? n : -1 - n; if (!Number.isSafeInteger(v)) bad("Unsafe integer"); return v; }
|
|
54
|
+
if (major === 3) { const n = arg(a), p = take(n); return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(p, p + n)); }
|
|
55
|
+
if (major === 4 || major === 5) {
|
|
56
|
+
if (depth >= 128) bad("CBOR nesting limit"); const n = arg(a); if (n > bytes.length - pos) bad("Invalid CBOR container length");
|
|
57
|
+
if (major === 4) { const out: unknown[] = []; for (let i = 0; i < n; i++) out.push(visit(depth + 1)); return out; }
|
|
58
|
+
const out: Record<string, unknown> = Object.create(null);
|
|
59
|
+
for (let i = 0; i < n; i++) { const k = visit(depth + 1); if (typeof k !== "string" || Object.hasOwn(out, k)) bad("Invalid map key"); Object.defineProperty(out, k as string, { value: visit(depth + 1), enumerable: true, writable: true, configurable: true }); }
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
if (major === 7) {
|
|
63
|
+
if (a === 20) return false; if (a === 21) return true; if (a === 22) return null;
|
|
64
|
+
let n: number;
|
|
65
|
+
if (a === 25) { const bits = view.getUint16(take(2)), sign = bits & 0x8000 ? -1 : 1, exp = (bits >> 10) & 31, frac = bits & 1023; n = exp === 0 ? sign * 2 ** -14 * (frac / 1024) : exp === 31 ? (frac ? NaN : sign * Infinity) : sign * 2 ** (exp - 15) * (1 + frac / 1024); }
|
|
66
|
+
else if (a === 26) n = view.getFloat32(take(4)); else if (a === 27) n = view.getFloat64(take(8)); else return bad("Unsupported CBOR simple value");
|
|
67
|
+
if (!Number.isFinite(n) || (Number.isInteger(n) && !Number.isSafeInteger(n))) bad("Invalid number"); return n;
|
|
68
|
+
}
|
|
69
|
+
return bad("Unsupported CBOR type");
|
|
70
|
+
};
|
|
71
|
+
const value = visit(0); if (pos !== bytes.length) bad("Extra CBOR item"); return value;
|
|
72
|
+
}
|
|
73
|
+
export function encodeSessionFile(value: unknown, maxBytes: number): Uint8Array {
|
|
74
|
+
let payload: Uint8Array;
|
|
75
|
+
try { payload = cborEncode(value); } catch (e) { throw new SessionFileError("serialization_error", String(e)); }
|
|
76
|
+
if (payload.length > 0xffffffff || payload.length + 14 > maxBytes) throw new SessionFileError("transfer_limit", "Session file exceeds limit");
|
|
77
|
+
const bytes = new Uint8Array(14 + payload.length); bytes.set(new TextEncoder().encode("HARNSESS")); const view = new DataView(bytes.buffer); view.setUint16(8, 1); view.setUint32(10, payload.length); bytes.set(payload, 14); return bytes;
|
|
78
|
+
}
|
|
79
|
+
export function decodeSessionFile(bytes: Uint8Array, maxBytes: number): unknown {
|
|
80
|
+
if (bytes.length < 14 || new TextDecoder().decode(bytes.subarray(0, 8)) !== "HARNSESS") throw new SessionFileError("invalid_archive", "Invalid session file header");
|
|
81
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
82
|
+
if (view.getUint16(8) !== 1 || bytes.length !== 14 + view.getUint32(10)) throw new SessionFileError("invalid_archive", "Invalid session file version or length");
|
|
83
|
+
if (bytes.length > maxBytes) throw new SessionFileError("transfer_limit", "Session file exceeds limit");
|
|
84
|
+
try { return cborDecode(bytes.subarray(14)); } catch (e) { throw new SessionFileError("invalid_archive", String(e)); }
|
|
85
|
+
}
|