@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,519 @@
|
|
|
1
|
+
import { OperatorFault, operatorMethods, operatorRead, readValue } from "./operator.ts";
|
|
2
|
+
import type { ProtocolEndpoint, RpcRequest, RpcResponse, RpcNotification, RpcSessionNotification, ProtocolConfig, Description, Subscription, DurableErrorCode } from "../../contracts/protocol.ts";
|
|
3
|
+
import type { PersistentSession } from "../../contracts/session.ts";
|
|
4
|
+
import type { SessionArchive, StorageResult, StoredSession } from "../../contracts/storage.ts";
|
|
5
|
+
import type { SessionFilePayload } from "../../contracts/session-file.ts";
|
|
6
|
+
import { SessionFileError, validateConfig } from "../../state/storage/session-file.ts";
|
|
7
|
+
import { validateManagedConfig } from "../../runtime/config/managed.ts";
|
|
8
|
+
import { MAX_FRAME_BYTES } from "./framing.ts";
|
|
9
|
+
import { FrameLimit, turnStatus, wireStatus } from "./load.ts";
|
|
10
|
+
import { TransferFault, createTransfers, decodeArchive, encodeArchive, readArchiveFile, writeArchiveFile, TRANSFER_LIMITS } from "./transfers.ts";
|
|
11
|
+
import type { ChannelChangeResult, PendingChannelChange, TransferLimits } from "../../contracts/protocol.ts";
|
|
12
|
+
import { ChannelChangeFault, applyChannelChanges, checkPolicies, parseChannelChanges, sameBatch } from "./channel-changes.ts";
|
|
13
|
+
import type { RpcCallbackCancel, RpcCallbackRequest } from "../../contracts/protocol.ts";
|
|
14
|
+
import type { ToolCatalogInput } from "../../contracts/tools.ts";
|
|
15
|
+
import { CatalogError, parseCatalog, sameCatalog } from "../../capabilities/tools/runtime/catalog.ts";
|
|
16
|
+
import { ToolFault, createCallbackBridge, isToolMethod, toolMethods, toolRequest } from "./functions.ts";
|
|
17
|
+
|
|
18
|
+
import { parseReminderBatch, parseReminderChange, parseReminderList, ReminderShapeError } from "../../runtime/reminder-validation.ts";
|
|
19
|
+
import { REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
|
|
20
|
+
import type { ReminderChange, ReminderChangeResult, ReminderSessionEvent } from "../../contracts/reminders.ts";
|
|
21
|
+
|
|
22
|
+
class Fault extends Error {
|
|
23
|
+
constructor(readonly tag: string, message: string, readonly rpc = -32602) { super(message); }
|
|
24
|
+
}
|
|
25
|
+
/** Thrown by a session factory to report a typed storage or lifecycle refusal. */
|
|
26
|
+
export class SessionOpenError extends Error {
|
|
27
|
+
constructor(readonly code: DurableErrorCode, message: string) { super(message); }
|
|
28
|
+
}
|
|
29
|
+
export interface SessionRequest { mode: "create" | "open"; sessionId: string; config?: ProtocolConfig;
|
|
30
|
+
/** Decision 0021: a catalog whose shape is valid. The factory checks its names
|
|
31
|
+
* against its built-in tools and passes it to the session. */
|
|
32
|
+
tools?: ToolCatalogInput }
|
|
33
|
+
/** `close` releases storage ownership; the endpoint calls it when it is disposed
|
|
34
|
+
* or when a load cannot be answered. */
|
|
35
|
+
export interface OpenedSession {
|
|
36
|
+
session: PersistentSession; close(): void;
|
|
37
|
+
config?: ProtocolConfig;
|
|
38
|
+
/** Persist the chosen config only after the response can be produced. */
|
|
39
|
+
commitConfig?(): void;
|
|
40
|
+
/** One consistent logical copy, or `busy`. */
|
|
41
|
+
exportArchive?(): StorageResult<SessionArchive>;
|
|
42
|
+
}
|
|
43
|
+
export interface ProtocolServerOptions {
|
|
44
|
+
durable?: boolean;
|
|
45
|
+
/** Publish a validated archive as a new session with this ID. Enables import. */
|
|
46
|
+
importArchive?(payload: SessionFilePayload<SessionArchive>, sessionId: string): StorageResult<StoredSession>;
|
|
47
|
+
/** Where transfer files live while a transfer is open. Enables transfers. */
|
|
48
|
+
transferDirectory?: string;
|
|
49
|
+
/** Smaller limits for tests; defaults are the contract's. */
|
|
50
|
+
limits?: Partial<{ chunkBytes: number; maxBytes: number; idleMs: number }>;
|
|
51
|
+
/** Decision 0021: the session factory accepts tool catalogs. */
|
|
52
|
+
functions?: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const bad = (message: string): never => { throw new Fault("invalid_params", message); };
|
|
56
|
+
function obj(value: unknown): Record<string, any> {
|
|
57
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) bad("Expected an object");
|
|
58
|
+
return value as Record<string, any>;
|
|
59
|
+
}
|
|
60
|
+
function keys(value: Record<string, unknown>, names: string[]) {
|
|
61
|
+
for (const name of Object.keys(value)) if (!names.includes(name)) bad(`Unsupported field: ${name}`);
|
|
62
|
+
}
|
|
63
|
+
function text(value: unknown): string {
|
|
64
|
+
if (typeof value !== "string" || !value.trim()) bad("Expected a nonempty string");
|
|
65
|
+
return value as string;
|
|
66
|
+
}
|
|
67
|
+
function count(value: unknown, fallback: number): number {
|
|
68
|
+
if (value === undefined) return fallback;
|
|
69
|
+
if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > 1000) bad("Expected a limit between 1 and 1000");
|
|
70
|
+
return value as number;
|
|
71
|
+
}
|
|
72
|
+
/** Capabilities describe this server instance: durable acceptance and load are
|
|
73
|
+
* advertised only when its sessions are opened from durable storage. */
|
|
74
|
+
export function describe(durable: boolean, archives = false, functions = false): Description {
|
|
75
|
+
return {
|
|
76
|
+
reminderLimits: { ...REMINDER_LIMITS, maxActiveRoutinesPerChannel: 20, maxRoutineCatchUp: 10 },
|
|
77
|
+
configOptions: [], commands: [], policies: [],
|
|
78
|
+
capabilities: { experimental: true, acceptance: durable ? "durable" : "memory", persistence: durable, startupChannelChanges: true, reminders: true, routines: true, unattendedTurnGuard: true, ...(functions ? { functions: true as const } : {}),
|
|
79
|
+
methods: ["initialize", "config/validate", "session/create", ...(durable ? ["session/open"] : []), ...operatorMethods, "session/status", "reminder/change", "reminder/get", "reminder/list",
|
|
80
|
+
"session/model-calls", "session/message/read", "session/suspend", "session/resume", "session/stop", "channel/push", "channel/notify", "channel/create", "channel/edit", "channel/suspend", "channel/resume", "channel/delete", "channel/withdraw", "channel/interrupt", "approval/respond", "session/idle",
|
|
81
|
+
...(archives ? ["session/export", "session/import", "transfer/open", "transfer/write", "transfer/read", "transfer/close"] : []), ...(functions ? toolMethods() : [])],
|
|
82
|
+
events: ["turn_started", "turn_took", "items_receipt", "text_delta", "text_gap", "text_incomplete", "tool_call", "message_completed", "turn_suspended", "turn_resumed", "turn_ended", "channel_state", "item_withdrawn", "approval_requested", "approval_closed", "reminder_changed", "reminder_fired", "reminder_expired", "reminder_cancelled", "routine_disposition", "routine_migration_blocked", "session/event"] },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function createProtocolServer(open: (request: SessionRequest) => Promise<OpenedSession>, options: ProtocolServerOptions = {}): ProtocolEndpoint & { dispose(): void } {
|
|
87
|
+
const limits = { ...TRANSFER_LIMITS, ...options.limits } as TransferLimits;
|
|
88
|
+
const transfers = options.importArchive && options.transferDirectory ? createTransfers(options.transferDirectory, limits) : undefined;
|
|
89
|
+
const description = describe(!!options.durable, !!transfers, !!options.functions);
|
|
90
|
+
let initialized = false;
|
|
91
|
+
let approvalConsumer = false;
|
|
92
|
+
let opening = false;
|
|
93
|
+
let current: OpenedSession | undefined;
|
|
94
|
+
// Decision 0020: the batch this connection's open applied, kept so a repeated
|
|
95
|
+
// load reports the same results without applying anything again.
|
|
96
|
+
let startup: { batch: PendingChannelChange[]; results: ChannelChangeResult[] } | undefined;
|
|
97
|
+
let reminderStartup: { batch: ReminderChange[]; results: ReminderChangeResult[] } | undefined;
|
|
98
|
+
let activeConfig: ProtocolConfig | undefined;
|
|
99
|
+
let subscription: Subscription = { text: "final", tools: "full" };
|
|
100
|
+
const listeners = new Set<(notification: RpcNotification) => void>();
|
|
101
|
+
const sessionListeners = new Set<(notification: RpcSessionNotification) => void>();
|
|
102
|
+
// While a load response is on its way out, later notifications wait behind it.
|
|
103
|
+
let held: (() => void)[] | undefined;
|
|
104
|
+
const publish = (deliver: () => void) => { if (held) held.push(deliver); else deliver(); };
|
|
105
|
+
// Decision 0021: callbacks to this connection's host share the event order.
|
|
106
|
+
const callbackListeners = new Set<(message: RpcCallbackRequest | RpcCallbackCancel) => void>();
|
|
107
|
+
const bridge = createCallbackBridge(message => publish(() => { for (const listener of callbackListeners) listener(structuredClone(message)); }));
|
|
108
|
+
let served: string[] | undefined, startupTools: ToolCatalogInput | undefined;
|
|
109
|
+
const catalogOf = (raw: unknown) => {
|
|
110
|
+
if (raw === undefined) return undefined;
|
|
111
|
+
if (!options.functions) bad("This server does not accept tool catalogs");
|
|
112
|
+
try { return parseCatalog(raw, []); } catch (error) { throw error instanceof CatalogError ? new Fault(error.code, error.message) : error; }
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
async function attach(request: SessionRequest): Promise<OpenedSession> {
|
|
116
|
+
if (current || opening) throw new Fault("already_exists", "One session per endpoint");
|
|
117
|
+
opening = true;
|
|
118
|
+
let opened: OpenedSession;
|
|
119
|
+
// On success `opening` stays set: the caller clears it once the session is
|
|
120
|
+
// published as `current` (or abandoned), leaving no gap for a second open.
|
|
121
|
+
try { opened = await open(request); }
|
|
122
|
+
catch (error) { opening = false; throw error instanceof SessionOpenError || error instanceof CatalogError ? new Fault(error.code, error.message) : new Fault("invalid_config", String(error)); }
|
|
123
|
+
// Handlers are bound before any recovered work can start.
|
|
124
|
+
opened.session.tools?.serve(served ?? [], served ? bridge.executor : undefined);
|
|
125
|
+
startupTools = request.tools;
|
|
126
|
+
opened.session.subscribe(value => {
|
|
127
|
+
const event = structuredClone(value);
|
|
128
|
+
if (!approvalConsumer && (event.event.type === "approval_requested" || event.event.type === "approval_closed")) return;
|
|
129
|
+
// Filtering is downstream of inference and its retry cutoff: a final-mode
|
|
130
|
+
// consumer must never see ephemeral stream events it cannot interpret.
|
|
131
|
+
if (subscription.text === "final" && (event.event.type === "text_delta" || event.event.type === "text_gap" || event.event.type === "text_incomplete")) return;
|
|
132
|
+
if (event.event.type === "message_completed" && event.event.parts && new TextEncoder().encode(JSON.stringify(event)).length > MAX_FRAME_BYTES - 1024) {
|
|
133
|
+
const { parts: _parts, ...completion } = event.event;
|
|
134
|
+
event.event = { ...completion, reference: true };
|
|
135
|
+
}
|
|
136
|
+
if (event.event.type === "tool_call") {
|
|
137
|
+
if (subscription.tools === "none") return;
|
|
138
|
+
if (subscription.tools === "summary") { delete event.event.input; delete event.event.output; }
|
|
139
|
+
}
|
|
140
|
+
const message: RpcNotification = { jsonrpc: "2.0", method: "channel/event", params: event };
|
|
141
|
+
publish(() => { for (const listener of listeners) { try { listener(structuredClone(message)); } catch { /* Isolate clients. */ } } });
|
|
142
|
+
});
|
|
143
|
+
const sendSession = (event: Parameters<Parameters<PersistentSession["subscribeSession"]>[0]>[0] | ReminderSessionEvent) => {
|
|
144
|
+
const message: RpcSessionNotification = { jsonrpc: "2.0", method: "session/event", params: event };
|
|
145
|
+
publish(() => { for (const listener of sessionListeners) { try { listener(structuredClone(message)); } catch { /* Isolate clients. */ } } });
|
|
146
|
+
};
|
|
147
|
+
opened.session.subscribeSession(sendSession);
|
|
148
|
+
opened.session.reminders?.subscribeWake(sendSession);
|
|
149
|
+
opened.session.approvals.setConsumer(approvalConsumer);
|
|
150
|
+
activeConfig = structuredClone(opened.config ?? request.config);
|
|
151
|
+
return opened;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Apply the open's batch to a session that is attached but not started.
|
|
155
|
+
* `opening` stays set by the caller until the session is published as
|
|
156
|
+
* `current`, so no other request can reach the session, or open a second
|
|
157
|
+
* one, while a suspension is awaited. The returned function applies the
|
|
158
|
+
* resumes and must run in the same synchronous block as the load view. */
|
|
159
|
+
async function prepare(opened: OpenedSession, batch: PendingChannelChange[]) {
|
|
160
|
+
checkPolicies(batch, Object.keys(activeConfig?.policies ?? { __legacy_allow: true }));
|
|
161
|
+
return applyChannelChanges(opened.session, batch);
|
|
162
|
+
}
|
|
163
|
+
/** An open that fails after attaching releases the session. With a batch,
|
|
164
|
+
* stop first: a resume in it may already have handed a turn to an executor. */
|
|
165
|
+
function abandon(opened: OpenedSession, batch: boolean) {
|
|
166
|
+
if (batch) { try { opened.session.stop("Open failed"); } catch { /* Storage may be the failure. */ } }
|
|
167
|
+
opened.close();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Read one snapshot, then keep every later notification behind the response.
|
|
171
|
+
* The response is handed to the transport in a microtask after this request
|
|
172
|
+
* resolves; a timer runs after all of those, so releasing held notifications
|
|
173
|
+
* (and, for a first load, starting execution) there places them after it. */
|
|
174
|
+
function ready(opened: OpenedSession) {
|
|
175
|
+
const reads = opened.session.operatorReads;
|
|
176
|
+
if (!reads) throw new Fault("invalid_state", "Focused reads are unavailable");
|
|
177
|
+
const { value, revision } = readValue(reads.readSession());
|
|
178
|
+
return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function holdAfterResponse(start?: () => void) {
|
|
182
|
+
if (held) { if (start) held.push(start); return; }
|
|
183
|
+
held = [];
|
|
184
|
+
setTimeout(() => {
|
|
185
|
+
const waiting = held ?? []; held = undefined;
|
|
186
|
+
for (const deliver of waiting) deliver();
|
|
187
|
+
start?.();
|
|
188
|
+
}, 0);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function reminderView(session: PersistentSession, results: ReminderChangeResult[] = []) {
|
|
192
|
+
const reminders = session.reminders;
|
|
193
|
+
if (!reminders) return {};
|
|
194
|
+
const page = readValue(reminders.listReminders({})).value;
|
|
195
|
+
const guard = reminders.executable() ? readValue(reminders.unattendedGuard()).value : undefined;
|
|
196
|
+
return { reminderChanges: results, reminders: page.reminders, ...(page.next ? { remindersNext: page.next } : {}),
|
|
197
|
+
...(reminders.executable() ? readValue(reminders.reminderWake()).value : {}),
|
|
198
|
+
...(reminders.executable() ? { unattendedTurnGuard: guard === undefined ? null : { maxConsecutiveTurns: guard } } : {}) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function prepareReminders(session: PersistentSession, batch: ReminderChange[]) {
|
|
202
|
+
const reminders = session.reminders;
|
|
203
|
+
if (batch.length && !reminders?.executable()) throw new Fault("incompatible", "Reminders cannot change in an inspection-only session");
|
|
204
|
+
const results = batch.map(change => readValue(reminders!.change(change)).value);
|
|
205
|
+
reminders?.processStartup();
|
|
206
|
+
const view = reminderView(session, results);
|
|
207
|
+
reminderStartup = { batch, results };
|
|
208
|
+
return view;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function dispatch(method: string, raw: unknown): Promise<unknown> {
|
|
212
|
+
if (!description.capabilities.methods.includes(method)) throw new Fault("method_not_found", `Unsupported method: ${method}`, -32601);
|
|
213
|
+
const p = obj(raw);
|
|
214
|
+
if (method === "initialize") {
|
|
215
|
+
keys(p, ["protocolVersion", "host", "callbacks", "subscription", "approval", "functions"]);
|
|
216
|
+
if (p.protocolVersion !== 1) throw new Fault("version_mismatch", "Only experimental protocol version 1 is supported");
|
|
217
|
+
if (initialized) throw new Fault("already_exists", "Already initialized");
|
|
218
|
+
const host = obj(p.host); keys(host, ["name", "version"]); text(host.name); text(host.version);
|
|
219
|
+
const callbacks = Array.isArray(p.callbacks) && (p.callbacks.length === 0 || (options.functions && p.callbacks.length === 1 && p.callbacks[0] === "functions/call"));
|
|
220
|
+
if (!callbacks) bad(options.functions ? "The only supported host callback is functions/call" : "Host callbacks are not supported yet");
|
|
221
|
+
const handlers = p.functions === undefined ? [] : p.functions;
|
|
222
|
+
if (!Array.isArray(handlers) || handlers.some((name: unknown) => typeof name !== "string" || !name.trim()) || new Set(handlers).size !== handlers.length) bad("functions must list distinct handler names");
|
|
223
|
+
if (handlers.length && !p.callbacks.length) bad("functions needs the functions/call callback");
|
|
224
|
+
served = p.callbacks.length ? [...handlers] : undefined;
|
|
225
|
+
const sub = obj(p.subscription); keys(sub, ["text", "tools"]);
|
|
226
|
+
if (!["final", "stream"].includes(sub.text) || !["none", "summary", "full"].includes(sub.tools)) bad("Only final/stream text and none/summary/full tools are supported");
|
|
227
|
+
subscription = { text: sub.text, tools: sub.tools };
|
|
228
|
+
approvalConsumer = p.approval === true;
|
|
229
|
+
initialized = true;
|
|
230
|
+
return { protocolVersion: 1, harness: { version: "0.0.0" }, description };
|
|
231
|
+
}
|
|
232
|
+
if (!initialized) throw new Fault("not_ready", "Initialize first");
|
|
233
|
+
if (method === "config/validate") {
|
|
234
|
+
keys(p, ["config"]);
|
|
235
|
+
try { validateManagedConfig(p.config); } catch (error) { throw new Fault("invalid_config", String(error)); }
|
|
236
|
+
return { valid: true };
|
|
237
|
+
}
|
|
238
|
+
if (method === "session/create") {
|
|
239
|
+
keys(p, ["sessionId", "config", "participants", "channels", "channelChanges", "tools", "reminderChanges"]);
|
|
240
|
+
const reminderBatch = parseReminderBatch(p.reminderChanges);
|
|
241
|
+
const tools = catalogOf(p.tools);
|
|
242
|
+
const sessionId = text(p.sessionId);
|
|
243
|
+
if (current || opening) throw new Fault("already_exists", "One session per endpoint");
|
|
244
|
+
if (p.config !== undefined) { try { validateManagedConfig(p.config); } catch (error) { throw new Fault("invalid_config", String(error)); } }
|
|
245
|
+
if (!Array.isArray(p.participants)) bad("participants must be an array");
|
|
246
|
+
const ids = new Set<string>();
|
|
247
|
+
for (const value of p.participants) {
|
|
248
|
+
const participant = obj(value); keys(participant, ["id", "kind"]); const id = text(participant.id);
|
|
249
|
+
if (ids.has(id) || !["person", "agent", "worker", "host"].includes(participant.kind)) bad("Invalid or duplicate participant");
|
|
250
|
+
ids.add(id);
|
|
251
|
+
}
|
|
252
|
+
if (Object.keys(obj(p.channels)).length) bad("Initial channel settings are not supported; channels are created on push");
|
|
253
|
+
// Reject an invalid batch before the session exists. Policy names are
|
|
254
|
+
// checked here when the configuration is inline, and again once the
|
|
255
|
+
// effective configuration is known.
|
|
256
|
+
const batch = p.channelChanges === undefined ? undefined : parseChannelChanges(p.channelChanges);
|
|
257
|
+
if (batch && p.config?.policies) checkPolicies(batch, Object.keys(p.config.policies));
|
|
258
|
+
const opened = await attach({ mode: "create", sessionId, config: p.config, ...(tools ? { tools } : {}) });
|
|
259
|
+
let results: ChannelChangeResult[] | undefined;
|
|
260
|
+
let reminderResult: ReturnType<typeof reminderView>;
|
|
261
|
+
try {
|
|
262
|
+
const finish = batch && await prepare(opened, batch);
|
|
263
|
+
opened.commitConfig?.();
|
|
264
|
+
if (opened.session.reminders) holdAfterResponse();
|
|
265
|
+
results = finish?.();
|
|
266
|
+
reminderResult = prepareReminders(opened.session, reminderBatch);
|
|
267
|
+
current = opened;
|
|
268
|
+
if (batch) startup = { batch, results: results! };
|
|
269
|
+
} catch (error) { abandon(opened, !!batch); throw error; }
|
|
270
|
+
finally { opening = false; }
|
|
271
|
+
if (batch?.length || opened.session.reminders) holdAfterResponse(() => { if (current === opened) opened.session.start(); });
|
|
272
|
+
else opened.session.start();
|
|
273
|
+
return { ...(opened.session.operatorReads ? ready(opened) : { sessionId }), ...reminderResult, ...(results ? { channelChanges: results } : {}) };
|
|
274
|
+
}
|
|
275
|
+
if (method === "session/open") {
|
|
276
|
+
keys(p, ["sessionId", "config", "channelChanges", "tools", "reminderChanges"]);
|
|
277
|
+
const reminderBatch = parseReminderBatch(p.reminderChanges);
|
|
278
|
+
const tools = catalogOf(p.tools);
|
|
279
|
+
const sessionId = text(p.sessionId);
|
|
280
|
+
const batch = p.channelChanges === undefined ? undefined : parseChannelChanges(p.channelChanges);
|
|
281
|
+
// A repeated load of the open session is a fresh view of it, nothing more:
|
|
282
|
+
// the batch was applied by the open and is only reported again. A new
|
|
283
|
+
// batch belongs to the live channel API.
|
|
284
|
+
if (current) {
|
|
285
|
+
if (ready(current).sessionId !== sessionId) throw new Fault("already_exists", "One session per endpoint");
|
|
286
|
+
if (batch && !sameBatch(startup?.batch ?? [], batch)) throw new Fault("invalid_state", "The session is already open; send newer channel changes through the channel methods");
|
|
287
|
+
if (tools && !(startupTools && sameCatalog(startupTools, tools))) throw new Fault("invalid_state", "The session is already open with another tool catalog; use the tool methods");
|
|
288
|
+
if (p.reminderChanges !== undefined && JSON.stringify(reminderBatch) !== JSON.stringify(reminderStartup?.batch ?? [])) throw new Fault("invalid_state", "The session is already open; send changes through reminder/change");
|
|
289
|
+
return { ...ready(current), ...reminderView(current.session, reminderStartup?.results), ...(startup ? { channelChanges: startup.results } : {}) };
|
|
290
|
+
}
|
|
291
|
+
const opened = await attach({ mode: "open", sessionId, config: p.config, ...(tools ? { tools } : {}) });
|
|
292
|
+
try {
|
|
293
|
+
const finish = batch && await prepare(opened, batch);
|
|
294
|
+
// From here to the end of the block nothing is awaited: the resumes, the
|
|
295
|
+
// view and the hold on later notifications are one synchronous step.
|
|
296
|
+
if (opened.session.reminders) holdAfterResponse();
|
|
297
|
+
const results = finish?.();
|
|
298
|
+
opened.commitConfig?.();
|
|
299
|
+
const reminderResult = prepareReminders(opened.session, reminderBatch);
|
|
300
|
+
const result = ready(opened);
|
|
301
|
+
holdAfterResponse(() => { if (current === opened) opened.session.start(); });
|
|
302
|
+
current = opened;
|
|
303
|
+
if (batch) startup = { batch, results: results! };
|
|
304
|
+
return { ...result, ...reminderResult, ...(results ? { channelChanges: results } : {}) };
|
|
305
|
+
}
|
|
306
|
+
// Work was not started; release the session so no partial load is observable.
|
|
307
|
+
catch (error) { abandon(opened, !!batch); throw error; }
|
|
308
|
+
finally { opening = false; }
|
|
309
|
+
}
|
|
310
|
+
if (transfers && method.startsWith("transfer/")) {
|
|
311
|
+
if (method === "transfer/open") { keys(p, ["bytes", "sha256"]); return { transferId: transfers.openUpload(p.bytes, p.sha256), limits }; }
|
|
312
|
+
if (method === "transfer/write") { keys(p, ["transferId", "offset", "data"]); return { received: transfers.write(p.transferId, p.offset, p.data) }; }
|
|
313
|
+
if (method === "transfer/read") { keys(p, ["transferId", "offset"]); return transfers.read(p.transferId, p.offset); }
|
|
314
|
+
keys(p, ["transferId"]); transfers.close(p.transferId); return {};
|
|
315
|
+
}
|
|
316
|
+
if (transfers && method === "session/import") {
|
|
317
|
+
keys(p, ["from", "sessionId"]);
|
|
318
|
+
const from = obj(p.from);
|
|
319
|
+
if (p.sessionId !== undefined) text(p.sessionId);
|
|
320
|
+
// Whole file first, whole validation next, and only then one atomic publish.
|
|
321
|
+
let bytes: Uint8Array;
|
|
322
|
+
if (from.type === "path") { keys(from, ["type", "path"]); bytes = readArchiveFile(text(from.path), limits.maxBytes); }
|
|
323
|
+
else if (from.type === "transfer") { keys(from, ["type", "transferId"]); bytes = transfers.consume(from.transferId); }
|
|
324
|
+
else return bad("Import source must be a path or a transfer");
|
|
325
|
+
const payload = decodeArchive(bytes, limits.maxBytes) as SessionFilePayload<SessionArchive>;
|
|
326
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).sort().join() !== "archive,config" || ![2, 3, 4, 5, 6, 7].includes(payload.archive?.archiveVersion))
|
|
327
|
+
throw new Fault("invalid_archive", "Invalid session file payload");
|
|
328
|
+
try { validateConfig(payload.config, (payload.archive as { archiveVersion: number }).archiveVersion === 2); } catch (error) { throw new Fault("invalid_archive", String(error)); }
|
|
329
|
+
const sessionId = p.sessionId ?? payload.archive?.snapshot?.session?.sessionId;
|
|
330
|
+
if (typeof sessionId !== "string" || !sessionId.trim()) throw new Fault("invalid_archive", "Archive does not name a session");
|
|
331
|
+
const imported = options.importArchive!(payload, sessionId);
|
|
332
|
+
if (!imported.ok) throw new Fault(imported.error.code === "invalid_input" ? "invalid_params" : imported.error.code, imported.error.message);
|
|
333
|
+
return { sessionId: imported.value.sessionId, lifecycle: imported.value.lifecycle, revision: imported.revision };
|
|
334
|
+
}
|
|
335
|
+
if (method === "channel/notify") {
|
|
336
|
+
keys(p, ["channel", "notice"]);
|
|
337
|
+
const channel = text(p.channel), notice = obj(p.notice);
|
|
338
|
+
keys(notice, ["id", "text", "source", "policyNames"]);
|
|
339
|
+
const id = text(notice.id), content = text(notice.text);
|
|
340
|
+
const source = notice.source === undefined ? undefined : text(notice.source);
|
|
341
|
+
if (!Array.isArray(notice.policyNames)) bad("Expected a policy name array");
|
|
342
|
+
const policyNames = notice.policyNames.map((name: unknown) => text(name));
|
|
343
|
+
if (!current) throw new Fault("invalid_state", "Open a session first");
|
|
344
|
+
const session = current.session;
|
|
345
|
+
const result = session.agent.notifyExternal({ channelId: channel, itemId: id, text: content, source, policyNames });
|
|
346
|
+
if (!result.accepted) throw new Fault(result.code === "invalid_input" ? "invalid_params" : result.code, result.error);
|
|
347
|
+
const saved = session.operatorReads
|
|
348
|
+
? readValue(session.operatorReads.readTracked(channel, [id], [])).value.items[0]
|
|
349
|
+
: session.snapshot().items.find(item => item.itemId === id);
|
|
350
|
+
return { accepted: true, duplicate: result.duplicate, item: { id, channel, kind: "external_notice", sender: source ?? "host",
|
|
351
|
+
...(source === undefined ? {} : { externalSource: source }), ...(saved?.policy ? { policy: saved.policy } : {}),
|
|
352
|
+
milestone: result.milestone, ...(result.turnId === undefined ? {} : { turnId: String(result.turnId) }) } };
|
|
353
|
+
}
|
|
354
|
+
if (!current) throw new Fault("not_ready", "Create or load a session first");
|
|
355
|
+
if (transfers && method === "session/export") {
|
|
356
|
+
keys(p, ["to"]);
|
|
357
|
+
const to = obj(p.to);
|
|
358
|
+
if (to.type === "path") { keys(to, ["type", "path"]); text(to.path); }
|
|
359
|
+
else if (to.type === "transfer") keys(to, ["type"]);
|
|
360
|
+
else bad("Export destination must be a path or a transfer");
|
|
361
|
+
const exported = current.exportArchive?.() ?? { ok: false as const, error: { code: "invalid_state" as const, message: "This session cannot be exported" } };
|
|
362
|
+
if (!exported.ok) throw new Fault(exported.error.code, exported.error.message);
|
|
363
|
+
const { bytes, sha256 } = encodeArchive({ archive: exported.value, config: activeConfig! }, limits.maxBytes);
|
|
364
|
+
if (to.type === "path") { writeArchiveFile(to.path, bytes); return { bytes: bytes.length, sha256 }; }
|
|
365
|
+
return { bytes: bytes.length, sha256, transferId: transfers.offer(bytes, sha256) };
|
|
366
|
+
}
|
|
367
|
+
const session = current.session;
|
|
368
|
+
if (operatorMethods.some(name => name === method)) {
|
|
369
|
+
const allowed = method === "channel/observe" ? ["channel"] : method === "channel/reconcile" ? ["channel", "itemIds", "turnIds", "cursor"]
|
|
370
|
+
: method === "channel/messages" ? ["channel", "limit", "cursor", "after", "throughRevision"] : ["limit", "cursor"];
|
|
371
|
+
keys(p, allowed);
|
|
372
|
+
const result = operatorRead(session, method, p, approvalConsumer);
|
|
373
|
+
if (method === "channel/observe") holdAfterResponse();
|
|
374
|
+
return result;
|
|
375
|
+
}
|
|
376
|
+
if (isToolMethod(method)) return toolRequest(session, method, p);
|
|
377
|
+
if (method === "approval/respond") {
|
|
378
|
+
keys(p, ["requestId", "decision"]);
|
|
379
|
+
if (!approvalConsumer) throw new Fault("invalid_state", "Connection has no approval authority");
|
|
380
|
+
if (p.decision !== "allow_once" && p.decision !== "deny") bad("Expected allow_once or deny");
|
|
381
|
+
if (!session.approvals.respond(text(p.requestId), p.decision)) throw new Fault("not_found", "Approval request is no longer available");
|
|
382
|
+
return { accepted: true };
|
|
383
|
+
}
|
|
384
|
+
if (method.startsWith("channel/") && method !== "channel/push" && method !== "channel/notify") {
|
|
385
|
+
const channel = text(p.channel);
|
|
386
|
+
let result;
|
|
387
|
+
if (method === "channel/create") {
|
|
388
|
+
keys(p, ["channel", "displayName", "policy"]);
|
|
389
|
+
result = session.channels.create({ channelId: channel, ...(p.displayName === undefined ? {} : { displayName: text(p.displayName) }), ...(p.policy === undefined ? {} : { policy: text(p.policy) }) });
|
|
390
|
+
} else if (method === "channel/edit") {
|
|
391
|
+
keys(p, ["channel", "displayName", "policy"]);
|
|
392
|
+
result = session.channels.edit(channel, p.displayName === null ? null : text(p.displayName), p.policy === undefined || p.policy === null ? p.policy : text(p.policy));
|
|
393
|
+
} else if (method === "channel/suspend") {
|
|
394
|
+
keys(p, ["channel"]); result = await session.channels.suspend(channel);
|
|
395
|
+
} else if (method === "channel/resume") {
|
|
396
|
+
keys(p, ["channel"]); result = session.channels.resume(channel);
|
|
397
|
+
} else if (method === "channel/delete") {
|
|
398
|
+
keys(p, ["channel"]); result = session.channels.delete(channel);
|
|
399
|
+
} else if (method === "channel/withdraw") {
|
|
400
|
+
keys(p, ["channel", "item"]); const outcome = session.channels.withdraw(channel, text(p.item));
|
|
401
|
+
if (!outcome.ok) throw new Fault(outcome.error.code, outcome.error.message);
|
|
402
|
+
const { item } = outcome.value;
|
|
403
|
+
return { outcome: outcome.value.outcome, item: { id: item.itemId, channel: item.channelId, kind: item.kind, sender: item.senderId, milestone: item.milestone,
|
|
404
|
+
...(item.policy === undefined ? {} : { policy: item.policy }),
|
|
405
|
+
...(item.turnId === undefined ? {} : { turnId: String(item.turnId) }) },
|
|
406
|
+
...(outcome.value.outcome === "withdrawn" ? { repeated: outcome.value.repeated } : {}) };
|
|
407
|
+
} else {
|
|
408
|
+
keys(p, ["channel", "turn", "reason"]); const rawTurn = text(p.turn), turn = Number(rawTurn);
|
|
409
|
+
if (!Number.isSafeInteger(turn) || turn < 1 || String(turn) !== rawTurn) bad("Expected a turn ID");
|
|
410
|
+
const outcome = session.channels.interrupt(channel, turn, p.reason === undefined ? undefined : text(p.reason));
|
|
411
|
+
if (!outcome.ok) throw new Fault(outcome.error.code, outcome.error.message);
|
|
412
|
+
return { interrupted: outcome.value.interrupted, turn: turnStatus(outcome.value.turn) };
|
|
413
|
+
}
|
|
414
|
+
if (!result.ok) throw new Fault(result.error.code, result.error.message);
|
|
415
|
+
const status = wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()).channels.find(value => value.channel === channel)!;
|
|
416
|
+
return { channel: status, ...(method === "channel/create" ? { created: (result.value as { created: boolean }).created } : {}) };
|
|
417
|
+
}
|
|
418
|
+
if (method === "session/idle") { keys(p, []); return { idle: session.agent.idle() && session.status().execution !== "working" }; }
|
|
419
|
+
if (method === "session/status") { keys(p, []); return wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()); }
|
|
420
|
+
if (method === "session/suspend" || method === "session/resume") {
|
|
421
|
+
keys(p, []);
|
|
422
|
+
// Suspend answers only once `suspended` is committed, after in-flight
|
|
423
|
+
// iterations settle; a refusal changes nothing and consumes nothing.
|
|
424
|
+
const outcome = method === "session/suspend" ? await session.suspend() : session.resume();
|
|
425
|
+
if (!outcome.ok) throw new Fault(outcome.error.code, outcome.error.message);
|
|
426
|
+
return wireStatus(outcome.status, session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot());
|
|
427
|
+
}
|
|
428
|
+
if (method.startsWith("reminder/")) {
|
|
429
|
+
const reminders = session.reminders;
|
|
430
|
+
if (!reminders) throw new Fault("invalid_state", "Reminders are unavailable");
|
|
431
|
+
if (method === "reminder/list") return readValue(reminders.listReminders(parseReminderList(p))).value;
|
|
432
|
+
if (method === "reminder/get") {
|
|
433
|
+
keys(p, ["id"]);
|
|
434
|
+
const reminder = readValue(reminders.readReminder(text(p.id))).value;
|
|
435
|
+
if (!reminder) throw new Fault("not_found", "Unknown reminder");
|
|
436
|
+
return { reminder };
|
|
437
|
+
}
|
|
438
|
+
if (!reminders.executable()) throw new Fault("incompatible", "Reminders cannot change in this session");
|
|
439
|
+
return readValue(reminders.change(parseReminderChange(p))).value;
|
|
440
|
+
}
|
|
441
|
+
if (method === "session/stop" && Object.keys(p).length) {
|
|
442
|
+
keys(p, ["ifIdle", "unlessDueWithinMs"]);
|
|
443
|
+
const windowMs = p.unlessDueWithinMs ?? 0;
|
|
444
|
+
if (p.ifIdle !== true || p.unlessDueWithinMs === null || !Number.isSafeInteger(windowMs) || windowMs < 0) bad("Invalid conditional stop");
|
|
445
|
+
if (!session.reminders) throw new Fault("invalid_state", "Conditional stop is unavailable");
|
|
446
|
+
return session.reminders.conditionalStop(windowMs);
|
|
447
|
+
}
|
|
448
|
+
if (method === "session/stop") { keys(p, []); return wireStatus(session.stop("Stopped by the host"), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()); }
|
|
449
|
+
if (method === "session/model-calls") {
|
|
450
|
+
keys(p, ["after", "limit"]);
|
|
451
|
+
const after = p.after === undefined ? undefined : text(p.after);
|
|
452
|
+
const limit = p.limit === undefined ? 100 : count(p.limit, 100); if (limit > 100) bad("Limit exceeds 100");
|
|
453
|
+
const { calls, next } = readValue(session.readModelCalls(after, limit)).value;
|
|
454
|
+
const page = []; let bytes = 0;
|
|
455
|
+
for (const call of calls) {
|
|
456
|
+
const size = new TextEncoder().encode(JSON.stringify(call)).length + 1;
|
|
457
|
+
if (size > MAX_FRAME_BYTES - 1024) {
|
|
458
|
+
if (page.length) break;
|
|
459
|
+
throw new Fault("transfer_limit", "Call summary exceeds frame limit");
|
|
460
|
+
}
|
|
461
|
+
if (bytes + size > MAX_FRAME_BYTES - 1024) break;
|
|
462
|
+
page.push(call); bytes += size;
|
|
463
|
+
}
|
|
464
|
+
return { calls: page, ...(next !== undefined || page.length < calls.length ? { next: page.at(-1)!.callId } : {}) };
|
|
465
|
+
}
|
|
466
|
+
if (method === "session/message/read") {
|
|
467
|
+
keys(p, ["messageId", "offset"]); const id = text(p.messageId), offset = p.offset;
|
|
468
|
+
if (!Number.isSafeInteger(offset) || offset < 0) bad("Invalid byte offset");
|
|
469
|
+
const entry = session.snapshot().timeline.find(value => (value.messageId ?? String(value.seq)) === id && value.message.role === "assistant");
|
|
470
|
+
if (!entry || entry.message.role !== "assistant" || entry.message.content === null) throw new Fault("not_found", "Unknown text message");
|
|
471
|
+
const bytes = new TextEncoder().encode(entry.message.content); if (offset > bytes.length) bad("Invalid byte offset");
|
|
472
|
+
const end = Math.min(bytes.length, offset + 524288);
|
|
473
|
+
return { messageId: id, offset, data: Buffer.from(bytes.subarray(offset, end)).toString("base64"), ...(end < bytes.length ? { nextOffset: end } : {}) };
|
|
474
|
+
}
|
|
475
|
+
keys(p, ["channel", "item"]);
|
|
476
|
+
const channel = text(p.channel), item = obj(p.item);
|
|
477
|
+
keys(item, ["id", "kind", "sender", "content", "policy", "delivery", "wake"]);
|
|
478
|
+
const id = text(item.id), sender = text(item.sender);
|
|
479
|
+
// One delivery behavior: the two legacy fields are checked, then ignored.
|
|
480
|
+
if (item.kind !== "user_message" || (item.delivery !== undefined && item.delivery !== "queue") || (item.wake !== undefined && item.wake !== true)) bad("Only waking, queued user messages are supported");
|
|
481
|
+
if (!Array.isArray(item.content) || !item.content.length) bad("Expected text parts");
|
|
482
|
+
const parts = item.content.map((value: unknown) => { const part = obj(value); keys(part, ["type", "text"]);
|
|
483
|
+
if (part.type !== "text") bad("Only text parts are supported"); return { type: "text", text: text(part.text) }; });
|
|
484
|
+
// send returns once the item is committed to the inbox (Received) or
|
|
485
|
+
// refused. It never waits for inference; the outcome arrives as events.
|
|
486
|
+
const result = session.agent.send({ channelId: channel, participantId: sender, itemId: id, ...(item.policy == null ? {} : { policy: text(item.policy) }),
|
|
487
|
+
text: parts.map((part: { text: string }) => part.text).join("\n") });
|
|
488
|
+
if (!result.accepted) throw new Fault(result.code === "invalid_input" ? "invalid_params" : result.code, result.error);
|
|
489
|
+
const policy = session.operatorReads
|
|
490
|
+
? readValue(session.operatorReads.readTracked(channel, [id], [])).value.items[0]?.policy
|
|
491
|
+
: session.snapshot().items.find(value => value.itemId === id)?.policy;
|
|
492
|
+
return { accepted: true, duplicate: result.duplicate, item: { id, channel, kind: "participant_message", sender, milestone: result.milestone,
|
|
493
|
+
...(policy === undefined ? {} : { policy }),
|
|
494
|
+
...(result.turnId === undefined ? {} : { turnId: String(result.turnId) }) } };
|
|
495
|
+
}
|
|
496
|
+
return {
|
|
497
|
+
async request(request: RpcRequest): Promise<RpcResponse> {
|
|
498
|
+
const id = request && Number.isSafeInteger(request.id) ? request.id : null;
|
|
499
|
+
try {
|
|
500
|
+
if (!request || request.jsonrpc !== "2.0" || !Number.isSafeInteger(request.id) || typeof request.method !== "string") throw new Fault("invalid_request", "Invalid request envelope", -32600);
|
|
501
|
+
const result = await dispatch(request.method, request.params);
|
|
502
|
+
return { jsonrpc: "2.0", id: request.id, result };
|
|
503
|
+
} catch (error) {
|
|
504
|
+
const fault = error instanceof FrameLimit ? new Fault("transfer_limit", error.message)
|
|
505
|
+
: error instanceof ReminderShapeError ? new Fault("invalid_params", error.message)
|
|
506
|
+
: error instanceof TransferFault || error instanceof SessionFileError || error instanceof OperatorFault || error instanceof ChannelChangeFault || error instanceof ToolFault ? new Fault(error.code, error.message) : error;
|
|
507
|
+
return { jsonrpc: "2.0", id, error: { code: fault instanceof Fault ? fault.rpc : -32603,
|
|
508
|
+
message: String(fault), data: { code: fault instanceof Fault ? fault.tag : "internal_error" } } };
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
512
|
+
subscribeSession(listener) { sessionListeners.add(listener); return () => { sessionListeners.delete(listener); }; },
|
|
513
|
+
subscribeCallbacks(listener) { callbackListeners.add(listener); return () => { callbackListeners.delete(listener); }; },
|
|
514
|
+
respond(response) { bridge.respond(response); },
|
|
515
|
+
// A connection that is gone serves no handler and answers no callback.
|
|
516
|
+
disconnect() { approvalConsumer = false; current?.session.approvals.disconnect(); current?.session.tools?.serve([]); bridge.disconnect(); },
|
|
517
|
+
dispose() { approvalConsumer = false; current?.session.approvals.disconnect(); bridge.disconnect(); transfers?.dispose(); current?.session.reminders?.releaseTimer(); current?.close(); current = undefined; },
|
|
518
|
+
};
|
|
519
|
+
}
|