@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,65 @@
|
|
|
1
|
+
import type { RoutineCalendar, RoutineDeliveryOptions } from "../../contracts/routines.ts";
|
|
2
|
+
import { routineBacklog, type OrdinalRange } from "./routine-backlog.ts";
|
|
3
|
+
import { routineExpiry } from "./routine-expiry.ts";
|
|
4
|
+
|
|
5
|
+
type SkipReason = "expired" | "missed" | "catch_up_limit";
|
|
6
|
+
export type RoutineStep = OrdinalRange & (
|
|
7
|
+
| { kind: SkipReason }
|
|
8
|
+
| { kind: "enqueue"; represented: number }
|
|
9
|
+
| { kind: "coalesced" }
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
/** Build one episode's chronological steps. A persisted cursor can consume
|
|
13
|
+
* these in transaction-sized batches without reclassifying elapsed work. */
|
|
14
|
+
export function planRoutineEpisode(
|
|
15
|
+
calendar: RoutineCalendar, next: number, cutoff: number, grace: number | null | undefined,
|
|
16
|
+
missed: NonNullable<RoutineDeliveryOptions["missedRuns"]>,
|
|
17
|
+
): RoutineStep[] {
|
|
18
|
+
const backlog = routineBacklog(calendar, next, cutoff, grace, missed);
|
|
19
|
+
const steps: RoutineStep[] = backlog.expired.map(range => ({ ...range, kind: "expired" }));
|
|
20
|
+
for (const range of backlog.discarded) steps.push({ ...range, kind: missed === "skip" ? "missed" : "catch_up_limit" });
|
|
21
|
+
for (const ordinal of backlog.queue) steps.push({ first: ordinal, last: ordinal, kind: "enqueue", represented: 1 });
|
|
22
|
+
const represented = backlog.coalesced.reduce((sum, range) => sum + range.last - range.first + 1, 0);
|
|
23
|
+
for (const [index, range] of backlog.coalesced.entries()) {
|
|
24
|
+
if (index + 1 === backlog.coalesced.length) steps.push({ ...range, kind: "enqueue", represented });
|
|
25
|
+
else steps.push({ ...range, kind: "coalesced" });
|
|
26
|
+
}
|
|
27
|
+
const current = calendar.rank(cutoff) - 1;
|
|
28
|
+
if (current >= next && current >= calendar.rank(Math.floor(cutoff / 60_000) * 60_000 - 1)) {
|
|
29
|
+
const expiry = routineExpiry(calendar, calendar.at(current)!, grace).expiresAt;
|
|
30
|
+
steps.push(expiry !== null && expiry <= cutoff ? { first: current, last: current, kind: "expired" }
|
|
31
|
+
: { first: current, last: current, kind: "enqueue", represented: 1 });
|
|
32
|
+
}
|
|
33
|
+
return steps.sort((left, right) => left.first - right.first);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function routineOccurrenceIdentity(reminderId: string, instant: number) {
|
|
37
|
+
const scheduledAt = new Date(instant).toISOString();
|
|
38
|
+
return { scheduledAt, occurrenceId: `reminder:${reminderId}:${scheduledAt}`,
|
|
39
|
+
noticeId: `reminder-notice:${reminderId}:${scheduledAt}` };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type ExpiredDisposition = {
|
|
43
|
+
type: "routine_disposition";
|
|
44
|
+
reminderId: string;
|
|
45
|
+
firstScheduledAt: string;
|
|
46
|
+
lastScheduledAt: string;
|
|
47
|
+
count: number;
|
|
48
|
+
reason: "expired";
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** The disposition describes consumption only. The returned cursor and
|
|
52
|
+
* remaining count are for updating the authoritative row in the same commit. */
|
|
53
|
+
export function expireRoutineRange(reminderId: string, calendar: RoutineCalendar, range: OrdinalRange, remainingCount?: number) {
|
|
54
|
+
const first = calendar.at(range.first), last = calendar.at(range.last);
|
|
55
|
+
const count = range.last - range.first + 1;
|
|
56
|
+
if (first === undefined || last === undefined || count < 1 || (remainingCount !== undefined && count > remainingCount))
|
|
57
|
+
throw new RangeError("Invalid routine expiry range");
|
|
58
|
+
const remaining = remainingCount === undefined ? undefined : remainingCount - count;
|
|
59
|
+
const next = remaining === 0 ? undefined : calendar.at(range.last + 1);
|
|
60
|
+
const event: ExpiredDisposition = {
|
|
61
|
+
type: "routine_disposition", reminderId, reason: "expired", count,
|
|
62
|
+
firstScheduledAt: new Date(first).toISOString(), lastScheduledAt: new Date(last).toISOString(),
|
|
63
|
+
};
|
|
64
|
+
return { event, remainingCount: remaining, nextRunAt: next === undefined ? null : new Date(next).toISOString() };
|
|
65
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { cronCivilCalendar } from "./cron-calendar.ts";
|
|
2
|
+
import { parseRoutineCron } from "./cron-fields.ts";
|
|
3
|
+
import { zonedCalendar } from "./cron-zone.ts";
|
|
4
|
+
import type { RoutineCalendar, RoutineSchedule } from "../../contracts/routines.ts";
|
|
5
|
+
import { reminderInstant, REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
|
|
6
|
+
import { proveRoutineCron } from "./cron-proof.ts";
|
|
7
|
+
import { resolveRoutineZone } from "./iana-zones.ts";
|
|
8
|
+
import { intervalCalendar } from "./interval.ts";
|
|
9
|
+
|
|
10
|
+
const invalid = { kind: "invalid_schedule" } as const;
|
|
11
|
+
|
|
12
|
+
function limitCalendar(calendar: RoutineCalendar, first: number, count: number | undefined, until: number | undefined): RoutineCalendar | undefined {
|
|
13
|
+
const end = until === undefined ? Infinity : calendar.rank(until);
|
|
14
|
+
const size = Math.min(end - first, count ?? Infinity);
|
|
15
|
+
if (size <= 0 || calendar.at(first) === undefined) return;
|
|
16
|
+
return {
|
|
17
|
+
at: ordinal => Number.isSafeInteger(ordinal) && ordinal >= 0 && ordinal < size ? calendar.at(first + ordinal) : undefined,
|
|
18
|
+
rank: through => Math.max(0, Math.min(size, calendar.rank(through) - first)),
|
|
19
|
+
nextCalendarMatch: instant => calendar.nextCalendarMatch(instant),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function prepareRoutineSchedule(schedule: RoutineSchedule, acceptedAt: string, now: number, processedThrough?: number) {
|
|
24
|
+
const anchor = reminderInstant(acceptedAt);
|
|
25
|
+
if (anchor === undefined || anchor > now + 30_000) return invalid;
|
|
26
|
+
if (schedule.count !== undefined && (schedule.until !== undefined || !Number.isSafeInteger(schedule.count) || schedule.count < 1)) return invalid;
|
|
27
|
+
const until = schedule.until === undefined ? undefined : reminderInstant(schedule.until);
|
|
28
|
+
if (schedule.until !== undefined && until === undefined) return invalid;
|
|
29
|
+
|
|
30
|
+
if ("every" in schedule) {
|
|
31
|
+
const calendar = intervalCalendar(schedule, anchor, processedThrough);
|
|
32
|
+
if (!calendar) return invalid;
|
|
33
|
+
const start = schedule.startAt === undefined ? anchor + schedule.every : reminderInstant(schedule.startAt)!;
|
|
34
|
+
return { kind: "valid", calendar, schedule: { ...schedule, startAt: new Date(start).toISOString() } } as const;
|
|
35
|
+
}
|
|
36
|
+
const zone = resolveRoutineZone(schedule.timezone);
|
|
37
|
+
if (!zone) return invalid;
|
|
38
|
+
const proof = proveRoutineCron(schedule.cron, zone);
|
|
39
|
+
if (proof.kind !== "valid") return proof;
|
|
40
|
+
const { calendar } = proof;
|
|
41
|
+
const first = calendar.at(calendar.rank(anchor));
|
|
42
|
+
if (first === undefined || first - anchor < REMINDER_LIMITS.minIntervalMs) return invalid;
|
|
43
|
+
const bounded = limitCalendar(calendar, calendar.rank(Math.max(anchor, processedThrough ?? anchor)), schedule.count, until);
|
|
44
|
+
return bounded
|
|
45
|
+
? { kind: "valid", calendar: bounded, schedule: { ...schedule, timezone: zone.timezone }, timezoneVersion: zone.timezoneVersion } as const
|
|
46
|
+
: invalid;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** An owner transaction can advance many rows or steps using one index per
|
|
50
|
+
* admitted cron. Existing schedules need evaluation, not a timed proof. */
|
|
51
|
+
export function createRoutineEvaluator() {
|
|
52
|
+
const calendars = new Map<string, RoutineCalendar | undefined>();
|
|
53
|
+
return (schedule: RoutineSchedule, acceptedAt: string, timezoneVersion: string | undefined, processedThrough?: number) => {
|
|
54
|
+
const anchor = reminderInstant(acceptedAt);
|
|
55
|
+
if (anchor === undefined) return;
|
|
56
|
+
if ("every" in schedule) return intervalCalendar(schedule, anchor, processedThrough);
|
|
57
|
+
const key = JSON.stringify([timezoneVersion, schedule.timezone, schedule.cron]);
|
|
58
|
+
if (!calendars.has(key)) {
|
|
59
|
+
const zone = resolveRoutineZone(schedule.timezone);
|
|
60
|
+
const fields = zone?.timezoneVersion === timezoneVersion ? parseRoutineCron(schedule.cron) : undefined;
|
|
61
|
+
const civil = fields && cronCivilCalendar(fields);
|
|
62
|
+
calendars.set(key, zone && civil ? zonedCalendar(civil, zone.start, zone.end, zone.initialOffset, zone.transitions) : undefined);
|
|
63
|
+
}
|
|
64
|
+
const calendar = calendars.get(key);
|
|
65
|
+
if (!calendar) return;
|
|
66
|
+
const until = schedule.until === undefined ? undefined : reminderInstant(schedule.until);
|
|
67
|
+
if (schedule.until !== undefined && until === undefined) return;
|
|
68
|
+
return limitCalendar(calendar, calendar.rank(Math.max(anchor, processedThrough ?? anchor)), schedule.count, until);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Use the same initial take when checking eligibility and charging a turn.
|
|
2
|
+
* Kept outside storage so memory and SQLite apply identical policy. */
|
|
3
|
+
export function unattendedAdmission(limit: number | undefined, spent: number, participantInInitialTake: boolean) {
|
|
4
|
+
if (limit === undefined) return { eligible: true, nextSpent: spent };
|
|
5
|
+
if (participantInInitialTake) return { eligible: true, nextSpent: 0 };
|
|
6
|
+
if (spent >= limit) return { eligible: false, nextSpent: spent };
|
|
7
|
+
return { eligible: true, nextSpent: spent + 1 };
|
|
8
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ExecuteTool, ToolDefinition } from "../../../contracts/loop.ts";
|
|
2
|
+
|
|
3
|
+
export const currentTimeDefinition: ToolDefinition = {
|
|
4
|
+
name: "current_time",
|
|
5
|
+
description: "Get the current UTC date and time.",
|
|
6
|
+
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export const executeCurrentTime: ExecuteTool = async (call) => {
|
|
10
|
+
console.log(`[tool] ${call.name} ${call.arguments}`);
|
|
11
|
+
try {
|
|
12
|
+
// The advertised schema is not an execution gate: reject unknown tools and
|
|
13
|
+
// invalid arguments here even if the model was only shown this definition.
|
|
14
|
+
if (call.name !== "current_time") throw new Error(`Tool not allowed: ${call.name}`);
|
|
15
|
+
const args = JSON.parse(call.arguments);
|
|
16
|
+
if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).length) {
|
|
17
|
+
throw new Error("current_time requires an empty object");
|
|
18
|
+
}
|
|
19
|
+
const result = JSON.stringify({ ok: true, time: new Date().toISOString() });
|
|
20
|
+
console.log(`[result] ${result}`);
|
|
21
|
+
return result;
|
|
22
|
+
} catch (error) {
|
|
23
|
+
// Expected tool failures go back to the model so it can choose what to do.
|
|
24
|
+
const result = JSON.stringify({ ok: false, error: String(error) });
|
|
25
|
+
console.log(`[result] ${result}`);
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { SessionAgent } from "../../../contracts/agent.ts";
|
|
2
|
+
import type { ToolDefinition } from "../../../contracts/loop.ts";
|
|
3
|
+
|
|
4
|
+
export const notifyChannelDefinition: ToolDefinition = {
|
|
5
|
+
name: "notify_channel",
|
|
6
|
+
description: "Deliver important information to an existing channel. Acceptance does not mean the target has acted.",
|
|
7
|
+
parameters: { type: "object", properties: { channelId: { type: "string" }, text: { type: "string" } },
|
|
8
|
+
required: ["channelId", "text"], additionalProperties: false },
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export function executeNotice(args: Record<string, unknown>, notify: (channel: string, text: string) => ReturnType<SessionAgent["notify"]>) {
|
|
12
|
+
if (!args || Array.isArray(args) || Object.keys(args).some(key => !["channelId", "text"].includes(key))
|
|
13
|
+
|| typeof args.channelId !== "string" || !args.channelId.trim() || typeof args.text !== "string" || !args.text.trim())
|
|
14
|
+
throw new Error("notify_channel requires channelId and text");
|
|
15
|
+
const receipt = notify(args.channelId, args.text);
|
|
16
|
+
return receipt.accepted ? { accepted: true } : { accepted: false, error: receipt.error };
|
|
17
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { testEcho, testEchoDefinition } from "./test-echo.ts";
|
|
2
|
+
import { testWait, testWaitDefinition } from "./test-wait.ts";
|
|
3
|
+
import { testFail, testFailDefinition } from "./test-fail.ts";
|
|
4
|
+
|
|
5
|
+
export const debugToolDefinitions = [testEchoDefinition, testWaitDefinition, testFailDefinition];
|
|
6
|
+
|
|
7
|
+
export const debugToolHandlers = new Map([
|
|
8
|
+
[testEchoDefinition.name, testEcho],
|
|
9
|
+
[testWaitDefinition.name, testWait],
|
|
10
|
+
[testFailDefinition.name, testFail],
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
export { testEcho, testEchoDefinition, testWait, testWaitDefinition, testFail, testFailDefinition };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ToolExecutionResult } from "../../../contracts/loop.ts";
|
|
2
|
+
|
|
3
|
+
export function debugFailure(code: "invalid_arguments" | "debug_failure", message: string): ToolExecutionResult {
|
|
4
|
+
return { content: JSON.stringify({ ok: false, error: { code, message } }), outcome: { status: "failed", code } };
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function debugArguments(raw: string): Record<string, unknown> | undefined {
|
|
8
|
+
try {
|
|
9
|
+
const value: unknown = JSON.parse(raw);
|
|
10
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
|
|
11
|
+
} catch { /* The executor reports a typed argument error. */ }
|
|
12
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
|
|
2
|
+
import { debugArguments, debugFailure } from "./result.ts";
|
|
3
|
+
|
|
4
|
+
const maxBytes = 1024;
|
|
5
|
+
export const testEchoDefinition: ToolDefinition = {
|
|
6
|
+
name: "test_echo",
|
|
7
|
+
description: "Debug only. Return the supplied text exactly, up to 1024 UTF-8 bytes.",
|
|
8
|
+
parameters: { type: "object", properties: { text: { type: "string", maxLength: maxBytes } },
|
|
9
|
+
required: ["text"], additionalProperties: false },
|
|
10
|
+
};
|
|
11
|
+
export const testEcho: ExecuteTool<string | ToolExecutionResult> = async ({ arguments: raw }) => {
|
|
12
|
+
const args = debugArguments(raw);
|
|
13
|
+
if (!args || typeof args.text !== "string" || Object.keys(args).length !== 1 || Buffer.byteLength(args.text) > maxBytes)
|
|
14
|
+
return debugFailure("invalid_arguments", "Expected only text, up to 1024 UTF-8 bytes.");
|
|
15
|
+
return JSON.stringify({ ok: true, text: args.text });
|
|
16
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
|
|
2
|
+
import { debugArguments, debugFailure } from "./result.ts";
|
|
3
|
+
|
|
4
|
+
export const testFailDefinition: ToolDefinition = {
|
|
5
|
+
name: "test_fail",
|
|
6
|
+
description: "Debug only. Return an intentional typed failure and let the turn continue.",
|
|
7
|
+
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
8
|
+
};
|
|
9
|
+
export const testFail: ExecuteTool<ToolExecutionResult> = async ({ arguments: raw }) => {
|
|
10
|
+
const args = debugArguments(raw);
|
|
11
|
+
if (!args || Object.keys(args).length)
|
|
12
|
+
return debugFailure("invalid_arguments", "Expected an empty object.");
|
|
13
|
+
return debugFailure("debug_failure", "Intentional test failure.");
|
|
14
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { setTimeout } from "node:timers/promises";
|
|
2
|
+
import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
|
|
3
|
+
import { debugArguments, debugFailure } from "./result.ts";
|
|
4
|
+
|
|
5
|
+
export const testWaitDefinition: ToolDefinition = {
|
|
6
|
+
name: "test_wait",
|
|
7
|
+
description: "Debug only. Hold this tool call for the requested duration so another channel can send input or the operator can interrupt. Performs no external work.",
|
|
8
|
+
parameters: { type: "object", properties: { durationMs: { type: "integer", minimum: 1, maximum: 30_000 } },
|
|
9
|
+
required: ["durationMs"], additionalProperties: false },
|
|
10
|
+
};
|
|
11
|
+
export const testWait: ExecuteTool<string | ToolExecutionResult> = async ({ arguments: raw }, signal) => {
|
|
12
|
+
const args = debugArguments(raw);
|
|
13
|
+
const durationMs = args?.durationMs;
|
|
14
|
+
if (!args || typeof durationMs !== "number" || !Number.isSafeInteger(durationMs) || durationMs < 1 || durationMs > 30_000 || Object.keys(args).length !== 1)
|
|
15
|
+
return debugFailure("invalid_arguments", "Expected only durationMs, an integer between 1 and 30000.");
|
|
16
|
+
signal?.throwIfAborted();
|
|
17
|
+
await setTimeout(durationMs, undefined, { signal });
|
|
18
|
+
return JSON.stringify({ ok: true, durationMs });
|
|
19
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { ToolDefinition } from "../../../contracts/loop.ts";
|
|
2
|
+
import type { AgentReminderSchedule, RoutineSchedule, RoutineDeliveryOptions } from "../../../contracts/reminders.ts";
|
|
3
|
+
import { SESSION_INPUT_MAX_BYTES } from "../../../contracts/input-limits.ts";
|
|
4
|
+
import { REMINDER_LIMITS, reminderInstant } from "../../../util/reminder-schedule.ts";
|
|
5
|
+
import type { ReminderStorage } from "../../../contracts/storage.ts";
|
|
6
|
+
import type { ReminderChannelEvent } from "../../../contracts/reminders.ts";
|
|
7
|
+
|
|
8
|
+
const names = ["schedule_reminder", "list_reminders", "cancel_reminder"] as const;
|
|
9
|
+
export const isReminderTool = (name: string) => names.some(candidate => candidate === name);
|
|
10
|
+
const string = { type: "string" };
|
|
11
|
+
const grace = { type: ["integer", "null"] };
|
|
12
|
+
export const reminderDefinitions: ToolDefinition[] = [
|
|
13
|
+
{ name: "schedule_reminder", description: "Schedule a one-off reminder in the current channel. Use UTC at or a relative duration such as 5m.",
|
|
14
|
+
parameters: { type: "object", properties: { schedule: { type: "object", properties: { at: string, in: string }, additionalProperties: false }, text: string, expiresAfter: grace },
|
|
15
|
+
required: ["schedule", "text"], additionalProperties: false } },
|
|
16
|
+
{ name: "list_reminders", description: "List reminders in the current channel.", parameters: {
|
|
17
|
+
type: "object", properties: { after: string, limit: { type: "integer" } }, additionalProperties: false } },
|
|
18
|
+
{ name: "cancel_reminder", description: "Cancel a reminder in the current channel.", parameters: {
|
|
19
|
+
type: "object", properties: { id: string }, required: ["id"], additionalProperties: false } },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
23
|
+
const allowed = (value: Record<string, unknown>, keys: string[]) => Object.keys(value).every(key => keys.includes(key));
|
|
24
|
+
const text = (value: unknown): value is string => typeof value === "string" && !!value.trim() && Buffer.byteLength(value) <= SESSION_INPUT_MAX_BYTES;
|
|
25
|
+
|
|
26
|
+
export const guardedReminderDefinitions: ToolDefinition[] = reminderDefinitions.map(tool => tool.name !== "schedule_reminder" ? tool : {
|
|
27
|
+
...tool, description: "Schedule a reminder or routine in the current channel. Cron uses five numeric fields and requires both day fields to match.",
|
|
28
|
+
parameters: { type: "object", properties: { text: string, expiresAfter: grace, missedRuns: { enum: ["coalesce", "skip", "each"] },
|
|
29
|
+
overlap: { enum: ["skip", "queue"] }, schedule: { type: "object", properties: { at: string, in: string,
|
|
30
|
+
every: { type: "integer" }, startAt: string, cron: string, timezone: string, count: { type: "integer" }, until: string },
|
|
31
|
+
additionalProperties: false } }, required: ["schedule", "text"], additionalProperties: false },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export type ReminderAction =
|
|
35
|
+
| { kind: "schedule"; schedule: AgentReminderSchedule | RoutineSchedule; text: string; expiresAfter?: number | null; delivery?: RoutineDeliveryOptions }
|
|
36
|
+
| { kind: "list"; after?: string; limit?: number }
|
|
37
|
+
| { kind: "cancel"; id: string };
|
|
38
|
+
|
|
39
|
+
export function reminderAction(tool: string, input: unknown): ReminderAction | undefined {
|
|
40
|
+
if (!object(input)) return;
|
|
41
|
+
if (tool === "cancel_reminder") {
|
|
42
|
+
if (allowed(input, ["id"]) && text(input.id)) return { kind: "cancel", id: input.id };
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (tool === "list_reminders") {
|
|
46
|
+
if (!allowed(input, ["after", "limit"])) return;
|
|
47
|
+
const { after, limit } = input;
|
|
48
|
+
if (after !== undefined && !text(after)) return;
|
|
49
|
+
if (limit !== undefined && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)) return;
|
|
50
|
+
return { kind: "list", ...(after === undefined ? {} : { after }), ...(limit === undefined ? {} : { limit }) };
|
|
51
|
+
}
|
|
52
|
+
if (!allowed(input, ["schedule", "text", "expiresAfter", "missedRuns", "overlap"]) || !text(input.text)) return;
|
|
53
|
+
const { schedule, expiresAfter } = input;
|
|
54
|
+
if (expiresAfter !== undefined && expiresAfter !== null && (typeof expiresAfter !== "number" || !Number.isSafeInteger(expiresAfter)
|
|
55
|
+
|| expiresAfter < REMINDER_LIMITS.minExpiryGraceMs || expiresAfter > REMINDER_LIMITS.maxExpiryGraceMs)) return;
|
|
56
|
+
if (!object(schedule)) return;
|
|
57
|
+
const payload = { kind: "schedule" as const, text: input.text, ...(expiresAfter === undefined ? {} : { expiresAfter }) };
|
|
58
|
+
const { missedRuns, overlap } = input;
|
|
59
|
+
if (missedRuns !== undefined && missedRuns !== "coalesce" && missedRuns !== "skip" && missedRuns !== "each") return;
|
|
60
|
+
if (overlap !== undefined && overlap !== "skip" && overlap !== "queue") return;
|
|
61
|
+
const { count, until } = schedule;
|
|
62
|
+
if (count !== undefined && (typeof count !== "number" || !Number.isSafeInteger(count) || count < 1 || until !== undefined)) return;
|
|
63
|
+
if (until !== undefined && !text(until)) return;
|
|
64
|
+
const end = count !== undefined ? { count } : until !== undefined ? { until } : {};
|
|
65
|
+
const delivery: RoutineDeliveryOptions = { missedRuns, overlap };
|
|
66
|
+
if (typeof schedule.every === "number" && Number.isSafeInteger(schedule.every)
|
|
67
|
+
&& allowed(schedule, ["every", "startAt", "count", "until"]) && (schedule.startAt === undefined || text(schedule.startAt)))
|
|
68
|
+
return { ...payload, delivery, schedule: { ...end, every: schedule.every, startAt: schedule.startAt } };
|
|
69
|
+
if (text(schedule.cron) && text(schedule.timezone) && allowed(schedule, ["cron", "timezone", "count", "until"]))
|
|
70
|
+
return { ...payload, delivery, schedule: { ...end, cron: schedule.cron, timezone: schedule.timezone } };
|
|
71
|
+
if (Object.keys(schedule).length !== 1 || missedRuns !== undefined || overlap !== undefined) return;
|
|
72
|
+
if (text(schedule.at) && reminderInstant(schedule.at) !== undefined) return { ...payload, schedule: { at: schedule.at } };
|
|
73
|
+
if (text(schedule.in) && /^[1-9]\d*[mhd]$/.test(schedule.in)) return { ...payload, schedule: { in: schedule.in } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
export function executeReminderTool(
|
|
78
|
+
storage: ReminderStorage, action: ReminderAction, channel: string, turnId: number, invocationId: string,
|
|
79
|
+
policies: readonly string[], now: number, publish: (event: ReminderChannelEvent, revision: number) => void,
|
|
80
|
+
): string {
|
|
81
|
+
if (action.kind === "list") {
|
|
82
|
+
const result = storage.listReminders({ channel, after: action.after, limit: action.limit });
|
|
83
|
+
return JSON.stringify(result.ok ? result.value : { error: result.error.code });
|
|
84
|
+
}
|
|
85
|
+
if (action.kind === "cancel") {
|
|
86
|
+
const result = storage.cancelAgentReminder(turnId, action.id);
|
|
87
|
+
if (!result.ok) return JSON.stringify({ error: result.error.code });
|
|
88
|
+
const { changed, ...value } = result.value;
|
|
89
|
+
if (changed) publish({ type: "reminder_cancelled", reminderId: value.id, by: "agent" }, result.revision);
|
|
90
|
+
return JSON.stringify(value);
|
|
91
|
+
}
|
|
92
|
+
const result = storage.scheduleAgentReminder(turnId, invocationId, action.schedule, action.text, policies, action.expiresAfter, now, action.delivery);
|
|
93
|
+
if (!result.ok) return JSON.stringify({ error: result.error.code });
|
|
94
|
+
const { reminder, created } = result.value;
|
|
95
|
+
if (created) publish({ type: "reminder_changed", reminder }, result.revision);
|
|
96
|
+
return JSON.stringify({ id: reminder.id, nextRunAt: reminder.nextRunAt });
|
|
97
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { timelineToolNames } from "../../../util/timeline-tool-names.ts";
|
|
2
|
+
import type { ToolDefinition } from "../../../contracts/loop.ts";
|
|
3
|
+
import type { ToolAvailability, ToolCatalogInput, ToolRegistration } from "../../../contracts/tools.ts";
|
|
4
|
+
|
|
5
|
+
/** A catalog the open must refuse, or a runtime operation on the wrong entry. */
|
|
6
|
+
export class CatalogError extends Error {
|
|
7
|
+
constructor(readonly code: "invalid_params" | "not_found" | "invalid_state", message: string) { super(message); }
|
|
8
|
+
}
|
|
9
|
+
const invalid = (message: string): never => { throw new CatalogError("invalid_params", message); };
|
|
10
|
+
const word = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
|
|
11
|
+
const duration = (value: unknown) => Number.isSafeInteger(value) && (value as number) > 0;
|
|
12
|
+
|
|
13
|
+
/** The scoped reader for results held by their producer. Offered whenever a
|
|
14
|
+
* catalog exists; its name is reserved. */
|
|
15
|
+
export const READ_TOOL_RESULT = "read_tool_result";
|
|
16
|
+
export const readToolResultDefinition: ToolDefinition = {
|
|
17
|
+
name: READ_TOOL_RESULT,
|
|
18
|
+
description: "Read part of a tool result that was too large to show in full. Use the result_id from that result. Only results produced in this conversation can be read.",
|
|
19
|
+
parameters: { type: "object", properties: { result_id: { type: "string" }, offset: { type: "integer", minimum: 0 }, length: { type: "integer", minimum: 1 } },
|
|
20
|
+
required: ["result_id"], additionalProperties: false },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Validate the whole catalog before anything is opened (decision 0021).
|
|
24
|
+
* `reserved` are the names of tools the session already has. */
|
|
25
|
+
export function parseCatalog(raw: unknown, reserved: readonly string[]): ToolCatalogInput {
|
|
26
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid("tools must be an object");
|
|
27
|
+
const input = raw as Record<string, unknown>;
|
|
28
|
+
for (const key of Object.keys(input)) if (!["catalog", "enabled", "defaultDeadlineMs"].includes(key)) invalid(`tools: unsupported field ${key}`);
|
|
29
|
+
if (!Array.isArray(input.catalog)) return invalid("tools.catalog must be an array");
|
|
30
|
+
const names = new Set<string>([...reserved, ...timelineToolNames, READ_TOOL_RESULT, "notify_channel"]);
|
|
31
|
+
const catalog = input.catalog.map((value, index): ToolRegistration => {
|
|
32
|
+
const at = `tools.catalog[${index}]`;
|
|
33
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) invalid(`${at} must be an object`);
|
|
34
|
+
const entry = value as Record<string, unknown>;
|
|
35
|
+
for (const key of Object.keys(entry)) if (!["name", "description", "parameters", "handler", "group", "deadlineMs"].includes(key)) invalid(`${at}: unsupported field ${key}`);
|
|
36
|
+
if (!word(entry.name)) return invalid(`${at}.name must be a nonempty string`);
|
|
37
|
+
if (names.has(entry.name)) invalid(`${at}: tool name ${entry.name} is already used`);
|
|
38
|
+
names.add(entry.name);
|
|
39
|
+
if (typeof entry.description !== "string") invalid(`${at}.description must be a string`);
|
|
40
|
+
if (!entry.parameters || typeof entry.parameters !== "object" || Array.isArray(entry.parameters)) invalid(`${at}.parameters must be a JSON schema object`);
|
|
41
|
+
if (!word(entry.handler)) invalid(`${at}.handler must be a nonempty string`);
|
|
42
|
+
if (entry.group !== "fixed" && entry.group !== "revocable" && entry.group !== "runtime") invalid(`${at}.group must be fixed, revocable or runtime`);
|
|
43
|
+
if (entry.deadlineMs !== undefined && !duration(entry.deadlineMs)) invalid(`${at}.deadlineMs must be a positive integer`);
|
|
44
|
+
return { name: entry.name, description: entry.description as string, parameters: structuredClone(entry.parameters) as Record<string, unknown>,
|
|
45
|
+
handler: entry.handler as string, group: entry.group as ToolRegistration["group"], ...(entry.deadlineMs === undefined ? {} : { deadlineMs: entry.deadlineMs as number }) };
|
|
46
|
+
});
|
|
47
|
+
const runtime = new Set(catalog.filter(entry => entry.group === "runtime").map(entry => entry.name));
|
|
48
|
+
if (input.enabled !== undefined && (!Array.isArray(input.enabled) || input.enabled.some(name => !word(name) || !runtime.has(name)) || new Set(input.enabled).size !== input.enabled.length))
|
|
49
|
+
invalid("tools.enabled must list distinct runtime tool names");
|
|
50
|
+
if (input.defaultDeadlineMs !== undefined && !duration(input.defaultDeadlineMs)) invalid("tools.defaultDeadlineMs must be a positive integer");
|
|
51
|
+
return { catalog, ...(input.enabled === undefined ? {} : { enabled: [...input.enabled as string[]] }),
|
|
52
|
+
...(input.defaultDeadlineMs === undefined ? {} : { defaultDeadlineMs: input.defaultDeadlineMs as number }) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Two catalog inputs ask for the same thing (a repeated load must). */
|
|
56
|
+
export const sameCatalog = (left: ToolCatalogInput, right: ToolCatalogInput) => JSON.stringify(canonical(left)) === JSON.stringify(canonical(right));
|
|
57
|
+
const canonical = (input: ToolCatalogInput) => [input.catalog.map(entry => [entry.name, entry.description, JSON.stringify(entry.parameters), entry.handler, entry.group, entry.deadlineMs ?? null]),
|
|
58
|
+
[...input.enabled ?? []].sort(), input.defaultDeadlineMs ?? null];
|
|
59
|
+
|
|
60
|
+
export interface ToolCatalog {
|
|
61
|
+
readonly entries: readonly ToolRegistration[];
|
|
62
|
+
readonly defaultDeadlineMs?: number;
|
|
63
|
+
get(name: string): ToolRegistration | undefined;
|
|
64
|
+
/** Why the entry cannot run now, or undefined if it can. Policy is not consulted. */
|
|
65
|
+
unavailable(name: string): ToolAvailability["reason"] | "unknown" | undefined;
|
|
66
|
+
availability(entry: ToolRegistration): ToolAvailability;
|
|
67
|
+
/** The handler names the current connection serves. */
|
|
68
|
+
serve(handlers: readonly string[]): void;
|
|
69
|
+
setRevoked(names: readonly string[]): void;
|
|
70
|
+
setEnabled(name: string, enabled: boolean): void;
|
|
71
|
+
/** Available entries, fixed group first, then by name: a stable order for the model. */
|
|
72
|
+
offered(): { fixed: ToolRegistration[]; changeable: ToolRegistration[] };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The catalog's state. Definitions come from the open; the revoked set mirrors
|
|
76
|
+
* storage; the enabled set and the served handlers are process state. */
|
|
77
|
+
export function createToolCatalog(input: ToolCatalogInput, revoked: readonly string[]): ToolCatalog {
|
|
78
|
+
const entries = input.catalog.map(entry => structuredClone(entry));
|
|
79
|
+
const byName = new Map(entries.map(entry => [entry.name, entry]));
|
|
80
|
+
let revokedNames = new Set(revoked), served = new Set<string>();
|
|
81
|
+
const enabled = new Set(input.enabled ?? []);
|
|
82
|
+
const reason = (entry: ToolRegistration): ToolAvailability["reason"] | undefined =>
|
|
83
|
+
entry.group === "revocable" && revokedNames.has(entry.name) ? "revoked"
|
|
84
|
+
: entry.group === "runtime" && !enabled.has(entry.name) ? "not_enabled"
|
|
85
|
+
: !served.has(entry.handler) ? "handler_missing" : undefined;
|
|
86
|
+
const byNameOrder = (left: ToolRegistration, right: ToolRegistration) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
|
|
87
|
+
return {
|
|
88
|
+
entries, ...(input.defaultDeadlineMs === undefined ? {} : { defaultDeadlineMs: input.defaultDeadlineMs }),
|
|
89
|
+
get: name => byName.get(name),
|
|
90
|
+
unavailable(name) { const entry = byName.get(name); return entry ? reason(entry) : "unknown"; },
|
|
91
|
+
availability(entry) {
|
|
92
|
+
const why = reason(entry);
|
|
93
|
+
return { name: entry.name, group: entry.group, handler: entry.handler, available: why === undefined, ...(why === undefined ? {} : { reason: why }) };
|
|
94
|
+
},
|
|
95
|
+
serve(handlers) { served = new Set(handlers); },
|
|
96
|
+
setRevoked(names) { revokedNames = new Set(names); },
|
|
97
|
+
setEnabled(name, on) { if (on) enabled.add(name); else enabled.delete(name); },
|
|
98
|
+
offered() {
|
|
99
|
+
const available = entries.filter(entry => reason(entry) === undefined);
|
|
100
|
+
return { fixed: available.filter(entry => entry.group === "fixed").sort(byNameOrder), changeable: available.filter(entry => entry.group !== "fixed").sort(byNameOrder) };
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { StorageSnapshot } from "../../../contracts/storage.ts";
|
|
2
|
+
import type { FunctionCall, FunctionExecutor, ResultReference, ToolLimits, ToolOutcome, ToolRegistration } from "../../../contracts/tools.ts";
|
|
3
|
+
|
|
4
|
+
/** Adjustable defaults (BUSINESS_RULES.md, tools and callbacks). */
|
|
5
|
+
export const TOOL_LIMITS: Readonly<ToolLimits> = { inlineBytes: 16_384, previewBytes: 1_024, readBytes: 16_384 };
|
|
6
|
+
|
|
7
|
+
/** The wait for a callback ended for a reason that says nothing about its
|
|
8
|
+
* effect on the host: the connection is gone. The call stays dispatched with
|
|
9
|
+
* no result, so recovery reports it uncertain and nothing repeats it. */
|
|
10
|
+
export class CallbackLost extends Error {
|
|
11
|
+
constructor(message: string) { super(message); this.name = "CallbackLost"; }
|
|
12
|
+
}
|
|
13
|
+
/** A typed failure from the handler or the host: `{ code, message }`. */
|
|
14
|
+
export class CallbackFailure extends Error {
|
|
15
|
+
constructor(readonly code: string, message: string) { super(message); this.name = "CallbackFailure"; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Settled = { content: string; outcome: ToolOutcome };
|
|
19
|
+
const bytes = (text: string) => new TextEncoder().encode(text).length;
|
|
20
|
+
const failure = (status: "failed" | "interrupted", code: string, message: string, extra: Record<string, unknown> = {}): Settled =>
|
|
21
|
+
({ content: JSON.stringify({ ok: false, code, message, ...extra }), outcome: { status, code } });
|
|
22
|
+
const validReference = (value: unknown): value is ResultReference => {
|
|
23
|
+
const reference = value as ResultReference;
|
|
24
|
+
return !!reference && typeof reference === "object" && typeof reference.resultId === "string" && reference.resultId.trim().length > 0
|
|
25
|
+
&& Number.isSafeInteger(reference.bytes) && reference.bytes >= 0 && (reference.retention === "temporary" || reference.retention === "durable")
|
|
26
|
+
&& (reference.expiresAt === undefined || typeof reference.expiresAt === "string");
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Run one authorized catalog call through the executor (decision 0021). The
|
|
30
|
+
* caller has already recorded dispatch evidence. Resolves with the paired
|
|
31
|
+
* result and its outcome whenever the turn can go on: success, a typed
|
|
32
|
+
* failure, or the tool's deadline. Rejects when the turn cannot: it was
|
|
33
|
+
* interrupted, or the connection carrying the callback is gone. */
|
|
34
|
+
export async function runFunction(options: {
|
|
35
|
+
executor: FunctionExecutor; request: FunctionCall; registration: ToolRegistration;
|
|
36
|
+
defaultDeadlineMs?: number; limits: ToolLimits; signal: AbortSignal;
|
|
37
|
+
}): Promise<Settled> {
|
|
38
|
+
const { executor, request, registration, limits, signal } = options;
|
|
39
|
+
const deadline = registration.deadlineMs ?? options.defaultDeadlineMs;
|
|
40
|
+
// The executor's own signal: aborted by the turn's interruption or by the
|
|
41
|
+
// deadline. Either way the host is asked to stop and a late answer is ignored.
|
|
42
|
+
const wait = new AbortController();
|
|
43
|
+
// The wait itself ends on interruption, whether or not the executor reacts.
|
|
44
|
+
let stop!: (reason: unknown) => void;
|
|
45
|
+
const stopped = new Promise<never>((_, reject) => { stop = reject; });
|
|
46
|
+
stopped.catch(() => undefined);
|
|
47
|
+
const interrupted = () => { wait.abort(signal.reason); stop(signal.reason); };
|
|
48
|
+
signal.addEventListener("abort", interrupted, { once: true });
|
|
49
|
+
let timer: ReturnType<typeof setTimeout> | undefined, expired = false;
|
|
50
|
+
const timedOut = deadline === undefined ? undefined : new Promise<"deadline">(resolve => {
|
|
51
|
+
// An executor that honours the abort rejects its wait at once; `expired`
|
|
52
|
+
// tells that rejection apart from a failure of the call.
|
|
53
|
+
timer = setTimeout(() => { expired = true; wait.abort(new Error("tool deadline")); resolve("deadline"); }, deadline);
|
|
54
|
+
});
|
|
55
|
+
const timeout = () => failure("interrupted", "tool_timeout", `The tool did not answer within ${deadline} ms and was asked to stop. Whether it took effect is unknown; it was not retried.`, { effect: "unknown" });
|
|
56
|
+
try {
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
const answering = executor.call(request, wait.signal);
|
|
59
|
+
// Observed here so a rejection after the deadline is never unhandled.
|
|
60
|
+
answering.catch(() => undefined);
|
|
61
|
+
const answer = await Promise.race(timedOut ? [answering, timedOut, stopped] : [answering, stopped]);
|
|
62
|
+
signal.throwIfAborted();
|
|
63
|
+
if (answer === "deadline") return timeout();
|
|
64
|
+
if (answer && typeof answer === "object" && "reference" in answer && answer.reference !== undefined) {
|
|
65
|
+
if (!validReference(answer.reference) || typeof answer.preview !== "string")
|
|
66
|
+
return failure("failed", "invalid_result", "The tool returned a malformed result reference.");
|
|
67
|
+
const preview = bytes(answer.preview) > limits.previewBytes ? new TextDecoder().decode(new TextEncoder().encode(answer.preview).subarray(0, limits.previewBytes)) : answer.preview;
|
|
68
|
+
return { content: JSON.stringify({ ok: true, preview, result_id: answer.reference.resultId, bytes: answer.reference.bytes,
|
|
69
|
+
...(answer.reference.expiresAt ? { expires_at: answer.reference.expiresAt } : {}),
|
|
70
|
+
note: "The full result is stored. Read it in parts with read_tool_result and this result_id." }),
|
|
71
|
+
outcome: { status: "succeeded", reference: structuredClone(answer.reference) } };
|
|
72
|
+
}
|
|
73
|
+
const content = JSON.stringify({ ok: true, output: (answer as { output?: unknown })?.output ?? null });
|
|
74
|
+
// A producer stores what does not fit and sends a reference. Bytes that
|
|
75
|
+
// arrive inline anyway cannot be kept or shown in full.
|
|
76
|
+
if (bytes(content) > limits.inlineBytes) return failure("failed", "result_too_large", `The tool's result exceeds ${limits.inlineBytes} bytes and was not stored by its producer.`);
|
|
77
|
+
return { content, outcome: { status: "succeeded" } };
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("Turn interrupted");
|
|
80
|
+
if (expired) return timeout();
|
|
81
|
+
if (error instanceof CallbackFailure) return failure("failed", error.code, error.message);
|
|
82
|
+
throw error;
|
|
83
|
+
} finally {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
signal.removeEventListener("abort", interrupted);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Where a result ID was produced, from the references recorded with tool
|
|
90
|
+
* results. Only IDs the harness itself recorded resolve: a path or a made-up
|
|
91
|
+
* ID finds nothing. */
|
|
92
|
+
export function locateResult(view: StorageSnapshot, resultId: string): { channel: string; turnId: number; callId: string; reference: ResultReference } | undefined {
|
|
93
|
+
for (const entry of view.timeline) {
|
|
94
|
+
if (entry.message.role !== "tool" || entry.message.outcome?.reference?.resultId !== resultId) continue;
|
|
95
|
+
return { channel: entry.channelId, turnId: entry.turnId, callId: entry.message.callId, reference: entry.message.outcome.reference };
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The scoped reader (decision 0021). The requesting channel comes from the
|
|
101
|
+
* harness, never from the arguments: only the channel that produced a result
|
|
102
|
+
* can read it, whatever it has seen in shared history. */
|
|
103
|
+
export async function readResult(options: {
|
|
104
|
+
executor: FunctionExecutor | undefined; view: StorageSnapshot; channel: string; arguments: string; limits: ToolLimits; signal: AbortSignal; now?: () => number;
|
|
105
|
+
}): Promise<Settled> {
|
|
106
|
+
let args: { result_id?: unknown; offset?: unknown; length?: unknown };
|
|
107
|
+
try { args = JSON.parse(options.arguments); } catch { return failure("failed", "invalid_arguments", "read_tool_result needs a JSON object."); }
|
|
108
|
+
if (typeof args?.result_id !== "string" || !args.result_id) return failure("failed", "invalid_arguments", "read_tool_result needs result_id.");
|
|
109
|
+
const offset = args.offset === undefined ? 0 : args.offset, length = args.length === undefined ? options.limits.readBytes : args.length;
|
|
110
|
+
if (!Number.isSafeInteger(offset) || (offset as number) < 0 || !Number.isSafeInteger(length) || (length as number) < 1)
|
|
111
|
+
return failure("failed", "invalid_arguments", "offset must be a nonnegative integer and length a positive integer.");
|
|
112
|
+
const found = locateResult(options.view, args.result_id);
|
|
113
|
+
if (!found) return failure("failed", "result_not_found", "No stored result has this result_id. Use an ID returned by a tool in this conversation.");
|
|
114
|
+
if (found.channel !== options.channel) return failure("failed", "result_forbidden", "That result belongs to another conversation and cannot be read here.");
|
|
115
|
+
if (found.reference.expiresAt !== undefined && Date.parse(found.reference.expiresAt) <= (options.now ?? Date.now)())
|
|
116
|
+
return failure("failed", "result_expired", "That result was temporary and has expired. The original tool call keeps its recorded outcome.");
|
|
117
|
+
if (!options.executor) return failure("failed", "result_unavailable", "The process that holds that result is not connected.");
|
|
118
|
+
try {
|
|
119
|
+
const page = await options.executor.read({ resultId: args.result_id, invocationId: `${found.turnId}:${found.callId}`, channel: options.channel,
|
|
120
|
+
offset: offset as number, length: Math.min(length as number, options.limits.readBytes) }, options.signal);
|
|
121
|
+
options.signal.throwIfAborted();
|
|
122
|
+
const text = String(page.text ?? "");
|
|
123
|
+
return { content: JSON.stringify({ ok: true, text, total_bytes: page.totalBytes, eof: page.eof === true,
|
|
124
|
+
...(page.eof === true ? {} : { next_offset: (offset as number) + bytes(text) }) }), outcome: { status: "succeeded" } };
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (options.signal.aborted) throw options.signal.reason instanceof Error ? options.signal.reason : new Error("Turn interrupted");
|
|
127
|
+
if (error instanceof CallbackFailure) return failure("failed", error.code, error.message);
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
}
|