@robota-sdk/agent-transport 3.0.0-beta.94 → 3.0.0-beta.96

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +2 -1
  3. package/dist/browser/client.d.ts +1 -1
  4. package/dist/browser/client.js +1 -1
  5. package/dist/browser/index.d.ts +34 -4
  6. package/dist/browser/index.d.ts.map +1 -1
  7. package/dist/browser/index.js +1 -1
  8. package/dist/browser/index.js.map +1 -1
  9. package/dist/browser/{observer-messages-Dnff2Tdb.d.ts → observer-messages-DoWb6RNv.d.ts} +23 -1
  10. package/dist/browser/observer-messages-DoWb6RNv.d.ts.map +1 -0
  11. package/dist/browser/observer-messages-UG77sTYK.js +2 -0
  12. package/dist/browser/observer-messages-UG77sTYK.js.map +1 -0
  13. package/dist/node/index.cjs +1 -1
  14. package/dist/node/index.d.cts +54 -3
  15. package/dist/node/index.d.cts.map +1 -1
  16. package/dist/node/index.d.ts +54 -3
  17. package/dist/node/index.d.ts.map +1 -1
  18. package/dist/node/index.js +1 -1
  19. package/dist/node/index.js.map +1 -1
  20. package/dist/node/node.cjs +1 -1
  21. package/dist/node/node.d.cts +19 -1
  22. package/dist/node/node.d.cts.map +1 -1
  23. package/dist/node/node.d.ts +19 -1
  24. package/dist/node/node.d.ts.map +1 -1
  25. package/dist/node/node.js +1 -1
  26. package/dist/node/node.js.map +1 -1
  27. package/package.json +8 -8
  28. package/src/__tests__/app-tool-messages.test.ts +463 -0
  29. package/src/__tests__/message-decoders.test.ts +101 -0
  30. package/src/__tests__/permission-summary.test.ts +18 -0
  31. package/src/__tests__/session-message-handler-observe.test.ts +6 -0
  32. package/src/__tests__/session-message-handler.test.ts +3 -2
  33. package/src/__tests__/session-resume-bridge.test.ts +66 -0
  34. package/src/__tests__/stdio-carrier.test.ts +85 -0
  35. package/src/app-tool-messages.ts +140 -0
  36. package/src/index.ts +7 -0
  37. package/src/message-decoders.ts +16 -0
  38. package/src/node/index.ts +2 -0
  39. package/src/node/stdio-carrier.ts +59 -0
  40. package/src/permission-summary.ts +18 -0
  41. package/src/protocol-session.ts +7 -1
  42. package/src/session-events.ts +1 -0
  43. package/src/session-message-handler.ts +37 -1
  44. package/src/session-resume-bridge.ts +15 -0
  45. package/src/wire-messages.ts +35 -0
  46. package/dist/browser/observer-messages-CEeisRaF.js +0 -2
  47. package/dist/browser/observer-messages-CEeisRaF.js.map +0 -1
  48. package/dist/browser/observer-messages-Dnff2Tdb.d.ts.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,155 @@
1
1
  # @robota-sdk/agent-transport
2
2
 
