@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,97 @@
|
|
|
1
|
+
import { hasRoutineCronShape, isRoutineSchedule, validInstant, type RoutineBound, type RoutineSchedule } from "./routine-schedule.ts";
|
|
2
|
+
import type { KnownReminderBlockReason } from "./wire.ts";
|
|
3
|
+
import { defaultReminderLimits, type ReminderLimits } from "./limits.ts";
|
|
4
|
+
|
|
5
|
+
export type ReminderSchedule =
|
|
6
|
+
| { readonly at: number }
|
|
7
|
+
| RoutineSchedule<number, { readonly startAt: number }>;
|
|
8
|
+
|
|
9
|
+
export type ReminderScheduleInput =
|
|
10
|
+
| { readonly at: number }
|
|
11
|
+
| { readonly in: number }
|
|
12
|
+
| RoutineSchedule<number>;
|
|
13
|
+
|
|
14
|
+
export type ReminderExpiryPolicy =
|
|
15
|
+
| { readonly kind: "unknown" }
|
|
16
|
+
| { readonly kind: "default" }
|
|
17
|
+
| { readonly kind: "duration"; readonly milliseconds: number }
|
|
18
|
+
| { readonly kind: "unlimited" };
|
|
19
|
+
|
|
20
|
+
export type ReminderExpiry =
|
|
21
|
+
| { readonly kind: "absolute"; readonly at: number; readonly graceMs: number }
|
|
22
|
+
| { readonly kind: "harness_default" }
|
|
23
|
+
| { readonly kind: "duration"; readonly milliseconds: number }
|
|
24
|
+
| null;
|
|
25
|
+
|
|
26
|
+
export type ReminderErrorCode = KnownReminderBlockReason
|
|
27
|
+
| "routines_unavailable" | "reminders_unavailable" | "reminders_unsupported"
|
|
28
|
+
| "invalid_input" | "unauthorized" | "invalid_config" | "storage_failure" | "unattended_guard_required";
|
|
29
|
+
|
|
30
|
+
export class ReminderError extends Error {
|
|
31
|
+
constructor(readonly code: ReminderErrorCode, message: string) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "ReminderError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function normalizeReminderSchedule(
|
|
38
|
+
input: ReminderScheduleInput,
|
|
39
|
+
acceptedAt: number,
|
|
40
|
+
limits: ReminderLimits = defaultReminderLimits,
|
|
41
|
+
replacement = false,
|
|
42
|
+
): ReminderSchedule {
|
|
43
|
+
if (isRoutineSchedule(input)) {
|
|
44
|
+
const { count, until } = input;
|
|
45
|
+
if (count !== undefined && (until !== undefined || !Number.isSafeInteger(count) || count <= 0)) {
|
|
46
|
+
throw new ReminderError("invalid_schedule", "Expected a positive safe count or an inclusive until, not both");
|
|
47
|
+
}
|
|
48
|
+
if (until !== undefined && (!validInstant(until) || (!replacement && until - acceptedAt < limits.repeatIntervalMs))) {
|
|
49
|
+
throw new ReminderError("invalid_schedule", "Until must include at least one eligible occurrence");
|
|
50
|
+
}
|
|
51
|
+
const bound: RoutineBound<number> = count !== undefined ? { count } : until !== undefined ? { until } : {};
|
|
52
|
+
if ("cron" in input) {
|
|
53
|
+
if (typeof input.cron !== "string" || !hasRoutineCronShape(input.cron) || typeof input.timezone !== "string" || !input.timezone.trim()) {
|
|
54
|
+
throw new ReminderError("invalid_schedule", "Expected a five-field numeric cron expression and timezone");
|
|
55
|
+
}
|
|
56
|
+
return { cron: input.cron, timezone: input.timezone, ...bound };
|
|
57
|
+
}
|
|
58
|
+
const startAt = input.startAt ?? acceptedAt + input.every;
|
|
59
|
+
if (!Number.isSafeInteger(input.every) || input.every < limits.repeatIntervalMs || !validInstant(startAt)
|
|
60
|
+
|| startAt - acceptedAt < limits.repeatIntervalMs || (!replacement && until !== undefined && until < startAt)) {
|
|
61
|
+
throw new ReminderError("invalid_schedule", "Invalid routine interval, start time or bound");
|
|
62
|
+
}
|
|
63
|
+
return { every: input.every, startAt, ...bound };
|
|
64
|
+
}
|
|
65
|
+
const at = "in" in input ? acceptedAt + input.in : input.at;
|
|
66
|
+
if (!Number.isSafeInteger(at) || at - acceptedAt < limits.oneShotLeadMs) {
|
|
67
|
+
throw new ReminderError("invalid_schedule", "Reminder does not meet the minimum lead time");
|
|
68
|
+
}
|
|
69
|
+
return { at };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function reminderExpiryPolicy(expiresAfter: number | null | undefined, limits = defaultReminderLimits): ReminderExpiryPolicy {
|
|
73
|
+
if (expiresAfter === undefined) return { kind: "default" };
|
|
74
|
+
if (expiresAfter === null) return { kind: "unlimited" };
|
|
75
|
+
if (!Number.isSafeInteger(expiresAfter) || expiresAfter < limits.minGraceMs || expiresAfter > limits.maxGraceMs) {
|
|
76
|
+
throw new ReminderError("invalid_input", "Invalid reminder expiry duration");
|
|
77
|
+
}
|
|
78
|
+
return { kind: "duration", milliseconds: expiresAfter };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function resolveReminderExpiry(
|
|
82
|
+
schedule: ReminderSchedule,
|
|
83
|
+
policy: ReminderExpiryPolicy,
|
|
84
|
+
acceptedAt: number,
|
|
85
|
+
limits: ReminderLimits = defaultReminderLimits,
|
|
86
|
+
): ReminderExpiry {
|
|
87
|
+
if (isRoutineSchedule(schedule) || policy.kind === "unknown") return { kind: "harness_default" };
|
|
88
|
+
if (policy.kind === "unlimited") return null;
|
|
89
|
+
const dueAt = schedule.at;
|
|
90
|
+
const lead = dueAt - acceptedAt;
|
|
91
|
+
const graceMs = policy.kind === "duration"
|
|
92
|
+
? policy.milliseconds
|
|
93
|
+
: Math.max(limits.minGraceMs, Math.min(limits.maxGraceMs, limits.expiryMultiplier * lead));
|
|
94
|
+
const at = dueAt + graceMs;
|
|
95
|
+
if (!Number.isSafeInteger(at)) throw new ReminderError("invalid_input", "Invalid reminder expiry instant");
|
|
96
|
+
return { kind: "absolute", at, graceMs };
|
|
97
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { isRoutineSchedule, type MissedRuns, type RoutineOverlap } from "./routine-schedule.ts";
|
|
2
|
+
import { SqliteAgentPersistence } from "../../persistence/sqlite-backend.ts";
|
|
3
|
+
import { ReminderWakeSupervisor } from "./supervisor.ts";
|
|
4
|
+
import { ReminderSync } from "./sync.ts";
|
|
5
|
+
import type { NativeHarnessHost } from "../host.ts";
|
|
6
|
+
import { noopLogger } from "../../logger.ts";
|
|
7
|
+
import { routineReminderRequest as reminderRequest } from "./wire.ts";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import type { PersistenceBackend } from "../../persistence/backend.ts";
|
|
10
|
+
import { createMemoryReminderPersistence, type Reminder, type ReminderChange, type ReminderJournal, type ReminderPersistence } from "../../persistence/reminders.ts";
|
|
11
|
+
import { defaultReminderLimits, type ReminderLimits } from "./limits.ts";
|
|
12
|
+
import { normalizeReminderSchedule, ReminderError, reminderExpiryPolicy, resolveReminderExpiry, type ReminderScheduleInput } from "./schedule.ts";
|
|
13
|
+
|
|
14
|
+
export interface ReminderEdit {
|
|
15
|
+
readonly text?: string;
|
|
16
|
+
readonly schedule?: ReminderScheduleInput;
|
|
17
|
+
readonly expiresAfter?: number | null;
|
|
18
|
+
readonly policyNames?: readonly string[];
|
|
19
|
+
readonly missedRuns?: MissedRuns;
|
|
20
|
+
readonly overlap?: RoutineOverlap;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ReminderCreate extends ReminderEdit {
|
|
24
|
+
readonly text: string;
|
|
25
|
+
readonly schedule: ReminderScheduleInput;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ReminderView extends Reminder {
|
|
29
|
+
readonly state: "pending" | "maybe_sent" | "confirmed" | "blocked";
|
|
30
|
+
readonly reason?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ReminderEvent = {
|
|
34
|
+
kind: "reminder_intent_recorded" | "reminder_intent_confirmed" | "reminder_intent_blocked" | "reminder_intent_discarded";
|
|
35
|
+
reminder: ReminderView;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type LiveReminderOutcome = { confirmed: Reminder } | { reason: string } | { retryable: true };
|
|
39
|
+
|
|
40
|
+
export interface ReminderServiceOptions {
|
|
41
|
+
readonly persistence?: PersistenceBackend;
|
|
42
|
+
readonly repository?: ReminderPersistence;
|
|
43
|
+
readonly supported?: () => boolean | undefined;
|
|
44
|
+
readonly routineUnavailable?: () => string | undefined;
|
|
45
|
+
readonly negotiatedLimits?: () => ReminderLimits | undefined;
|
|
46
|
+
readonly refresh?: (channel?: string, id?: string) => Promise<void>;
|
|
47
|
+
readonly running?: () => boolean;
|
|
48
|
+
readonly canDiscardExhausted?: () => boolean;
|
|
49
|
+
readonly now?: () => number;
|
|
50
|
+
readonly limits?: ReminderLimits;
|
|
51
|
+
readonly authorize?: (conversationId: string, op: ReminderChange["op"]) => boolean;
|
|
52
|
+
readonly live?: (change: ReturnType<typeof reminderRequest>, original?: ReminderChange) => Promise<LiveReminderOutcome>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export { routineReminderRequest as reminderRequest } from "./wire.ts";
|
|
56
|
+
|
|
57
|
+
function view(journal: ReminderJournal): ReminderView | undefined {
|
|
58
|
+
const change = journal.changes.findLast(({ state }) => state !== "applied");
|
|
59
|
+
if (change && (change.op !== "cancel" || change.state === "blocked")) {
|
|
60
|
+
return { ...change.reminder, state: change.state as Exclude<ReminderView["state"], "confirmed">,
|
|
61
|
+
...(change.reason === undefined ? {} : { reason: change.reason }) };
|
|
62
|
+
}
|
|
63
|
+
if (!change && journal.confirmed) return { ...journal.confirmed, state: "confirmed" };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class ReminderService {
|
|
67
|
+
readonly repository: ReminderPersistence;
|
|
68
|
+
private get limits(): ReminderLimits { return this.options.negotiatedLimits?.() ?? this.options.limits ?? defaultReminderLimits; }
|
|
69
|
+
|
|
70
|
+
constructor(private readonly options: ReminderServiceOptions = {}) {
|
|
71
|
+
this.repository = options.persistence?.reminders ?? options.repository ?? createMemoryReminderPersistence();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private transact<T>(work: (repository: ReminderPersistence) => Promise<T>): Promise<T> {
|
|
75
|
+
const persistence = this.options.persistence;
|
|
76
|
+
return persistence?.reminders
|
|
77
|
+
? persistence.transaction((scope) => work(scope.reminders!))
|
|
78
|
+
: work(this.repository);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async list({ after, limit = 50 }: { after?: string; limit?: number } = {}) {
|
|
82
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new ReminderError("invalid_input", "Page size must be 1–100");
|
|
83
|
+
if (this.options.running?.()) await this.options.refresh?.();
|
|
84
|
+
const rows = (await this.repository.list()).flatMap((journal) => view(journal) ?? []);
|
|
85
|
+
const items = rows.filter(({ id }) => after === undefined || id > after).sort((a, b) => a.id < b.id ? -1 : 1);
|
|
86
|
+
return { items: items.slice(0, limit), nextCursor: items.length > limit ? items[limit - 1]!.id : null };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
conversation(conversationId: string, supported: boolean, emit: (event: ReminderEvent) => void) {
|
|
90
|
+
const check = () => {
|
|
91
|
+
if (!supported || this.options.supported?.() === false) throw new ReminderError("reminders_unsupported", "This conversation does not support reminders");
|
|
92
|
+
};
|
|
93
|
+
const authorize = (op: ReminderChange["op"]) => {
|
|
94
|
+
if (this.options.authorize?.(conversationId, op) === false) {
|
|
95
|
+
throw new ReminderError("unauthorized", "Reminder change is not authorized");
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const list = async (id?: string) => {
|
|
99
|
+
check();
|
|
100
|
+
if (this.options.running?.()) await this.options.refresh?.(conversationId, id);
|
|
101
|
+
return (await this.repository.list()).filter((row) => row.conversationId === conversationId)
|
|
102
|
+
.flatMap((journal) => view(journal) ?? []);
|
|
103
|
+
};
|
|
104
|
+
const mutate = async (op: ReminderChange["op"], id: string, edit: ReminderEdit = {}, status?: Reminder["status"]) => {
|
|
105
|
+
check();
|
|
106
|
+
authorize(op);
|
|
107
|
+
if (op === "update" && (edit.policyNames !== undefined || (!status && edit.text === undefined && edit.schedule === undefined && edit.expiresAfter === undefined && edit.missedRuns === undefined && edit.overlap === undefined))) {
|
|
108
|
+
throw new ReminderError("invalid_input", "Expected a nonempty reminder patch with immutable policies");
|
|
109
|
+
}
|
|
110
|
+
const live = this.options.running?.() ? this.options.live : undefined;
|
|
111
|
+
const acceptedAt = (this.options.now ?? Date.now)();
|
|
112
|
+
const retryKey = JSON.stringify([op, status, edit], (_key, value: unknown) =>
|
|
113
|
+
value !== null && typeof value === "object" && !Array.isArray(value)
|
|
114
|
+
? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))) : value);
|
|
115
|
+
const prepared = await this.transact(async (repo) => {
|
|
116
|
+
const rows = (await repo.list()).filter((row) => row.conversationId === conversationId);
|
|
117
|
+
const retry = rows.filter(row => op === "create" || row.id === id)
|
|
118
|
+
.map(row => row.changes.at(-1))
|
|
119
|
+
.find(change => change?.state === "maybe_sent" && change.reason === "storage_failure" && change.retryKey === retryKey);
|
|
120
|
+
if (retry) {
|
|
121
|
+
id = retry.reminder.id;
|
|
122
|
+
return { reminder: retry.reminder, change: retry, retry: true };
|
|
123
|
+
}
|
|
124
|
+
const previous = rows.find((row) => row.id === id);
|
|
125
|
+
const existing = previous && view(previous);
|
|
126
|
+
const confirmed = previous?.confirmed;
|
|
127
|
+
if (op !== "create" && confirmed && ["completed", "cancelled", "expired"].includes(confirmed.status)) {
|
|
128
|
+
if (op === "cancel") return { unchanged: { ...confirmed, state: "confirmed" as const } };
|
|
129
|
+
throw new ReminderError("conflict", "Reminder is already terminal");
|
|
130
|
+
}
|
|
131
|
+
const last = previous?.changes.at(-1);
|
|
132
|
+
if (op !== "create" && last?.op === "cancel" && (last.state === "pending" || last.state === "maybe_sent")) {
|
|
133
|
+
if (op === "cancel") return { unchanged: { ...last.reminder, state: last.state } };
|
|
134
|
+
throw new ReminderError("conflict", "Reminder already has a cancellation in progress");
|
|
135
|
+
}
|
|
136
|
+
if (op !== "create" && (!existing || (!confirmed && last?.op === "create" && last.state === "blocked"))) throw new ReminderError("not_found", "Reminder was not found");
|
|
137
|
+
const routine = edit.schedule ? isRoutineSchedule(edit.schedule) : isRoutineSchedule(existing?.schedule);
|
|
138
|
+
if (op !== "create" && edit.schedule && routine !== isRoutineSchedule(existing?.schedule)) {
|
|
139
|
+
throw new ReminderError("invalid_schedule", "Reminder schedule kind cannot change");
|
|
140
|
+
}
|
|
141
|
+
if (edit.schedule && existing && routine && ("every" in edit.schedule) !== ("every" in existing.schedule)) {
|
|
142
|
+
throw new ReminderError("invalid_schedule", "Routine schedule kind cannot change");
|
|
143
|
+
}
|
|
144
|
+
if (routine && (op === "create" || edit.schedule || status === "active")) {
|
|
145
|
+
const why = this.options.routineUnavailable ? this.options.routineUnavailable() : "Routine reminders are unavailable";
|
|
146
|
+
if (why !== undefined) throw new ReminderError("routines_unavailable", why);
|
|
147
|
+
}
|
|
148
|
+
if ((!routine && (edit.missedRuns !== undefined || edit.overlap !== undefined)) ||
|
|
149
|
+
(edit.missedRuns !== undefined && !["coalesce", "skip", "each"].includes(edit.missedRuns)) ||
|
|
150
|
+
(edit.overlap !== undefined && !["skip", "queue"].includes(edit.overlap))) {
|
|
151
|
+
throw new ReminderError("invalid_input", "Invalid routine missed-run or overlap policy");
|
|
152
|
+
}
|
|
153
|
+
if (!live && !repo.durable) {
|
|
154
|
+
throw new ReminderError("reminders_unavailable", "Reminders require a live service or durable persistence");
|
|
155
|
+
}
|
|
156
|
+
const schedule = edit.schedule
|
|
157
|
+
? normalizeReminderSchedule(edit.schedule, acceptedAt, this.limits, op === "update")
|
|
158
|
+
: existing!.schedule;
|
|
159
|
+
const expiryPolicy = edit.expiresAfter !== undefined || !existing
|
|
160
|
+
? reminderExpiryPolicy(edit.expiresAfter, this.limits) : existing.expiryPolicy;
|
|
161
|
+
const scheduleAcceptedAt = edit.schedule ? acceptedAt : existing?.scheduleAcceptedAt ?? acceptedAt;
|
|
162
|
+
const expiry = edit.schedule || edit.expiresAfter !== undefined
|
|
163
|
+
? resolveReminderExpiry(schedule, expiryPolicy, scheduleAcceptedAt, this.limits)
|
|
164
|
+
: existing!.expiry;
|
|
165
|
+
const text = edit.text ?? existing!.text;
|
|
166
|
+
if (!text.trim()) throw new ReminderError("invalid_input", "Reminder text is required");
|
|
167
|
+
const policyNames = edit.policyNames ?? existing?.policyNames;
|
|
168
|
+
const reminder: Reminder = {
|
|
169
|
+
...(routine ? previous?.changes.findLast(change => change.state !== "applied")?.reminder ?? confirmed ?? {} : {}),
|
|
170
|
+
id, conversationId, text, schedule, expiry, expiryPolicy, scheduleAcceptedAt,
|
|
171
|
+
status: status ?? existing?.status ?? "active",
|
|
172
|
+
...(routine ? {
|
|
173
|
+
missedRuns: edit.missedRuns ?? existing?.missedRuns ?? "coalesce",
|
|
174
|
+
overlap: edit.overlap ?? existing?.overlap ?? "skip",
|
|
175
|
+
...(edit.schedule ? { remainingCount: "count" in schedule ? schedule.count : undefined } : {}),
|
|
176
|
+
} : {}),
|
|
177
|
+
...(policyNames === undefined ? {} : { policyNames }),
|
|
178
|
+
};
|
|
179
|
+
const fields: NonNullable<ReminderChange["fields"]>[number][] = [];
|
|
180
|
+
if (edit.text !== undefined) fields.push("text");
|
|
181
|
+
if (edit.schedule !== undefined) fields.push("schedule");
|
|
182
|
+
if (edit.expiresAfter !== undefined) fields.push("expiry");
|
|
183
|
+
if (status !== undefined) fields.push("status");
|
|
184
|
+
if (edit.policyNames !== undefined) fields.push("policyNames");
|
|
185
|
+
if (edit.missedRuns !== undefined) fields.push("missedRuns");
|
|
186
|
+
if (edit.overlap !== undefined) fields.push("overlap");
|
|
187
|
+
const pending = await repo.enqueue({ reminder, acceptedAt, op, fields, ...(routine && live ? { retryKey } : {}) });
|
|
188
|
+
const outgoing = pending && live ? await repo.markMaybeSent(id, pending.changeId) : pending;
|
|
189
|
+
return { reminder, change: outgoing };
|
|
190
|
+
});
|
|
191
|
+
if (prepared.unchanged) return prepared.unchanged;
|
|
192
|
+
let result: ReminderView = { ...prepared.reminder, state: prepared.change?.state === "maybe_sent" ? "maybe_sent" : "pending" };
|
|
193
|
+
if (!prepared.retry) emit({ kind: prepared.change ? "reminder_intent_recorded" : "reminder_intent_discarded", reminder: result });
|
|
194
|
+
if (live && prepared.change) {
|
|
195
|
+
const outcome = await live(reminderRequest(prepared.change, this.limits), prepared.change);
|
|
196
|
+
if ("retryable" in outcome) {
|
|
197
|
+
await this.repository.deferStorageFailure(id, prepared.change.changeId);
|
|
198
|
+
return { ...result, reason: "storage_failure" };
|
|
199
|
+
}
|
|
200
|
+
await this.repository.acknowledge(id, prepared.change.changeId, outcome);
|
|
201
|
+
result = "reason" in outcome
|
|
202
|
+
? { ...result, state: "blocked", reason: outcome.reason }
|
|
203
|
+
: { ...outcome.confirmed, state: "confirmed" };
|
|
204
|
+
emit({ kind: result.state === "blocked" ? "reminder_intent_blocked" : "reminder_intent_confirmed", reminder: result });
|
|
205
|
+
}
|
|
206
|
+
return result;
|
|
207
|
+
};
|
|
208
|
+
return {
|
|
209
|
+
create: (input: ReminderCreate) => mutate("create", randomUUID(), input),
|
|
210
|
+
get: async (id: string) => (await list(id)).find((item) => item.id === id),
|
|
211
|
+
list: () => list(),
|
|
212
|
+
update: (id: string, input: ReminderEdit) => mutate("update", id, input),
|
|
213
|
+
pause: (id: string) => mutate("update", id, {}, "paused"),
|
|
214
|
+
resume: (id: string) => mutate("update", id, {}, "active"),
|
|
215
|
+
cancel: (id: string) => mutate("cancel", id, {}, "cancelled"),
|
|
216
|
+
discardExhausted: async (id: string) => {
|
|
217
|
+
check();
|
|
218
|
+
authorize("update");
|
|
219
|
+
return this.transact(async repo => {
|
|
220
|
+
if (this.options.canDiscardExhausted?.() === false) {
|
|
221
|
+
throw new ReminderError("conflict", "Stop the harness before discarding exhausted reminder entries");
|
|
222
|
+
}
|
|
223
|
+
return repo.discardExhausted(id, conversationId);
|
|
224
|
+
});
|
|
225
|
+
},
|
|
226
|
+
discardBlocked: async (id: string) => {
|
|
227
|
+
check();
|
|
228
|
+
authorize("update");
|
|
229
|
+
const discarded = await this.transact(async (repo) => {
|
|
230
|
+
const row = (await repo.list()).find(row => row.id === id && row.conversationId === conversationId);
|
|
231
|
+
const item = row && view(row);
|
|
232
|
+
if (item?.state !== "blocked") return;
|
|
233
|
+
await repo.discardBlocked(id);
|
|
234
|
+
return item;
|
|
235
|
+
});
|
|
236
|
+
if (discarded) emit({ kind: "reminder_intent_discarded", reminder: discarded });
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function createAgentReminderService(
|
|
243
|
+
host: NativeHarnessHost | null,
|
|
244
|
+
persistence: PersistenceBackend,
|
|
245
|
+
options?: Pick<ReminderServiceOptions, "authorize" | "limits">,
|
|
246
|
+
log = noopLogger,
|
|
247
|
+
): ReminderService {
|
|
248
|
+
const service = new ReminderService({
|
|
249
|
+
...options, persistence,
|
|
250
|
+
canDiscardExhausted: () => host?.state === "stopped" || host?.state === "failed",
|
|
251
|
+
running: () => host?.state === "running" && host.reminderSync?.supported === true,
|
|
252
|
+
supported: () => host?.reminderSync?.supported,
|
|
253
|
+
routineUnavailable: () => host?.reminderSync
|
|
254
|
+
? host.reminderSync.routineAdmission.unavailable() : "Routine reminders are unavailable",
|
|
255
|
+
negotiatedLimits: () => host?.reminderSync?.supported === true ? host.reminderSync.limits : undefined,
|
|
256
|
+
refresh: async (channel, id) => { await host?.refreshReminders(channel, id); },
|
|
257
|
+
live: async (change) => await host?.changeReminder(change) ?? { reason: "not_found" },
|
|
258
|
+
});
|
|
259
|
+
if (host) {
|
|
260
|
+
host.reminderSync = new ReminderSync(persistence, service.repository, log);
|
|
261
|
+
host.armIdleStop(async () => {
|
|
262
|
+
const rows = await service.repository.list();
|
|
263
|
+
return {
|
|
264
|
+
held: rows.some(row => row.changes.some(change => change.state === "pending" || change.state === "maybe_sent")),
|
|
265
|
+
channels: rows.filter(row => row.confirmed?.status === "active" && row.confirmed.nextRunAt != null).map(row => row.conversationId),
|
|
266
|
+
};
|
|
267
|
+
});
|
|
268
|
+
if (persistence instanceof SqliteAgentPersistence && persistence.ownsReminderWake) {
|
|
269
|
+
host.reminderWake = new ReminderWakeSupervisor({
|
|
270
|
+
state: () => host.reminderWakeState,
|
|
271
|
+
index: () => service.repository.wake(host.state === "running" && host.reminderSync?.routineAdmission.available === true),
|
|
272
|
+
subscribe: listener => persistence.subscribeReminderWake(listener),
|
|
273
|
+
start: now => host.startForReminder(now),
|
|
274
|
+
error: error => log.warn("reminder_wake_failed", { error: String(error) }),
|
|
275
|
+
}, host.reminderTimer);
|
|
276
|
+
host.reminderWake.subscribeHost(listener => host.subscribeState(listener));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return service;
|
|
280
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { NativeHostState } from "../host.ts";
|
|
2
|
+
import type { ReminderWakeIndex } from "../../persistence/reminders.ts";
|
|
3
|
+
|
|
4
|
+
export interface ReminderTimer {
|
|
5
|
+
now(): number;
|
|
6
|
+
set(delayMs: number, task: () => void): () => void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const wallReminderTimer: ReminderTimer = {
|
|
10
|
+
now: Date.now,
|
|
11
|
+
set(delay, task) {
|
|
12
|
+
const timer = setTimeout(task, delay);
|
|
13
|
+
timer.unref?.();
|
|
14
|
+
return () => clearTimeout(timer);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
interface WakeSource {
|
|
19
|
+
state(): NativeHostState;
|
|
20
|
+
index(): Promise<ReminderWakeIndex>;
|
|
21
|
+
subscribe(listener: () => void): () => void;
|
|
22
|
+
start(now: number): Promise<void>;
|
|
23
|
+
error(error: unknown): void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** One owner may arm one cold wake. The harness owns scheduling while running. */
|
|
27
|
+
export class ReminderWakeSupervisor {
|
|
28
|
+
private release?: () => void;
|
|
29
|
+
private unsubscribe?: () => void;
|
|
30
|
+
private generation = 0;
|
|
31
|
+
private closed = false;
|
|
32
|
+
private waking = false;
|
|
33
|
+
private armed?: { target: number; cancel: () => void };
|
|
34
|
+
|
|
35
|
+
constructor(private readonly source: WakeSource, private readonly clock: ReminderTimer = wallReminderTimer) {
|
|
36
|
+
this.unsubscribe = source.subscribe(() => this.refresh());
|
|
37
|
+
this.refresh();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
close(): void {
|
|
41
|
+
this.closed = true;
|
|
42
|
+
this.unsubscribe?.();
|
|
43
|
+
this.release?.();
|
|
44
|
+
this.disarm();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
subscribeHost(subscribe: (listener: () => void) => () => void): void {
|
|
48
|
+
this.release = subscribe(() => this.refresh());
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
refresh(): void {
|
|
52
|
+
const generation = ++this.generation;
|
|
53
|
+
if (!this.eligible()) { this.disarm(); return; }
|
|
54
|
+
void this.source.index().then(({ effectiveAt }) => {
|
|
55
|
+
if (generation !== this.generation || !this.eligible()) return;
|
|
56
|
+
if (effectiveAt !== null && this.armed?.target === effectiveAt) return;
|
|
57
|
+
this.disarm();
|
|
58
|
+
if (effectiveAt === null) return;
|
|
59
|
+
const delay = Math.min(60_000, Math.max(1_000, effectiveAt - this.clock.now()));
|
|
60
|
+
this.armed = { target: effectiveAt, cancel: this.clock.set(delay, () => void this.wake(effectiveAt)) };
|
|
61
|
+
}).catch(error => { if (!this.closed) this.source.error(error); });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private eligible(): boolean {
|
|
65
|
+
const state = this.source.state();
|
|
66
|
+
return !this.closed && !this.waking && (state === "stopped" || state === "starting");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private disarm(): void {
|
|
70
|
+
this.armed?.cancel();
|
|
71
|
+
this.armed = undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async wake(target: number): Promise<void> {
|
|
75
|
+
if (this.armed?.target !== target) return;
|
|
76
|
+
this.disarm();
|
|
77
|
+
if (!this.eligible()) return;
|
|
78
|
+
if (this.clock.now() < target) { this.refresh(); return; }
|
|
79
|
+
this.waking = true;
|
|
80
|
+
try {
|
|
81
|
+
const { effectiveAt } = await this.source.index();
|
|
82
|
+
if (this.closed || effectiveAt === null || effectiveAt > this.clock.now() || this.source.state() === "running") return;
|
|
83
|
+
await this.source.start(this.clock.now());
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!this.closed) this.source.error(error);
|
|
86
|
+
} finally {
|
|
87
|
+
this.waking = false;
|
|
88
|
+
this.refresh();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|