@arnilo/prism-hosts 0.0.0-stage → 0.13.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.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import type { JsonObject, JsonValue } from "@arnilo/prism";
|
|
2
|
+
import { isRemoteErrorCode, jsonRpcCodeOf, RemoteError, type RemoteErrorCode } from "./errors.js";
|
|
3
|
+
import { type RemoteLimitOptions, resolveRemoteLimits } from "./limits.js";
|
|
4
|
+
import {
|
|
5
|
+
type InitializeParams,
|
|
6
|
+
type InitializeResult,
|
|
7
|
+
isSupportedProtocol,
|
|
8
|
+
knownCapabilities,
|
|
9
|
+
REMOTE_PROTOCOL,
|
|
10
|
+
type RemoteCapabilities,
|
|
11
|
+
} from "./protocol.js";
|
|
12
|
+
import type { RemoteTransport } from "./transport.js";
|
|
13
|
+
|
|
14
|
+
export type RemoteHandler = (params: JsonObject, context: DispatcherContext) => Promise<JsonValue | undefined> | JsonValue | undefined;
|
|
15
|
+
|
|
16
|
+
export type RemoteNotificationHandler = (params: JsonObject) => void;
|
|
17
|
+
|
|
18
|
+
export interface DispatcherContext {
|
|
19
|
+
/** Capabilities both sides declared and this protocol knows. Empty before `initialize`. */
|
|
20
|
+
readonly capabilities: RemoteCapabilities;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DispatcherOptions {
|
|
24
|
+
readonly transport: RemoteTransport;
|
|
25
|
+
/** A server refuses every request except `initialize` until one succeeds. */
|
|
26
|
+
readonly role: "client" | "server";
|
|
27
|
+
/** Capabilities this side offers. */
|
|
28
|
+
readonly capabilities?: RemoteCapabilities;
|
|
29
|
+
readonly limits?: RemoteLimitOptions;
|
|
30
|
+
/** Server only: builds the `initialize` result (the dispatcher adds `protocol` and `capabilities`). */
|
|
31
|
+
readonly onInitialize?: (
|
|
32
|
+
params: InitializeParams,
|
|
33
|
+
negotiated: RemoteCapabilities,
|
|
34
|
+
) => Promise<Omit<InitializeResult, "protocol" | "capabilities">> | Omit<InitializeResult, "protocol" | "capabilities">;
|
|
35
|
+
readonly requests?: Readonly<Record<string, RemoteHandler>>;
|
|
36
|
+
readonly notifications?: Readonly<Record<string, RemoteNotificationHandler>>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface Dispatcher {
|
|
40
|
+
/** Sends a request and resolves with its result. Rejects with `RemoteError`. */
|
|
41
|
+
request(method: string, params?: JsonObject): Promise<JsonValue>;
|
|
42
|
+
notify(method: string, params?: JsonObject): Promise<void>;
|
|
43
|
+
/** Client side: negotiates `prism.remote/1` and returns the server's result. */
|
|
44
|
+
initialize(): Promise<InitializeResult>;
|
|
45
|
+
readonly capabilities: RemoteCapabilities;
|
|
46
|
+
readonly initialized: boolean;
|
|
47
|
+
close(reason?: string): Promise<void>;
|
|
48
|
+
readonly closed: Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface Pending {
|
|
52
|
+
readonly resolve: (value: JsonValue) => void;
|
|
53
|
+
readonly reject: (error: Error) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createDispatcher(options: DispatcherOptions): Dispatcher {
|
|
57
|
+
const { transport, role } = options;
|
|
58
|
+
const limits = resolveRemoteLimits(options.limits);
|
|
59
|
+
const offered = knownCapabilities(options.capabilities);
|
|
60
|
+
const requests = options.requests ?? {};
|
|
61
|
+
const notifications = options.notifications ?? {};
|
|
62
|
+
const pending = new Map<number, Pending>();
|
|
63
|
+
let nextId = 1;
|
|
64
|
+
let inFlight = 0;
|
|
65
|
+
let negotiated: RemoteCapabilities = {};
|
|
66
|
+
let initialized = false;
|
|
67
|
+
let ended = false;
|
|
68
|
+
|
|
69
|
+
const failPending = (error: Error) => {
|
|
70
|
+
for (const entry of pending.values()) entry.reject(error);
|
|
71
|
+
pending.clear();
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const send = async (frame: JsonObject): Promise<void> => {
|
|
75
|
+
try {
|
|
76
|
+
await transport.send(frame);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error instanceof RemoteError) throw error;
|
|
79
|
+
throw new RemoteError("disconnected", "transport send failed");
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const sendError = async (id: JsonValue, code: RemoteErrorCode, message: string, data?: JsonObject) => {
|
|
84
|
+
await send({ jsonrpc: "2.0", id, error: { code: jsonRpcCodeOf(code), message, data: { code, ...data } } });
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const context = (): DispatcherContext => ({ capabilities: negotiated });
|
|
88
|
+
|
|
89
|
+
async function handleRequest(id: JsonValue, method: string, params: JsonObject): Promise<void> {
|
|
90
|
+
if (inFlight >= limits.maxConcurrentRequests) {
|
|
91
|
+
await sendError(id, "busy", `more than ${limits.maxConcurrentRequests} concurrent requests`).catch(() => {});
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
inFlight++;
|
|
95
|
+
try {
|
|
96
|
+
if (method === "initialize" && role === "server") {
|
|
97
|
+
await handleInitialize(id, params);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (role === "server" && !initialized) {
|
|
101
|
+
await sendError(id, "not_initialized", "initialize must succeed before other calls");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const handler = Object.hasOwn(requests, method) ? requests[method] : undefined;
|
|
105
|
+
if (!handler) {
|
|
106
|
+
await sendError(id, "method_not_found", "unknown method");
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const result = await handler(params, context());
|
|
110
|
+
await send({ jsonrpc: "2.0", id, result: result ?? null });
|
|
111
|
+
} catch (error) {
|
|
112
|
+
await respondError(id, error);
|
|
113
|
+
} finally {
|
|
114
|
+
inFlight--;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function handleInitialize(id: JsonValue, params: JsonObject): Promise<void> {
|
|
119
|
+
if (!isSupportedProtocol(params.protocol)) {
|
|
120
|
+
await sendError(id, "protocol_unsupported", `supported protocol: ${REMOTE_PROTOCOL}`, { supported: REMOTE_PROTOCOL });
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const peer = knownCapabilities(params.capabilities);
|
|
124
|
+
const agreed: Record<string, boolean> = {};
|
|
125
|
+
for (const name of Object.keys(peer)) if ((offered as Record<string, boolean | undefined>)[name]) agreed[name] = true;
|
|
126
|
+
const body = await options.onInitialize?.(params as unknown as InitializeParams, agreed as RemoteCapabilities);
|
|
127
|
+
negotiated = agreed as RemoteCapabilities;
|
|
128
|
+
initialized = true;
|
|
129
|
+
await send({
|
|
130
|
+
jsonrpc: "2.0",
|
|
131
|
+
id,
|
|
132
|
+
result: { ...(body as unknown as JsonObject | undefined), protocol: REMOTE_PROTOCOL, capabilities: agreed },
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function respondError(id: JsonValue, error: unknown): Promise<void> {
|
|
137
|
+
try {
|
|
138
|
+
if (error instanceof RemoteError) await sendError(id, error.code, error.message);
|
|
139
|
+
else {
|
|
140
|
+
const message = error instanceof Error ? error.message.slice(0, 500) : "request failed";
|
|
141
|
+
const code = (error as { code?: unknown } | null)?.code;
|
|
142
|
+
await sendError(id, "internal_error", message, typeof code === "string" ? { cause: code.slice(0, 100) } : undefined);
|
|
143
|
+
}
|
|
144
|
+
} catch {
|
|
145
|
+
// The transport is gone; the peer sees the disconnect.
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function handleResponse(frame: JsonObject): void {
|
|
150
|
+
const id = frame.id;
|
|
151
|
+
if (typeof id !== "number") return;
|
|
152
|
+
const entry = pending.get(id);
|
|
153
|
+
if (!entry) return;
|
|
154
|
+
pending.delete(id);
|
|
155
|
+
const failure = frame.error;
|
|
156
|
+
if (failure !== undefined && failure !== null && typeof failure === "object" && !Array.isArray(failure)) {
|
|
157
|
+
const body = failure as JsonObject;
|
|
158
|
+
const data = body.data;
|
|
159
|
+
const code = data !== null && typeof data === "object" && !Array.isArray(data) ? (data as JsonObject).code : undefined;
|
|
160
|
+
entry.reject(
|
|
161
|
+
new RemoteError(
|
|
162
|
+
isRemoteErrorCode(code) ? code : "internal_error",
|
|
163
|
+
typeof body.message === "string" ? body.message : "remote error",
|
|
164
|
+
),
|
|
165
|
+
);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
entry.resolve((frame.result ?? null) as JsonValue);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const reject = (id: JsonValue, code: RemoteErrorCode, message: string, data?: JsonObject) =>
|
|
172
|
+
sendError(id, code, message, data).catch(() => {});
|
|
173
|
+
|
|
174
|
+
async function onFrame(text: string): Promise<void> {
|
|
175
|
+
const bytes = new TextEncoder().encode(text).length;
|
|
176
|
+
if (bytes > limits.maxFrameBytes) {
|
|
177
|
+
await reject(null, "frame_too_large", `frame exceeds ${limits.maxFrameBytes} bytes`, { bytes });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
let value: unknown;
|
|
181
|
+
try {
|
|
182
|
+
value = JSON.parse(text);
|
|
183
|
+
} catch {
|
|
184
|
+
await send({
|
|
185
|
+
jsonrpc: "2.0",
|
|
186
|
+
id: null,
|
|
187
|
+
error: { code: -32700, message: "parse error", data: { code: "invalid_frame", bytes } },
|
|
188
|
+
}).catch(() => {});
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || (value as JsonObject).jsonrpc !== "2.0") {
|
|
192
|
+
await reject(null, "invalid_frame", "frame is not a JSON-RPC 2.0 object", { bytes });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const frame = value as JsonObject;
|
|
196
|
+
const params = frame.params;
|
|
197
|
+
const isObject = params !== null && typeof params === "object" && !Array.isArray(params);
|
|
198
|
+
const object: JsonObject = isObject ? (params as JsonObject) : {};
|
|
199
|
+
if (typeof frame.method === "string") {
|
|
200
|
+
if (frame.id === undefined || frame.id === null) {
|
|
201
|
+
if ((params === undefined || isObject) && Object.hasOwn(notifications, frame.method)) notifications[frame.method]?.(object);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (typeof frame.id !== "string" && typeof frame.id !== "number") {
|
|
205
|
+
await reject(null, "invalid_frame", "request id must be a string or number");
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (params !== undefined && !isObject) {
|
|
209
|
+
await reject(frame.id, "invalid_params", "params must be an object");
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
// Handlers run concurrently; the read loop never waits on one.
|
|
213
|
+
void handleRequest(frame.id, frame.method, object);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (frame.result !== undefined || frame.error !== undefined) {
|
|
217
|
+
handleResponse(frame);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
await reject(null, "invalid_frame", "frame has no method, result, or error", { bytes });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function loop(): Promise<void> {
|
|
224
|
+
try {
|
|
225
|
+
for await (const item of transport.frames()) {
|
|
226
|
+
if (typeof item === "string") await onFrame(item);
|
|
227
|
+
else await reject(null, "frame_too_large", `frame exceeds ${limits.maxFrameBytes} bytes`);
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
// A broken transport ends the loop like a clean close.
|
|
231
|
+
} finally {
|
|
232
|
+
ended = true;
|
|
233
|
+
failPending(new RemoteError("disconnected", "connection closed"));
|
|
234
|
+
await transport.close().catch(() => {});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
void loop();
|
|
238
|
+
|
|
239
|
+
const request = async (method: string, params: JsonObject = {}): Promise<JsonValue> => {
|
|
240
|
+
if (ended) throw new RemoteError("disconnected", "connection closed");
|
|
241
|
+
if (pending.size >= limits.maxPendingRequests) throw new RemoteError("busy", `more than ${limits.maxPendingRequests} pending requests`);
|
|
242
|
+
const id = nextId++;
|
|
243
|
+
const result = new Promise<JsonValue>((resolve, rejectPending) => pending.set(id, { resolve, reject: rejectPending }));
|
|
244
|
+
try {
|
|
245
|
+
await send({ jsonrpc: "2.0", id, method, params });
|
|
246
|
+
} catch (error) {
|
|
247
|
+
pending.delete(id);
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
return result;
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
request,
|
|
255
|
+
async notify(method, params = {}) {
|
|
256
|
+
if (ended) throw new RemoteError("disconnected", "connection closed");
|
|
257
|
+
await send({ jsonrpc: "2.0", method, params });
|
|
258
|
+
},
|
|
259
|
+
async initialize() {
|
|
260
|
+
const result = (await request("initialize", {
|
|
261
|
+
protocol: REMOTE_PROTOCOL,
|
|
262
|
+
capabilities: offered as JsonObject,
|
|
263
|
+
})) as unknown as InitializeResult;
|
|
264
|
+
if (!isSupportedProtocol(result?.protocol)) throw new RemoteError("protocol_unsupported", `supported protocol: ${REMOTE_PROTOCOL}`);
|
|
265
|
+
negotiated = knownCapabilities(result.capabilities);
|
|
266
|
+
initialized = true;
|
|
267
|
+
return result;
|
|
268
|
+
},
|
|
269
|
+
get capabilities() {
|
|
270
|
+
return negotiated;
|
|
271
|
+
},
|
|
272
|
+
get initialized() {
|
|
273
|
+
return initialized;
|
|
274
|
+
},
|
|
275
|
+
async close(reason) {
|
|
276
|
+
ended = true;
|
|
277
|
+
failPending(new RemoteError("disconnected", "connection closed"));
|
|
278
|
+
await transport.close(reason);
|
|
279
|
+
},
|
|
280
|
+
closed: transport.closed,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** Stable codes carried in JSON-RPC `error.data.code` and on `RemoteError.code`. */
|
|
2
|
+
export type RemoteErrorCode =
|
|
3
|
+
| "invalid_frame"
|
|
4
|
+
| "frame_too_large"
|
|
5
|
+
| "method_not_found"
|
|
6
|
+
| "invalid_params"
|
|
7
|
+
| "internal_error"
|
|
8
|
+
| "busy"
|
|
9
|
+
| "not_initialized"
|
|
10
|
+
| "protocol_unsupported"
|
|
11
|
+
| "unauthorized"
|
|
12
|
+
| "forbidden_host"
|
|
13
|
+
| "forbidden_origin"
|
|
14
|
+
| "body_too_large"
|
|
15
|
+
| "remote_unsupported"
|
|
16
|
+
| "disconnected"
|
|
17
|
+
| "session_not_found"
|
|
18
|
+
| "limit"
|
|
19
|
+
| "literal_secret"
|
|
20
|
+
| "unauthenticated_bind";
|
|
21
|
+
|
|
22
|
+
export class RemoteError extends Error {
|
|
23
|
+
readonly code: RemoteErrorCode;
|
|
24
|
+
|
|
25
|
+
constructor(code: RemoteErrorCode, message: string) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "RemoteError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const JSON_RPC_CODES: Record<RemoteErrorCode, number> = {
|
|
33
|
+
invalid_frame: -32600,
|
|
34
|
+
frame_too_large: -32600,
|
|
35
|
+
method_not_found: -32601,
|
|
36
|
+
invalid_params: -32602,
|
|
37
|
+
internal_error: -32603,
|
|
38
|
+
busy: -32001,
|
|
39
|
+
not_initialized: -32002,
|
|
40
|
+
protocol_unsupported: -32003,
|
|
41
|
+
unauthorized: -32004,
|
|
42
|
+
forbidden_host: -32005,
|
|
43
|
+
forbidden_origin: -32006,
|
|
44
|
+
body_too_large: -32007,
|
|
45
|
+
remote_unsupported: -32008,
|
|
46
|
+
disconnected: -32009,
|
|
47
|
+
session_not_found: -32010,
|
|
48
|
+
limit: -32011,
|
|
49
|
+
literal_secret: -32012,
|
|
50
|
+
unauthenticated_bind: -32013,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function jsonRpcCodeOf(code: RemoteErrorCode): number {
|
|
54
|
+
return JSON_RPC_CODES[code];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function isRemoteErrorCode(value: unknown): value is RemoteErrorCode {
|
|
58
|
+
return typeof value === "string" && Object.hasOwn(JSON_RPC_CODES, value);
|
|
59
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { Decision, HostUi, HostUiRequest, HostUiRequestKind, HostUiResponse, JsonObject, PendingDecision } from "@arnilo/prism";
|
|
2
|
+
import type { HostUiRequestParams } from "./protocol.js";
|
|
3
|
+
|
|
4
|
+
/** One attached client, as `remoteHostUi` sees it. */
|
|
5
|
+
export interface RemoteUiConnection {
|
|
6
|
+
/** The client declared `hostUi.secret`. Without it a `secret` request answers `unavailable`. */
|
|
7
|
+
readonly canSecret: boolean;
|
|
8
|
+
/** Partition key of the authenticated principal (`""` for single-principal connections). */
|
|
9
|
+
readonly principalKey?: string;
|
|
10
|
+
/** Whether this connection may answer agent-scoped (`sessionId` absent) host-UI requests. */
|
|
11
|
+
readonly operator?: boolean;
|
|
12
|
+
ask(params: HostUiRequestParams): Promise<HostUiResponse>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface HostUiBinding {
|
|
16
|
+
readonly byPrincipal: Map<string, RemoteUiConnection[]>;
|
|
17
|
+
readonly operators: RemoteUiConnection[];
|
|
18
|
+
ownerOf?: (sessionId: string) => string | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const UNAVAILABLE: HostUiResponse = { status: "unavailable" };
|
|
22
|
+
const bindings = new WeakMap<HostUi, HostUiBinding>();
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A `HostUi` that asks the connected `prism.remote/1` client. Pass it as the agent's `host.ui` and to
|
|
26
|
+
* `serveAgent(agent, { hostUi: ui })`. With no matching owner/operator client bound, or after the client
|
|
27
|
+
* disconnects mid-request, every request answers `unavailable`: the kernel then suspends the run durably
|
|
28
|
+
* and a later client of the owning principal answers it.
|
|
29
|
+
*/
|
|
30
|
+
export function remoteHostUi(): HostUi {
|
|
31
|
+
const binding: HostUiBinding = {
|
|
32
|
+
byPrincipal: new Map(),
|
|
33
|
+
operators: [],
|
|
34
|
+
};
|
|
35
|
+
const ui: HostUi = {
|
|
36
|
+
async request<K extends HostUiRequestKind>(request: Extract<HostUiRequest, { kind: K }>): Promise<HostUiResponse<K>> {
|
|
37
|
+
let connection: RemoteUiConnection | undefined;
|
|
38
|
+
if (request.sessionId !== undefined && request.sessionId !== "") {
|
|
39
|
+
const ownerKey = binding.ownerOf ? binding.ownerOf(request.sessionId) : "";
|
|
40
|
+
if (ownerKey === undefined) return UNAVAILABLE as HostUiResponse<K>;
|
|
41
|
+
const list = binding.byPrincipal.get(ownerKey);
|
|
42
|
+
connection = list?.[list.length - 1];
|
|
43
|
+
} else {
|
|
44
|
+
connection = binding.operators[binding.operators.length - 1];
|
|
45
|
+
}
|
|
46
|
+
if (!connection) return UNAVAILABLE as HostUiResponse<K>;
|
|
47
|
+
if (request.kind === "secret" && !connection.canSecret) return UNAVAILABLE as HostUiResponse<K>;
|
|
48
|
+
let answer: HostUiResponse;
|
|
49
|
+
try {
|
|
50
|
+
answer = await connection.ask({
|
|
51
|
+
...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),
|
|
52
|
+
request,
|
|
53
|
+
});
|
|
54
|
+
} catch {
|
|
55
|
+
return UNAVAILABLE as HostUiResponse<K>;
|
|
56
|
+
}
|
|
57
|
+
return (validAnswer(request.kind, answer) ? answer : UNAVAILABLE) as HostUiResponse<K>;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
bindings.set(ui, binding);
|
|
61
|
+
return ui;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Injects the server's session-to-principal resolver into a `remoteHostUi()`. Throws for any other `HostUi`. */
|
|
65
|
+
export function bindRemoteHostUiOwner(ui: HostUi, ownerOf: (sessionId: string) => string | undefined): void {
|
|
66
|
+
const binding = bindings.get(ui);
|
|
67
|
+
if (!binding) throw new TypeError("serveAgent hostUi must come from remoteHostUi()");
|
|
68
|
+
binding.ownerOf = ownerOf;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Attaches a client to a `remoteHostUi`. Returns the detach function. Throws for any other `HostUi`. */
|
|
72
|
+
export function bindRemoteHostUi(ui: HostUi, connection: RemoteUiConnection): () => void {
|
|
73
|
+
const binding = bindings.get(ui);
|
|
74
|
+
if (!binding) throw new TypeError("serveAgent hostUi must come from remoteHostUi()");
|
|
75
|
+
const key = connection.principalKey ?? "";
|
|
76
|
+
const isOperator = connection.operator ?? key === "";
|
|
77
|
+
let list = binding.byPrincipal.get(key);
|
|
78
|
+
if (!list) {
|
|
79
|
+
list = [];
|
|
80
|
+
binding.byPrincipal.set(key, list);
|
|
81
|
+
}
|
|
82
|
+
list.push(connection);
|
|
83
|
+
if (isOperator) binding.operators.push(connection);
|
|
84
|
+
return () => {
|
|
85
|
+
const owned = binding.byPrincipal.get(key);
|
|
86
|
+
if (owned) {
|
|
87
|
+
const index = owned.indexOf(connection);
|
|
88
|
+
if (index >= 0) owned.splice(index, 1);
|
|
89
|
+
if (owned.length === 0) binding.byPrincipal.delete(key);
|
|
90
|
+
}
|
|
91
|
+
if (isOperator) {
|
|
92
|
+
const opIndex = binding.operators.indexOf(connection);
|
|
93
|
+
if (opIndex >= 0) binding.operators.splice(opIndex, 1);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function validAnswer(kind: HostUiRequestKind, answer: unknown): answer is HostUiResponse {
|
|
99
|
+
if (answer === null || typeof answer !== "object") return false;
|
|
100
|
+
const status = (answer as { status?: unknown }).status;
|
|
101
|
+
if (status === "dismissed" || status === "unavailable") return true;
|
|
102
|
+
if (status !== "answered") return false;
|
|
103
|
+
const value = (answer as { value?: unknown }).value;
|
|
104
|
+
switch (kind) {
|
|
105
|
+
case "confirm":
|
|
106
|
+
return typeof value === "boolean";
|
|
107
|
+
case "input":
|
|
108
|
+
return typeof value === "string";
|
|
109
|
+
case "select":
|
|
110
|
+
return typeof value === "string" || (Array.isArray(value) && value.every((item) => typeof item === "string"));
|
|
111
|
+
case "terminal":
|
|
112
|
+
return value !== null && typeof value === "object" && Number.isInteger((value as { exitCode?: unknown }).exitCode);
|
|
113
|
+
case "secret":
|
|
114
|
+
return value === undefined || typeof value === "string";
|
|
115
|
+
default:
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The request a pending decision becomes when a client reconnects. */
|
|
121
|
+
export function requestForPending(sessionId: string, pending: PendingDecision): HostUiRequest {
|
|
122
|
+
if (pending.kind === "elicitation") {
|
|
123
|
+
return {
|
|
124
|
+
kind: "input",
|
|
125
|
+
sessionId,
|
|
126
|
+
title: pending.reason,
|
|
127
|
+
...(pending.elicitationSchema ? { detail: JSON.stringify(pending.elicitationSchema) } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
return { kind: "confirm", sessionId, title: `Approve ${pending.scope.toolName ?? "tool call"}`, detail: pending.reason };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Maps a client's answer to a `Decision`, or `undefined` to leave the decision pending. `dismissed` rejects
|
|
135
|
+
* an approval; an elicitation answer must be a JSON object (the kernel validates it against the schema).
|
|
136
|
+
*/
|
|
137
|
+
export function decisionFromAnswer(pending: PendingDecision, answer: HostUiResponse): Decision | undefined {
|
|
138
|
+
if (answer.status === "unavailable") return undefined;
|
|
139
|
+
if (pending.kind === "elicitation") {
|
|
140
|
+
if (answer.status !== "answered" || typeof answer.value !== "string") return undefined;
|
|
141
|
+
try {
|
|
142
|
+
const parsed: unknown = JSON.parse(answer.value);
|
|
143
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
144
|
+
return { approvalId: pending.approvalId, outcome: "allow_once", elicitation: parsed as JsonObject };
|
|
145
|
+
} catch {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (answer.status === "dismissed") return { approvalId: pending.approvalId, outcome: "reject_once" };
|
|
150
|
+
if (typeof answer.value !== "boolean") return undefined;
|
|
151
|
+
return { approvalId: pending.approvalId, outcome: answer.value ? "allow_once" : "reject_once" };
|
|
152
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { RemoteError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
export const rejection = (status: number, code: string) => Response.json({ error: code }, { status });
|
|
4
|
+
|
|
5
|
+
// Host/Origin matching parity with hosts/mcp-server/src/server.ts hostOriginRejection.
|
|
6
|
+
export function hostOriginRejection(
|
|
7
|
+
request: Request,
|
|
8
|
+
options: { allowedHosts?: readonly string[]; allowedOrigins?: readonly string[] },
|
|
9
|
+
): Response | undefined {
|
|
10
|
+
if (options.allowedHosts?.length) {
|
|
11
|
+
const host = request.headers.get("host")?.toLowerCase();
|
|
12
|
+
if (!host || !options.allowedHosts.some((allowed) => allowed.toLowerCase() === host)) return rejection(403, "forbidden_host");
|
|
13
|
+
}
|
|
14
|
+
if (options.allowedOrigins?.length) {
|
|
15
|
+
const origin = request.headers.get("origin");
|
|
16
|
+
if (origin && !options.allowedOrigins.some((allowed) => allowed.toLowerCase() === origin.toLowerCase()))
|
|
17
|
+
return rejection(403, "forbidden_origin");
|
|
18
|
+
}
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function readBody(request: Request, cap: number): Promise<string> {
|
|
23
|
+
const reader = request.body?.getReader();
|
|
24
|
+
if (!reader) return "";
|
|
25
|
+
const decoder = new TextDecoder();
|
|
26
|
+
let bytes = 0;
|
|
27
|
+
let text = "";
|
|
28
|
+
try {
|
|
29
|
+
while (true) {
|
|
30
|
+
const { value, done } = await reader.read();
|
|
31
|
+
if (done) break;
|
|
32
|
+
bytes += value.byteLength;
|
|
33
|
+
if (bytes > cap) {
|
|
34
|
+
void reader.cancel().catch(() => {});
|
|
35
|
+
throw new RemoteError("body_too_large", "body_too_large");
|
|
36
|
+
}
|
|
37
|
+
text += decoder.decode(value, { stream: true });
|
|
38
|
+
}
|
|
39
|
+
return text + decoder.decode();
|
|
40
|
+
} finally {
|
|
41
|
+
reader.releaseLock();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export { type AttributionSource, attribute } from "./attribution.js";
|
|
2
|
+
export { type ConnectAgentOptions, type ConnectEndpoint, connectAgent } from "./connect.js";
|
|
3
|
+
export {
|
|
4
|
+
createDispatcher,
|
|
5
|
+
type Dispatcher,
|
|
6
|
+
type DispatcherContext,
|
|
7
|
+
type DispatcherOptions,
|
|
8
|
+
type RemoteHandler,
|
|
9
|
+
type RemoteNotificationHandler,
|
|
10
|
+
} from "./dispatcher.js";
|
|
11
|
+
export { isRemoteErrorCode, RemoteError, type RemoteErrorCode } from "./errors.js";
|
|
12
|
+
export { remoteHostUi } from "./host-ui.js";
|
|
13
|
+
export { type OversizeFrame, readJsonlFrames } from "./jsonl.js";
|
|
14
|
+
export {
|
|
15
|
+
REMOTE_LIMITS,
|
|
16
|
+
type RemoteLimitName,
|
|
17
|
+
type RemoteLimitOptions,
|
|
18
|
+
type ResolvedRemoteLimits,
|
|
19
|
+
resolveRemoteLimits,
|
|
20
|
+
} from "./limits.js";
|
|
21
|
+
export { createSessionMirror, type SessionMirror } from "./mirror.js";
|
|
22
|
+
export { pendingDecisionsOf } from "./pending.js";
|
|
23
|
+
export {
|
|
24
|
+
CLIENT_METHODS,
|
|
25
|
+
type HostUiRequestParams,
|
|
26
|
+
type HostUiRequestResult,
|
|
27
|
+
type InitializeParams,
|
|
28
|
+
type InitializeResult,
|
|
29
|
+
isSupportedProtocol,
|
|
30
|
+
KNOWN_CAPABILITIES,
|
|
31
|
+
knownCapabilities,
|
|
32
|
+
REMOTE_PROTOCOL,
|
|
33
|
+
type RemoteCapabilities,
|
|
34
|
+
type RemoteCapabilityName,
|
|
35
|
+
type RemoteClientMethod,
|
|
36
|
+
type RemoteMethods,
|
|
37
|
+
type RemoteNotifications,
|
|
38
|
+
type RemoteRunOptions,
|
|
39
|
+
SERVER_NOTIFICATIONS,
|
|
40
|
+
SERVER_REQUESTS,
|
|
41
|
+
} from "./protocol.js";
|
|
42
|
+
export { type RemoteResumeAuthority, type ServeAgentOptions, type ServedAgent, type ServeTransport, serveAgent } from "./serve.js";
|
|
43
|
+
export type { StdioEndpoint } from "./stdio-client.js";
|
|
44
|
+
export {
|
|
45
|
+
createMemoryTransportPair,
|
|
46
|
+
type RemoteTransport,
|
|
47
|
+
type StdioTransportOptions,
|
|
48
|
+
stdioTransport,
|
|
49
|
+
type WritableLike,
|
|
50
|
+
} from "./transport.js";
|
|
51
|
+
|
|
52
|
+
export type { NetworkEndpoint } from "./transports/client.js";
|
|
53
|
+
export type { Authenticate, NetworkTransport } from "./transports/network.js";
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Marks a line that exceeded `maxBytes`. The line is discarded, never buffered. */
|
|
2
|
+
export interface OversizeFrame {
|
|
3
|
+
readonly oversize: true;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export const OVERSIZE: OversizeFrame = Object.freeze({ oversize: true });
|
|
7
|
+
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
const decoder = new TextDecoder();
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Splits a byte or string stream into newline-delimited frames. A line over `maxBytes`
|
|
13
|
+
* is dropped while reading and surfaced as `OVERSIZE`; memory never exceeds `maxBytes`
|
|
14
|
+
* plus one chunk. Blank lines are skipped.
|
|
15
|
+
*/
|
|
16
|
+
export async function* readJsonlFrames(
|
|
17
|
+
source: AsyncIterable<Uint8Array | string>,
|
|
18
|
+
maxBytes: number,
|
|
19
|
+
): AsyncGenerator<string | OversizeFrame> {
|
|
20
|
+
let pending: Uint8Array[] = [];
|
|
21
|
+
let pendingBytes = 0;
|
|
22
|
+
let discarding = false;
|
|
23
|
+
const reset = () => {
|
|
24
|
+
pending = [];
|
|
25
|
+
pendingBytes = 0;
|
|
26
|
+
discarding = false;
|
|
27
|
+
};
|
|
28
|
+
const line = (): string | undefined => {
|
|
29
|
+
if (pendingBytes === 0) return undefined;
|
|
30
|
+
const joined = new Uint8Array(pendingBytes);
|
|
31
|
+
let offset = 0;
|
|
32
|
+
for (const part of pending) {
|
|
33
|
+
joined.set(part, offset);
|
|
34
|
+
offset += part.length;
|
|
35
|
+
}
|
|
36
|
+
const text = decoder.decode(joined).replace(/\r$/, "");
|
|
37
|
+
return text.length > 0 ? text : undefined;
|
|
38
|
+
};
|
|
39
|
+
for await (const chunk of source) {
|
|
40
|
+
let bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk;
|
|
41
|
+
while (bytes.length > 0) {
|
|
42
|
+
const newline = bytes.indexOf(10);
|
|
43
|
+
const part = newline < 0 ? bytes : bytes.subarray(0, newline);
|
|
44
|
+
if (!discarding) {
|
|
45
|
+
pendingBytes += part.length;
|
|
46
|
+
if (pendingBytes > maxBytes) {
|
|
47
|
+
discarding = true;
|
|
48
|
+
pending = [];
|
|
49
|
+
pendingBytes = 0;
|
|
50
|
+
} else {
|
|
51
|
+
pending.push(part);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (newline < 0) break;
|
|
55
|
+
if (discarding) yield OVERSIZE;
|
|
56
|
+
else {
|
|
57
|
+
const text = line();
|
|
58
|
+
if (text !== undefined) yield text;
|
|
59
|
+
}
|
|
60
|
+
reset();
|
|
61
|
+
bytes = bytes.subarray(newline + 1);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (discarding) yield OVERSIZE;
|
|
65
|
+
else {
|
|
66
|
+
const text = line();
|
|
67
|
+
if (text !== undefined) yield text;
|
|
68
|
+
}
|
|
69
|
+
}
|