@arnilo/prism-hosts 0.0.0-stage → 0.13.0
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 +6167 -0
- package/host-builder/data/errors.json +546 -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 +252 -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 +317 -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 +64 -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,560 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Agent,
|
|
3
|
+
type AgentEvent,
|
|
4
|
+
type Decision,
|
|
5
|
+
type HostUi,
|
|
6
|
+
type HostUiResponse,
|
|
7
|
+
isSessionNotFound,
|
|
8
|
+
type JsonObject,
|
|
9
|
+
type JsonValue,
|
|
10
|
+
type Message,
|
|
11
|
+
type OwnershipScope,
|
|
12
|
+
OwnershipScopeError,
|
|
13
|
+
type PendingDecision,
|
|
14
|
+
type Principal,
|
|
15
|
+
type RunOptions,
|
|
16
|
+
type RunResult,
|
|
17
|
+
type Session,
|
|
18
|
+
} from "@arnilo/prism";
|
|
19
|
+
import { createDispatcher, type Dispatcher, type RemoteHandler } from "./dispatcher.js";
|
|
20
|
+
import { RemoteError } from "./errors.js";
|
|
21
|
+
import { bindRemoteHostUi, bindRemoteHostUiOwner, decisionFromAnswer, requestForPending } from "./host-ui.js";
|
|
22
|
+
import { type RemoteLimitOptions, type ResolvedRemoteLimits, resolveRemoteLimits } from "./limits.js";
|
|
23
|
+
import { pendingDecisionsOf } from "./pending.js";
|
|
24
|
+
import type { HostUiRequestParams, InitializeResult, RemoteCapabilities } from "./protocol.js";
|
|
25
|
+
import { type RemoteTransport, stdioTransport } from "./transport.js";
|
|
26
|
+
|
|
27
|
+
import { type Authenticate, type NetworkTransport, serveNetwork } from "./transports/network.js";
|
|
28
|
+
import {
|
|
29
|
+
invalid,
|
|
30
|
+
isObject,
|
|
31
|
+
parseDecisions,
|
|
32
|
+
parseInput,
|
|
33
|
+
parseRunOptions,
|
|
34
|
+
parseSessionListQuery,
|
|
35
|
+
parseSessionParentLink,
|
|
36
|
+
parseSteerOptions,
|
|
37
|
+
str,
|
|
38
|
+
} from "./wire.js";
|
|
39
|
+
|
|
40
|
+
export type ServeTransport =
|
|
41
|
+
| NetworkTransport
|
|
42
|
+
| RemoteTransport
|
|
43
|
+
| {
|
|
44
|
+
readonly kind: "stdio";
|
|
45
|
+
readonly input?: AsyncIterable<Uint8Array | string>;
|
|
46
|
+
readonly output?: { write(chunk: string, cb?: (error?: Error | null) => void): unknown; end?(): unknown };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Optional host-owned authority shared with other resume entry points. */
|
|
50
|
+
export interface RemoteResumeAuthority {
|
|
51
|
+
resume(id: string, decisions: readonly Decision[], options?: RunOptions): AsyncIterable<AgentEvent>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ServeAgentOptions {
|
|
55
|
+
readonly resumeAuthority?: RemoteResumeAuthority;
|
|
56
|
+
readonly transport: ServeTransport;
|
|
57
|
+
readonly authenticate?: Authenticate;
|
|
58
|
+
/** Derives the kernel `OwnershipScope` for an authenticated connection. */
|
|
59
|
+
readonly ownershipFor?: (principal: Principal) => OwnershipScope;
|
|
60
|
+
/** Marks a principal as an operator allowed to receive agent-scoped events and host-UI requests. */
|
|
61
|
+
readonly operator?: (principal: Principal) => boolean;
|
|
62
|
+
/** Allows clients to send `Decision.modifiedArguments` in `sessions.resume` (re-gated by the kernel). Defaults to `false`. */
|
|
63
|
+
readonly allowModifiedArguments?: boolean;
|
|
64
|
+
/** The `remoteHostUi()` the agent was created with. The connected client is bound to it. */
|
|
65
|
+
readonly hostUi?: HostUi;
|
|
66
|
+
readonly limits?: RemoteLimitOptions;
|
|
67
|
+
/** Id reported to clients as `origin.remote`. Defaults to a random id. */
|
|
68
|
+
readonly endpointId?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ServedAgent {
|
|
72
|
+
readonly endpointId: string;
|
|
73
|
+
readonly url?: string;
|
|
74
|
+
readonly token?: string;
|
|
75
|
+
/** Await before using a keyring-backed token. */
|
|
76
|
+
readonly ready?: Promise<void>;
|
|
77
|
+
readonly closed: Promise<void>;
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Canonical collision-free partition key for a connection's `Principal` (`""` for single-principal connections). */
|
|
82
|
+
export function principalKeyOf(principal: Principal | undefined): string {
|
|
83
|
+
return principal ? `${principal.kind.length}:${principal.kind}:${principal.id}` : "";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** State shared by every connection to one served agent: the open sessions and the one-resume-at-a-time guard. */
|
|
87
|
+
export interface ServerState {
|
|
88
|
+
readonly agent: Agent;
|
|
89
|
+
readonly endpointId: string;
|
|
90
|
+
/** Open sessions partitioned by `principalKeyOf(principal)` -> `sessionId` -> `Session`. */
|
|
91
|
+
readonly sessions: Map<string, Map<string, Session>>;
|
|
92
|
+
/** Session owner index (`sessionId` -> `principalKeyOf(principal)`) for constant-time routing and isolation checks. */
|
|
93
|
+
readonly sessionOwners: Map<string, string>;
|
|
94
|
+
readonly ownershipFor?: (principal: Principal) => OwnershipScope;
|
|
95
|
+
readonly operator?: (principal: Principal) => boolean;
|
|
96
|
+
readonly allowModifiedArguments?: boolean;
|
|
97
|
+
readonly resumeAuthority?: RemoteResumeAuthority;
|
|
98
|
+
readonly resuming: Set<string>;
|
|
99
|
+
readonly active: Set<string>;
|
|
100
|
+
readonly limits: ResolvedRemoteLimits;
|
|
101
|
+
readonly hostUi?: HostUi;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface EventRouter {
|
|
105
|
+
readonly pendingOpens: Set<Promise<void>>;
|
|
106
|
+
readonly byPrincipal: Map<string, Set<(event: AgentEvent) => Promise<void>>>;
|
|
107
|
+
readonly operators: Set<(event: AgentEvent) => Promise<void>>;
|
|
108
|
+
subscriberCount: number;
|
|
109
|
+
stopPump?: () => void;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const eventRouters = new WeakMap<ServerState, EventRouter>();
|
|
113
|
+
|
|
114
|
+
function routerOf(state: ServerState): EventRouter {
|
|
115
|
+
let router = eventRouters.get(state);
|
|
116
|
+
if (!router) {
|
|
117
|
+
router = {
|
|
118
|
+
pendingOpens: new Set(),
|
|
119
|
+
byPrincipal: new Map(),
|
|
120
|
+
operators: new Set(),
|
|
121
|
+
subscriberCount: 0,
|
|
122
|
+
};
|
|
123
|
+
eventRouters.set(state, router);
|
|
124
|
+
}
|
|
125
|
+
return router;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createServerState(
|
|
129
|
+
agent: Agent,
|
|
130
|
+
options: Pick<ServeAgentOptions, "hostUi" | "limits" | "endpointId" | "resumeAuthority">,
|
|
131
|
+
): ServerState {
|
|
132
|
+
const full = options as Partial<ServeAgentOptions>;
|
|
133
|
+
const sessionOwners = new Map<string, string>();
|
|
134
|
+
const state: ServerState = {
|
|
135
|
+
agent,
|
|
136
|
+
resumeAuthority: options.resumeAuthority,
|
|
137
|
+
endpointId: options.endpointId ?? `remote-${crypto.randomUUID()}`,
|
|
138
|
+
sessions: new Map(),
|
|
139
|
+
sessionOwners,
|
|
140
|
+
...(full.ownershipFor ? { ownershipFor: full.ownershipFor } : {}),
|
|
141
|
+
...(full.operator ? { operator: full.operator } : {}),
|
|
142
|
+
...(full.allowModifiedArguments !== undefined ? { allowModifiedArguments: full.allowModifiedArguments } : {}),
|
|
143
|
+
resuming: new Set(),
|
|
144
|
+
active: new Set(),
|
|
145
|
+
limits: resolveRemoteLimits(options.limits),
|
|
146
|
+
...(options.hostUi ? { hostUi: options.hostUi } : {}),
|
|
147
|
+
};
|
|
148
|
+
if (options.hostUi) {
|
|
149
|
+
try {
|
|
150
|
+
bindRemoteHostUiOwner(options.hostUi, (sessionId) => state.sessionOwners.get(sessionId));
|
|
151
|
+
} catch {
|
|
152
|
+
// Validated when a connection negotiates hostUi.
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return state;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Serves an `Agent` to one client over `prism.remote/1`. */
|
|
159
|
+
export function serveAgent(agent: Agent, options: ServeAgentOptions): ServedAgent {
|
|
160
|
+
const state = createServerState(agent, options);
|
|
161
|
+
if ("kind" in options.transport && options.transport.kind !== "stdio")
|
|
162
|
+
return serveNetwork(state, options.transport, options.authenticate);
|
|
163
|
+
const transport = "kind" in options.transport ? stdioTransport({ ...options.transport, limits: options.limits }) : options.transport;
|
|
164
|
+
const connection = serveConnection(state, transport, {});
|
|
165
|
+
return { endpointId: state.endpointId, closed: connection.closed, close: () => connection.close() };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const textOf = (message: Message | undefined): string =>
|
|
169
|
+
message
|
|
170
|
+
? (message.content as readonly { type: string; text?: string }[])
|
|
171
|
+
.flatMap((block) => (block.type === "text" && block.text ? [block.text] : []))
|
|
172
|
+
.join("")
|
|
173
|
+
: "";
|
|
174
|
+
|
|
175
|
+
/** `run.settled` result, projected from the events of one run or resume. */
|
|
176
|
+
function projectResult(session: Session, runId: string, events: readonly AgentEvent[]): RunResult {
|
|
177
|
+
const messages = events.flatMap((event) => (event.type === "message.completed" ? [event.message] : []));
|
|
178
|
+
const final = [...messages].reverse().find((message) => message.role === "assistant");
|
|
179
|
+
let status: RunResult["status"] = "failed";
|
|
180
|
+
let extra: Partial<Mutable<RunResult>> = {};
|
|
181
|
+
for (const event of events) {
|
|
182
|
+
if (event.type === "run.completed") {
|
|
183
|
+
status = event.status;
|
|
184
|
+
extra = {
|
|
185
|
+
...(event.usage ? { usage: event.usage } : {}),
|
|
186
|
+
...(event.stopReason ? { stopReason: event.stopReason } : {}),
|
|
187
|
+
...(event.stopDetail ? { stopDetail: event.stopDetail } : {}),
|
|
188
|
+
};
|
|
189
|
+
} else if (event.type === "run.failed") {
|
|
190
|
+
status = /abort/i.test(`${event.error.code ?? ""} ${event.error.name ?? ""}`) ? "aborted" : "failed";
|
|
191
|
+
extra = { error: event.error, ...(event.limit ? { limit: event.limit } : {}) };
|
|
192
|
+
} else if (event.type === "run.suspended") {
|
|
193
|
+
status = "suspended";
|
|
194
|
+
extra = { pending: event.interruption.pendingDecisions ?? [] };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
sessionId: session.id,
|
|
199
|
+
runId,
|
|
200
|
+
status,
|
|
201
|
+
...(session.leafId !== undefined ? { leafId: session.leafId } : {}),
|
|
202
|
+
text: textOf(final),
|
|
203
|
+
content: final?.content ?? [],
|
|
204
|
+
...(final ? { message: final } : {}),
|
|
205
|
+
messages,
|
|
206
|
+
...extra,
|
|
207
|
+
} as RunResult;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
|
211
|
+
|
|
212
|
+
const TERMINAL = new Set(["run.completed", "run.failed", "run.suspended"]);
|
|
213
|
+
|
|
214
|
+
export interface ConnectionOptions {
|
|
215
|
+
/** The principal `authenticate` returned for this connection (Task 5). Carried on every run and resume. */
|
|
216
|
+
readonly principal?: Principal;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function mapOwnershipError(error: unknown): unknown {
|
|
220
|
+
if (isSessionNotFound(error) || error instanceof OwnershipScopeError) {
|
|
221
|
+
return new RemoteError("session_not_found", "session not found");
|
|
222
|
+
}
|
|
223
|
+
return error;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function subscribeAgentEvents(
|
|
227
|
+
state: ServerState,
|
|
228
|
+
principalKey: string,
|
|
229
|
+
isOperator: boolean,
|
|
230
|
+
send: (event: AgentEvent) => Promise<void>,
|
|
231
|
+
): () => void {
|
|
232
|
+
const router = routerOf(state);
|
|
233
|
+
let bucket = router.byPrincipal.get(principalKey);
|
|
234
|
+
if (!bucket) {
|
|
235
|
+
bucket = new Set();
|
|
236
|
+
router.byPrincipal.set(principalKey, bucket);
|
|
237
|
+
}
|
|
238
|
+
bucket.add(send);
|
|
239
|
+
if (isOperator) router.operators.add(send);
|
|
240
|
+
router.subscriberCount += 1;
|
|
241
|
+
if (router.subscriberCount === 1) {
|
|
242
|
+
const events = state.agent
|
|
243
|
+
.subscribe({ maxQueuedEvents: state.limits.maxQueuedEvents, overflow: "drop_oldest" })
|
|
244
|
+
[Symbol.asyncIterator]();
|
|
245
|
+
router.stopPump = () => void events.return?.();
|
|
246
|
+
void (async () => {
|
|
247
|
+
try {
|
|
248
|
+
for (let next = await events.next(); !next.done; next = await events.next()) {
|
|
249
|
+
const event = next.value;
|
|
250
|
+
const sessionId = "sessionId" in event && typeof event.sessionId === "string" ? event.sessionId : "";
|
|
251
|
+
if (sessionId !== "") {
|
|
252
|
+
let ownerKey = state.sessionOwners.get(sessionId);
|
|
253
|
+
while (ownerKey === undefined && router.pendingOpens.size > 0) {
|
|
254
|
+
await Promise.all([...router.pendingOpens]);
|
|
255
|
+
ownerKey = state.sessionOwners.get(sessionId);
|
|
256
|
+
}
|
|
257
|
+
const targets = ownerKey !== undefined ? router.byPrincipal.get(ownerKey) : router.operators;
|
|
258
|
+
if (targets) {
|
|
259
|
+
for (const fn of targets) await fn(event);
|
|
260
|
+
}
|
|
261
|
+
} else {
|
|
262
|
+
for (const fn of router.operators) await fn(event);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
} catch {
|
|
266
|
+
// Subscription ended.
|
|
267
|
+
}
|
|
268
|
+
})();
|
|
269
|
+
}
|
|
270
|
+
let stopped = false;
|
|
271
|
+
return () => {
|
|
272
|
+
if (stopped) return;
|
|
273
|
+
stopped = true;
|
|
274
|
+
const currentBucket = router.byPrincipal.get(principalKey);
|
|
275
|
+
if (currentBucket) {
|
|
276
|
+
currentBucket.delete(send);
|
|
277
|
+
if (currentBucket.size === 0) router.byPrincipal.delete(principalKey);
|
|
278
|
+
}
|
|
279
|
+
if (isOperator) router.operators.delete(send);
|
|
280
|
+
router.subscriberCount -= 1;
|
|
281
|
+
if (router.subscriberCount <= 0) {
|
|
282
|
+
router.subscriberCount = 0;
|
|
283
|
+
router.stopPump?.();
|
|
284
|
+
router.stopPump = undefined;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** One client connection to a served agent. */
|
|
290
|
+
export function serveConnection(state: ServerState, transport: RemoteTransport, options: ConnectionOptions): Dispatcher {
|
|
291
|
+
const { agent, limits } = state;
|
|
292
|
+
const principal = options.principal;
|
|
293
|
+
const principalKey = principalKeyOf(principal);
|
|
294
|
+
const isOperator = principal === undefined ? true : state.operator?.(principal) === true;
|
|
295
|
+
const ownership = principal && state.ownershipFor ? state.ownershipFor(principal) : undefined;
|
|
296
|
+
let detach: (() => void) | undefined;
|
|
297
|
+
let canHostUi = false;
|
|
298
|
+
const delivering = new Set<string>();
|
|
299
|
+
let dispatcher!: Dispatcher;
|
|
300
|
+
let stopAgentEvents: (() => void) | undefined;
|
|
301
|
+
|
|
302
|
+
const session = (id: string): Session => {
|
|
303
|
+
const ownerKey = state.sessionOwners.get(id);
|
|
304
|
+
if (ownerKey !== principalKey) throw new RemoteError("session_not_found", "session is not open");
|
|
305
|
+
const found = state.sessions.get(principalKey)?.get(id);
|
|
306
|
+
if (!found) throw new RemoteError("session_not_found", "session is not open");
|
|
307
|
+
return found;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const forward = async (
|
|
311
|
+
target: Session,
|
|
312
|
+
events: AsyncIterable<AgentEvent>,
|
|
313
|
+
started: (runId: string) => void,
|
|
314
|
+
failed: (error: unknown) => void,
|
|
315
|
+
) => {
|
|
316
|
+
const seen: AgentEvent[] = [];
|
|
317
|
+
let runId = "";
|
|
318
|
+
let terminal = false;
|
|
319
|
+
let gone = false;
|
|
320
|
+
try {
|
|
321
|
+
for await (const event of events) {
|
|
322
|
+
if ("runId" in event && typeof event.runId === "string" && runId === "") {
|
|
323
|
+
runId = event.runId;
|
|
324
|
+
started(runId);
|
|
325
|
+
}
|
|
326
|
+
if (TERMINAL.has(event.type)) terminal = true;
|
|
327
|
+
seen.push(event);
|
|
328
|
+
// A gone client must not abort the run: keep draining so it can suspend at its next ask.
|
|
329
|
+
if (!gone)
|
|
330
|
+
await dispatcher
|
|
331
|
+
.notify("run.event", { sessionId: target.id, runId, event: event as unknown as JsonValue })
|
|
332
|
+
.catch(() => void (gone = true));
|
|
333
|
+
}
|
|
334
|
+
if (gone) return;
|
|
335
|
+
if (runId === "") throw new RemoteError("internal_error", "run produced no events");
|
|
336
|
+
if (!terminal) {
|
|
337
|
+
// The kernel closed this subscriber: the client could not keep up.
|
|
338
|
+
await dispatcher.close("slow_consumer");
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
await dispatcher.notify("run.settled", {
|
|
342
|
+
sessionId: target.id,
|
|
343
|
+
runId,
|
|
344
|
+
result: projectResult(target, runId, seen) as unknown as JsonValue,
|
|
345
|
+
});
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (runId === "") failed(mapOwnershipError(error));
|
|
348
|
+
} finally {
|
|
349
|
+
state.active.delete(target.id);
|
|
350
|
+
state.resuming.delete(target.id);
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
/** Starts `events`, resolves with the run id once the run announced itself. Events keep streaming afterwards. */
|
|
355
|
+
const startRun = (target: Session, events: AsyncIterable<AgentEvent>): Promise<JsonObject> =>
|
|
356
|
+
new Promise((resolve, reject) => {
|
|
357
|
+
void forward(target, events, (runId) => resolve({ runId }), reject);
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
const resume = async (target: Session, decisions: readonly Decision[], runOptions: RunOptions): Promise<JsonObject> => {
|
|
361
|
+
if (state.resuming.has(target.id) || state.active.has(target.id))
|
|
362
|
+
throw new RemoteError("busy", "session already has a run or resume in progress");
|
|
363
|
+
state.resuming.add(target.id);
|
|
364
|
+
state.active.add(target.id);
|
|
365
|
+
try {
|
|
366
|
+
const options = { ...runOptions, maxQueuedEvents: limits.maxQueuedEvents };
|
|
367
|
+
const events = state.resumeAuthority
|
|
368
|
+
? state.resumeAuthority.resume(target.id, decisions, options)
|
|
369
|
+
: target.resume(decisions, options);
|
|
370
|
+
return await startRun(target, events);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
state.resuming.delete(target.id);
|
|
373
|
+
state.active.delete(target.id);
|
|
374
|
+
throw mapOwnershipError(error);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
async function deliverPending(target: Session): Promise<void> {
|
|
379
|
+
if (!canHostUi || delivering.has(target.id)) return;
|
|
380
|
+
if (state.resuming.has(target.id) || state.active.has(target.id)) return;
|
|
381
|
+
delivering.add(target.id);
|
|
382
|
+
try {
|
|
383
|
+
const pending: readonly PendingDecision[] = pendingDecisionsOf(await target.entries());
|
|
384
|
+
if (pending.length === 0) return;
|
|
385
|
+
const decisions: Decision[] = [];
|
|
386
|
+
for (const item of pending) {
|
|
387
|
+
const params: HostUiRequestParams = {
|
|
388
|
+
sessionId: target.id,
|
|
389
|
+
approvalId: item.approvalId,
|
|
390
|
+
request: requestForPending(target.id, item),
|
|
391
|
+
};
|
|
392
|
+
const answer = (await dispatcher.request("hostUi.request", params as unknown as JsonObject)) as unknown as HostUiResponse;
|
|
393
|
+
const decision = decisionFromAnswer(item, answer);
|
|
394
|
+
if (!decision) return;
|
|
395
|
+
decisions.push(decision);
|
|
396
|
+
}
|
|
397
|
+
await resume(target, decisions, {
|
|
398
|
+
...(principal ? { principal } : {}),
|
|
399
|
+
...(ownership ? { ownership } : {}),
|
|
400
|
+
});
|
|
401
|
+
} catch {
|
|
402
|
+
// A disconnect or a lost resume race leaves the suspension pending for the next client.
|
|
403
|
+
} finally {
|
|
404
|
+
delivering.delete(target.id);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const requests: Record<string, RemoteHandler> = {
|
|
409
|
+
async "sessions.open"(params) {
|
|
410
|
+
if (params.id !== undefined && typeof params.id !== "string") throw invalid("id must be a string");
|
|
411
|
+
if (params.create !== undefined && typeof params.create !== "boolean") throw invalid("create must be a boolean");
|
|
412
|
+
const parent = parseSessionParentLink(params.parent);
|
|
413
|
+
if (params.id !== undefined) {
|
|
414
|
+
const existingOwner = state.sessionOwners.get(params.id);
|
|
415
|
+
if (existingOwner !== undefined && existingOwner !== principalKey) {
|
|
416
|
+
throw new RemoteError("session_not_found", "session not found");
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const router = routerOf(state);
|
|
420
|
+
let finishOpen!: () => void;
|
|
421
|
+
const openGate = new Promise<void>((resolve) => {
|
|
422
|
+
finishOpen = resolve;
|
|
423
|
+
});
|
|
424
|
+
router.pendingOpens.add(openGate);
|
|
425
|
+
let current: Session;
|
|
426
|
+
try {
|
|
427
|
+
let opened: Session;
|
|
428
|
+
try {
|
|
429
|
+
opened = await agent.session({
|
|
430
|
+
...(params.id !== undefined ? { id: params.id as string } : {}),
|
|
431
|
+
...(params.create !== undefined ? { create: params.create as boolean } : {}),
|
|
432
|
+
...(parent ? { parent } : {}),
|
|
433
|
+
...(ownership ? { ownership } : {}),
|
|
434
|
+
});
|
|
435
|
+
} catch (error) {
|
|
436
|
+
throw mapOwnershipError(error);
|
|
437
|
+
}
|
|
438
|
+
const existingOwner = state.sessionOwners.get(opened.id);
|
|
439
|
+
if (existingOwner !== undefined && existingOwner !== principalKey) {
|
|
440
|
+
throw new RemoteError("session_not_found", "session not found");
|
|
441
|
+
}
|
|
442
|
+
state.sessionOwners.set(opened.id, principalKey);
|
|
443
|
+
let principalSessions = state.sessions.get(principalKey);
|
|
444
|
+
if (!principalSessions) {
|
|
445
|
+
principalSessions = new Map();
|
|
446
|
+
state.sessions.set(principalKey, principalSessions);
|
|
447
|
+
}
|
|
448
|
+
const known = principalSessions.get(opened.id);
|
|
449
|
+
current = known ?? opened;
|
|
450
|
+
principalSessions.set(current.id, current);
|
|
451
|
+
} finally {
|
|
452
|
+
router.pendingOpens.delete(openGate);
|
|
453
|
+
finishOpen();
|
|
454
|
+
}
|
|
455
|
+
void deliverPending(current);
|
|
456
|
+
return { sessionId: current.id, ...(current.leafId !== undefined ? { leafId: current.leafId } : {}) };
|
|
457
|
+
},
|
|
458
|
+
async "sessions.list"(params) {
|
|
459
|
+
const listQuery = parseSessionListQuery(params.query, ownership);
|
|
460
|
+
return (await agent.sessions.list(listQuery)) as unknown as JsonValue;
|
|
461
|
+
},
|
|
462
|
+
async "sessions.messages"(params) {
|
|
463
|
+
return { messages: (await session(str(params, "sessionId")).messages()) as unknown as JsonValue[] };
|
|
464
|
+
},
|
|
465
|
+
async "sessions.resume"(params) {
|
|
466
|
+
const target = session(str(params, "sessionId"));
|
|
467
|
+
const pending = typeof target.entries === "function" ? pendingDecisionsOf(await target.entries()) : [];
|
|
468
|
+
return resume(
|
|
469
|
+
target,
|
|
470
|
+
parseDecisions(params.decisions, {
|
|
471
|
+
allowModifiedArguments: state.allowModifiedArguments === true,
|
|
472
|
+
pending,
|
|
473
|
+
}),
|
|
474
|
+
parseRunOptions(params.options, principal, ownership),
|
|
475
|
+
);
|
|
476
|
+
},
|
|
477
|
+
async run(params) {
|
|
478
|
+
const target = session(str(params, "sessionId"));
|
|
479
|
+
const input = parseInput(params.input);
|
|
480
|
+
const runOptions = parseRunOptions(params.options, principal, ownership);
|
|
481
|
+
if (state.resuming.has(target.id) || state.active.has(target.id))
|
|
482
|
+
throw new RemoteError("busy", "session already has a run in progress");
|
|
483
|
+
state.active.add(target.id);
|
|
484
|
+
try {
|
|
485
|
+
return await startRun(target, target.stream(input, { ...runOptions, maxQueuedEvents: limits.maxQueuedEvents }));
|
|
486
|
+
} catch (error) {
|
|
487
|
+
state.active.delete(target.id);
|
|
488
|
+
throw mapOwnershipError(error);
|
|
489
|
+
}
|
|
490
|
+
},
|
|
491
|
+
steer(params) {
|
|
492
|
+
session(str(params, "sessionId")).steer(parseInput(params.input), parseSteerOptions(params.options));
|
|
493
|
+
return null;
|
|
494
|
+
},
|
|
495
|
+
abort(params) {
|
|
496
|
+
session(str(params, "sessionId")).abort(typeof params.reason === "string" ? params.reason : undefined);
|
|
497
|
+
return null;
|
|
498
|
+
},
|
|
499
|
+
"commands.list": () => agent.commands.list() as unknown as JsonValue,
|
|
500
|
+
async "commands.run"(params) {
|
|
501
|
+
if (params.args !== undefined && !isObject(params.args)) throw invalid("args must be an object");
|
|
502
|
+
const target = typeof params.sessionId === "string" ? session(params.sessionId) : undefined;
|
|
503
|
+
const result = await agent.commands.run(
|
|
504
|
+
str(params, "name"),
|
|
505
|
+
params.args as JsonObject | undefined,
|
|
506
|
+
target ? { session: target } : undefined,
|
|
507
|
+
);
|
|
508
|
+
return (result === undefined ? null : result) as JsonValue;
|
|
509
|
+
},
|
|
510
|
+
inspect: () => agent.inspect() as unknown as JsonValue,
|
|
511
|
+
async "models.list"() {
|
|
512
|
+
return (await agent.models.list()) as unknown as JsonValue;
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
const offered: RemoteCapabilities = { hostUi: true, "hostUi.secret": true, agentEvents: true };
|
|
517
|
+
dispatcher = createDispatcher({
|
|
518
|
+
transport,
|
|
519
|
+
role: "server",
|
|
520
|
+
capabilities: offered,
|
|
521
|
+
limits,
|
|
522
|
+
requests,
|
|
523
|
+
onInitialize: (_params, negotiated): Omit<InitializeResult, "protocol" | "capabilities"> => {
|
|
524
|
+
canHostUi = negotiated.hostUi === true;
|
|
525
|
+
if (negotiated.hostUi && state.hostUi) {
|
|
526
|
+
bindRemoteHostUiOwner(state.hostUi, (sessionId) => state.sessionOwners.get(sessionId));
|
|
527
|
+
detach = bindRemoteHostUi(state.hostUi, {
|
|
528
|
+
canSecret: negotiated["hostUi.secret"] === true,
|
|
529
|
+
principalKey,
|
|
530
|
+
operator: isOperator,
|
|
531
|
+
ask: async (params) => (await dispatcher.request("hostUi.request", params as unknown as JsonObject)) as unknown as HostUiResponse,
|
|
532
|
+
});
|
|
533
|
+
const owned = state.sessions.get(principalKey);
|
|
534
|
+
if (owned) {
|
|
535
|
+
for (const open of owned.values()) void deliverPending(open);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (negotiated.agentEvents) {
|
|
539
|
+
stopAgentEvents = subscribeAgentEvents(state, principalKey, isOperator, async (event) => {
|
|
540
|
+
await dispatcher.notify("agent.event", { event: event as unknown as JsonValue }).catch(() => undefined);
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
return {
|
|
544
|
+
endpointId: state.endpointId,
|
|
545
|
+
agent: {
|
|
546
|
+
id: agent.id,
|
|
547
|
+
name: agent.config.name ?? agent.id,
|
|
548
|
+
tools: agent.tools as unknown as JsonObject[],
|
|
549
|
+
skills: agent.skills as unknown as JsonObject[],
|
|
550
|
+
inspection: agent.inspect(),
|
|
551
|
+
},
|
|
552
|
+
};
|
|
553
|
+
},
|
|
554
|
+
});
|
|
555
|
+
void dispatcher.closed.then(() => {
|
|
556
|
+
detach?.();
|
|
557
|
+
stopAgentEvents?.();
|
|
558
|
+
});
|
|
559
|
+
return dispatcher;
|
|
560
|
+
}
|