3
+ ## 3.0.0-beta.96
4
+ ### Patch Changes
5
+
6
+ - @robota-sdk/agent-core@3.0.0-beta.96
7
+ - @robota-sdk/agent-interface-analytics@3.0.0-beta.96
8
+ - @robota-sdk/agent-interface-command@3.0.0-beta.96
9
+ - @robota-sdk/agent-interface-execution@3.0.0-beta.96
10
+ - @robota-sdk/agent-interface-session@3.0.0-beta.96
11
+ - @robota-sdk/agent-interface-session-mobility@3.0.0-beta.96
12
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.96
13
+
14
+ ## 3.0.0-beta.95
15
+ ### Major Changes
16
+
17
+ - 0ba247b: A tool result can now carry a view its source declared (an MCP app), and a surface can invoke a
18
+ runtime tool through the session's permission gate with a prompt. This is the contract and wiring
19
+ layer: nothing produces a view yet, and the GUI does not yet host one.
20
+
21
+ - `agent-core` — `IToolResult.view` carries an `IToolAppView` (source, `ui://` resource, mime type,
22
+ HTML, structured content, callable tools, the call's input). `view` is now a typed key of
23
+ `IToolResult`, so an extension that already used a `view` key with another type must rename it.
24
+ The view is display data: it never enters model context or the size that decides a spill, and a
25
+ result replaced by its reference keeps it.
26
+ - `agent-interface-session` — `invokeRuntimeTool` takes `permissionInteraction` (`'interactive'` or
27
+ the default `'deny'`), a `driverId` (a host that attributes prompts names it as the requester) and
28
+ an `executionId` its events carry. A finished model call's `tool_end` names its view with
29
+ `IToolState.appView` (`viewId`, source, resource), and the new
30
+ `ISessionToolAppViews.readToolAppView(viewId)` reads the document. A permission handler may take
31
+ `{ signal }`, and aborting it withdraws the prompt.
32
+ - `agent-session` — a direct call asks a person only when its caller says so, and the handler is
33
+ given the call's own signal; the tool end event carries the view, never in the logged result data.
34
+ - `agent-framework` — the view of a model's call is kept under a `viewId` the session mints, in a
35
+ bounded per-session store (16 views, 4 MiB each, 16 MiB in all, measured on the whole serialized
36
+ view), and read on demand, so the document never rides `tool_end` to every surface, never enters
37
+ the recorded history, and a repeated provider tool-call id cannot overwrite another turn's view.
38
+ A malformed view is dropped. A direct call keeps and names no view, recognised by the id it was
39
+ started with. A submission or agent wakeup that arrives while a direct call holds the session is
40
+ queued behind it, as during a turn, instead of refused. A direct call acting for a driver
41
+ attributes its permission prompt and tool events to that driver, and aborting its signal withdraws
42
+ an open prompt from every surface.
43
+ - `agent-transport` — a driving connection sends `call-app-tool` (answered by `app_tool_result`) and
44
+ `read-app-view` (answered by `app_view`). A call names its view and reaches only the tools that
45
+ view's source declared; a call or read that decodes but cannot be served answers `protocol_error`
46
+ echoing the `requestId`, while an observer's attempt is refused like any non-read. A call still
47
+ waiting on its prompt is cancelled when its connection goes away (for the resume bridge, when the
48
+ bridge is disposed). `maxFrameBytes` bounds an app answer to what a carrier's channel carries;
49
+ the WebRTC carrier uses a history page's worth. `IProtocolSession` now includes the runtime-tool
50
+ and app-view roles.
51
+ - `agent-ui-web` — the two new server messages are recorded as not rendered until the app-view host
52
+ consumes them.
53
+
54
+ An implementation of `IInteractiveSession` or `IProtocolSession` outside this repository must add
55
+ `readToolAppView` (and, for `IProtocolSession`, `listRuntimeTools` and `invokeRuntimeTool`); the
56
+ members are required so a host cannot silently lack them.
57
+
58
+ ### Minor Changes
59
+
60
+ - c967c57: `robota acp` runs the agent as an Agent Client Protocol (v1) agent over stdio, so an editor that launches it (Zed, JetBrains and other ACP clients) can create a session, send prompts, see streamed replies and tool calls, approve or reject permission requests, and cancel a turn. Workspace trust, permission rules and the sandbox behave as in the terminal: the editor answers prompts and widens nothing. A folder that is not trusted yet is refused at `session/new` with the `trust` command to run, a working directory other than the one the agent was started in and any editor-supplied MCP servers or extra roots are refused, and a prompt that starts with `/` runs that command.
61
+
62
+ New package `@robota-sdk/agent-transport-acp` provides `createAcpTransport`, the ACP `ITransportAdapter` the command uses.
63
+
64
+ `@robota-sdk/agent-transport/node` gains `attachStdioCarrier`, the process-input bridge and close observation a stdio protocol carrier shares. `agent-transport-mcp` now uses it for its stdio carrier; its behavior is unchanged.
65
+
66
+ ### Patch Changes
67
+
68
+ - 60f3965: **`robota mcp serve --ask-client` puts a caller's permission and ask prompts to the calling MCP client through elicitation instead of failing them.**
69
+
70
+ `@robota-sdk/agent-transport-mcp`: `createMcpTransport`, `createMcpHttpHost`,
71
+ `createMcpRemoteHttpHost` and `createAgentMcpServer` take `askClient`. Off by default, every prompt
72
+ is a tool error as before. On, and when the client declared form-mode elicitation, a permission or
73
+ ask prompt raised by that client's own call is put to it: a permission offers allow once or deny
74
+ only, never a remembered grant; an ask becomes a form (choice, multiple choice, free text); a masked
75
+ ask is never sent; deny, decline, cancel, a client error or an answer naming nothing offered keeps
76
+ today's outcome. stdio asks during the call. The HTTP hosts keep no session state, so they ask only
77
+ a client on the 2026-07-28 revision, through input-required rounds whose `requestState` is a
78
+ single-use random token naming one parked call; a 2025-era HTTP client keeps the tool error.
79
+ A call listens for prompts only while its own work drives the session, so a submission waiting
80
+ in the queue never holds another caller's prompt that it cannot answer.
81
+ Breaking for hand-written sessions: `IMcpTransportSession` now also requires `ISessionEvents`
82
+ (`on`/`off`), `ISessionPromptResolution` (`resolvePermission`/`resolveAsk`) and
83
+ `ISessionDriverAttribution` (`getActiveDriverId`), which `InteractiveSession` and the published
84
+ test double already implement.
85
+
86
+ `@robota-sdk/agent-interface-session` / `@robota-sdk/agent-session` / `@robota-sdk/agent-framework`:
87
+ `ISessionRuntimeTools.invokeRuntimeTool` (and `Session.invokeRuntimeTool`) accept
88
+ `options.permissionInteraction` and `options.driverId`. A direct call still denies a decision that
89
+ would need a person, and finds no one to ask a question, unless its caller passes
90
+ `permissionInteraction: 'interactive'`; then it asks the session's permission handler and its
91
+ tools get the session's ask port. `InteractiveSession` makes `driverId` the active driver while
92
+ the direct call runs, so a prompt the call raises carries it as `requesterDriverId`. With
93
+ `askClient` on, an MCP call runs under its own `mcp:<n>` driver id; a submission made that way is
94
+ attributed to it rather than to the owner.
95
+
96
+ `@robota-sdk/agent-transport`: exports `permissionSummaryArgument`, the argument a person recognises
97
+ a tool call by (`filePath` for the built-in file tools), for every transport that puts a permission
98
+ request to a person in its own wire form.
99
+
100
+ `@robota-sdk/agent-cli`: `mcp serve --ask-client` turns this on for whichever carrier the run serves.
101
+ - 04a6de4: **Reasoning text a provider streams now reaches the editor as an ACP `agent_thought_chunk`, through a new `thinking_delta` session event.**
102
+
103
+ `IChatOptions.onThinkingDelta`, `IRunOptions.onThinkingDelta` and `IResumeExecutionOptions.onThinkingDelta`
104
+ (typed `TThinkingDeltaCallback`) carry reasoning text from a provider through the run, and the session
105
+ options (`ISessionOptions.onThinkingDelta`, `ICreateSessionOptions.onThinkingDelta`) hand it to the
106
+ session's owner. `InteractiveSession` emits it as `thinking_delta(delta)`, beside `text_delta`. The
107
+ text is never part of the reply: it is not appended to the conversation, not streamed through
108
+ `onTextDelta`, and the core adds no record of its own for it (no text-delta log entry, no
109
+ `provider_stream_raw_delta`); a provider's own native payload capture and response metadata keep
110
+ what the provider sent, as before. A reasoning delta counts as provider activity for the idle
111
+ timeout whether or not anyone listens to it, so a model that is only thinking is not cut off. The
112
+ existing `thinking(isThinking)` event is unchanged and remains the busy indicator. Where a provider
113
+ sends no reasoning text, nothing is emitted and nothing new is switched on.
114
+
115
+ `@robota-sdk/agent-interface-session` is a major change because a new session event name makes an
116
+ exhaustive map over the event names stop compiling until it classifies the event.
117
+
118
+ `@robota-sdk/agent-transport-acp` sends each non-empty `thinking_delta` to the editor as an
119
+ `agent_thought_chunk`, in order with the message chunks, so `robota acp` shows the model's reasoning
120
+ in the editor. A turn that streamed only thoughts still shows its result text, because only reply
121
+ text marks a turn as streamed. The WebSocket wire, the HTTP stream, headless stream-json, `query()`
122
+ and the terminal UI do not carry the new event in this change (`@robota-sdk/agent-transport` and
123
+ `@robota-sdk/agent-ui-terminal` classify it as non-surface). A forked skill and an in-process subagent
124
+ pass their reply text up but not their reasoning.
125
+
126
+ Two providers already receive reasoning text and now report it. `@robota-sdk/agent-provider-openai`
127
+ passes `response.reasoning_summary_text.delta` events of a streamed Responses call to
128
+ `onThinkingDelta`; the API sends them only when the provider profile asks for a reasoning summary, and
129
+ no request option changed; a summary streamed in several parts, and the summary of a later reasoning
130
+ item, each start on a new paragraph (`\n\n`) so the parts do not run together.
131
+ `@robota-sdk/agent-provider-openai-compatible` reports the text of Gemma's thought channel, which the
132
+ provider already removed from the reply, as it streams across chunk boundaries, with each later
133
+ channel of one reply on a new paragraph; the reply text is unchanged. No other provider reports
134
+ reasoning, and Anthropic thinking is not enabled. A model fallback chain still moves to the next model when only reasoning had streamed.
135
+
136
+ The scripted test provider (`@robota-sdk/agent-core/testing`) accepts an optional `thinking` string on
137
+ a turn and delivers it through `onThinkingDelta` before the turn's text; the scripted session harness
138
+ collects `thinking_delta` and now keeps a scripted tool-call turn's `usage`, which it used to drop.
139
+ - Updated dependencies [60f3965]
140
+ - Updated dependencies [115e104]
141
+ - Updated dependencies [04719a9]
142
+ - Updated dependencies [04a6de4]
143
+ - Updated dependencies [0ba247b]
144
+ - Updated dependencies [02053ec]
145
+ - @robota-sdk/agent-interface-session@3.0.0-beta.95
146
+ - @robota-sdk/agent-core@3.0.0-beta.95
147
+ - @robota-sdk/agent-interface-session-mobility@3.0.0-beta.95
148
+ - @robota-sdk/agent-interface-command@3.0.0-beta.95
149
+ - @robota-sdk/agent-interface-execution@3.0.0-beta.95
150
+ - @robota-sdk/agent-interface-transport@3.0.0-beta.95
151
+ - @robota-sdk/agent-interface-analytics@3.0.0-beta.95
152
+
3
153
  ## 3.0.0-beta.94
4
154
  ### Patch Changes
5
155
 
package/README.md CHANGED
@@ -97,6 +97,7 @@ Each carrier is its own package, so an application installs only the protocol de
97
97
  | WebSocket | [`@robota-sdk/agent-transport-ws`](../agent-transport-ws/README.md) | Serves a session on a loopback WebSocket server (token-authenticated by default) |
98
98
  | HTTP | [`@robota-sdk/agent-transport-http`](../agent-transport-http/README.md) | Hono routes for submitting prompts and reading session state over HTTP + SSE |
99
99
  | MCP | [`@robota-sdk/agent-transport-mcp`](../agent-transport-mcp/README.md) | Exposes a session as an MCP server over stdio or Streamable HTTP |
100
+ | ACP | [`@robota-sdk/agent-transport-acp`](../agent-transport-acp/README.md) | Runs a session as an Agent Client Protocol agent over stdio, for editors |
100
101
  | WebRTC | [`@robota-sdk/agent-transport-webrtc`](../agent-transport-webrtc/README.md) | Carries a session peer-to-peer over a pairing-gated data channel (Node host side) |
101
102
 
102
103
  The headless (non-interactive text / JSON / stream-JSON) transport and `TransportRegistry`, which
@@ -110,7 +111,7 @@ starts and stops a set of transports together, live in `@robota-sdk/agent-framew
110
111
  `-transport` (contract packages)
111
112
  - `jose` (access-token signature verification under `./node`)
112
113
 
113
- The protocol libraries (`ws`, `hono`, `@modelcontextprotocol/sdk`, `node-datachannel`) are
114
+ The protocol libraries (`ws`, `hono`, `@modelcontextprotocol/server`, `node-datachannel`) are
114
115
  dependencies of the individual transport packages, not of this one.
115
116
 
116
117
  ## Documentation
@@ -1,2 +1,2 @@
1
- import { a as decodeFrame, c as IWireHistoryEntry, d as TServerMessage, f as TWireExecutionResult, i as decodeClientMessage, l as TClientMessage, n as MAX_INBOUND_FRAME_BYTES, o as decodeServerMessage, r as TMessageDecodeResult, t as isObserverMessageType, u as TSeqServerMessage } from "./observer-messages-Dnff2Tdb.js";
1
+ import { a as decodeFrame, c as IWireHistoryEntry, d as TServerMessage, f as TWireExecutionResult, i as decodeClientMessage, l as TClientMessage, n as MAX_INBOUND_FRAME_BYTES, o as decodeServerMessage, r as TMessageDecodeResult, t as isObserverMessageType, u as TSeqServerMessage } from "./observer-messages-DoWb6RNv.js";
2
2
  export { type IWireHistoryEntry, MAX_INBOUND_FRAME_BYTES, type TClientMessage, type TMessageDecodeResult, type TSeqServerMessage, type TServerMessage, type TWireExecutionResult, decodeClientMessage, decodeFrame, decodeServerMessage, isObserverMessageType };
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"./observer-messages-CEeisRaF.js";export{n as MAX_INBOUND_FRAME_BYTES,r as decodeClientMessage,t as decodeFrame,e as decodeServerMessage,i as isObserverMessageType};
1
+ import{a as e,i as t,n,r,t as i}from"./observer-messages-UG77sTYK.js";export{n as MAX_INBOUND_FRAME_BYTES,r as decodeClientMessage,t as decodeFrame,e as decodeServerMessage,i as isObserverMessageType};
@@ -1,5 +1,6 @@
1
- import { a as decodeFrame, c as IWireHistoryEntry, d as TServerMessage, f as TWireExecutionResult, i as decodeClientMessage, l as TClientMessage, n as MAX_INBOUND_FRAME_BYTES, o as decodeServerMessage, r as TMessageDecodeResult, s as IWireAgentDefinitionSummary, t as isObserverMessageType, u as TSeqServerMessage } from "./observer-messages-Dnff2Tdb.js";
2
- import { ISessionAgentJobs, ISessionBackgroundGroups, ISessionBackgroundTasks, ISessionCommands, ISessionConversationRead, ISessionDirectory, ISessionDriverAttribution, ISessionEvents, ISessionExecutionDetail, ISessionExecutionState, ISessionExecutionWorkspace, ISessionProjectRead, ISessionPromptResolution, ISessionSelfPacedLoopControl, ISessionStatusRead, ISessionTurnControl, ISessionTurnSubmission, ISettingsSnapshot, TDriverId, TSettingsPatch } from "@robota-sdk/agent-interface-session";
1
+ import { a as decodeFrame, c as IWireHistoryEntry, d as TServerMessage, f as TWireExecutionResult, i as decodeClientMessage, l as TClientMessage, n as MAX_INBOUND_FRAME_BYTES, o as decodeServerMessage, r as TMessageDecodeResult, s as IWireAgentDefinitionSummary, t as isObserverMessageType, u as TSeqServerMessage } from "./observer-messages-DoWb6RNv.js";
2
+ import { ISessionAgentJobs, ISessionBackgroundGroups, ISessionBackgroundTasks, ISessionCommands, ISessionConversationRead, ISessionDirectory, ISessionDriverAttribution, ISessionEvents, ISessionExecutionDetail, ISessionExecutionState, ISessionExecutionWorkspace, ISessionProjectRead, ISessionPromptResolution, ISessionRuntimeTools, ISessionSelfPacedLoopControl, ISessionStatusRead, ISessionToolAppViews, ISessionTurnControl, ISessionTurnSubmission, ISettingsSnapshot, TDriverId, TSettingsPatch } from "@robota-sdk/agent-interface-session";
3
+ import { TToolArgs } from "@robota-sdk/agent-core";
3
4
  import { IPersonalUsageReport, IPersonalUsageRequest, IUsageBySourceReport, TUsageSurface } from "@robota-sdk/agent-interface-analytics";
4
5
  import { TCommandSurfaceLocality } from "@robota-sdk/agent-interface-command";
5
6
  import { IBinaryFrame, IChannelEventFrame, TChannelReceiveResult } from "@robota-sdk/agent-interface-transport";
@@ -95,7 +96,7 @@ declare function createOutboundDelivery(send: (message: TServerMessage) => void,
95
96
  //#endregion
96
97
  //#region src/protocol-session.d.ts
97
98
  /** Session roles required by the shared WebSocket/WebRTC protocol. */
98
- interface IProtocolSession extends ISessionTurnSubmission, ISessionTurnControl, ISessionCommands, ISessionStatusRead, ISessionEvents, ISessionPromptResolution, ISessionConversationRead, ISessionExecutionState, ISessionDriverAttribution, ISessionBackgroundTasks, ISessionBackgroundGroups, ISessionExecutionWorkspace, ISessionExecutionDetail, ISessionSelfPacedLoopControl, ISessionAgentJobs {}
99
+ interface IProtocolSession extends ISessionTurnSubmission, ISessionTurnControl, ISessionCommands, ISessionStatusRead, ISessionEvents, ISessionPromptResolution, ISessionConversationRead, ISessionExecutionState, ISessionDriverAttribution, ISessionBackgroundTasks, ISessionBackgroundGroups, ISessionExecutionWorkspace, ISessionExecutionDetail, ISessionSelfPacedLoopControl, ISessionAgentJobs, ISessionRuntimeTools, ISessionToolAppViews {}
99
100
  /**
100
101
  * #3282 §4c: a protocol session that ALSO answers the Project panel's reads. `Partial` (not a fourth
101
102
  * mandatory role on {@link IProtocolSession} itself) deliberately: every existing test double and
@@ -153,6 +154,7 @@ declare const PROTOCOL_SESSION_EVENT_CLASSIFICATION: {
153
154
  readonly tool_start: "forwarded";
154
155
  readonly tool_end: "forwarded";
155
156
  readonly thinking: "forwarded";
157
+ readonly thinking_delta: "non-surface";
156
158
  readonly complete: "forwarded";
157
159
  readonly error: "forwarded";
158
160
  readonly context_update: "forwarded";
@@ -224,6 +226,13 @@ interface ISessionMessageHandlerOptions {
224
226
  * command that runs code from outside the session (installing a plugin) can refuse a remote device.
225
227
  */
226
228
  commandSurfaceLocality?: TCommandSurfaceLocality;
229
+ /**
230
+ * The most bytes one frame answering an app tool call or view read may take, for a carrier whose
231
+ * channel carries less than the inbound limit (a WebRTC data channel). An answer over it is
232
+ * replaced by a `protocol_error` before it reaches any buffer. Defaults to the inbound limit less
233
+ * a margin for a carrier that stamps frames afterwards.
234
+ */
235
+ maxFrameBytes?: number;
227
236
  }
228
237
  /**
229
238
  * Create a carrier-neutral message handler for an IProtocolSession.
@@ -249,6 +258,14 @@ declare function createSessionMessageHandler(options: ISessionMessageHandlerOpti
249
258
  cleanup: () => void;
250
259
  };
251
260
  //#endregion
261
+ //#region src/session-query-messages.d.ts
262
+ /**
263
+ * #3189: the most serialized history one `history` frame carries. Well under the tightest outbound
264
+ * budget (an attached terminal's, 1 MiB), so a client reading page after page is never mistaken for
265
+ * one that stopped reading.
266
+ */
267
+ declare const HISTORY_PAGE_MAX_BYTES: number;
268
+ //#endregion
252
269
  //#region src/resume-buffer.d.ts
253
270
  /** One retained frame: its sequence number and the message. */
254
271
  interface IBufferedFrame {
@@ -355,6 +372,8 @@ interface ISessionResumeBridgeOptions {
355
372
  readonly storedSessionUsageReporter?: IUsageQueryReporters['storedSessionUsageReporter'];
356
373
  /** #3282 §4 part b-2: this bridge is the reconnectable WebRTC path, so it is always `'remote'`. */
357
374
  readonly commandSurfaceLocality?: TCommandSurfaceLocality;
375
+ /** See {@link ISessionMessageHandlerOptions.maxFrameBytes}: the channel's limit, not the inbound one. */
376
+ readonly maxFrameBytes?: number;
358
377
  }
359
378
  declare class SessionResumeBridge {
360
379
  private readonly session;
@@ -363,6 +382,13 @@ declare class SessionResumeBridge {
363
382
  private readonly reporters;
364
383
  private readonly surface?;
365
384
  private readonly commandSurfaceLocality?;
385
+ private readonly maxFrameBytes?;
386
+ /**
387
+ * Ends with the bridge, not with a channel: a channel drop keeps the session reconnectable, so work
388
+ * started for a hosted app view (a call waiting on its prompt) survives it and is cancelled only when
389
+ * the host gives up on the session.
390
+ */
391
+ private readonly lifetime;
366
392
  private readonly unsubscribe;
367
393
  private onDeliveryError?;
368
394
  /**
@@ -499,6 +525,10 @@ declare function acknowledgePeerMessage(ledger: IPeerMessageLedger, originSessio
499
525
  /** Forget one origin — used when a peer disconnects and its sequence space is no longer meaningful. */
500
526
  declare function forgetPeerOrigin(ledger: IPeerMessageLedger, originSessionId: string): void;
501
527
  //#endregion
528
+ //#region src/permission-summary.d.ts
529
+ /** The call's identifying argument, or `undefined` when it has none worth showing. */
530
+ declare function permissionSummaryArgument(toolArgs: TToolArgs): string | undefined;
531
+ //#endregion
502
532
  //#region src/handoff-chunking.d.ts
503
533
  /**
504
534
  * One piece of a payload in flight.
@@ -590,5 +620,5 @@ declare class HandoffChunkAssembler {
590
620
  */
591
621
  declare function chunkCountFor(integrity: IHandoffIntegrity, maxChunkBytes?: number): number;
592
622
  //#endregion
593
- export { ATTACHED_SURFACE_MAX_PENDING_BYTES, CHANNEL_FRAME_MAGIC, CHANNEL_FRAME_VERSION, DEFAULT_MAX_CHUNK_BYTES, DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_PENDING_MS, HandoffChunkAssembler, type IAttachOptions, type IBufferedFrame, type IChunkResult, type IHandoffChunk, type IPeerMessageLedger, type IPeerMessageRejection, type IPeerMessageVerdict, type IPendingStallClock, type IProtocolSession, type IResumeBufferOptions, type ISessionMessageHandlerOptions, type ISessionResumeBridgeOptions, type ISettingsReporter, type IWireAgentDefinitionSummary, type IWireHistoryEntry, MAX_INBOUND_FRAME_BYTES, PROTOCOL_SESSION_EVENT_CLASSIFICATION, ResumeBuffer, SessionResumeBridge, type TChunkOutcome, type TChunkRejection, type TClientMessage, type TDeliveryErrorHandler, type TMessageDecodeResult, type TOutboundDeliver, type TProtocolSessionEventClassification, type TResumeSink, type TResumeTail, type TSeqServerMessage, type TServerMessage, type TSessionSurfaceRole, type TSettingsUpdateOutcome, type TWireExecutionResult, acknowledgePeerMessage, admitPeerMessage, chunkCountFor, chunkHandoffPayload, createOutboundDelivery, createPeerMessageLedger, createPendingStallClock, createSessionMessageHandler, decodeChannelFrame, decodeClientMessage, decodeFrame, decodeServerMessage, encodeBinaryFrame, encodeChannelEventFrame, forgetPeerOrigin, handleSettingsMessage, isChannelFrame, isObserverMessageType, isOverPendingBudget, isSettingsMessage };
623
+ export { ATTACHED_SURFACE_MAX_PENDING_BYTES, CHANNEL_FRAME_MAGIC, CHANNEL_FRAME_VERSION, DEFAULT_MAX_CHUNK_BYTES, DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_PENDING_MS, HISTORY_PAGE_MAX_BYTES, HandoffChunkAssembler, type IAttachOptions, type IBufferedFrame, type IChunkResult, type IHandoffChunk, type IPeerMessageLedger, type IPeerMessageRejection, type IPeerMessageVerdict, type IPendingStallClock, type IProtocolSession, type IResumeBufferOptions, type ISessionMessageHandlerOptions, type ISessionResumeBridgeOptions, type ISettingsReporter, type IWireAgentDefinitionSummary, type IWireHistoryEntry, MAX_INBOUND_FRAME_BYTES, PROTOCOL_SESSION_EVENT_CLASSIFICATION, ResumeBuffer, SessionResumeBridge, type TChunkOutcome, type TChunkRejection, type TClientMessage, type TDeliveryErrorHandler, type TMessageDecodeResult, type TOutboundDeliver, type TProtocolSessionEventClassification, type TResumeSink, type TResumeTail, type TSeqServerMessage, type TServerMessage, type TSessionSurfaceRole, type TSettingsUpdateOutcome, type TWireExecutionResult, acknowledgePeerMessage, admitPeerMessage, chunkCountFor, chunkHandoffPayload, createOutboundDelivery, createPeerMessageLedger, createPendingStallClock, createSessionMessageHandler, decodeChannelFrame, decodeClientMessage, decodeFrame, decodeServerMessage, encodeBinaryFrame, encodeChannelEventFrame, forgetPeerOrigin, handleSettingsMessage, isChannelFrame, isObserverMessageType, isOverPendingBudget, isSettingsMessage, permissionSummaryArgument };
594
624
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/outbound-delivery.ts","../../src/protocol-session.ts","../../src/settings-messages.ts","../../src/usage-messages.ts","../../src/session-events.ts","../../src/session-message-handler.ts","../../src/resume-buffer.ts","../../src/channel-frames.ts","../../src/session-resume-bridge.ts","../../src/peer-message-ledger.ts","../../src/handoff-chunking.ts"],"mappings":"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"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/outbound-delivery.ts","../../src/protocol-session.ts","../../src/settings-messages.ts","../../src/usage-messages.ts","../../src/session-events.ts","../../src/session-message-handler.ts","../../src/session-query-messages.ts","../../src/resume-buffer.ts","../../src/channel-frames.ts","../../src/session-resume-bridge.ts","../../src/peer-message-ledger.ts","../../src/permission-summary.ts","../../src/handoff-chunking.ts"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import{a as e,i as t,n,r,t as i}from"./observer-messages-CEeisRaF.js";import{isSessionChangeRefusal as a,isSessionDeleteRefusal as o}from"@robota-sdk/agent-interface-session";import{AuthenticationError as s,ModelNotAvailableError as c,NetworkError as l,ProviderError as u,RateLimitError as d}from"@robota-sdk/agent-core";function f(e,t,n){if(n.type===`get-background-tasks`){t({type:`background_tasks`,tasks:e.listBackgroundTasks(n.filter)});return}if(n.type===`get-background-task`){m(e,t,n);return}if(n.type===`get-background-job-groups`){t({type:`background_job_groups`,groups:e.listBackgroundJobGroups()});return}if(n.type===`get-background-job-group`){g(e,t,n);return}if(n.type===`wait-background-job-group`){_(e,t,n);return}h(e,t,n)}function p(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}if(n.type===`cancel-background-task`){y(t,`cancel`,n.taskId,e.cancelBackgroundTask(n.taskId,n.reason));return}if(n.type===`close-background-task`){y(t,`close`,n.taskId,e.closeBackgroundTask(n.taskId));return}v(e,t,n)}function m(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}t({type:`background_task`,taskId:n.taskId,task:e.getBackgroundTask(n.taskId)??null})}function h(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}e.readBackgroundTaskLog(n.taskId,n.cursor).then(e=>t({type:`background_task_log`,taskId:n.taskId,page:e}),e=>t({type:`protocol_error`,message:e.message}))}function g(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}t({type:`background_job_group`,groupId:n.groupId,group:e.getBackgroundJobGroup(n.groupId)??null})}function _(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}e.waitBackgroundJobGroup(n.groupId).then(e=>t({type:`background_job_group`,groupId:n.groupId,group:e}),e=>t({type:`protocol_error`,message:e.message}))}function v(e,t,n){if(!n.input){t({type:`protocol_error`,message:`input is required`});return}y(t,`send`,n.taskId,e.sendBackgroundTask(n.taskId,n.input))}function y(e,t,n,r){r.then(()=>e({type:`background_task_control_result`,action:t,taskId:n,success:!0}),r=>e({type:`background_task_control_result`,action:t,taskId:n,success:!1,message:r.message}))}function b(e){return e.type===`stop-waiting-loop`}function x(e,t,n){let{requestId:r}=n;e.stopWaitingSelfPacedLoop().then(e=>t({type:`waiting_loop_stop`,requestId:r,outcome:e}),e=>t({type:`waiting_loop_stop`,requestId:r,outcome:{kind:`failed`,message:S(e)}}))}function S(e){return e instanceof Error?e.message:String(e)}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function w(e){return typeof e==`string`&&e.length>0?e:void 0}function T(e){if(!(new TextEncoder().encode(e).byteLength>4194304))try{let t=JSON.parse(e);if(!C(t))return;let n=w(t.requestId);if(!n)return;if(t.type===`get-personal-usage-report`)return{type:`personal`,requestId:n};let r=w(t.sessionId);return t.type===`get-stored-session-usage-report`&&r?{type:`stored-session`,requestId:n,sessionId:r}:void 0}catch{return}}function E(e,t,n,r){return n.type===`get-personal-usage-report`?(A(t,n,r.personalUsageReporter),!0):n.type===`get-stored-session-usage-report`?(O(t,n,r.storedSessionUsageReporter),!0):n.type===`get-usage-report`?(D(e,t,r.usageReporter),!0):!1}function D(e,t,n){if(!n){t({type:`protocol_error`,message:`Per-session usage reporting is not available on this host.`});return}try{Promise.resolve(n(e)).then(e=>t({type:`usage_report`,report:e}),e=>t({type:`protocol_error`,message:M(e)}))}catch(e){t({type:`protocol_error`,message:M(e instanceof Error?e:String(e))})}}function O(e,t,n){if(!n){k(e,t,`not_available`,`Stored-session usage reporting is not available on this host.`);return}try{Promise.resolve(n(t.sessionId)).then(n=>e({type:`stored_session_usage_report`,requestId:t.requestId,sessionId:t.sessionId,report:n}),n=>k(e,t,`report_failed`,M(n)))}catch(n){k(e,t,`report_failed`,M(n instanceof Error?n:String(n)))}}function k(e,t,n,r){e({type:`stored_session_usage_report_error`,requestId:t.requestId,sessionId:t.sessionId,code:n,message:r})}function A(e,t,n){if(!n){j(e,t.requestId,`not_available`,`Personal usage reporting is not available on this host.`);return}try{Promise.resolve(n({period:t.period,timezone:t.timezone})).then(n=>e({type:`personal_usage_report`,requestId:t.requestId,report:n}),n=>j(e,t.requestId,`report_failed`,M(n)))}catch(n){j(e,t.requestId,`report_failed`,M(n instanceof Error?n:String(n)))}}function j(e,t,n,r){e({type:`personal_usage_report_error`,requestId:t,code:n,message:r})}function M(e){return e instanceof Error?e.message:String(e)}function ee(e,n){let i=t(e,r);if(i.ok)return i.message;let a=T(e);return a?.type===`personal`?(n({type:`personal_usage_report_error`,requestId:a.requestId,code:`report_failed`,message:`Invalid personal usage report request.`}),null):a?.type===`stored-session`?(n({type:`stored_session_usage_report_error`,requestId:a.requestId,sessionId:a.sessionId,code:`report_failed`,message:`Invalid stored-session usage report request.`}),null):(n({type:`protocol_error`,message:i.reason}),null)}function te(e){return e.type===`project-status`||e.type===`project-diff`||e.type===`project-memory`}function N(e,t){e({type:`protocol_error`,message:`This host does not support the Project panel.`,requestId:t})}function ne(e,t,n){let{requestId:r}=n;if(n.type===`project-status`){if(!e.readProjectStatus)return N(t,r);e.readProjectStatus().then(e=>t({type:`project_status`,requestId:r,result:e}),e=>t({type:`project_status`,requestId:r,result:{kind:`failed`,message:e instanceof Error?e.message:String(e)}}))}else if(n.type===`project-diff`){if(!e.readProjectDiff)return N(t,r);e.readProjectDiff(n.path).then(e=>t({type:`project_diff`,requestId:r,result:e}),e=>t({type:`project_diff`,requestId:r,result:{kind:`failed`,message:e instanceof Error?e.message:String(e)}}))}else{if(!e.readProjectMemory)return N(t,r);e.readProjectMemory().then(e=>t({type:`project_memory`,requestId:r,result:e}),e=>t({type:`project_memory`,requestId:r,result:{kind:`unavailable`,message:e instanceof Error?e.message:String(e)}}))}}function re(e){return e.type===`list-sessions`||e.type===`new-session`||e.type===`switch-session`}function ie(e){return e.type===`rename-session`}function ae(e){return e.type===`delete-session`}function oe(e,t,n){if(t.type===`list-sessions`){se(e,t.requestId,n);return}let r=t.requestId===void 0?{}:{requestId:t.requestId};if(!n){e({type:`session_change_failed`,code:`not_available`,message:`Sessions cannot be switched on this host.`,...r});return}Promise.resolve().then(()=>t.type===`new-session`?n.newSession():n.switchSession(t.sessionId)).catch(t=>e({type:`session_change_failed`,code:a(t)?t.code:`failed`,message:P(t),...r}))}function se(e,t,n){if(!n){e({type:`sessions_error`,requestId:t,code:`not_available`,message:`Session listing is not available on this host.`});return}try{e({type:`sessions`,requestId:t,listing:n.listSessions()})}catch(n){e({type:`sessions_error`,requestId:t,code:`list_failed`,message:P(n instanceof Error?n:String(n))})}}function P(e){return e instanceof Error?e.message:String(e)}function ce(e,t,n){if(!n){e({type:`session_rename_failed`,requestId:t.requestId,message:`Sessions cannot be renamed on this host.`});return}n.renameSession(t.sessionId,t.name).then(()=>e({type:`session_renamed_in_list`,requestId:t.requestId,sessionId:t.sessionId,name:t.name}),n=>e({type:`session_rename_failed`,requestId:t.requestId,message:P(n)}))}function le(e,t,n){if(!n){e({type:`session_delete_failed`,requestId:t.requestId,code:`not_available`,message:`Sessions cannot be deleted on this host.`});return}n.deleteSession(t.sessionId).then(()=>e({type:`session_deleted`,requestId:t.requestId,sessionId:t.sessionId}),n=>e({type:`session_delete_failed`,requestId:t.requestId,code:o(n)?n.code:`failed`,message:P(n)}))}const F=new WeakMap;function ue(e){let t=F.get(e);t===void 0&&(t={frames:new Map,holders:0},F.set(e,t));let n=t;n.holders+=1;let r=!1;return{record:e=>{r||n.frames.set(e.event.id,e)},forget:e=>{n.frames.delete(e)},clear:()=>{n.frames.clear()},release:()=>{r||(r=!0,--n.holders,n.holders===0&&F.get(e)===n&&F.delete(e))}}}function de(e){return[...F.get(e)?.frames.values()??[]]}function fe(e){let t=[],n=new Set,r=[e];for(let e=0;e<=8&&r.length>0;e++){let e=[];for(let i of r)if(!(i==null||n.has(i))&&(n.add(i),t.push(i),typeof i==`object`)){let t=i;e.push(t.originalError,t.cause)}r=e}return t}function pe(e){let t;for(let n of fe(e)){if(n instanceof s)return{code:`auth`,...n.provider!==void 0&&{provider:n.provider}};if(n instanceof d)return{code:`rate_limit`,...n.provider!==void 0&&{provider:n.provider},...n.retryAfter!==void 0&&{retryAfterSeconds:n.retryAfter}};if(n instanceof c)return{code:`model_unavailable`,provider:n.provider,...n.model!==void 0&&{model:n.model}};if(n instanceof l)return{code:`network`,...n.provider!==void 0&&{provider:n.provider}};t===void 0&&n instanceof u&&(t={code:`provider`,provider:n.provider})}return t??{}}const me={text_delta:`forwarded`,tool_start:`forwarded`,tool_end:`forwarded`,thinking:`forwarded`,complete:`forwarded`,error:`forwarded`,context_update:`forwarded`,compact:`forwarded`,interrupted:`forwarded`,skill_activation:`forwarded`,background_task_event:`forwarded`,background_job_group_event:`forwarded`,execution_workspace_event:`forwarded`,user_message:`forwarded`,turn_source:`forwarded`,context_file_refreshed:`forwarded`,memory_event:`forwarded`,goal_event:`non-surface`,plan_event:`forwarded`,branch_event:`forwarded`,permission_request:`forwarded`,ask_request:`forwarded`,prompt_resolved:`forwarded`,ui_intent:`requester-routed`,session_renamed:`forwarded`,history_cleared:`forwarded`,session_switched:`forwarded`,status_changed:`forwarded`};function he(e,t,n={}){let r=()=>{let t=e.getActiveDriverId();return t?{driverId:t}:{}},i=e=>t({type:`user_message`,content:e,...r()}),a=e=>t({type:`text_delta`,delta:e,...r()}),o=e=>t({type:`tool_start`,state:e,...r()}),s=e=>t({type:`tool_end`,state:e,...r()}),c=e=>t({type:`thinking`,isThinking:e,...r()}),l=e=>t({type:`complete`,result:I(e),...r()}),u=e=>t({type:`interrupted`,result:I(e),...r()}),d=e=>t({type:`error`,message:e.message,...pe(e),...r()}),f=e=>t({type:`background_task_event`,event:e}),p=e=>t({type:`background_job_group_event`,event:e}),m=e=>t({type:`execution_workspace_event`,snapshot:e.snapshot}),h=e=>t({type:`plan_event`,event:e}),g=e=>t({type:`context_file_refreshed`,event:e}),_=e=>t({type:`branch_event`,event:e}),v=n.receivePrompts??!0,y=v?ue(e):void 0,b=e=>{let n={type:`permission_request`,event:e};y?.record(n),t(n)},x=e=>{let n={type:`ask_request`,event:e};y?.record(n),t(n)},S=e=>{y?.forget(e.id),t({type:`prompt_resolved`,event:e})},C=e=>{(e.requesterDriverId===void 0||e.requesterDriverId===n.getSurfaceDriverId?.())&&t({type:`ui_intent`,event:e})},w=e=>t({type:`session_renamed`,event:e}),T=()=>t({type:`history_cleared`}),E=e=>{y?.clear(),t({type:`session_switched`,event:e})},D=e=>t({type:`context`,state:e}),O=()=>t({type:`history_changed`}),k=e=>t({type:`turn_source`,source:e}),A=e=>t({type:`session_status`,status:e});return e.on(`user_message`,i),e.on(`text_delta`,a),e.on(`tool_start`,o),e.on(`tool_end`,s),e.on(`thinking`,c),e.on(`complete`,l),e.on(`interrupted`,u),e.on(`error`,d),e.on(`background_task_event`,f),e.on(`background_job_group_event`,p),e.on(`execution_workspace_event`,m),e.on(`plan_event`,h),e.on(`context_file_refreshed`,g),e.on(`branch_event`,_),v&&(e.on(`permission_request`,b),e.on(`ask_request`,x)),e.on(`prompt_resolved`,S),e.on(`ui_intent`,C),e.on(`session_renamed`,w),e.on(`history_cleared`,T),e.on(`session_switched`,E),e.on(`context_update`,D),e.on(`compact`,O),e.on(`skill_activation`,O),e.on(`memory_event`,O),e.on(`turn_source`,k),e.on(`status_changed`,A),()=>{e.off(`user_message`,i),e.off(`text_delta`,a),e.off(`tool_start`,o),e.off(`tool_end`,s),e.off(`thinking`,c),e.off(`complete`,l),e.off(`interrupted`,u),e.off(`error`,d),e.off(`background_task_event`,f),e.off(`background_job_group_event`,p),e.off(`execution_workspace_event`,m),e.off(`plan_event`,h),e.off(`context_file_refreshed`,g),e.off(`branch_event`,_),v&&(e.off(`permission_request`,b),e.off(`ask_request`,x)),e.off(`prompt_resolved`,S),e.off(`ui_intent`,C),e.off(`session_renamed`,w),e.off(`history_cleared`,T),e.off(`session_switched`,E),e.off(`context_update`,D),e.off(`compact`,O),e.off(`skill_activation`,O),e.off(`memory_event`,O),e.off(`turn_source`,k),e.off(`status_changed`,A),y?.release()}}function I(e){let{history:t,...n}=e;return n}const ge=new TextEncoder;function _e(e){return e.type===`get-messages`||e.type===`get-history`||e.type===`get-prompts`||e.type===`get-context`||e.type===`get-commands`||e.type===`get-status`||e.type===`list-models`||e.type===`get-agent-definitions`||e.type===`get-executing`||e.type===`get-pending`||e.type===`get-execution-workspace`||e.type===`read-execution-detail`}function ve(e,t,n){if(n.type===`get-messages`)t({type:`messages`,messages:e.getMessages(),display:e.getMessagesDisplay()});else if(n.type===`get-history`)t(be(e,n.fromIndex??0));else if(n.type===`get-prompts`)for(let n of de(e))t(n);else if(n.type===`get-context`)t({type:`context`,state:e.getContextState()});else if(n.type===`get-commands`)t({type:`commands`,commands:e.listCommands(),skills:e.listSkills()});else if(n.type===`get-status`)t({type:`session_status`,status:e.getStatusSnapshot()});else if(n.type===`list-models`){let r=e.listModels();t({type:`model_list`,requestId:n.requestId,...r})}else n.type===`get-agent-definitions`?t({type:`agent_definitions`,requestId:n.requestId,agents:e.listAgentDefinitions(),current:e.getDefaultAgentType()}):n.type===`get-executing`?t({type:`executing`,executing:e.isExecuting()}):n.type===`get-execution-workspace`?t({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()}):n.type===`read-execution-detail`?ye(e,t,n):t(L(e))}function ye(e,t,n){let{requestId:r}=n;e.readExecutionWorkspaceDetail(n.entryId,n.cursor).then(e=>t({type:`execution_detail`,requestId:r,page:e}),e=>t({type:`execution_detail_error`,requestId:r,message:e instanceof Error?e.message:String(e)}))}function L(e){return{type:`pending`,pending:e.getPendingPrompt(),pendingCount:e.getPendingCount()}}function be(e,t){let n=e.getFullHistory(),r=n.length,i=Math.min(t,r),a=[],o=0;for(let e=i;e<r;e+=1){let t=xe(n[e]),r=ge.encode(JSON.stringify(t)).byteLength;if(a.length>0&&o+r>262144)break;a.push(t),o+=r}return{type:`history`,startIndex:i,total:r,entries:a}}function xe(e){return{...e,timestamp:Se(e.timestamp)}}function Se(e){return typeof e==`string`?e:e.toISOString()}function R(e){return e.type===`get-settings`||e.type===`update-settings`}function Ce(e,t,n,r,i){if(!r){z(t,n.requestId,`not_available`,`Settings are not available on this host.`);return}try{if(n.type===`get-settings`){Promise.resolve(r.getSettings(e,i)).then(e=>t({type:`settings`,requestId:n.requestId,settings:e}),e=>z(t,n.requestId,`update_failed`,B(e)));return}Promise.resolve(r.updateSettings(e,n.patch,i)).then(e=>{e.ok?t({type:`settings`,requestId:n.requestId,settings:e.settings}):z(t,n.requestId,e.code,e.message)},e=>z(t,n.requestId,`update_failed`,B(e)))}catch(e){z(t,n.requestId,`update_failed`,B(e instanceof Error?e:String(e)))}}function z(e,t,n,r){e({type:`settings_error`,requestId:t,code:n,message:r})}function B(e){return e instanceof Error?e.message:String(e)}function we(e){let t=e.role??`drive`,n=he(e.session,e.deliver,{getSurfaceDriverId:()=>e.driverId,receivePrompts:t===`drive`});return{onMessage:Te(e.session,e.deliver,e.driverId,{personalUsageReporter:e.personalUsageReporter,usageReporter:e.usageReporter,storedSessionUsageReporter:e.storedSessionUsageReporter},e.surface,t,e.sessionDirectory,e.settingsReporter,e.commandSurfaceLocality),cleanup:n}}function Te(e,t,n,r=Ee,a,o=`drive`,s,c,l){return u=>{let d=ee(u,t);if(d){if(o===`observe`&&!i(d.type)){t({type:`protocol_error`,message:`Not permitted for an observer: ${d.type}`});return}V(e,t,d,n,r,a,s,c,l)}}}const Ee={personalUsageReporter:void 0,usageReporter:void 0,storedSessionUsageReporter:void 0};function V(e,t,n,r,i=Ee,a,o,s,c){if(E(e,t,n,i))return;if(re(n)){oe(t,n,o);return}if(R(n)){Ce(e,t,n,s,c);return}if(ie(n)){ce(t,n,o);return}if(ae(n)){le(t,n,o);return}if(De(n)){Me(e,t,n,r,a,c);return}if(b(n)){x(e,t,n);return}if(_e(n)){ve(e,t,n);return}if(te(n)){ne(e,t,n);return}if(Oe(n)){f(e,t,n);return}if(ke(n)){p(e,t,n);return}if(Ae(n)){je(e,n,r);return}let l=n.type;t({type:`protocol_error`,message:`Unknown message type: ${l}`})}function De(e){return e.type===`submit`||e.type===`command`||e.type===`abort`||e.type===`cancel-queue`}function Oe(e){return e.type===`get-background-tasks`||e.type===`get-background-task`||e.type===`read-background-task-log`||e.type===`get-background-job-groups`||e.type===`get-background-job-group`||e.type===`wait-background-job-group`}function ke(e){return e.type===`cancel-background-task`||e.type===`close-background-task`||e.type===`send-background-task`}function Ae(e){return e.type===`permission-response`||e.type===`ask-response`}function je(e,t,n){t.type===`permission-response`?e.resolvePermission(t.id,t.result,n):e.resolveAsk(t.id,t.response,n)}function Me(e,t,n,r,i,a){if(n.type===`submit`){if(typeof n.prompt!=`string`||n.prompt.length===0){t({type:`protocol_error`,message:`prompt must be a non-empty string`});return}let a={...r?{driverId:r}:{},...i?{surface:i}:{}};e.submit(n.prompt,void 0,void 0,Object.keys(a).length>0?a:void 0).then(()=>t(L(e)),e=>t({type:`protocol_error`,message:e.message}))}else if(n.type===`command`){let i=n.requestId===void 0?{}:{requestId:n.requestId};if(!n.name){t({type:`protocol_error`,message:`name is required`,...i});return}e.executeCommand(n.name,n.args??``,`remote`,r,a).then(e=>{t({type:`command_result`,name:n.name,message:e?.message??`Unknown command: ${n.name}`,success:e?.success??!1,data:e?.data,...i})},e=>{t({type:`protocol_error`,message:e.message,...i})})}else n.type===`abort`?e.abort():e.cancelQueue()}const H=1024*1024,U=8*H,Ne=H;function W(e,t=U){return e!==void 0&&e>t}const G=120*1e3;function K(e=G,t=Date.now){let n;return{maxPendingMs:e,observe(r){if(r===void 0)return;if(r===0){n=void 0;return}let i=t();n??=i;let a=i-n;return a>e?a:void 0}}}function q(e,t,n,r=U,i=K()){let a=!1,o=t=>{if(a)return;let o=n?.();if(W(o,r)){a=!0,s(Error(`outbound backpressure budget exceeded: ${o} byte(s) pending, limit ${r}. The peer has accepted frames it is not reading.`),t.type);return}let c=i.observe(o);if(c!==void 0){a=!0,s(Error(`outbound drain budget exceeded: ${o} byte(s) pending for ${c} ms, limit ${i.maxPendingMs} ms. The peer is reading too slowly to ever drain what it accepted.`),t.type);return}try{e(t)}catch(e){a=!0,s(e instanceof Error?e:Error(String(e)),t.type)}};function s(e,n){try{t(e,n)}catch{}}return Object.assign(o,{pendingBytes:()=>n?.()})}var J=class{frames=[];sizes=[];nextSeq=1;bytes=0;maxFrames;maxBytes;sizeOf;constructor(e={}){this.maxFrames=e.maxFrames??512,this.maxBytes=e.maxBytes??4194304,this.sizeOf=e.sizeOf??(e=>JSON.stringify(e).length)}append(e){let t=this.nextSeq;this.nextSeq+=1;let n=this.sizeOf(e);return this.frames.push({seq:t,message:e}),this.sizes.push(n),this.bytes+=n,this.evict(),t}ackThrough(e){let t=0;for(;t<this.frames.length&&this.frames[t].seq<=e;)t+=1;this.removeOldest(t)}tailAfter(e){return this.frames.length===0?e>=this.nextSeq-1?{kind:`tail`,frames:[]}:{kind:`overrun`}:e<this.frames[0].seq-1?{kind:`overrun`}:{kind:`tail`,frames:this.frames.filter(t=>t.seq>e)}}get lastSeq(){return this.nextSeq-1}get size(){return this.frames.length}evict(){let e=0,t=this.bytes;for(;this.frames.length-e>this.maxFrames||t>this.maxBytes&&this.frames.length-e>1;)t-=this.sizes[e],e+=1;this.removeOldest(e)}removeOldest(e){if(!(e<=0)){for(let t=0;t<e;t+=1)this.bytes-=this.sizes[t]??0;this.frames.splice(0,e),this.sizes.splice(0,e),this.frames.length===0&&(this.bytes=0)}}};const Y=new TextEncoder,X=new TextDecoder,Z=Y.encode(`RBF`),Pe=1,Fe=4294967295;function Q(e,t){let n=Y.encode(e);if(n.byteLength===0||n.byteLength>255)throw Error(`channel name must be 1..255 UTF-8 bytes (got ${n.byteLength})`);if(!Number.isInteger(t)||t<0||t>Fe)throw Error(`seq must be an integer in 0..${Fe} (got ${t})`);return n}function Ie(e,t,n,r){e.set(Z,0),e[3]=1,e[4]=t,e[5]=n.byteLength,e.set(n,6);let i=6+n.byteLength;return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(i,r,!1),i+4}function Le(e){let t=Q(e.channel,e.seq),n=new Uint8Array(6+t.byteLength+4+e.payload.byteLength),r=Ie(n,1,t,e.seq);return n.set(e.payload,r),n}function Re(e){let t=Q(e.channel,e.seq),n=Y.encode(JSON.stringify({event:e.event,payload:e.payload})),r=new Uint8Array(6+t.byteLength+4+n.byteLength),i=Ie(r,2,t,e.seq);return r.set(n,i),r}function ze(e){return e.byteLength<Z.length?!1:Z.every((t,n)=>e[n]===t)}function Be(e){let t=X.decode(e),n;try{n=JSON.parse(t)}catch{return{ok:!1,error:`channel frame: malformed JSON body`}}if(typeof n!=`object`||!n||Array.isArray(n))return{ok:!1,error:`channel frame: event body must be a JSON object`};let{event:r,payload:i}=n;return typeof r!=`string`||r.length===0?{ok:!1,error:"channel frame: event body is missing a non-empty `event` name"}:{ok:!0,event:r,payload:i??null}}function Ve(e){if(!ze(e))return{ok:!1,error:`channel frame: bad magic (not a channel frame)`};if(e.byteLength<6)return{ok:!1,error:`channel frame: truncated header`};if(e[3]!==1)return{ok:!1,error:`channel frame: unsupported version ${String(e[3])}`};let t=e[4],n=e[5]??0;if(n===0)return{ok:!1,error:`channel frame: empty channel name`};let r=6+n,i=r+4;if(e.byteLength<i)return{ok:!1,error:`channel frame: truncated (header longer than the frame)`};let a=X.decode(e.subarray(6,r)),o=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(r,!1),s=e.subarray(i);if(t===1)return{ok:!0,frame:{kind:`binary`,channel:a,seq:o,payload:Uint8Array.from(s)}};if(t===2){let e=Be(s);return e.ok?{ok:!0,frame:{kind:`event`,channel:a,seq:o,event:e.event,payload:e.payload}}:{ok:!1,error:e.error}}return{ok:!1,error:`channel frame: unknown kind ${String(t)}`}}var He=class{session;buffer;driverId;reporters;surface;commandSurfaceLocality;unsubscribe;onDeliveryError;outbound;emitBoundary;disposed=!1;holding=!1;constructor(e){this.session=e.session,this.buffer=new J(e.buffer),this.driverId=e.driverId,this.surface=e.surface,this.commandSurfaceLocality=e.commandSurfaceLocality,this.reporters={personalUsageReporter:e.personalUsageReporter,usageReporter:e.usageReporter,storedSessionUsageReporter:e.storedSessionUsageReporter},this.emitBoundary=q(e=>this.emit(e),(e,t)=>this.reportDeliveryError(e,t)),this.unsubscribe=he(this.session,this.emitBoundary,{getSurfaceDriverId:()=>this.driverId})}attach(e,t){this.disposed||(this.onDeliveryError=t.onDeliveryError,this.outbound=q(t=>e(JSON.stringify(t)),(e,t)=>this.reportDeliveryError(e,t),t.pendingBytes),this.holding=t.awaitResume===!0)}detach(){this.outbound=void 0,this.onDeliveryError=void 0}setDriverId(e){this.driverId=e}onClientMessage(e){if(this.disposed)return;let t=ee(e,this.emitBoundary);if(t){if(t.type===`resume`){this.replay(t.lastSeq);return}if(t.type===`ack`){this.buffer.ackThrough(t.seq);return}V(this.session,this.emitBoundary,t,this.driverId,this.reporters,this.surface,void 0,void 0,this.commandSurfaceLocality)}}dispose(){this.disposed||(this.disposed=!0,this.detach(),this.unsubscribe())}get lastSeq(){return this.buffer.lastSeq}emit(e){if(this.disposed)return;let t=this.buffer.append(e);this.holding||this.deliverFrame({...e,seq:t})}replay(e){let t=this.buffer.tailAfter(e);if(t.kind===`overrun`){this.deliverFrame({type:`resume_gap`}),this.holding=!1;return}for(let e of t.frames)this.deliverFrame({...e.message,seq:e.seq});this.holding=!1}deliverFrame(e){this.outbound?.(e)}reportDeliveryError(e,t){let n=this.onDeliveryError;this.detach();try{n?.(e,t)}catch{}}};function Ue(){return{origins:new Map}}function We(e,t,n){let r=t.origin.sessionId,i=e.origins.get(r);i===void 0&&(i={highestSequence:0,delivered:new Set,issued:new Map},e.origins.set(r,i));let a=i.issued.get(t.id);if(a!==void 0)return{ack:{...a,state:`duplicate`},deliver:!1};if(n!==void 0){let e={id:t.id,sequence:t.sequence,state:n.state,reason:n.reason};return i.issued.set(t.id,e),{ack:e,deliver:!1}}if(i.delivered.has(t.sequence)){let e={id:t.id,sequence:t.sequence,state:`refused`,reason:`sequence ${t.sequence} was already delivered by this origin under a different message id. A retry must repeat its id; a new id on a delivered sequence cannot be ordered against what the receiver already has.`};return i.issued.set(t.id,e),{ack:e,deliver:!1}}let o=i.highestSequence+1,s=t.sequence>o?o:void 0,c={id:t.id,sequence:t.sequence,state:`delivered`};return i.issued.set(t.id,c),i.delivered.add(t.sequence),i.highestSequence=Math.max(i.highestSequence,t.sequence),s===void 0?{ack:c,deliver:!0}:{ack:c,deliver:!0,gapBefore:s}}function Ge(e,t,n){let r=e.origins.get(t),i=r?.issued.get(n);if(r===void 0||i===void 0||i.state!==`delivered`)return;let a={...i,state:`acknowledged`};return r.issued.set(n,a),a}function Ke(e,t){e.origins.delete(t)}const $=16*1024,qe=32768;function Je(e){let t=``;for(let n=0;n<e.length;n+=qe)t+=String.fromCharCode(...e.subarray(n,n+qe));return btoa(t)}function Ye(e){let t;try{t=atob(e)}catch{return}let n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function Xe(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Ze(e,t,n=$){if(!Number.isInteger(n)||n<1)throw Error(`handoff chunking: maxChunkBytes must be a positive integer, got ${n}. A zero or negative budget produces an infinite sequence of empty chunks, which presents as a hang rather than as the configuration error it is.`);let r=new TextEncoder().encode(t),i=Math.max(1,Math.ceil(r.byteLength/n)),a=[];for(let t=0;t<i;t+=1){let o=r.subarray(t*n,(t+1)*n);a.push({handoffId:e,index:t,total:i,data:Je(o)})}return a}var Qe=class{handoffId;chunks=new Map;declaredTotal;constructor(e){this.handoffId=e}get received(){return this.chunks.size}get expected(){return this.declaredTotal}accept(e){let t=e=>({outcome:`refused`,rejection:e,received:this.chunks.size,...this.declaredTotal===void 0?{}:{expected:this.declaredTotal}});if(e.handoffId!==this.handoffId)return t(`wrong-handoff`);if(!Number.isInteger(e.total)||e.total<1||this.declaredTotal!==void 0&&e.total!==this.declaredTotal)return t(`inconsistent-total`);if(!Number.isInteger(e.index)||e.index<0||e.index>=e.total)return t(`out-of-range`);let n=Ye(e.data);if(n===void 0||Je(n)!==e.data)return t(`undecodable`);this.declaredTotal=e.total;let r=this.chunks.get(e.index);return r===void 0?(this.chunks.set(e.index,n),this.chunks.size<e.total?{outcome:`accepted`,received:this.chunks.size,expected:e.total}:{outcome:`complete`,serialized:this.reassemble(e.total),received:this.chunks.size,expected:e.total}):Xe(r,n)?{outcome:`duplicate`,received:this.chunks.size,expected:e.total}:t(`inconsistent-total`)}missing(){if(this.declaredTotal===void 0)return[];let e=[];for(let t=0;t<this.declaredTotal;t+=1)this.chunks.has(t)||e.push(t);return e}discard(){this.chunks.clear(),this.declaredTotal=void 0}reassemble(e){let t=[];for(let n=0;n<e;n+=1){let r=this.chunks.get(n);if(r===void 0)throw Error(`handoff chunking: chunk ${n} of ${e} is missing at reassembly.`);t.push(r)}let n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),r=0;for(let e of t)n.set(e,r),r+=e.length;return new TextDecoder(`utf-8`,{ignoreBOM:!0}).decode(n)}};function $e(e,t=$){return Math.max(1,Math.ceil(e.byteLength/t))}export{Ne as ATTACHED_SURFACE_MAX_PENDING_BYTES,Z as CHANNEL_FRAME_MAGIC,Pe as CHANNEL_FRAME_VERSION,$ as DEFAULT_MAX_CHUNK_BYTES,U as DEFAULT_MAX_PENDING_BYTES,G as DEFAULT_MAX_PENDING_MS,Qe as HandoffChunkAssembler,n as MAX_INBOUND_FRAME_BYTES,me as PROTOCOL_SESSION_EVENT_CLASSIFICATION,J as ResumeBuffer,He as SessionResumeBridge,Ge as acknowledgePeerMessage,We as admitPeerMessage,$e as chunkCountFor,Ze as chunkHandoffPayload,q as createOutboundDelivery,Ue as createPeerMessageLedger,K as createPendingStallClock,we as createSessionMessageHandler,Ve as decodeChannelFrame,r as decodeClientMessage,t as decodeFrame,e as decodeServerMessage,Le as encodeBinaryFrame,Re as encodeChannelEventFrame,Ke as forgetPeerOrigin,Ce as handleSettingsMessage,ze as isChannelFrame,i as isObserverMessageType,W as isOverPendingBudget,R as isSettingsMessage};
1
+ import{a as e,i as t,n,r,t as i}from"./observer-messages-UG77sTYK.js";import{isSessionChangeRefusal as a,isSessionDeleteRefusal as o}from"@robota-sdk/agent-interface-session";import{AuthenticationError as s,ModelNotAvailableError as c,NetworkError as l,ProviderError as u,RateLimitError as d}from"@robota-sdk/agent-core";function f(e){return e.type===`call-app-tool`}function p(e){return e.type===`read-app-view`}function m(e){return e?.maxFrameBytes??4193280}function h(e,t){return new TextEncoder().encode(JSON.stringify(e)).byteLength<=t}function g(e,t,n,r,i){let{requestId:a}=n,o=e.readToolAppView(n.viewId);if(o===void 0){t({type:`protocol_error`,message:`This app view is no longer available.`,requestId:a});return}if(!Object.values(o.callableTools).includes(n.name)){t({type:`protocol_error`,message:`This tool is not available to this app view.`,requestId:a});return}let{signal:s}=i??{},c=m(i);e.invokeRuntimeTool(n.name,n.arguments,{permissionInteraction:`interactive`,...r?{driverId:r}:{},...s?{signal:s}:{}}).then(e=>{if(s?.aborted)return;let n={type:`app_tool_result`,requestId:a,success:e.success,...e.result===void 0?{}:{data:e.result},...e.parts===void 0?{}:{parts:e.parts},...e.error===void 0?{}:{error:e.error}};h(n,c)?t(n):t({type:`protocol_error`,message:`This app tool result is too large to send.`,requestId:a})},e=>{s?.aborted||t({type:`protocol_error`,message:e instanceof Error?e.message:String(e),requestId:a})})}function _(e,t,n,r){let{requestId:i}=n,a=e.readToolAppView(n.viewId);if(a===void 0){t({type:`protocol_error`,message:`This app view is no longer available.`,requestId:i});return}let o={type:`app_view`,requestId:i,view:a};if(!h(o,m(r))){t({type:`protocol_error`,message:`This app view is too large to send.`,requestId:i});return}t(o)}function v(e,t,n){if(n.type===`get-background-tasks`){t({type:`background_tasks`,tasks:e.listBackgroundTasks(n.filter)});return}if(n.type===`get-background-task`){b(e,t,n);return}if(n.type===`get-background-job-groups`){t({type:`background_job_groups`,groups:e.listBackgroundJobGroups()});return}if(n.type===`get-background-job-group`){S(e,t,n);return}if(n.type===`wait-background-job-group`){C(e,t,n);return}x(e,t,n)}function y(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}if(n.type===`cancel-background-task`){T(t,`cancel`,n.taskId,e.cancelBackgroundTask(n.taskId,n.reason));return}if(n.type===`close-background-task`){T(t,`close`,n.taskId,e.closeBackgroundTask(n.taskId));return}w(e,t,n)}function b(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}t({type:`background_task`,taskId:n.taskId,task:e.getBackgroundTask(n.taskId)??null})}function x(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}e.readBackgroundTaskLog(n.taskId,n.cursor).then(e=>t({type:`background_task_log`,taskId:n.taskId,page:e}),e=>t({type:`protocol_error`,message:e.message}))}function S(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}t({type:`background_job_group`,groupId:n.groupId,group:e.getBackgroundJobGroup(n.groupId)??null})}function C(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}e.waitBackgroundJobGroup(n.groupId).then(e=>t({type:`background_job_group`,groupId:n.groupId,group:e}),e=>t({type:`protocol_error`,message:e.message}))}function w(e,t,n){if(!n.input){t({type:`protocol_error`,message:`input is required`});return}T(t,`send`,n.taskId,e.sendBackgroundTask(n.taskId,n.input))}function T(e,t,n,r){r.then(()=>e({type:`background_task_control_result`,action:t,taskId:n,success:!0}),r=>e({type:`background_task_control_result`,action:t,taskId:n,success:!1,message:r.message}))}function E(e){return e.type===`stop-waiting-loop`}function D(e,t,n){let{requestId:r}=n;e.stopWaitingSelfPacedLoop().then(e=>t({type:`waiting_loop_stop`,requestId:r,outcome:e}),e=>t({type:`waiting_loop_stop`,requestId:r,outcome:{kind:`failed`,message:O(e)}}))}function O(e){return e instanceof Error?e.message:String(e)}function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e){return typeof e==`string`&&e.length>0?e:void 0}function ee(e){if(!(new TextEncoder().encode(e).byteLength>4194304))try{let t=JSON.parse(e);if(!k(t))return;let n=A(t.requestId);if(!n)return;if(t.type===`get-personal-usage-report`)return{type:`personal`,requestId:n};let r=A(t.sessionId);return t.type===`get-stored-session-usage-report`&&r?{type:`stored-session`,requestId:n,sessionId:r}:void 0}catch{return}}function te(e,t,n,r){return n.type===`get-personal-usage-report`?(ie(t,n,r.personalUsageReporter),!0):n.type===`get-stored-session-usage-report`?(re(t,n,r.storedSessionUsageReporter),!0):n.type===`get-usage-report`?(ne(e,t,r.usageReporter),!0):!1}function ne(e,t,n){if(!n){t({type:`protocol_error`,message:`Per-session usage reporting is not available on this host.`});return}try{Promise.resolve(n(e)).then(e=>t({type:`usage_report`,report:e}),e=>t({type:`protocol_error`,message:N(e)}))}catch(e){t({type:`protocol_error`,message:N(e instanceof Error?e:String(e))})}}function re(e,t,n){if(!n){j(e,t,`not_available`,`Stored-session usage reporting is not available on this host.`);return}try{Promise.resolve(n(t.sessionId)).then(n=>e({type:`stored_session_usage_report`,requestId:t.requestId,sessionId:t.sessionId,report:n}),n=>j(e,t,`report_failed`,N(n)))}catch(n){j(e,t,`report_failed`,N(n instanceof Error?n:String(n)))}}function j(e,t,n,r){e({type:`stored_session_usage_report_error`,requestId:t.requestId,sessionId:t.sessionId,code:n,message:r})}function ie(e,t,n){if(!n){M(e,t.requestId,`not_available`,`Personal usage reporting is not available on this host.`);return}try{Promise.resolve(n({period:t.period,timezone:t.timezone})).then(n=>e({type:`personal_usage_report`,requestId:t.requestId,report:n}),n=>M(e,t.requestId,`report_failed`,N(n)))}catch(n){M(e,t.requestId,`report_failed`,N(n instanceof Error?n:String(n)))}}function M(e,t,n,r){e({type:`personal_usage_report_error`,requestId:t,code:n,message:r})}function N(e){return e instanceof Error?e.message:String(e)}function ae(e,n){let i=t(e,r);if(i.ok)return i.message;let a=ee(e);return a?.type===`personal`?(n({type:`personal_usage_report_error`,requestId:a.requestId,code:`report_failed`,message:`Invalid personal usage report request.`}),null):a?.type===`stored-session`?(n({type:`stored_session_usage_report_error`,requestId:a.requestId,sessionId:a.sessionId,code:`report_failed`,message:`Invalid stored-session usage report request.`}),null):(n({type:`protocol_error`,message:i.reason}),null)}function oe(e){return e.type===`project-status`||e.type===`project-diff`||e.type===`project-memory`}function P(e,t){e({type:`protocol_error`,message:`This host does not support the Project panel.`,requestId:t})}function se(e,t,n){let{requestId:r}=n;if(n.type===`project-status`){if(!e.readProjectStatus)return P(t,r);e.readProjectStatus().then(e=>t({type:`project_status`,requestId:r,result:e}),e=>t({type:`project_status`,requestId:r,result:{kind:`failed`,message:e instanceof Error?e.message:String(e)}}))}else if(n.type===`project-diff`){if(!e.readProjectDiff)return P(t,r);e.readProjectDiff(n.path).then(e=>t({type:`project_diff`,requestId:r,result:e}),e=>t({type:`project_diff`,requestId:r,result:{kind:`failed`,message:e instanceof Error?e.message:String(e)}}))}else{if(!e.readProjectMemory)return P(t,r);e.readProjectMemory().then(e=>t({type:`project_memory`,requestId:r,result:e}),e=>t({type:`project_memory`,requestId:r,result:{kind:`unavailable`,message:e instanceof Error?e.message:String(e)}}))}}function ce(e){return e.type===`list-sessions`||e.type===`new-session`||e.type===`switch-session`}function le(e){return e.type===`rename-session`}function ue(e){return e.type===`delete-session`}function de(e,t,n){if(t.type===`list-sessions`){fe(e,t.requestId,n);return}let r=t.requestId===void 0?{}:{requestId:t.requestId};if(!n){e({type:`session_change_failed`,code:`not_available`,message:`Sessions cannot be switched on this host.`,...r});return}Promise.resolve().then(()=>t.type===`new-session`?n.newSession():n.switchSession(t.sessionId)).catch(t=>e({type:`session_change_failed`,code:a(t)?t.code:`failed`,message:F(t),...r}))}function fe(e,t,n){if(!n){e({type:`sessions_error`,requestId:t,code:`not_available`,message:`Session listing is not available on this host.`});return}try{e({type:`sessions`,requestId:t,listing:n.listSessions()})}catch(n){e({type:`sessions_error`,requestId:t,code:`list_failed`,message:F(n instanceof Error?n:String(n))})}}function F(e){return e instanceof Error?e.message:String(e)}function pe(e,t,n){if(!n){e({type:`session_rename_failed`,requestId:t.requestId,message:`Sessions cannot be renamed on this host.`});return}n.renameSession(t.sessionId,t.name).then(()=>e({type:`session_renamed_in_list`,requestId:t.requestId,sessionId:t.sessionId,name:t.name}),n=>e({type:`session_rename_failed`,requestId:t.requestId,message:F(n)}))}function me(e,t,n){if(!n){e({type:`session_delete_failed`,requestId:t.requestId,code:`not_available`,message:`Sessions cannot be deleted on this host.`});return}n.deleteSession(t.sessionId).then(()=>e({type:`session_deleted`,requestId:t.requestId,sessionId:t.sessionId}),n=>e({type:`session_delete_failed`,requestId:t.requestId,code:o(n)?n.code:`failed`,message:F(n)}))}const I=new WeakMap;function he(e){let t=I.get(e);t===void 0&&(t={frames:new Map,holders:0},I.set(e,t));let n=t;n.holders+=1;let r=!1;return{record:e=>{r||n.frames.set(e.event.id,e)},forget:e=>{n.frames.delete(e)},clear:()=>{n.frames.clear()},release:()=>{r||(r=!0,--n.holders,n.holders===0&&I.get(e)===n&&I.delete(e))}}}function ge(e){return[...I.get(e)?.frames.values()??[]]}function _e(e){let t=[],n=new Set,r=[e];for(let e=0;e<=8&&r.length>0;e++){let e=[];for(let i of r)if(!(i==null||n.has(i))&&(n.add(i),t.push(i),typeof i==`object`)){let t=i;e.push(t.originalError,t.cause)}r=e}return t}function ve(e){let t;for(let n of _e(e)){if(n instanceof s)return{code:`auth`,...n.provider!==void 0&&{provider:n.provider}};if(n instanceof d)return{code:`rate_limit`,...n.provider!==void 0&&{provider:n.provider},...n.retryAfter!==void 0&&{retryAfterSeconds:n.retryAfter}};if(n instanceof c)return{code:`model_unavailable`,provider:n.provider,...n.model!==void 0&&{model:n.model}};if(n instanceof l)return{code:`network`,...n.provider!==void 0&&{provider:n.provider}};t===void 0&&n instanceof u&&(t={code:`provider`,provider:n.provider})}return t??{}}const ye={text_delta:`forwarded`,tool_start:`forwarded`,tool_end:`forwarded`,thinking:`forwarded`,thinking_delta:`non-surface`,complete:`forwarded`,error:`forwarded`,context_update:`forwarded`,compact:`forwarded`,interrupted:`forwarded`,skill_activation:`forwarded`,background_task_event:`forwarded`,background_job_group_event:`forwarded`,execution_workspace_event:`forwarded`,user_message:`forwarded`,turn_source:`forwarded`,context_file_refreshed:`forwarded`,memory_event:`forwarded`,goal_event:`non-surface`,plan_event:`forwarded`,branch_event:`forwarded`,permission_request:`forwarded`,ask_request:`forwarded`,prompt_resolved:`forwarded`,ui_intent:`requester-routed`,session_renamed:`forwarded`,history_cleared:`forwarded`,session_switched:`forwarded`,status_changed:`forwarded`};function be(e,t,n={}){let r=()=>{let t=e.getActiveDriverId();return t?{driverId:t}:{}},i=e=>t({type:`user_message`,content:e,...r()}),a=e=>t({type:`text_delta`,delta:e,...r()}),o=e=>t({type:`tool_start`,state:e,...r()}),s=e=>t({type:`tool_end`,state:e,...r()}),c=e=>t({type:`thinking`,isThinking:e,...r()}),l=e=>t({type:`complete`,result:L(e),...r()}),u=e=>t({type:`interrupted`,result:L(e),...r()}),d=e=>t({type:`error`,message:e.message,...ve(e),...r()}),f=e=>t({type:`background_task_event`,event:e}),p=e=>t({type:`background_job_group_event`,event:e}),m=e=>t({type:`execution_workspace_event`,snapshot:e.snapshot}),h=e=>t({type:`plan_event`,event:e}),g=e=>t({type:`context_file_refreshed`,event:e}),_=e=>t({type:`branch_event`,event:e}),v=n.receivePrompts??!0,y=v?he(e):void 0,b=e=>{let n={type:`permission_request`,event:e};y?.record(n),t(n)},x=e=>{let n={type:`ask_request`,event:e};y?.record(n),t(n)},S=e=>{y?.forget(e.id),t({type:`prompt_resolved`,event:e})},C=e=>{(e.requesterDriverId===void 0||e.requesterDriverId===n.getSurfaceDriverId?.())&&t({type:`ui_intent`,event:e})},w=e=>t({type:`session_renamed`,event:e}),T=()=>t({type:`history_cleared`}),E=e=>{y?.clear(),t({type:`session_switched`,event:e})},D=e=>t({type:`context`,state:e}),O=()=>t({type:`history_changed`}),k=e=>t({type:`turn_source`,source:e}),A=e=>t({type:`session_status`,status:e});return e.on(`user_message`,i),e.on(`text_delta`,a),e.on(`tool_start`,o),e.on(`tool_end`,s),e.on(`thinking`,c),e.on(`complete`,l),e.on(`interrupted`,u),e.on(`error`,d),e.on(`background_task_event`,f),e.on(`background_job_group_event`,p),e.on(`execution_workspace_event`,m),e.on(`plan_event`,h),e.on(`context_file_refreshed`,g),e.on(`branch_event`,_),v&&(e.on(`permission_request`,b),e.on(`ask_request`,x)),e.on(`prompt_resolved`,S),e.on(`ui_intent`,C),e.on(`session_renamed`,w),e.on(`history_cleared`,T),e.on(`session_switched`,E),e.on(`context_update`,D),e.on(`compact`,O),e.on(`skill_activation`,O),e.on(`memory_event`,O),e.on(`turn_source`,k),e.on(`status_changed`,A),()=>{e.off(`user_message`,i),e.off(`text_delta`,a),e.off(`tool_start`,o),e.off(`tool_end`,s),e.off(`thinking`,c),e.off(`complete`,l),e.off(`interrupted`,u),e.off(`error`,d),e.off(`background_task_event`,f),e.off(`background_job_group_event`,p),e.off(`execution_workspace_event`,m),e.off(`plan_event`,h),e.off(`context_file_refreshed`,g),e.off(`branch_event`,_),v&&(e.off(`permission_request`,b),e.off(`ask_request`,x)),e.off(`prompt_resolved`,S),e.off(`ui_intent`,C),e.off(`session_renamed`,w),e.off(`history_cleared`,T),e.off(`session_switched`,E),e.off(`context_update`,D),e.off(`compact`,O),e.off(`skill_activation`,O),e.off(`memory_event`,O),e.off(`turn_source`,k),e.off(`status_changed`,A),y?.release()}}function L(e){let{history:t,...n}=e;return n}const xe=256*1024,Se=new TextEncoder;function Ce(e){return e.type===`get-messages`||e.type===`get-history`||e.type===`get-prompts`||e.type===`get-context`||e.type===`get-commands`||e.type===`get-status`||e.type===`list-models`||e.type===`get-agent-definitions`||e.type===`get-executing`||e.type===`get-pending`||e.type===`get-execution-workspace`||e.type===`read-execution-detail`}function we(e,t,n){if(n.type===`get-messages`)t({type:`messages`,messages:e.getMessages(),display:e.getMessagesDisplay()});else if(n.type===`get-history`)t(Ee(e,n.fromIndex??0));else if(n.type===`get-prompts`)for(let n of ge(e))t(n);else if(n.type===`get-context`)t({type:`context`,state:e.getContextState()});else if(n.type===`get-commands`)t({type:`commands`,commands:e.listCommands(),skills:e.listSkills()});else if(n.type===`get-status`)t({type:`session_status`,status:e.getStatusSnapshot()});else if(n.type===`list-models`){let r=e.listModels();t({type:`model_list`,requestId:n.requestId,...r})}else n.type===`get-agent-definitions`?t({type:`agent_definitions`,requestId:n.requestId,agents:e.listAgentDefinitions(),current:e.getDefaultAgentType()}):n.type===`get-executing`?t({type:`executing`,executing:e.isExecuting()}):n.type===`get-execution-workspace`?t({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()}):n.type===`read-execution-detail`?Te(e,t,n):t(R(e))}function Te(e,t,n){let{requestId:r}=n;e.readExecutionWorkspaceDetail(n.entryId,n.cursor).then(e=>t({type:`execution_detail`,requestId:r,page:e}),e=>t({type:`execution_detail_error`,requestId:r,message:e instanceof Error?e.message:String(e)}))}function R(e){return{type:`pending`,pending:e.getPendingPrompt(),pendingCount:e.getPendingCount()}}function Ee(e,t){let n=e.getFullHistory(),r=n.length,i=Math.min(t,r),a=[],o=0;for(let e=i;e<r;e+=1){let t=De(n[e]),r=Se.encode(JSON.stringify(t)).byteLength;if(a.length>0&&o+r>262144)break;a.push(t),o+=r}return{type:`history`,startIndex:i,total:r,entries:a}}function De(e){return{...e,timestamp:Oe(e.timestamp)}}function Oe(e){return typeof e==`string`?e:e.toISOString()}function z(e){return e.type===`get-settings`||e.type===`update-settings`}function ke(e,t,n,r,i){if(!r){B(t,n.requestId,`not_available`,`Settings are not available on this host.`);return}try{if(n.type===`get-settings`){Promise.resolve(r.getSettings(e,i)).then(e=>t({type:`settings`,requestId:n.requestId,settings:e}),e=>B(t,n.requestId,`update_failed`,V(e)));return}Promise.resolve(r.updateSettings(e,n.patch,i)).then(e=>{e.ok?t({type:`settings`,requestId:n.requestId,settings:e.settings}):B(t,n.requestId,e.code,e.message)},e=>B(t,n.requestId,`update_failed`,V(e)))}catch(e){B(t,n.requestId,`update_failed`,V(e instanceof Error?e:String(e)))}}function B(e,t,n,r){e({type:`settings_error`,requestId:t,code:n,message:r})}function V(e){return e instanceof Error?e.message:String(e)}function Ae(e){let t=e.role??`drive`,n=be(e.session,e.deliver,{getSurfaceDriverId:()=>e.driverId,receivePrompts:t===`drive`}),r=new AbortController,i=()=>{r.abort(),n()};return{onMessage:je(e.session,e.deliver,e.driverId,{personalUsageReporter:e.personalUsageReporter,usageReporter:e.usageReporter,storedSessionUsageReporter:e.storedSessionUsageReporter},e.surface,t,e.sessionDirectory,e.settingsReporter,e.commandSurfaceLocality,{signal:r.signal,...e.maxFrameBytes===void 0?{}:{maxFrameBytes:e.maxFrameBytes}}),cleanup:i}}function je(e,t,n,r=Me,a,o=`drive`,s,c,l,u){return d=>{let f=ae(d,t);if(f){if(o===`observe`&&!i(f.type)){t({type:`protocol_error`,message:`Not permitted for an observer: ${f.type}`});return}H(e,t,f,n,r,a,s,c,l,u)}}}const Me={personalUsageReporter:void 0,usageReporter:void 0,storedSessionUsageReporter:void 0};function H(e,t,n,r,i=Me,a,o,s,c,l){if(te(e,t,n,i))return;if(ce(n)){de(t,n,o);return}if(z(n)){ke(e,t,n,s,c);return}if(le(n)){pe(t,n,o);return}if(ue(n)){me(t,n,o);return}if(Ne(n)){Re(e,t,n,r,a,c);return}if(E(n)){D(e,t,n);return}if(Ce(n)){we(e,t,n);return}if(oe(n)){se(e,t,n);return}if(f(n)){g(e,t,n,r,l);return}if(p(n)){_(e,t,n,l);return}if(Pe(n)){v(e,t,n);return}if(Fe(n)){y(e,t,n);return}if(Ie(n)){Le(e,n,r);return}let u=n.type;t({type:`protocol_error`,message:`Unknown message type: ${u}`})}function Ne(e){return e.type===`submit`||e.type===`command`||e.type===`abort`||e.type===`cancel-queue`}function Pe(e){return e.type===`get-background-tasks`||e.type===`get-background-task`||e.type===`read-background-task-log`||e.type===`get-background-job-groups`||e.type===`get-background-job-group`||e.type===`wait-background-job-group`}function Fe(e){return e.type===`cancel-background-task`||e.type===`close-background-task`||e.type===`send-background-task`}function Ie(e){return e.type===`permission-response`||e.type===`ask-response`}function Le(e,t,n){t.type===`permission-response`?e.resolvePermission(t.id,t.result,n):e.resolveAsk(t.id,t.response,n)}function Re(e,t,n,r,i,a){if(n.type===`submit`){if(typeof n.prompt!=`string`||n.prompt.length===0){t({type:`protocol_error`,message:`prompt must be a non-empty string`});return}let a={...r?{driverId:r}:{},...i?{surface:i}:{}};e.submit(n.prompt,void 0,void 0,Object.keys(a).length>0?a:void 0).then(()=>t(R(e)),e=>t({type:`protocol_error`,message:e.message}))}else if(n.type===`command`){let i=n.requestId===void 0?{}:{requestId:n.requestId};if(!n.name){t({type:`protocol_error`,message:`name is required`,...i});return}e.executeCommand(n.name,n.args??``,`remote`,r,a).then(e=>{t({type:`command_result`,name:n.name,message:e?.message??`Unknown command: ${n.name}`,success:e?.success??!1,data:e?.data,...i})},e=>{t({type:`protocol_error`,message:e.message,...i})})}else n.type===`abort`?e.abort():e.cancelQueue()}const U=1024*1024,W=8*U,ze=U;function G(e,t=W){return e!==void 0&&e>t}const K=120*1e3;function q(e=K,t=Date.now){let n;return{maxPendingMs:e,observe(r){if(r===void 0)return;if(r===0){n=void 0;return}let i=t();n??=i;let a=i-n;return a>e?a:void 0}}}function J(e,t,n,r=W,i=q()){let a=!1,o=t=>{if(a)return;let o=n?.();if(G(o,r)){a=!0,s(Error(`outbound backpressure budget exceeded: ${o} byte(s) pending, limit ${r}. The peer has accepted frames it is not reading.`),t.type);return}let c=i.observe(o);if(c!==void 0){a=!0,s(Error(`outbound drain budget exceeded: ${o} byte(s) pending for ${c} ms, limit ${i.maxPendingMs} ms. The peer is reading too slowly to ever drain what it accepted.`),t.type);return}try{e(t)}catch(e){a=!0,s(e instanceof Error?e:Error(String(e)),t.type)}};function s(e,n){try{t(e,n)}catch{}}return Object.assign(o,{pendingBytes:()=>n?.()})}var Y=class{frames=[];sizes=[];nextSeq=1;bytes=0;maxFrames;maxBytes;sizeOf;constructor(e={}){this.maxFrames=e.maxFrames??512,this.maxBytes=e.maxBytes??4194304,this.sizeOf=e.sizeOf??(e=>JSON.stringify(e).length)}append(e){let t=this.nextSeq;this.nextSeq+=1;let n=this.sizeOf(e);return this.frames.push({seq:t,message:e}),this.sizes.push(n),this.bytes+=n,this.evict(),t}ackThrough(e){let t=0;for(;t<this.frames.length&&this.frames[t].seq<=e;)t+=1;this.removeOldest(t)}tailAfter(e){return this.frames.length===0?e>=this.nextSeq-1?{kind:`tail`,frames:[]}:{kind:`overrun`}:e<this.frames[0].seq-1?{kind:`overrun`}:{kind:`tail`,frames:this.frames.filter(t=>t.seq>e)}}get lastSeq(){return this.nextSeq-1}get size(){return this.frames.length}evict(){let e=0,t=this.bytes;for(;this.frames.length-e>this.maxFrames||t>this.maxBytes&&this.frames.length-e>1;)t-=this.sizes[e],e+=1;this.removeOldest(e)}removeOldest(e){if(!(e<=0)){for(let t=0;t<e;t+=1)this.bytes-=this.sizes[t]??0;this.frames.splice(0,e),this.sizes.splice(0,e),this.frames.length===0&&(this.bytes=0)}}};const X=new TextEncoder,Be=new TextDecoder,Z=X.encode(`RBF`),Ve=1,He=4294967295;function Q(e,t){let n=X.encode(e);if(n.byteLength===0||n.byteLength>255)throw Error(`channel name must be 1..255 UTF-8 bytes (got ${n.byteLength})`);if(!Number.isInteger(t)||t<0||t>He)throw Error(`seq must be an integer in 0..${He} (got ${t})`);return n}function Ue(e,t,n,r){e.set(Z,0),e[3]=1,e[4]=t,e[5]=n.byteLength,e.set(n,6);let i=6+n.byteLength;return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(i,r,!1),i+4}function We(e){let t=Q(e.channel,e.seq),n=new Uint8Array(6+t.byteLength+4+e.payload.byteLength),r=Ue(n,1,t,e.seq);return n.set(e.payload,r),n}function Ge(e){let t=Q(e.channel,e.seq),n=X.encode(JSON.stringify({event:e.event,payload:e.payload})),r=new Uint8Array(6+t.byteLength+4+n.byteLength),i=Ue(r,2,t,e.seq);return r.set(n,i),r}function Ke(e){return e.byteLength<Z.length?!1:Z.every((t,n)=>e[n]===t)}function qe(e){let t=Be.decode(e),n;try{n=JSON.parse(t)}catch{return{ok:!1,error:`channel frame: malformed JSON body`}}if(typeof n!=`object`||!n||Array.isArray(n))return{ok:!1,error:`channel frame: event body must be a JSON object`};let{event:r,payload:i}=n;return typeof r!=`string`||r.length===0?{ok:!1,error:"channel frame: event body is missing a non-empty `event` name"}:{ok:!0,event:r,payload:i??null}}function Je(e){if(!Ke(e))return{ok:!1,error:`channel frame: bad magic (not a channel frame)`};if(e.byteLength<6)return{ok:!1,error:`channel frame: truncated header`};if(e[3]!==1)return{ok:!1,error:`channel frame: unsupported version ${String(e[3])}`};let t=e[4],n=e[5]??0;if(n===0)return{ok:!1,error:`channel frame: empty channel name`};let r=6+n,i=r+4;if(e.byteLength<i)return{ok:!1,error:`channel frame: truncated (header longer than the frame)`};let a=Be.decode(e.subarray(6,r)),o=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(r,!1),s=e.subarray(i);if(t===1)return{ok:!0,frame:{kind:`binary`,channel:a,seq:o,payload:Uint8Array.from(s)}};if(t===2){let e=qe(s);return e.ok?{ok:!0,frame:{kind:`event`,channel:a,seq:o,event:e.event,payload:e.payload}}:{ok:!1,error:e.error}}return{ok:!1,error:`channel frame: unknown kind ${String(t)}`}}var Ye=class{session;buffer;driverId;reporters;surface;commandSurfaceLocality;maxFrameBytes;lifetime=new AbortController;unsubscribe;onDeliveryError;outbound;emitBoundary;disposed=!1;holding=!1;constructor(e){this.session=e.session,this.buffer=new Y(e.buffer),this.driverId=e.driverId,this.surface=e.surface,this.commandSurfaceLocality=e.commandSurfaceLocality,this.maxFrameBytes=e.maxFrameBytes,this.reporters={personalUsageReporter:e.personalUsageReporter,usageReporter:e.usageReporter,storedSessionUsageReporter:e.storedSessionUsageReporter},this.emitBoundary=J(e=>this.emit(e),(e,t)=>this.reportDeliveryError(e,t)),this.unsubscribe=be(this.session,this.emitBoundary,{getSurfaceDriverId:()=>this.driverId})}attach(e,t){this.disposed||(this.onDeliveryError=t.onDeliveryError,this.outbound=J(t=>e(JSON.stringify(t)),(e,t)=>this.reportDeliveryError(e,t),t.pendingBytes),this.holding=t.awaitResume===!0)}detach(){this.outbound=void 0,this.onDeliveryError=void 0}setDriverId(e){this.driverId=e}onClientMessage(e){if(this.disposed)return;let t=ae(e,this.emitBoundary);if(t){if(t.type===`resume`){this.replay(t.lastSeq);return}if(t.type===`ack`){this.buffer.ackThrough(t.seq);return}H(this.session,this.emitBoundary,t,this.driverId,this.reporters,this.surface,void 0,void 0,this.commandSurfaceLocality,{signal:this.lifetime.signal,...this.maxFrameBytes===void 0?{}:{maxFrameBytes:this.maxFrameBytes}})}}dispose(){this.disposed||(this.disposed=!0,this.lifetime.abort(),this.detach(),this.unsubscribe())}get lastSeq(){return this.buffer.lastSeq}emit(e){if(this.disposed)return;let t=this.buffer.append(e);this.holding||this.deliverFrame({...e,seq:t})}replay(e){let t=this.buffer.tailAfter(e);if(t.kind===`overrun`){this.deliverFrame({type:`resume_gap`}),this.holding=!1;return}for(let e of t.frames)this.deliverFrame({...e.message,seq:e.seq});this.holding=!1}deliverFrame(e){this.outbound?.(e)}reportDeliveryError(e,t){let n=this.onDeliveryError;this.detach();try{n?.(e,t)}catch{}}};function Xe(){return{origins:new Map}}function Ze(e,t,n){let r=t.origin.sessionId,i=e.origins.get(r);i===void 0&&(i={highestSequence:0,delivered:new Set,issued:new Map},e.origins.set(r,i));let a=i.issued.get(t.id);if(a!==void 0)return{ack:{...a,state:`duplicate`},deliver:!1};if(n!==void 0){let e={id:t.id,sequence:t.sequence,state:n.state,reason:n.reason};return i.issued.set(t.id,e),{ack:e,deliver:!1}}if(i.delivered.has(t.sequence)){let e={id:t.id,sequence:t.sequence,state:`refused`,reason:`sequence ${t.sequence} was already delivered by this origin under a different message id. A retry must repeat its id; a new id on a delivered sequence cannot be ordered against what the receiver already has.`};return i.issued.set(t.id,e),{ack:e,deliver:!1}}let o=i.highestSequence+1,s=t.sequence>o?o:void 0,c={id:t.id,sequence:t.sequence,state:`delivered`};return i.issued.set(t.id,c),i.delivered.add(t.sequence),i.highestSequence=Math.max(i.highestSequence,t.sequence),s===void 0?{ack:c,deliver:!0}:{ack:c,deliver:!0,gapBefore:s}}function Qe(e,t,n){let r=e.origins.get(t),i=r?.issued.get(n);if(r===void 0||i===void 0||i.state!==`delivered`)return;let a={...i,state:`acknowledged`};return r.issued.set(n,a),a}function $e(e,t){e.origins.delete(t)}const et=[`command`,`filePath`,`file_path`,`path`,`url`,`pattern`,`query`];function tt(e){for(let t of et){let n=e[t];if(typeof n==`string`&&n!==``)return n}}const $=16*1024,nt=32768;function rt(e){let t=``;for(let n=0;n<e.length;n+=nt)t+=String.fromCharCode(...e.subarray(n,n+nt));return btoa(t)}function it(e){let t;try{t=atob(e)}catch{return}let n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function at(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function ot(e,t,n=$){if(!Number.isInteger(n)||n<1)throw Error(`handoff chunking: maxChunkBytes must be a positive integer, got ${n}. A zero or negative budget produces an infinite sequence of empty chunks, which presents as a hang rather than as the configuration error it is.`);let r=new TextEncoder().encode(t),i=Math.max(1,Math.ceil(r.byteLength/n)),a=[];for(let t=0;t<i;t+=1){let o=r.subarray(t*n,(t+1)*n);a.push({handoffId:e,index:t,total:i,data:rt(o)})}return a}var st=class{handoffId;chunks=new Map;declaredTotal;constructor(e){this.handoffId=e}get received(){return this.chunks.size}get expected(){return this.declaredTotal}accept(e){let t=e=>({outcome:`refused`,rejection:e,received:this.chunks.size,...this.declaredTotal===void 0?{}:{expected:this.declaredTotal}});if(e.handoffId!==this.handoffId)return t(`wrong-handoff`);if(!Number.isInteger(e.total)||e.total<1||this.declaredTotal!==void 0&&e.total!==this.declaredTotal)return t(`inconsistent-total`);if(!Number.isInteger(e.index)||e.index<0||e.index>=e.total)return t(`out-of-range`);let n=it(e.data);if(n===void 0||rt(n)!==e.data)return t(`undecodable`);this.declaredTotal=e.total;let r=this.chunks.get(e.index);return r===void 0?(this.chunks.set(e.index,n),this.chunks.size<e.total?{outcome:`accepted`,received:this.chunks.size,expected:e.total}:{outcome:`complete`,serialized:this.reassemble(e.total),received:this.chunks.size,expected:e.total}):at(r,n)?{outcome:`duplicate`,received:this.chunks.size,expected:e.total}:t(`inconsistent-total`)}missing(){if(this.declaredTotal===void 0)return[];let e=[];for(let t=0;t<this.declaredTotal;t+=1)this.chunks.has(t)||e.push(t);return e}discard(){this.chunks.clear(),this.declaredTotal=void 0}reassemble(e){let t=[];for(let n=0;n<e;n+=1){let r=this.chunks.get(n);if(r===void 0)throw Error(`handoff chunking: chunk ${n} of ${e} is missing at reassembly.`);t.push(r)}let n=new Uint8Array(t.reduce((e,t)=>e+t.length,0)),r=0;for(let e of t)n.set(e,r),r+=e.length;return new TextDecoder(`utf-8`,{ignoreBOM:!0}).decode(n)}};function ct(e,t=$){return Math.max(1,Math.ceil(e.byteLength/t))}export{ze as ATTACHED_SURFACE_MAX_PENDING_BYTES,Z as CHANNEL_FRAME_MAGIC,Ve as CHANNEL_FRAME_VERSION,$ as DEFAULT_MAX_CHUNK_BYTES,W as DEFAULT_MAX_PENDING_BYTES,K as DEFAULT_MAX_PENDING_MS,xe as HISTORY_PAGE_MAX_BYTES,st as HandoffChunkAssembler,n as MAX_INBOUND_FRAME_BYTES,ye as PROTOCOL_SESSION_EVENT_CLASSIFICATION,Y as ResumeBuffer,Ye as SessionResumeBridge,Qe as acknowledgePeerMessage,Ze as admitPeerMessage,ct as chunkCountFor,ot as chunkHandoffPayload,J as createOutboundDelivery,Xe as createPeerMessageLedger,q as createPendingStallClock,Ae as createSessionMessageHandler,Je as decodeChannelFrame,r as decodeClientMessage,t as decodeFrame,e as decodeServerMessage,We as encodeBinaryFrame,Ge as encodeChannelEventFrame,$e as forgetPeerOrigin,ke as handleSettingsMessage,Ke as isChannelFrame,i as isObserverMessageType,G as isOverPendingBudget,z as isSettingsMessage,tt as permissionSummaryArgument};
2
2
  //# sourceMappingURL=index.js.map