@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9
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/README.i18n.yaml +2 -2
- package/README.md +93 -26
- package/README.zh.md +91 -26
- package/icon.svg +3 -0
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +8891 -2433
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/approvals.d.ts +24 -0
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +124 -5
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/dsh-frames.d.ts +155 -4
- package/lib/types/core/envelope.d.ts +34 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/hub.d.ts +96 -20
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +491 -2
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +109 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/core/wire.d.ts +1 -1
- package/lib/types/core/ws-frames.d.ts +11 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/host/websocket.d.ts +8 -1
- package/lib/types/index.d.ts +34 -3
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +20 -14
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/approvals.ts +32 -1
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +1483 -31
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +221 -3
- package/src/core/dsh-frames.ts +365 -8
- package/src/core/envelope.ts +46 -0
- package/src/core/extension.ts +197 -0
- package/src/core/hub.ts +441 -49
- package/src/core/jobs.ts +372 -0
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +556 -2
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +264 -17
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +13 -1
- package/src/core/ws-frames.ts +14 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/host/websocket.ts +37 -3
- package/src/index.ts +310 -9
- package/src/mount-once.ts +142 -0
package/src/core/connection.ts
CHANGED
|
@@ -17,63 +17,145 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import type { ApprovalRegistry } from './approvals.ts'
|
|
20
|
-
import
|
|
21
|
-
import {
|
|
20
|
+
import { commandItems, commandsUnavailable } from './commands.ts'
|
|
21
|
+
import type { DeviceRoster, PushEnvironment, PushLiveActivityToken, PushRegistration } from './devices.ts'
|
|
22
|
+
import { ROSTER_DELTA_MAX_ROWS, RemoteBridgeDeltas, type DeltaRow } from './delta.ts'
|
|
23
|
+
import { deltaOfFollowFrame, MessageIndex, oldestEntrySeq, pageTurns, readFollowBaseline, SpawnCallIndex, ToolCallIndex, trimUnrenderedEntries, turnsAbove, turnsOfRecords, type FollowBaseline, type SnapshotTurn } from './dsh-frames.ts'
|
|
22
24
|
import { EventSequence, FRAME_TOO_LARGE, MAX_FRAME_BYTES, decodeClientFrame, encodeFrame, errorFrame, responseFrame, type ReqFrame, type ServerFrame } from './envelope.ts'
|
|
25
|
+
import type { RemoteBridgeMethodResult, RemoteBridgeRegistry } from './extension.ts'
|
|
23
26
|
import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
|
|
27
|
+
import { scopeKey, type JobRoster, type JobsPayload } from './jobs.ts'
|
|
28
|
+
import type { LiveActivityNotifier } from './liveactivity.ts'
|
|
24
29
|
import type { PairingService } from './pairing.ts'
|
|
25
|
-
import type {
|
|
30
|
+
import type { PushNotifier } from './push.ts'
|
|
31
|
+
import { pushEventOfTurnEnd } from './push.ts'
|
|
32
|
+
import type { ListedQuestion, QuestionAnswerItem, QuestionClaims, QuestionListPayload } from './questions.ts'
|
|
26
33
|
import {
|
|
34
|
+
CAP_AGENTS,
|
|
35
|
+
CAP_COMMANDS,
|
|
36
|
+
CAP_DELTA,
|
|
37
|
+
CAP_FRAME_DEFLATE,
|
|
38
|
+
CAP_JOBS,
|
|
39
|
+
CAP_PUSH,
|
|
27
40
|
CAP_QUESTIONS,
|
|
41
|
+
CAP_QUESTION_LIST,
|
|
42
|
+
CAP_ROSTER_COMPACT,
|
|
43
|
+
CAP_SESSION_ADMIN,
|
|
44
|
+
CAP_SESSION_FORK,
|
|
28
45
|
CAP_SESSION_SNAPSHOT_PAGE,
|
|
46
|
+
CAP_SESSION_SNAPSHOT_SINCE,
|
|
29
47
|
CAP_SESSION_SNAPSHOT_TRIM,
|
|
48
|
+
CAP_SQUADS,
|
|
49
|
+
CAP_SUBAGENT_THREAD,
|
|
50
|
+
CAP_USAGE,
|
|
51
|
+
CAP_USAGE_STATS,
|
|
52
|
+
CAP_WORKSPACE,
|
|
30
53
|
CODE_APPROVAL_UNKNOWN,
|
|
54
|
+
CODE_COMMANDS_UNAVAILABLE,
|
|
31
55
|
CODE_INTERNAL,
|
|
32
56
|
CODE_INVALID_ARGS,
|
|
57
|
+
CODE_JOBS_UNAVAILABLE,
|
|
33
58
|
CODE_NONCE_INVALID,
|
|
34
59
|
CODE_PROTO_UNSUPPORTED,
|
|
60
|
+
CODE_QUESTION_LIST_UNAVAILABLE,
|
|
61
|
+
CODE_SESSION_NOT_FOLLOWABLE,
|
|
35
62
|
CODE_SNAPSHOT_TOO_LARGE,
|
|
36
63
|
CODE_SNAPSHOT_UNAVAILABLE,
|
|
64
|
+
CODE_SQUADS_UNAVAILABLE,
|
|
37
65
|
CODE_TOKEN_INVALID,
|
|
38
66
|
CODE_UNKNOWN_METHOD,
|
|
67
|
+
CODE_UNKNOWN_SESSION,
|
|
39
68
|
CODE_UNPAIRED,
|
|
40
69
|
KNOWN_METHODS,
|
|
41
70
|
METHOD_APPROVAL_RESOLVE,
|
|
42
71
|
METHOD_HELLO,
|
|
72
|
+
METHOD_JOBS_LIST,
|
|
43
73
|
METHOD_PAIR_BEGIN,
|
|
44
74
|
METHOD_PAIR_FINISH,
|
|
75
|
+
METHOD_PRESETS_LIST,
|
|
76
|
+
METHOD_PUSH_REGISTER,
|
|
45
77
|
METHOD_QUESTION_ANSWER,
|
|
78
|
+
METHOD_QUESTION_LIST,
|
|
79
|
+
METHOD_SESSION_ARCHIVE,
|
|
46
80
|
METHOD_SESSION_ATTACHMENT,
|
|
81
|
+
METHOD_SESSION_COMMAND,
|
|
82
|
+
METHOD_SESSION_COMMANDS,
|
|
83
|
+
METHOD_SESSION_CREATE,
|
|
84
|
+
METHOD_SESSION_FORK,
|
|
47
85
|
METHOD_SESSION_HISTORY,
|
|
86
|
+
METHOD_SESSION_HISTORY_DEEP,
|
|
48
87
|
METHOD_SESSION_INTERRUPT,
|
|
49
88
|
METHOD_SESSION_LIST,
|
|
50
89
|
METHOD_SESSION_MODELS,
|
|
51
90
|
METHOD_SESSION_PERMISSIONS,
|
|
91
|
+
METHOD_SESSION_PIN,
|
|
52
92
|
METHOD_SESSION_PROMPT,
|
|
93
|
+
METHOD_SESSION_RENAME,
|
|
53
94
|
METHOD_SESSION_SET_MODEL,
|
|
54
95
|
METHOD_SESSION_SET_PERMISSION,
|
|
55
96
|
METHOD_SESSION_SNAPSHOT,
|
|
56
97
|
METHOD_SESSION_TITLES,
|
|
98
|
+
METHOD_SESSION_UNARCHIVE,
|
|
99
|
+
METHOD_SESSION_UNPIN,
|
|
100
|
+
METHOD_SQUADS_LIST,
|
|
101
|
+
METHOD_SQUADS_RUNS,
|
|
102
|
+
METHOD_SQUADS_RUN_MEMBER,
|
|
103
|
+
METHOD_SQUADS_RUN_SQUAD,
|
|
104
|
+
METHOD_SQUADS_STATE,
|
|
105
|
+
METHOD_USAGE_BALANCE,
|
|
106
|
+
METHOD_USAGE_SESSION,
|
|
107
|
+
METHOD_USAGE_STATS,
|
|
108
|
+
METHOD_WORKSPACE_LIST,
|
|
57
109
|
MINOR,
|
|
58
110
|
PROTO,
|
|
111
|
+
SERVED_CAPABILITIES,
|
|
59
112
|
SERVER_ID,
|
|
113
|
+
TOPIC_JOBS_CHANGED,
|
|
60
114
|
TOPIC_SESSION_DELTA,
|
|
61
115
|
UNPAIRED_METHODS,
|
|
62
116
|
} from './protocol.ts'
|
|
63
117
|
import { base64UrlDecode, verifyEs256 } from './crypto.ts'
|
|
118
|
+
import { isSquadRefusal, parseSquadMemberRun, parseSquadRun, squadRunOf, SQUAD_METHODS, squadsStateOf, type SquadTransport, type SquadsState } from './squads.ts'
|
|
64
119
|
import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
|
|
65
120
|
import type { SessionPermissions } from './session-permissions.ts'
|
|
121
|
+
import { USAGE_METHODS, type UsageService } from './usage.ts'
|
|
66
122
|
import type { BridgeGateway, GatewayPeer } from './wire.ts'
|
|
67
123
|
import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
|
|
124
|
+
import { CLOSE_LIVENESS_TIMEOUT } from './ws-frames.ts'
|
|
68
125
|
|
|
69
126
|
/** Protocol-level heartbeat period: a frame is sent after this long without one. */
|
|
70
127
|
export const IDLE_PING_MS = 20_000
|
|
128
|
+
/**
|
|
129
|
+
* Deadline behind one liveness ping: a peer that sends no frame at all within
|
|
130
|
+
* this long of the ping is torn down.
|
|
131
|
+
*
|
|
132
|
+
* It only ever exists because a ping was sent — a connection the host has not
|
|
133
|
+
* pinged has no deadline — so a quiet client is never closed for being quiet,
|
|
134
|
+
* only for failing to answer. The measured one-way path over the relay is about
|
|
135
|
+
* 410 ms (2026-10-19), so this is more than an order of magnitude of slack.
|
|
136
|
+
*/
|
|
137
|
+
export const LIVENESS_TIMEOUT_MS = 10_000
|
|
71
138
|
/** How long `session.snapshot` waits for its follow stream's opening frame. */
|
|
72
139
|
export const SNAPSHOT_OPEN_TIMEOUT_MS = 10_000
|
|
73
140
|
/** Largest turn window one snapshot asks DSH for. */
|
|
74
141
|
export const SNAPSHOT_MAX_MESSAGES = 200
|
|
75
142
|
/** Default byte budget of one `session.history` page: 512 KiB. */
|
|
76
143
|
export const HISTORY_PAGE_BYTES = 512 * 1024
|
|
144
|
+
/**
|
|
145
|
+
* Window one `session.history.deep` read asks DSH for: at least 50 user or
|
|
146
|
+
* assistant messages across at least 2 turns, and never more than 500 messages.
|
|
147
|
+
*
|
|
148
|
+
* It is the window the harness's own Web client pages history with, and it is
|
|
149
|
+
* deliberately wider than one answer: a byte budget is the caller's, so the
|
|
150
|
+
* store is asked for a whole span once and the bridge then cuts that span to
|
|
151
|
+
* `maxBytes` by entry. Nothing in the answer depends on where the store cut:
|
|
152
|
+
* the host's `hasMore` is folded into the answer's own `hasMore`, and the
|
|
153
|
+
* cursor is always the oldest entry the answer carries.
|
|
154
|
+
*/
|
|
155
|
+
export const DEEP_HISTORY_WINDOW = {
|
|
156
|
+
maxMessages: 500,
|
|
157
|
+
turnWindow: { minMessages: 50, minTurns: 2 },
|
|
158
|
+
} as const
|
|
77
159
|
/** Highest number of prompt receipts one connection remembers for idempotency. */
|
|
78
160
|
export const PROMPT_RECEIPT_LIMIT = 512
|
|
79
161
|
/** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
|
|
@@ -83,6 +165,14 @@ export const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024
|
|
|
83
165
|
export interface BridgeTransport {
|
|
84
166
|
send(text: string): void
|
|
85
167
|
close(code: number, reason: string): void
|
|
168
|
+
/**
|
|
169
|
+
* Optional: whether the peer declared `frame.deflate.v1`, reported once the
|
|
170
|
+
* `hello` that declares it has been recorded. The capability is the client's
|
|
171
|
+
* declaration and the wire form is the carrier's, so this is the one fact that
|
|
172
|
+
* has to cross between them. A carrier with no socket to compress — a
|
|
173
|
+
* recording double, for one — omits the member and keeps writing text.
|
|
174
|
+
*/
|
|
175
|
+
frameDeflate?(declared: boolean): void
|
|
86
176
|
}
|
|
87
177
|
|
|
88
178
|
export interface BridgeConnectionOptions {
|
|
@@ -92,8 +182,16 @@ export interface BridgeConnectionOptions {
|
|
|
92
182
|
readonly approvals: ApprovalRegistry
|
|
93
183
|
/** Pending user questions: the claims this bridge holds and the answer path back to the host. */
|
|
94
184
|
readonly questions: QuestionClaims
|
|
185
|
+
/** The host's background jobs: the read-only projection and the scopes this connection watches. */
|
|
186
|
+
readonly jobs: JobRoster
|
|
95
187
|
/** Process-local session metadata: live titles and the host's archive set. */
|
|
96
188
|
readonly sessionMeta: SessionMeta
|
|
189
|
+
/**
|
|
190
|
+
* `usage.v1` 背后两半读数:一条会话的上下文窗口与请求组成估算,以及某条
|
|
191
|
+
* provider 路由背后账户的余额。两者都是宿主侧的事实而不是某个设备的事实,
|
|
192
|
+
* 所以一个宿主一份、所有连接共享(见 `core/usage.ts`)。
|
|
193
|
+
*/
|
|
194
|
+
readonly usage: UsageService
|
|
97
195
|
/** Host-process permission presets, read and switched through their real service objects. */
|
|
98
196
|
readonly permissions: SessionPermissions
|
|
99
197
|
/**
|
|
@@ -114,6 +212,44 @@ export interface BridgeConnectionOptions {
|
|
|
114
212
|
*/
|
|
115
213
|
readonly onDeclare?: (connection: BridgeConnection) => void
|
|
116
214
|
readonly heartbeatMs?: number
|
|
215
|
+
/**
|
|
216
|
+
* Methods plugins registered on the bridge's extension seam. Absent is the
|
|
217
|
+
* protocol exactly as this package defines it: every name outside
|
|
218
|
+
* `KNOWN_METHODS` answers `unknown-method`.
|
|
219
|
+
*/
|
|
220
|
+
readonly extensions?: RemoteBridgeRegistry
|
|
221
|
+
/**
|
|
222
|
+
* The host's squad domain, behind the `squads.v1` channel. Absent is a host
|
|
223
|
+
* that serves no `dsh-agents` domain: the capability stays advertised and only
|
|
224
|
+
* a call that needs the domain answers `squads-unavailable`.
|
|
225
|
+
*/
|
|
226
|
+
readonly squads?: SquadTransport
|
|
227
|
+
/**
|
|
228
|
+
* The outbound notification path, behind the `push.v1` channel. Absent is a
|
|
229
|
+
* bridge that sends nothing: `push.register` still answers `ok:true` (the
|
|
230
|
+
* device row is written either way), and no notification is ever built. That
|
|
231
|
+
* is the default, because a sender needs an Apple signing key this bridge is
|
|
232
|
+
* not shipped with.
|
|
233
|
+
*/
|
|
234
|
+
readonly push?: PushNotifier
|
|
235
|
+
/**
|
|
236
|
+
* The lock-screen card path, behind the same `push.v1` channel. Absent — and it
|
|
237
|
+
* is absent whenever no APNs key is configured — is a bridge that never builds a
|
|
238
|
+
* card: the roster is still served and a question is still answered, because
|
|
239
|
+
* registering the phone's tokens and pushing to them are two different things
|
|
240
|
+
* (§28.3, §29).
|
|
241
|
+
*/
|
|
242
|
+
readonly liveActivity?: LiveActivityNotifier
|
|
243
|
+
/**
|
|
244
|
+
* Called after a registration changed the device table.
|
|
245
|
+
*
|
|
246
|
+
* A session's first live-activity token is what asks this bridge to keep a
|
|
247
|
+
* follow stream of its own open for that session (`host/watchers.ts`), so the
|
|
248
|
+
* roster is the trigger. The hook is guarded at the call site: a standing
|
|
249
|
+
* watcher is this bridge's own background work and may never turn a
|
|
250
|
+
* `push.register` into a failure.
|
|
251
|
+
*/
|
|
252
|
+
readonly onPushRegistered?: () => void
|
|
117
253
|
}
|
|
118
254
|
|
|
119
255
|
/** A device the connection proved itself to be, resolved from the upgrade request. */
|
|
@@ -146,8 +282,18 @@ interface CallFailure {
|
|
|
146
282
|
|
|
147
283
|
type DispatchOutcome = { readonly ok: true; readonly r: unknown } | CallFailure
|
|
148
284
|
|
|
285
|
+
/**
|
|
286
|
+
* One snapshot baseline answer, typed rather than opaque so the incremental
|
|
287
|
+
* fallback can extend the very payload protocol v1 serves instead of rebuilding
|
|
288
|
+
* it. `hasMore` is present exactly for a connection that declared the page
|
|
289
|
+
* capability.
|
|
290
|
+
*/
|
|
291
|
+
type BaselineAnswer =
|
|
292
|
+
| { readonly ok: true; readonly r: { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number; readonly hasMore?: boolean } }
|
|
293
|
+
| CallFailure
|
|
294
|
+
|
|
149
295
|
/** One session-list row as the protocol publishes it. */
|
|
150
|
-
interface SessionRow {
|
|
296
|
+
interface SessionRow extends DeltaRow {
|
|
151
297
|
readonly id: string
|
|
152
298
|
readonly title: string
|
|
153
299
|
readonly updatedAt: number
|
|
@@ -167,6 +313,37 @@ function refusal(code: string, msg: string): CallFailure {
|
|
|
167
313
|
return { ok: false, code, msg }
|
|
168
314
|
}
|
|
169
315
|
|
|
316
|
+
/**
|
|
317
|
+
* The opaque `since` token one request carried.
|
|
318
|
+
*
|
|
319
|
+
* Anything that is not a non-empty string is "no usable token", which answers a
|
|
320
|
+
* reset — the same answer an unknown token gets, because a request that named
|
|
321
|
+
* no base cannot be diffed against one.
|
|
322
|
+
* @param payload - the request's `p`.
|
|
323
|
+
* @returns the token, or undefined.
|
|
324
|
+
*/
|
|
325
|
+
function sinceOf(payload: Readonly<Record<string, unknown>>): string | undefined {
|
|
326
|
+
const value = payload.since
|
|
327
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Whether a plugin's answer is one of the two shapes the seam defines.
|
|
332
|
+
*
|
|
333
|
+
* An extension is ordinary JavaScript calling into this bridge, so a result the
|
|
334
|
+
* type system never saw still has to leave the client with an answer instead of
|
|
335
|
+
* a lost frame.
|
|
336
|
+
* @param value - what the extension method returned.
|
|
337
|
+
* @returns whether it carries a usable answer or refusal.
|
|
338
|
+
*/
|
|
339
|
+
function isMethodResult(value: unknown): value is RemoteBridgeMethodResult {
|
|
340
|
+
if (typeof value !== 'object' || value === null) return false
|
|
341
|
+
const result = value as { ok?: unknown; code?: unknown; msg?: unknown }
|
|
342
|
+
if (result.ok === true) return true
|
|
343
|
+
if (result.ok !== false) return false
|
|
344
|
+
return typeof result.code === 'string' && result.code !== '' && typeof result.msg === 'string'
|
|
345
|
+
}
|
|
346
|
+
|
|
170
347
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
171
348
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
172
349
|
}
|
|
@@ -182,11 +359,44 @@ function optionalText(value: unknown): string | undefined {
|
|
|
182
359
|
return typeof value === 'string' && value !== '' ? value : undefined
|
|
183
360
|
}
|
|
184
361
|
|
|
362
|
+
/**
|
|
363
|
+
* One roster row's own title, as the host's projection carries it.
|
|
364
|
+
*
|
|
365
|
+
* `SessionSummary` has no top-level `title` — which is why this bridge once read
|
|
366
|
+
* its own live-title cache and nothing else. Every row nevertheless carries
|
|
367
|
+
* `projections.values.title`: the host folds that out of its projection cache
|
|
368
|
+
* synchronously for a cold session as well as a live one, with no log read and no
|
|
369
|
+
* follow stream, and its own desktop list renders exactly that field. Reading it
|
|
370
|
+
* costs no call, because it is already inside the listing the bridge just paid
|
|
371
|
+
* for.
|
|
372
|
+
*
|
|
373
|
+
* The guard is the one every optional field here takes: a `projections` block
|
|
374
|
+
* that is not an object, a `values` member that is not one, and a `title` that is
|
|
375
|
+
* not a non-empty string are all simply absent, so an answer of another shape
|
|
376
|
+
* costs a row its title rather than failing the listing.
|
|
377
|
+
* @param item - one row of the host's `session/list` answer.
|
|
378
|
+
* @returns the projected title, or undefined when the row carries none.
|
|
379
|
+
*/
|
|
380
|
+
function projectedTitleOf(item: Readonly<Record<string, unknown>>): string | undefined {
|
|
381
|
+
const projections = isRecord(item.projections) ? item.projections : undefined
|
|
382
|
+
if (projections === undefined) return undefined
|
|
383
|
+
const values = isRecord(projections.values) ? projections.values : undefined
|
|
384
|
+
return values === undefined ? undefined : optionalText(values.title)
|
|
385
|
+
}
|
|
386
|
+
|
|
185
387
|
/** @returns a non-negative safe integer page argument, or undefined. */
|
|
186
388
|
function pageNumber(value: unknown): number | undefined {
|
|
187
389
|
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
|
|
188
390
|
}
|
|
189
391
|
|
|
392
|
+
/**
|
|
393
|
+
* @param value - a request's event-seq member, or undefined.
|
|
394
|
+
* @returns the seq, or undefined when it is not a positive safe integer.
|
|
395
|
+
*/
|
|
396
|
+
function seqNumber(value: unknown): number | undefined {
|
|
397
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : undefined
|
|
398
|
+
}
|
|
399
|
+
|
|
190
400
|
/**
|
|
191
401
|
* Read one request's page budget.
|
|
192
402
|
*
|
|
@@ -206,6 +416,54 @@ function pageBudgetOf(value: unknown, method: string): { readonly ok: true; read
|
|
|
206
416
|
return { ok: true, maxBytes }
|
|
207
417
|
}
|
|
208
418
|
|
|
419
|
+
/** The compact roster parameters one listing carried, when it carried any. */
|
|
420
|
+
interface RosterCompact {
|
|
421
|
+
/** Rows per page; absent means every row. */
|
|
422
|
+
readonly maxRows?: number
|
|
423
|
+
/** Exclusive cursor: serve the rows after the row this id names. */
|
|
424
|
+
readonly after?: string
|
|
425
|
+
/** Whether each row carries the host's absolute `cwd`. */
|
|
426
|
+
readonly cwd: boolean
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Read one listing's compact roster parameters.
|
|
431
|
+
*
|
|
432
|
+
* The parameters are the switch, not the capability: a listing that names none
|
|
433
|
+
* of them is answered today's body byte for byte, so declaring
|
|
434
|
+
* {@link CAP_ROSTER_COMPACT} alone can never change what a client is sent. The
|
|
435
|
+
* page size reuses {@link pageNumber} and is bounded by the same cap the roster
|
|
436
|
+
* delta window retains ({@link ROSTER_DELTA_MAX_ROWS}), so no second limit is
|
|
437
|
+
* invented here. A value that cannot be honoured — a page size of zero,
|
|
438
|
+
* negative, fractional or past that cap, an `after` that is not an id, a `cwd`
|
|
439
|
+
* that is not a boolean — is refused rather than clamped, so a caller never
|
|
440
|
+
* mistakes a silently reduced page for the one it asked for.
|
|
441
|
+
* @param payload - the request's `p`.
|
|
442
|
+
* @returns the parameters, or `ok` with no `compact` member when there are none.
|
|
443
|
+
*/
|
|
444
|
+
function rosterCompactOf(payload: Readonly<Record<string, unknown>>): { readonly ok: true; readonly compact?: RosterCompact } | CallFailure {
|
|
445
|
+
const { cwd: rawCwd, maxRows: rawRows, after: rawAfter } = payload
|
|
446
|
+
if (rawCwd === undefined && rawRows === undefined && rawAfter === undefined) return { ok: true }
|
|
447
|
+
if (rawCwd !== undefined && typeof rawCwd !== 'boolean') return refusal(CODE_INVALID_ARGS, 'session.list cwd must be a boolean')
|
|
448
|
+
let maxRows: number | undefined
|
|
449
|
+
if (rawRows !== undefined) {
|
|
450
|
+
maxRows = pageNumber(rawRows)
|
|
451
|
+
if (maxRows === undefined || maxRows < 1 || maxRows > ROSTER_DELTA_MAX_ROWS) {
|
|
452
|
+
return refusal(CODE_INVALID_ARGS, `session.list maxRows must be between 1 and ${ROSTER_DELTA_MAX_ROWS}`)
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const after = rawAfter === undefined ? undefined : optionalText(rawAfter)
|
|
456
|
+
if (rawAfter !== undefined && after === undefined) return refusal(CODE_INVALID_ARGS, 'session.list after must be a non-empty session id')
|
|
457
|
+
return {
|
|
458
|
+
ok: true,
|
|
459
|
+
compact: {
|
|
460
|
+
...(maxRows === undefined ? {} : { maxRows }),
|
|
461
|
+
...(after === undefined ? {} : { after }),
|
|
462
|
+
cwd: rawCwd === true,
|
|
463
|
+
},
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
209
467
|
/**
|
|
210
468
|
* Read the capability names a `hello` announced.
|
|
211
469
|
*
|
|
@@ -246,15 +504,23 @@ function answersOf(value: unknown): readonly QuestionAnswerItem[] | undefined {
|
|
|
246
504
|
return answers
|
|
247
505
|
}
|
|
248
506
|
|
|
249
|
-
/**
|
|
250
|
-
|
|
507
|
+
/**
|
|
508
|
+
* One model selection, in the field names the protocol publishes.
|
|
509
|
+
*
|
|
510
|
+
* Exported beside {@link selectionOf} and {@link modelSelectionOf} because the
|
|
511
|
+
* host half resolves a session's current route for `usage.stats`'s neighbour
|
|
512
|
+
* key `usage.session`/`modelContextWindow` with exactly this fold: two readings
|
|
513
|
+
* of "which model is this session on" would let the two methods name different
|
|
514
|
+
* routes for the same session.
|
|
515
|
+
*/
|
|
516
|
+
export type ModelSelection = {
|
|
251
517
|
readonly provider: string
|
|
252
518
|
readonly model: string
|
|
253
519
|
readonly reasoningEffort?: string
|
|
254
520
|
}
|
|
255
521
|
|
|
256
522
|
/** @returns the selection this value describes, or undefined when it describes none. */
|
|
257
|
-
function selectionOf(value: unknown): ModelSelection | undefined {
|
|
523
|
+
export function selectionOf(value: unknown): ModelSelection | undefined {
|
|
258
524
|
if (!isRecord(value)) return undefined
|
|
259
525
|
const provider = optionalText(value.provider)
|
|
260
526
|
const model = optionalText(value.model)
|
|
@@ -269,7 +535,7 @@ function selectionOf(value: unknown): ModelSelection | undefined {
|
|
|
269
535
|
* Both halves stay optional: a session that never ran has neither, and the
|
|
270
536
|
* catalog default is then the only truthful current value.
|
|
271
537
|
*/
|
|
272
|
-
function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
|
|
538
|
+
export function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
|
|
273
539
|
if (!isRecord(value) || !isRecord(value.values)) return {}
|
|
274
540
|
const selection = value.values.modelSelection
|
|
275
541
|
if (!isRecord(selection)) return {}
|
|
@@ -330,7 +596,15 @@ function promptAttachmentsOf(value: unknown): PromptAttachments {
|
|
|
330
596
|
* one frame at a time by the carrier's reader, and the only background work is
|
|
331
597
|
* a subscription's own drain loop.
|
|
332
598
|
*/
|
|
599
|
+
/**
|
|
600
|
+
* Monotonic source for {@link BridgeConnection.id}. The counter is process-wide
|
|
601
|
+
* and never reused, so a plugin keying connection-scoped state can trust that a
|
|
602
|
+
* reclaimed id belongs to no later socket.
|
|
603
|
+
*/
|
|
604
|
+
let connectionSeq = 0
|
|
605
|
+
|
|
333
606
|
export class BridgeConnection {
|
|
607
|
+
readonly #id = `c${connectionSeq += 1}`
|
|
334
608
|
readonly #options: BridgeConnectionOptions
|
|
335
609
|
readonly #transport: BridgeTransport
|
|
336
610
|
readonly #sequence = new EventSequence()
|
|
@@ -341,10 +615,41 @@ export class BridgeConnection {
|
|
|
341
615
|
#capabilities: ReadonlySet<string> = new Set()
|
|
342
616
|
/** Delegated children this connection has learned the durable parent of, by child id. */
|
|
343
617
|
readonly #lineage = new Map<string, string>()
|
|
618
|
+
/**
|
|
619
|
+
* Sessions this connection may read: the ordinary sessions the host's roster
|
|
620
|
+
* names, plus every session this connection already opened. A delegated child
|
|
621
|
+
* belongs here only once it has been opened itself, never because the roster
|
|
622
|
+
* merely names it.
|
|
623
|
+
*/
|
|
624
|
+
readonly #authorized = new Set<string>()
|
|
625
|
+
/**
|
|
626
|
+
* The job scopes this connection asked about, by {@link scopeKey}, with the
|
|
627
|
+
* disposer of each watch. A scope is watched exactly while this connection has
|
|
628
|
+
* listed it: that is what keeps a declared capability from turning into a
|
|
629
|
+
* subscription the client never requested.
|
|
630
|
+
*/
|
|
631
|
+
readonly #jobWatches = new Map<string, () => void>()
|
|
632
|
+
/**
|
|
633
|
+
* The `updatedAt` this connection already sent per session id, for the
|
|
634
|
+
* compact roster: a row whose value this client holds is answered without it.
|
|
635
|
+
* Pruned to the roster on every compact answer, so it is bounded by the set it
|
|
636
|
+
* describes rather than by every id the connection ever listed.
|
|
637
|
+
*/
|
|
638
|
+
readonly #rosterUpdatedAt = new Map<string, number>()
|
|
639
|
+
/** The last roster payload this connection received per scope key, for whole-set dedupe. */
|
|
640
|
+
readonly #jobSeen = new Map<string, string>()
|
|
641
|
+
/**
|
|
642
|
+
* This connection's delta windows, one per set it is served incrementally.
|
|
643
|
+
* Held here so the base is released exactly when the connection is, and so no
|
|
644
|
+
* two connections can ever diff against each other's set.
|
|
645
|
+
*/
|
|
646
|
+
readonly #deltas = new RemoteBridgeDeltas()
|
|
344
647
|
#lineageRead = false
|
|
345
648
|
#deviceId: string | undefined
|
|
346
649
|
#nonce: { readonly value: string; readonly expiresAt: number } | undefined
|
|
347
650
|
#heartbeat: NodeJS.Timeout | undefined
|
|
651
|
+
/** The deadline armed by the liveness ping currently outstanding, if any. */
|
|
652
|
+
#liveness: NodeJS.Timeout | undefined
|
|
348
653
|
#lastSendAt = 0
|
|
349
654
|
#disposed = false
|
|
350
655
|
|
|
@@ -370,6 +675,14 @@ export class BridgeConnection {
|
|
|
370
675
|
return this.#disposed
|
|
371
676
|
}
|
|
372
677
|
|
|
678
|
+
/**
|
|
679
|
+
* @returns this connection's identity for the extension seam. Stable for the
|
|
680
|
+
* life of the socket and never reused by a later one.
|
|
681
|
+
*/
|
|
682
|
+
get id(): string {
|
|
683
|
+
return this.#id
|
|
684
|
+
}
|
|
685
|
+
|
|
373
686
|
/**
|
|
374
687
|
* @param capability - one capability name this protocol defines.
|
|
375
688
|
* @returns whether this connection announced it in `hello`.
|
|
@@ -383,7 +696,11 @@ export class BridgeConnection {
|
|
|
383
696
|
if (this.#heartbeat !== undefined) return
|
|
384
697
|
const period = this.#options.heartbeatMs ?? IDLE_PING_MS
|
|
385
698
|
this.#heartbeat = setInterval(() => {
|
|
386
|
-
if (this.#options.now() - this.#lastSendAt
|
|
699
|
+
if (this.#options.now() - this.#lastSendAt < period) return
|
|
700
|
+
this.#send({ t: 'ping', ts: this.#options.now() })
|
|
701
|
+
// The ping is out, so the peer now owes an answer: a peer that went
|
|
702
|
+
// silent without closing its socket is exactly what this deadline finds.
|
|
703
|
+
this.#armLivenessDeadline()
|
|
387
704
|
}, period)
|
|
388
705
|
this.#heartbeat.unref?.()
|
|
389
706
|
}
|
|
@@ -401,6 +718,9 @@ export class BridgeConnection {
|
|
|
401
718
|
*/
|
|
402
719
|
async handleText(text: string): Promise<void> {
|
|
403
720
|
if (this.#disposed) return
|
|
721
|
+
// Any frame at all proves the peer is alive, so it satisfies the deadline
|
|
722
|
+
// behind the outstanding ping — a pong that answers no ping included.
|
|
723
|
+
this.#clearLivenessDeadline()
|
|
404
724
|
const outcome = decodeClientFrame(text)
|
|
405
725
|
if (!outcome.ok) {
|
|
406
726
|
this.#send(errorFrame(outcome.id, outcome.code, outcome.msg))
|
|
@@ -431,40 +751,156 @@ export class BridgeConnection {
|
|
|
431
751
|
* Tear the connection down: stop the heartbeat, abort every follow stream it
|
|
432
752
|
* owns, and tell the carrier to go away. Idempotent, and safe to call from a
|
|
433
753
|
* socket error handler — a carrier whose socket already closed ignores it.
|
|
754
|
+
* @param close - the close frame to send instead of the bridge-unloading one.
|
|
755
|
+
* Only the liveness deadline passes it, so a client can tell a peer that
|
|
756
|
+
* stopped answering from an ordinary teardown; every other caller leaves it
|
|
757
|
+
* out and keeps the same code and reason as before.
|
|
434
758
|
*/
|
|
435
|
-
dispose(): void {
|
|
759
|
+
dispose(close?: { readonly code: number; readonly reason: string }): void {
|
|
436
760
|
if (this.#disposed) return
|
|
437
761
|
this.#disposed = true
|
|
762
|
+
this.#clearLivenessDeadline()
|
|
438
763
|
if (this.#heartbeat !== undefined) {
|
|
439
764
|
clearInterval(this.#heartbeat)
|
|
440
765
|
this.#heartbeat = undefined
|
|
441
766
|
}
|
|
442
767
|
for (const subscription of this.#subscriptions.values()) subscription.controller.abort()
|
|
443
768
|
this.#subscriptions.clear()
|
|
769
|
+
// A scope nobody left can read must stop costing the host a read per burst.
|
|
770
|
+
for (const dispose of this.#jobWatches.values()) dispose()
|
|
771
|
+
this.#jobWatches.clear()
|
|
772
|
+
this.#jobSeen.clear()
|
|
773
|
+
// A dropped connection's incremental bases are released with it: a token it
|
|
774
|
+
// was given names nothing afterwards, and nothing here outlives its socket.
|
|
775
|
+
this.#deltas.clear()
|
|
444
776
|
// The bridge itself may be unloading with live sockets: the client is told
|
|
445
777
|
// the endpoint is going away instead of being left on a dead protocol.
|
|
446
|
-
this.#transport.close(1001, 'the bridge is going away')
|
|
778
|
+
this.#transport.close(close?.code ?? 1001, close?.reason ?? 'the bridge is going away')
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** Arm the deadline behind one liveness ping, replacing any earlier one. */
|
|
782
|
+
#armLivenessDeadline(): void {
|
|
783
|
+
this.#clearLivenessDeadline()
|
|
784
|
+
this.#liveness = setTimeout(() => {
|
|
785
|
+
this.#options.log(`connection closed on the liveness deadline: no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`)
|
|
786
|
+
this.dispose({
|
|
787
|
+
code: CLOSE_LIVENESS_TIMEOUT,
|
|
788
|
+
reason: `no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`,
|
|
789
|
+
})
|
|
790
|
+
}, LIVENESS_TIMEOUT_MS)
|
|
791
|
+
this.#liveness.unref?.()
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Drop the deadline: the peer answered, or the connection is already gone. */
|
|
795
|
+
#clearLivenessDeadline(): void {
|
|
796
|
+
if (this.#liveness === undefined) return
|
|
797
|
+
clearTimeout(this.#liveness)
|
|
798
|
+
this.#liveness = undefined
|
|
447
799
|
}
|
|
448
800
|
|
|
449
801
|
async #dispatch(frame: ReqFrame): Promise<DispatchOutcome> {
|
|
450
|
-
|
|
802
|
+
const builtIn = KNOWN_METHODS.has(frame.m)
|
|
803
|
+
// A method no plugin registered is refused here, before the pairing gate, so
|
|
804
|
+
// the answer costs no plugin lookup and names the method the client invented.
|
|
805
|
+
if (!builtIn && this.#options.extensions?.has(frame.m) !== true) {
|
|
806
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
807
|
+
}
|
|
451
808
|
// `question.answer` exists only for a client that asked for the question
|
|
452
809
|
// channel: without the capability it is an unknown method, which is exactly
|
|
453
810
|
// what this frame was before the channel existed.
|
|
454
811
|
if (frame.m === METHOD_QUESTION_ANSWER && !this.declares(CAP_QUESTIONS)) {
|
|
455
812
|
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
456
813
|
}
|
|
814
|
+
// `question.list` is its own channel capability, declared by the client and
|
|
815
|
+
// announced by the bridge: a client that never declared it is told what it was
|
|
816
|
+
// told before the method existed, and no claim registry is read on its behalf.
|
|
817
|
+
if (frame.m === METHOD_QUESTION_LIST && !this.declares(CAP_QUESTION_LIST)) {
|
|
818
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
819
|
+
}
|
|
820
|
+
// `jobs.list` is the whole of the job channel: without the capability the
|
|
821
|
+
// method does not exist, and without the method no scope is ever watched, so
|
|
822
|
+
// a client that never declared it can receive no `jobs.changed` either.
|
|
823
|
+
if (frame.m === METHOD_JOBS_LIST && !this.declares(CAP_JOBS)) {
|
|
824
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
825
|
+
}
|
|
826
|
+
// The agent channel is one capability: without `agents.v1` neither the preset
|
|
827
|
+
// roster nor session creation is part of this client's protocol, so a client
|
|
828
|
+
// that predates them is told what it was told before they existed.
|
|
829
|
+
if ((frame.m === METHOD_PRESETS_LIST || frame.m === METHOD_SESSION_CREATE) && !this.declares(CAP_AGENTS)) {
|
|
830
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
831
|
+
}
|
|
832
|
+
// Forking one session into another exists only for a client that declared
|
|
833
|
+
// the fork channel: without it the method is what it was before the channel
|
|
834
|
+
// existed, and the host is asked nothing on that client's behalf.
|
|
835
|
+
if (frame.m === METHOD_SESSION_FORK && !this.declares(CAP_SESSION_FORK)) {
|
|
836
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
837
|
+
}
|
|
838
|
+
// The command channel is one capability: without `commands.v1` neither the
|
|
839
|
+
// directory nor the dispatch is part of this client's protocol, so no
|
|
840
|
+
// registry and no skill catalog is read on a client's behalf that never
|
|
841
|
+
// asked for either.
|
|
842
|
+
if ((frame.m === METHOD_SESSION_COMMANDS || frame.m === METHOD_SESSION_COMMAND) && !this.declares(CAP_COMMANDS)) {
|
|
843
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
844
|
+
}
|
|
845
|
+
// Reading workspaces is its own capability, apart from the five writes beside
|
|
846
|
+
// it: a client may ask what this host has and where without ever renaming,
|
|
847
|
+
// pinning or archiving anything, so the reading half is declared on its own
|
|
848
|
+
// and a client that declared only the writing half reads no registry.
|
|
849
|
+
if (frame.m === METHOD_WORKSPACE_LIST && !this.declares(CAP_WORKSPACE)) {
|
|
850
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
851
|
+
}
|
|
852
|
+
// The session-admin writes are one capability: without it none of the five is
|
|
853
|
+
// part of this client's protocol, so no title is written and no set is
|
|
854
|
+
// mutated on behalf of a client that predates the channel.
|
|
855
|
+
if (!this.declares(CAP_SESSION_ADMIN)
|
|
856
|
+
&& (frame.m === METHOD_SESSION_RENAME
|
|
857
|
+
|| frame.m === METHOD_SESSION_PIN
|
|
858
|
+
|| frame.m === METHOD_SESSION_UNPIN
|
|
859
|
+
|| frame.m === METHOD_SESSION_ARCHIVE
|
|
860
|
+
|| frame.m === METHOD_SESSION_UNARCHIVE)) {
|
|
861
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
862
|
+
}
|
|
863
|
+
// The squads channel is one capability: without `squads.v1` none of the five
|
|
864
|
+
// commands is part of this client's protocol, so no squad domain is read and
|
|
865
|
+
// no session is launched on behalf of a client that never asked to drive one.
|
|
866
|
+
if (SQUAD_METHODS.has(frame.m) && !this.declares(CAP_SQUADS)) {
|
|
867
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
868
|
+
}
|
|
869
|
+
// Registering an APNs token is its own capability: without `push.v1` the
|
|
870
|
+
// method does not exist for this client, and no device row is written on its
|
|
871
|
+
// behalf. The capability gates the WRITE only — whether a notification ever
|
|
872
|
+
// leaves this process is a deployment fact the wire cannot express (§28.3).
|
|
873
|
+
if (frame.m === METHOD_PUSH_REGISTER && !this.declares(CAP_PUSH)) {
|
|
874
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
875
|
+
}
|
|
876
|
+
// 用量通道是一个能力:不宣告 `usage.v1` 的客户端看到的仍是它从前看到的
|
|
877
|
+
// `unknown-method`,本桥也不会替它折一条会话事件、更不会替它打一次上游
|
|
878
|
+
// 余额端点。
|
|
879
|
+
if (USAGE_METHODS.has(frame.m) && !this.declares(CAP_USAGE)) {
|
|
880
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
881
|
+
}
|
|
882
|
+
// 台账聚合是另一个能力,因为它读的是另一个插件挂在这个宿主上的路由:不宣告
|
|
883
|
+
// `usage.stats.v1` 的客户端看不到这个方法,本桥也不会替它去读那两条路由。
|
|
884
|
+
if (frame.m === METHOD_USAGE_STATS && !this.declares(CAP_USAGE_STATS)) {
|
|
885
|
+
return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
886
|
+
}
|
|
457
887
|
// Unconditional: a loopback Host buys nothing here. Without a device token
|
|
458
888
|
// only the handshake and the two pairing steps run.
|
|
459
889
|
if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
|
|
890
|
+
// Extension methods run after both gates, so a registered name answers
|
|
891
|
+
// `unpaired` exactly as a protocol method does, and a client that never
|
|
892
|
+
// declared the capability is told the method does not exist rather than
|
|
893
|
+
// that it lacks rights to it.
|
|
894
|
+
if (!builtIn) return await this.#extension(frame)
|
|
460
895
|
switch (frame.m) {
|
|
461
896
|
case METHOD_HELLO: return this.#hello(frame.p)
|
|
462
897
|
case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p)
|
|
463
898
|
case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p)
|
|
464
|
-
case METHOD_SESSION_LIST: return await this.#sessionList()
|
|
899
|
+
case METHOD_SESSION_LIST: return await this.#sessionList(frame.p)
|
|
465
900
|
case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p)
|
|
466
901
|
case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id)
|
|
467
902
|
case METHOD_SESSION_HISTORY: return await this.#sessionHistory(frame.p, frame.id)
|
|
903
|
+
case METHOD_SESSION_HISTORY_DEEP: return await this.#sessionHistoryDeep(frame.p, frame.id)
|
|
468
904
|
case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p)
|
|
469
905
|
case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p)
|
|
470
906
|
case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id)
|
|
@@ -474,13 +910,68 @@ export class BridgeConnection {
|
|
|
474
910
|
case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
|
|
475
911
|
case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
|
|
476
912
|
case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
|
|
913
|
+
case METHOD_QUESTION_LIST: return this.#questionList(frame.p)
|
|
914
|
+
case METHOD_PUSH_REGISTER: return await this.#pushRegister(frame.p)
|
|
915
|
+
case METHOD_USAGE_SESSION: return await this.#usageSession(frame.p)
|
|
916
|
+
case METHOD_USAGE_BALANCE: return await this.#usageBalance(frame.p)
|
|
917
|
+
case METHOD_USAGE_STATS: return await this.#usageStats(frame.p)
|
|
918
|
+
case METHOD_JOBS_LIST: return await this.#jobsList(frame.p)
|
|
919
|
+
case METHOD_PRESETS_LIST: return await this.#presetsList()
|
|
920
|
+
case METHOD_SESSION_CREATE: return await this.#sessionCreate(frame.p)
|
|
921
|
+
case METHOD_SESSION_FORK: return await this.#sessionFork(frame.p)
|
|
922
|
+
case METHOD_SESSION_COMMANDS: return await this.#sessionCommands(frame.p)
|
|
923
|
+
case METHOD_SESSION_COMMAND: return await this.#sessionCommand(frame.p)
|
|
924
|
+
case METHOD_SQUADS_STATE: return await this.#squadsState()
|
|
925
|
+
case METHOD_SQUADS_LIST: return await this.#squadsProjection('squads')
|
|
926
|
+
case METHOD_SQUADS_RUNS: return await this.#squadsProjection('runs')
|
|
927
|
+
case METHOD_SQUADS_RUN_MEMBER: return await this.#squadsRunMember(frame.p)
|
|
928
|
+
case METHOD_SQUADS_RUN_SQUAD: return await this.#squadsRunSquad(frame.p)
|
|
929
|
+
case METHOD_WORKSPACE_LIST: return this.#workspaceList()
|
|
930
|
+
case METHOD_SESSION_RENAME: return await this.#sessionRename(frame.p)
|
|
931
|
+
case METHOD_SESSION_PIN: return await this.#sessionSetWrite(METHOD_SESSION_PIN, 'pinSession', frame.p)
|
|
932
|
+
case METHOD_SESSION_UNPIN: return await this.#sessionSetWrite(METHOD_SESSION_UNPIN, 'unpinSession', frame.p)
|
|
933
|
+
case METHOD_SESSION_ARCHIVE: return await this.#sessionArchive(frame.p)
|
|
934
|
+
case METHOD_SESSION_UNARCHIVE: return await this.#sessionSetWrite(METHOD_SESSION_UNARCHIVE, 'unarchiveSession', frame.p)
|
|
477
935
|
default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
478
936
|
}
|
|
479
937
|
}
|
|
480
938
|
|
|
939
|
+
/**
|
|
940
|
+
* Run one method a plugin registered on the extension seam.
|
|
941
|
+
*
|
|
942
|
+
* The plugin decides everything: whether the payload is usable, what an
|
|
943
|
+
* answer looks like, and which refusal codes exist in its own protocol. This
|
|
944
|
+
* bridge only forwards — and owns `internal`, because a handler that throws
|
|
945
|
+
* or answers nothing usable has left the client with no other honest code.
|
|
946
|
+
* @param frame - the request being served.
|
|
947
|
+
*/
|
|
948
|
+
async #extension(frame: ReqFrame): Promise<DispatchOutcome> {
|
|
949
|
+
const handler = this.#options.extensions?.handlerFor(frame.m, capability => this.declares(capability))
|
|
950
|
+
// Reached when the name is registered but this client never declared the
|
|
951
|
+
// capability: the method is not part of its protocol.
|
|
952
|
+
if (handler === undefined) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
|
|
953
|
+
try {
|
|
954
|
+
const result = await handler(frame.p, {
|
|
955
|
+
connectionId: this.#id,
|
|
956
|
+
declares: capability => this.declares(capability),
|
|
957
|
+
deltas: this.#deltas,
|
|
958
|
+
})
|
|
959
|
+
if (!isMethodResult(result)) return refusal(CODE_INTERNAL, `${frame.m} answered no result`)
|
|
960
|
+
return result.ok ? { ok: true, r: result.r } : refusal(result.code, result.msg)
|
|
961
|
+
} catch (error) {
|
|
962
|
+
// The plugin's own message is the diagnostic; the client is told the call
|
|
963
|
+
// failed in this bridge because no extension code would be truthful here.
|
|
964
|
+
this.#options.log(`${frame.m} failed: ${failureText(error)}`)
|
|
965
|
+
return refusal(CODE_INTERNAL, failureText(error))
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
|
|
481
969
|
#hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
|
|
482
970
|
if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
|
|
483
971
|
this.#capabilities = capabilitiesOf(payload.cap)
|
|
972
|
+
// The frame form is decided where the frame is written, so the carrier is
|
|
973
|
+
// told the one thing it cannot read for itself: what this peer can inflate.
|
|
974
|
+
this.#transport.frameDeflate?.(this.#capabilities.has(CAP_FRAME_DEFLATE))
|
|
484
975
|
// The hub replays anything this client can now receive but missed: a phone
|
|
485
976
|
// that connected after a question was raised has no other way to learn of it.
|
|
486
977
|
this.#options.onDeclare?.(this)
|
|
@@ -490,6 +981,7 @@ export class BridgeConnection {
|
|
|
490
981
|
proto: PROTO,
|
|
491
982
|
minor: MINOR,
|
|
492
983
|
server: SERVER_ID,
|
|
984
|
+
capabilities: [...SERVED_CAPABILITIES],
|
|
493
985
|
resume: 'snapshot',
|
|
494
986
|
auth: this.paired ? 'paired' : 'unpaired',
|
|
495
987
|
},
|
|
@@ -535,25 +1027,94 @@ export class BridgeConnection {
|
|
|
535
1027
|
return { ok: true, r: { deviceToken: enrollment.deviceToken, deviceId: enrollment.deviceId } }
|
|
536
1028
|
}
|
|
537
1029
|
|
|
538
|
-
|
|
1030
|
+
/**
|
|
1031
|
+
* Answer the roster as a whole set, as one compact page, or as the increment
|
|
1032
|
+
* since a token.
|
|
1033
|
+
*
|
|
1034
|
+
* `since` and the two answer modes exist only for a client that declared
|
|
1035
|
+
* {@link CAP_DELTA}: every other client is answered the roster it always was,
|
|
1036
|
+
* with `mode:"reset"` and an empty `token` beside it, and this connection
|
|
1037
|
+
* keeps no copy of a set that client cannot continue from.
|
|
1038
|
+
*
|
|
1039
|
+
* The compact form needs both halves: the capability, and at least one compact
|
|
1040
|
+
* parameter in the request. Either one alone is today's answer, which is what
|
|
1041
|
+
* keeps an older client — and a client that declared the name but asks for
|
|
1042
|
+
* nothing — byte identical to protocol v1.
|
|
1043
|
+
* @param payload - `{since?, cwd?, maxRows?, after?}`.
|
|
1044
|
+
*/
|
|
1045
|
+
async #sessionList(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1046
|
+
if (this.declares(CAP_ROSTER_COMPACT)) {
|
|
1047
|
+
const requested = rosterCompactOf(payload)
|
|
1048
|
+
if (!requested.ok) return requested
|
|
1049
|
+
const compact = requested.compact
|
|
1050
|
+
if (compact !== undefined) {
|
|
1051
|
+
// One answer is a whole page a client continues with `after`, the other
|
|
1052
|
+
// is an increment it continues with `token`; a request naming both bases
|
|
1053
|
+
// is refused rather than answered against one of them silently.
|
|
1054
|
+
if (sinceOf(payload) !== undefined) {
|
|
1055
|
+
return refusal(CODE_INVALID_ARGS, 'session.list cannot combine a compact page with a since token')
|
|
1056
|
+
}
|
|
1057
|
+
const compactRoster = await this.#readRoster()
|
|
1058
|
+
if (!compactRoster.ok) return compactRoster
|
|
1059
|
+
return { ok: true, r: this.#compactRoster(compactRoster.rows, compact) }
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
const roster = await this.#readRoster()
|
|
1063
|
+
if (!roster.ok) return roster
|
|
1064
|
+
if (!this.declares(CAP_DELTA)) {
|
|
1065
|
+
this.#deltas.drop('session.list')
|
|
1066
|
+
return { ok: true, r: { mode: 'reset', token: '', sessions: roster.rows } }
|
|
1067
|
+
}
|
|
1068
|
+
const answer = this.#deltas
|
|
1069
|
+
.window<SessionRow>('session.list', { maxRows: ROSTER_DELTA_MAX_ROWS })
|
|
1070
|
+
.answer(roster.rows, sinceOf(payload))
|
|
1071
|
+
return {
|
|
1072
|
+
ok: true,
|
|
1073
|
+
r: answer.mode === 'reset'
|
|
1074
|
+
? { mode: 'reset', token: answer.token, sessions: answer.rows }
|
|
1075
|
+
: { mode: 'delta', token: answer.token, changed: answer.changed, removed: answer.removed },
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/**
|
|
1080
|
+
* Read the roster once, as the host answers it.
|
|
1081
|
+
*
|
|
1082
|
+
* Deliberately separate from {@link #sessionList}: lineage and authorization
|
|
1083
|
+
* are learned from the same read, and an internal read must not consume or
|
|
1084
|
+
* advance this connection's incremental base.
|
|
1085
|
+
*/
|
|
1086
|
+
async #readRoster(): Promise<{ readonly ok: true; readonly rows: SessionRow[] } | CallFailure> {
|
|
539
1087
|
const call = await this.#unary('session', 'list')
|
|
540
1088
|
if (!call.ok) return call
|
|
541
1089
|
const items = isRecord(call.value) ? call.value.items : undefined
|
|
542
1090
|
if (!Array.isArray(items)) return refusal(CODE_INTERNAL, 'session/list returned no item table')
|
|
543
1091
|
// Read once for the whole roster: the archive flag comes from one process-wide
|
|
544
|
-
// set, and an unreadable registry leaves the key out of every row
|
|
1092
|
+
// set, and an unreadable registry leaves the key out of every row — and drops
|
|
1093
|
+
// nothing, because a bridge that cannot tell must not answer a shorter roster.
|
|
1094
|
+
// A row that survives therefore always carries `archived: false`: the key stays
|
|
1095
|
+
// in the schema even though no `true` crosses it any more.
|
|
545
1096
|
const archived = this.#options.sessionMeta.archiveSet()
|
|
546
1097
|
const sessions: SessionRow[] = []
|
|
547
1098
|
for (const item of items) {
|
|
548
1099
|
if (!isRecord(item) || typeof item.sessionId !== 'string') continue
|
|
1100
|
+
// An archived session is not part of the roster this connection is sent at
|
|
1101
|
+
// all: the phone hides such a row on arrival, so sending it is bytes paid
|
|
1102
|
+
// for nothing. Skipped before the row is built, so no field of it is read.
|
|
1103
|
+
// A live child keeps its own row, and with it the parent id that row names,
|
|
1104
|
+
// so an archived parent never costs a child its lineage; the follow gate
|
|
1105
|
+
// does notice, because that parent is no longer a session the roster names.
|
|
1106
|
+
if (archived?.has(item.sessionId) === true) continue
|
|
549
1107
|
const cwd = optionalText(item.cwd)
|
|
550
1108
|
const parentSessionId = optionalText(item.parentSessionId)
|
|
551
1109
|
sessions.push({
|
|
552
1110
|
id: item.sessionId,
|
|
553
|
-
// The
|
|
554
|
-
//
|
|
555
|
-
//
|
|
556
|
-
|
|
1111
|
+
// The row's own title. `SessionSummary` has no top-level `title`, but the
|
|
1112
|
+
// projection block beside it does — `projections.values.title` — and the
|
|
1113
|
+
// host answers that synchronously for a cold session too, which is the
|
|
1114
|
+
// field its own desktop list renders. The live-title cache is the
|
|
1115
|
+
// fallback for a row whose projection carries none, and no lookup is
|
|
1116
|
+
// spent here, so listing stays one call either way.
|
|
1117
|
+
title: projectedTitleOf(item) ?? this.#options.sessionMeta.cachedTitle(item.sessionId) ?? '',
|
|
557
1118
|
updatedAt: typeof item.updatedAt === 'number' ? item.updatedAt : 0,
|
|
558
1119
|
agentRunning: item.running === true,
|
|
559
1120
|
...(cwd === undefined ? {} : { cwd }),
|
|
@@ -567,7 +1128,77 @@ export class BridgeConnection {
|
|
|
567
1128
|
// child's durable parent is on its own row, so a client that lists before it
|
|
568
1129
|
// opens a session never costs a second read to address that session.
|
|
569
1130
|
this.#rememberLineage(sessions)
|
|
570
|
-
|
|
1131
|
+
// The workspace short name a notification carries is picked up from a roster
|
|
1132
|
+
// this bridge just served, because the alternative is a gateway read on the
|
|
1133
|
+
// notification path. Best effort by construction: a session never listed
|
|
1134
|
+
// simply produces a payload without `w`.
|
|
1135
|
+
this.#options.push?.noteSessions(sessions)
|
|
1136
|
+
// The same roster answers how many sessions are running, which is what a card
|
|
1137
|
+
// reports; the call returns before any delivery starts, so listing pays no
|
|
1138
|
+
// APNs round trip.
|
|
1139
|
+
this.#options.liveActivity?.noteRoster(sessions)
|
|
1140
|
+
return { ok: true, rows: sessions }
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/**
|
|
1144
|
+
* Answer one compact roster page out of the roster just read.
|
|
1145
|
+
*
|
|
1146
|
+
* Rows are ordered most recent first, with the id as the tiebreak, because a
|
|
1147
|
+
* cursor is only meaningful over an order that does not depend on the order
|
|
1148
|
+
* the host happened to answer in. `after` is exclusive and names the last row
|
|
1149
|
+
* the previous page carried; a cursor this roster no longer names is an
|
|
1150
|
+
* unknown base and answers a first page again, the way a delta token this
|
|
1151
|
+
* window never issued answers a reset, so the client continues from the page
|
|
1152
|
+
* it is given instead of stalling on an id that no longer exists.
|
|
1153
|
+
*
|
|
1154
|
+
* Three members are what makes the body shorter: `cwd` is present only when
|
|
1155
|
+
* the request asked for it, `updatedAt` only when this connection has not
|
|
1156
|
+
* already sent this id that exact value (a client keeps the one it holds), and
|
|
1157
|
+
* `nextAfter` only while the roster continues past this page. Every other
|
|
1158
|
+
* field of the row is today's, under today's names, so a page is the same
|
|
1159
|
+
* roster cut short rather than a second schema — and `compact:true` says which
|
|
1160
|
+
* schema the rows are in, so a client whose bookkeeping drifted can tell an
|
|
1161
|
+
* omitted `updatedAt` from one this bridge never had.
|
|
1162
|
+
* @param rows - the roster as the host answered it.
|
|
1163
|
+
* @param compact - the parameters this listing carried.
|
|
1164
|
+
*/
|
|
1165
|
+
#compactRoster(rows: readonly SessionRow[], compact: RosterCompact): Record<string, unknown> {
|
|
1166
|
+
const ordered = [...rows].sort((left, right) => (right.updatedAt - left.updatedAt)
|
|
1167
|
+
|| (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
|
|
1168
|
+
// A cursor that names no row of this roster resolves to -1, which is a first
|
|
1169
|
+
// page: the honest answer to a base this bridge cannot place.
|
|
1170
|
+
const from = compact.after === undefined ? 0 : ordered.findIndex(row => row.id === compact.after) + 1
|
|
1171
|
+
const end = compact.maxRows === undefined ? ordered.length : Math.min(ordered.length, from + compact.maxRows)
|
|
1172
|
+
const page = ordered.slice(from, end)
|
|
1173
|
+
const sessions = page.map(row => {
|
|
1174
|
+
const held = this.#rosterUpdatedAt.get(row.id) === row.updatedAt
|
|
1175
|
+
this.#rosterUpdatedAt.set(row.id, row.updatedAt)
|
|
1176
|
+
return {
|
|
1177
|
+
id: row.id,
|
|
1178
|
+
title: row.title,
|
|
1179
|
+
...(held ? {} : { updatedAt: row.updatedAt }),
|
|
1180
|
+
agentRunning: row.agentRunning,
|
|
1181
|
+
...(compact.cwd && row.cwd !== undefined ? { cwd: row.cwd } : {}),
|
|
1182
|
+
...(row.parentSessionId === undefined ? {} : { parentSessionId: row.parentSessionId }),
|
|
1183
|
+
...(row.origin === undefined ? {} : { origin: row.origin }),
|
|
1184
|
+
blank: row.blank,
|
|
1185
|
+
...(row.archived === undefined ? {} : { archived: row.archived }),
|
|
1186
|
+
}
|
|
1187
|
+
})
|
|
1188
|
+
// Bounded by the set it describes: an id this roster no longer names is gone
|
|
1189
|
+
// from the memory too, and a row that comes back simply carries its value.
|
|
1190
|
+
const current = new Set(rows.map(row => row.id))
|
|
1191
|
+
for (const id of this.#rosterUpdatedAt.keys()) {
|
|
1192
|
+
if (!current.has(id)) this.#rosterUpdatedAt.delete(id)
|
|
1193
|
+
}
|
|
1194
|
+
const last = page[page.length - 1]?.id
|
|
1195
|
+
return {
|
|
1196
|
+
mode: 'reset',
|
|
1197
|
+
token: '',
|
|
1198
|
+
compact: true,
|
|
1199
|
+
sessions,
|
|
1200
|
+
...(last === undefined || end >= ordered.length ? {} : { nextAfter: last }),
|
|
1201
|
+
}
|
|
571
1202
|
}
|
|
572
1203
|
|
|
573
1204
|
/**
|
|
@@ -606,32 +1237,137 @@ export class BridgeConnection {
|
|
|
606
1237
|
* than a refusal, and `snapshot-too-large` cannot answer such a connection.
|
|
607
1238
|
* The oldest entry's own `seq` is the `before` cursor for the next, older
|
|
608
1239
|
* page; no second field restates it.
|
|
609
|
-
*
|
|
1240
|
+
*
|
|
1241
|
+
* The budget is measured on the WHOLE answer — `{turns, lastSeq, hasMore}`
|
|
1242
|
+
* encoded as the `res` frame the client receives — and never per turn, so a
|
|
1243
|
+
* turn of many small entries is cut like any other run of entries. What it
|
|
1244
|
+
* does not bound is a single entry: `pageTurns` ends a page at an entry, never
|
|
1245
|
+
* inside one, so when the newest entry alone is past the budget that entry IS
|
|
1246
|
+
* the page and the answer is exactly as large as it is (measured: a 2.2 MB
|
|
1247
|
+
* newest message answers a 2.2 MB page against a 512 KiB budget, while the
|
|
1248
|
+
* same window of ordinary entries answers 513794 bytes). Trimming or splitting
|
|
1249
|
+
* such an entry would hand the client something other than what the session
|
|
1250
|
+
* says, and refusing it would take the session away from the very capability
|
|
1251
|
+
* that exists to open big sessions, so this is a stated bound of the page
|
|
1252
|
+
* budget rather than a defect to be closed by a smaller number elsewhere.
|
|
1253
|
+
* A client that declared {@link CAP_SESSION_SNAPSHOT_SINCE} and named
|
|
1254
|
+
* `sinceSeq` is answered incrementally instead: only the entries above that
|
|
1255
|
+
* durable watermark, in the same turn shape, with `mode:"since"` and
|
|
1256
|
+
* `reset:false`. When the bridge cannot PROVE the chain is unbroken — the
|
|
1257
|
+
* window's oldest entry has scrolled past the watermark — the answer is the
|
|
1258
|
+
* baseline below, carrying `mode:"full"` and `reset:true` so the client knows
|
|
1259
|
+
* to throw its copy away. Nothing else about this method moves: a request
|
|
1260
|
+
* without `sinceSeq`, or from a connection that never declared the capability,
|
|
1261
|
+
* is answered exactly the bytes protocol v1 answered before.
|
|
1262
|
+
* @param payload - `{sessionId, sinceSeq?, maxBytes?}`.
|
|
610
1263
|
* @param id - the request id the page budget is measured against.
|
|
611
1264
|
*/
|
|
612
1265
|
async #sessionSnapshot(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
|
|
613
1266
|
const sessionId = stringArg(payload, 'sessionId')
|
|
614
1267
|
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot requires sessionId')
|
|
1268
|
+
const unfollowable = await this.#unfollowable(sessionId)
|
|
1269
|
+
if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
|
|
615
1270
|
const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
|
|
616
1271
|
if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
|
|
617
1272
|
// A client that declared the trim capability chooses what it is sent, never
|
|
618
1273
|
// which turns it gets: the projection is trimmed inside each turn first, and
|
|
619
1274
|
// only then does any frame or page budget apply.
|
|
620
|
-
const
|
|
1275
|
+
const window = turnsOfRecords(opening.baseline.records)
|
|
1276
|
+
const projection = this.#trimmedFor(window)
|
|
1277
|
+
const lastSeq = opening.baseline.cursor
|
|
1278
|
+
// An incremental answer takes two declarations: the capability in the
|
|
1279
|
+
// handshake AND the watermark in this request. Every other request keeps
|
|
1280
|
+
// protocol v1's own answer, byte for byte, so a client can adopt the name
|
|
1281
|
+
// before it relies on any of it.
|
|
1282
|
+
if (payload.sinceSeq !== undefined && this.#capabilities.has(CAP_SESSION_SNAPSHOT_SINCE)) {
|
|
1283
|
+
const sinceSeq = pageNumber(payload.sinceSeq)
|
|
1284
|
+
if (sinceSeq === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot sinceSeq must be a non-negative integer')
|
|
1285
|
+
// A connection that declared the page capability declared the budget its
|
|
1286
|
+
// requests must carry, and an incremental request is one of its requests:
|
|
1287
|
+
// an unusable budget is refused here, so whether this reply ends up being
|
|
1288
|
+
// the increment or the baseline that spends the budget never decides it.
|
|
1289
|
+
if (this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
|
|
1290
|
+
const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
|
|
1291
|
+
if (!budget.ok) return budget
|
|
1292
|
+
}
|
|
1293
|
+
const incremental = this.#sinceAnswer(projection, window, sinceSeq, lastSeq, id)
|
|
1294
|
+
if (incremental !== undefined) return { ok: true, r: incremental }
|
|
1295
|
+
const baseline = this.#baselineAnswer(sessionId, projection, lastSeq, payload, id)
|
|
1296
|
+
if (!baseline.ok) return baseline
|
|
1297
|
+
return { ok: true, r: { ...baseline.r, mode: 'full', reset: true } }
|
|
1298
|
+
}
|
|
1299
|
+
return this.#baselineAnswer(sessionId, projection, lastSeq, payload, id)
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* The answer protocol v1 has always served: the whole window, or the newest
|
|
1304
|
+
* page of it for a connection that declared {@link CAP_SESSION_SNAPSHOT_PAGE}.
|
|
1305
|
+
*
|
|
1306
|
+
* One home for that answer, so an incremental request that has to fall back to
|
|
1307
|
+
* a full baseline is sent exactly the bytes it would have been sent without
|
|
1308
|
+
* asking — plus the two fields that say the client must reset.
|
|
1309
|
+
* @param sessionId - the session this baseline is of; the refusal names it.
|
|
1310
|
+
* @param projection - this connection's projection of the opening window.
|
|
1311
|
+
* @param lastSeq - the harness cursor the answer reports.
|
|
1312
|
+
* @param payload - the request, read only for `maxBytes`.
|
|
1313
|
+
* @param id - the request id any page budget is measured against.
|
|
1314
|
+
*/
|
|
1315
|
+
#baselineAnswer(
|
|
1316
|
+
sessionId: string,
|
|
1317
|
+
projection: readonly SnapshotTurn[],
|
|
1318
|
+
lastSeq: number,
|
|
1319
|
+
payload: Readonly<Record<string, unknown>>,
|
|
1320
|
+
id: number,
|
|
1321
|
+
): BaselineAnswer {
|
|
621
1322
|
if (!this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
|
|
622
1323
|
// Not declared: the whole window, shrunk by whole turns, unchanged.
|
|
623
|
-
const fitted = this.#fitTurns(projection,
|
|
1324
|
+
const fitted = this.#fitTurns(projection, lastSeq, id)
|
|
624
1325
|
if (fitted === undefined) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`)
|
|
625
1326
|
return { ok: true, r: { turns: fitted.turns, lastSeq: fitted.lastSeq } }
|
|
626
1327
|
}
|
|
627
1328
|
const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
|
|
628
1329
|
if (!budget.ok) return budget
|
|
629
|
-
const lastSeq = opening.baseline.cursor
|
|
630
1330
|
const page = pageTurns(projection, undefined, budget.maxBytes, (turns, _nextBefore, hasMore) =>
|
|
631
1331
|
Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, lastSeq, hasMore })), 'utf8'))
|
|
632
1332
|
return { ok: true, r: { turns: page.turns, lastSeq, hasMore: page.hasMore } }
|
|
633
1333
|
}
|
|
634
1334
|
|
|
1335
|
+
/**
|
|
1336
|
+
* Answer a snapshot that named a watermark, or hand back undefined when this
|
|
1337
|
+
* request has to be answered with the full baseline instead.
|
|
1338
|
+
*
|
|
1339
|
+
* The continuity proof is the whole contract, and it reads the WINDOW rather
|
|
1340
|
+
* than the trimmed projection: an entry the client never renders is still an
|
|
1341
|
+
* entry the window holds, and continuing past a watermark below it would hand
|
|
1342
|
+
* the client a view it cannot attach to what it already has. Only the window's
|
|
1343
|
+
* own oldest entry can say whether anything between that watermark and this
|
|
1344
|
+
* window is missing, and `oldest <= sinceSeq + 1` is the one case where nothing
|
|
1345
|
+
* is; an empty window proves it trivially, because there is nothing to lose. A
|
|
1346
|
+
* reset is always correct, so an unprovable window takes the safe answer.
|
|
1347
|
+
*
|
|
1348
|
+
* The bound this form still carries is the frame cap: a delta that cannot
|
|
1349
|
+
* cross one frame answers the baseline instead of a refusal, because the
|
|
1350
|
+
* client's recovery from a hole is the `reset` flag, not a failed request.
|
|
1351
|
+
* @param projection - the projection the incremental turns are cut from.
|
|
1352
|
+
* @param window - the same window before trimming, read for its oldest entry.
|
|
1353
|
+
* @param sinceSeq - the durable watermark the client already holds.
|
|
1354
|
+
* @param lastSeq - the harness cursor the answer reports.
|
|
1355
|
+
* @param id - the request id the frame cap is measured against.
|
|
1356
|
+
*/
|
|
1357
|
+
#sinceAnswer(
|
|
1358
|
+
projection: readonly SnapshotTurn[],
|
|
1359
|
+
window: readonly SnapshotTurn[],
|
|
1360
|
+
sinceSeq: number,
|
|
1361
|
+
lastSeq: number,
|
|
1362
|
+
id: number,
|
|
1363
|
+
): { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number; readonly mode: 'since'; readonly reset: false } | undefined {
|
|
1364
|
+
const oldest = oldestEntrySeq(window)
|
|
1365
|
+
if (oldest !== undefined && oldest > sinceSeq + 1) return undefined
|
|
1366
|
+
const answer = { turns: turnsAbove(projection, sinceSeq), lastSeq, mode: 'since' as const, reset: false as const }
|
|
1367
|
+
if (Buffer.byteLength(JSON.stringify(responseFrame(id, answer)), 'utf8') > MAX_FRAME_BYTES) return undefined
|
|
1368
|
+
return answer
|
|
1369
|
+
}
|
|
1370
|
+
|
|
635
1371
|
/**
|
|
636
1372
|
* Read one backwards page of a session's history.
|
|
637
1373
|
*
|
|
@@ -652,6 +1388,8 @@ export class BridgeConnection {
|
|
|
652
1388
|
}
|
|
653
1389
|
const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY)
|
|
654
1390
|
if (!budget.ok) return budget
|
|
1391
|
+
const unfollowable = await this.#unfollowable(sessionId)
|
|
1392
|
+
if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
|
|
655
1393
|
const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
|
|
656
1394
|
if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
|
|
657
1395
|
const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) =>
|
|
@@ -666,10 +1404,127 @@ export class BridgeConnection {
|
|
|
666
1404
|
}
|
|
667
1405
|
}
|
|
668
1406
|
|
|
1407
|
+
/**
|
|
1408
|
+
* Read one backwards page of a session's DURABLE history.
|
|
1409
|
+
*
|
|
1410
|
+
* `session.history` slices the follow window this connection holds, and that
|
|
1411
|
+
* window is only as wide as the harness was asked to open it (200 messages), so
|
|
1412
|
+
* a client that scrolls past it has no older page to ask for. This method reads
|
|
1413
|
+
* the session store itself: one `session/page` call walked backwards with
|
|
1414
|
+
* `beforeSeq`, with no follow stream and no window involved.
|
|
1415
|
+
*
|
|
1416
|
+
* It is a pure read in the same sense `session.history` is: nothing is
|
|
1417
|
+
* subscribed, remembered, dropped or re-addressed, so the same `before`
|
|
1418
|
+
* answers the same page and reading cannot change what the session is.
|
|
1419
|
+
* @param payload - `{sessionId, before?, maxBytes?}`.
|
|
1420
|
+
* @param id - the request id the page budget is measured against.
|
|
1421
|
+
*/
|
|
1422
|
+
async #sessionHistoryDeep(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
|
|
1423
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1424
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.history.deep requires sessionId')
|
|
1425
|
+
const before = payload.before === undefined ? undefined : pageNumber(payload.before)
|
|
1426
|
+
if (payload.before !== undefined && before === undefined) {
|
|
1427
|
+
return refusal(CODE_INVALID_ARGS, 'session.history.deep before must be a non-negative integer')
|
|
1428
|
+
}
|
|
1429
|
+
const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY_DEEP)
|
|
1430
|
+
if (!budget.ok) return budget
|
|
1431
|
+
// The same fence every other history read passes, and it runs before any
|
|
1432
|
+
// store call: a child this connection may not read costs no read at all.
|
|
1433
|
+
const unfollowable = await this.#unfollowable(sessionId)
|
|
1434
|
+
if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
|
|
1435
|
+
const cut = await this.#durableCutOf(sessionId)
|
|
1436
|
+
if (!cut.ok) return cut
|
|
1437
|
+
const store = await this.#storePageOf(sessionId, cut.cut, before)
|
|
1438
|
+
if (!store.ok) return store
|
|
1439
|
+
const projection = turnsOfRecords(store.records)
|
|
1440
|
+
const oldestOf = (turns: readonly SnapshotTurn[]): number | undefined => turns[0]?.entries[0]?.seq
|
|
1441
|
+
const page = pageTurns(projection, before, budget.maxBytes, (turns, nextBefore, hasMore) => {
|
|
1442
|
+
// The measured frame is the ANSWER, not the store read: a store page that
|
|
1443
|
+
// ends short of the session's oldest entry still leaves older entries
|
|
1444
|
+
// behind the answer, and the cursor is the answer's own oldest entry.
|
|
1445
|
+
const more = hasMore || store.hasMore
|
|
1446
|
+
const cursor = more ? nextBefore ?? oldestOf(turns) : undefined
|
|
1447
|
+
return Buffer.byteLength(JSON.stringify(responseFrame(id, {
|
|
1448
|
+
turns,
|
|
1449
|
+
...(cursor === undefined ? {} : { nextBefore: cursor }),
|
|
1450
|
+
hasMore: more,
|
|
1451
|
+
})), 'utf8')
|
|
1452
|
+
})
|
|
1453
|
+
if (page.turns.length === 0) return { ok: true, r: { turns: [], hasMore: false } }
|
|
1454
|
+
const hasMore = page.hasMore || store.hasMore
|
|
1455
|
+
const nextBefore = page.nextBefore ?? oldestOf(page.turns)
|
|
1456
|
+
return {
|
|
1457
|
+
ok: true,
|
|
1458
|
+
r: {
|
|
1459
|
+
turns: page.turns,
|
|
1460
|
+
...(hasMore && nextBefore !== undefined ? { nextBefore } : {}),
|
|
1461
|
+
hasMore,
|
|
1462
|
+
},
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
/**
|
|
1467
|
+
* The inclusive log cut one durable page read names.
|
|
1468
|
+
*
|
|
1469
|
+
* `session/page` takes that cut as `throughSeq` and refuses one the store does
|
|
1470
|
+
* not hold, so a page read has to name a seq the session actually has. The
|
|
1471
|
+
* projection watermark is that seq: the cut every finished projection value has
|
|
1472
|
+
* folded through, read from the non-activating projection service
|
|
1473
|
+
* `session.models` already uses. `-1` is the harness's own name for a log with
|
|
1474
|
+
* no events at all, and the store answers it with an empty page.
|
|
1475
|
+
*/
|
|
1476
|
+
async #durableCutOf(sessionId: string): Promise<{ readonly ok: true; readonly cut: number } | CallFailure> {
|
|
1477
|
+
const call = await this.#unary('session', 'projections', { sessionId })
|
|
1478
|
+
if (!call.ok) return call
|
|
1479
|
+
const cut = isRecord(call.value) ? call.value.asOfSeq : undefined
|
|
1480
|
+
if (typeof cut !== 'number' || !Number.isSafeInteger(cut) || cut < -1) {
|
|
1481
|
+
return refusal(CODE_SNAPSHOT_UNAVAILABLE, `session ${sessionId} reported no durable cut to page from`)
|
|
1482
|
+
}
|
|
1483
|
+
return { ok: true, cut }
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
/**
|
|
1487
|
+
* Read one span of a session's durable history, at the address the harness demands.
|
|
1488
|
+
*
|
|
1489
|
+
* A delegated child is addressable only through its durable parent, and the
|
|
1490
|
+
* harness answers `session/agent-busy` when it is asked as an ordinary session.
|
|
1491
|
+
* That refusal is the one signal that distinguishes it from a real failure, so
|
|
1492
|
+
* it is the only one that triggers the roster lookup and the retry — the same
|
|
1493
|
+
* resolution {@link #openSubscription} performs for the follow stream.
|
|
1494
|
+
*/
|
|
1495
|
+
async #storePageOf(sessionId: string, cut: number, before: number | undefined): Promise<{ readonly ok: true; readonly records: readonly unknown[]; readonly hasMore: boolean } | CallFailure> {
|
|
1496
|
+
let call = await this.#pageCall(this.#addressOf(sessionId), cut, before)
|
|
1497
|
+
if (!call.ok && call.code === CODE_SUBAGENT_ADDRESS_REQUIRED) {
|
|
1498
|
+
const parent = await this.#parentOf(sessionId)
|
|
1499
|
+
if (parent === undefined) return call
|
|
1500
|
+
this.#lineage.set(sessionId, parent)
|
|
1501
|
+
call = await this.#pageCall(subagentAddress(parent, sessionId), cut, before)
|
|
1502
|
+
}
|
|
1503
|
+
if (!call.ok) return call
|
|
1504
|
+
const value = call.value
|
|
1505
|
+
const records = isRecord(value) && Array.isArray(value.records) ? value.records as readonly unknown[] : undefined
|
|
1506
|
+
if (records === undefined) return refusal(CODE_INTERNAL, 'session/page answered no records')
|
|
1507
|
+
return { ok: true, records, hasMore: isRecord(value) && value.hasMore === true }
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/** One `session/page` call at one resolved address. */
|
|
1511
|
+
async #pageCall(address: SessionAddress, cut: number, before: number | undefined) {
|
|
1512
|
+
return await this.#unary('session', 'page', {
|
|
1513
|
+
address,
|
|
1514
|
+
throughSeq: cut,
|
|
1515
|
+
...(before === undefined ? {} : { beforeSeq: before }),
|
|
1516
|
+
...DEEP_HISTORY_WINDOW,
|
|
1517
|
+
})
|
|
1518
|
+
}
|
|
1519
|
+
|
|
669
1520
|
/** The projection a baseline is served with: trimmed only for a client that asked for it. */
|
|
670
|
-
#projectionOf(records: readonly unknown[]): SnapshotTurn[] {
|
|
671
|
-
|
|
672
|
-
|
|
1521
|
+
#projectionOf(records: readonly unknown[]): readonly SnapshotTurn[] {
|
|
1522
|
+
return this.#trimmedFor(turnsOfRecords(records))
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
/** Drop the bookkeeping entries only for a client that declared the trim capability. */
|
|
1526
|
+
#trimmedFor(turns: readonly SnapshotTurn[]): readonly SnapshotTurn[] {
|
|
1527
|
+
return this.#capabilities.has(CAP_SESSION_SNAPSHOT_TRIM) ? trimUnrenderedEntries(turns) : turns
|
|
673
1528
|
}
|
|
674
1529
|
|
|
675
1530
|
async #sessionPrompt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
@@ -823,6 +1678,339 @@ export class BridgeConnection {
|
|
|
823
1678
|
return { ok: true, r: { ok: true, current: selected } }
|
|
824
1679
|
}
|
|
825
1680
|
|
|
1681
|
+
/**
|
|
1682
|
+
* Answer `presets.list`: the host's Agent-preset roster, forwarded verbatim.
|
|
1683
|
+
*
|
|
1684
|
+
* The bridge has no vocabulary of its own for a preset — a row is whatever
|
|
1685
|
+
* `agentPresets/list` publishes, and that endpoint takes no request — so the
|
|
1686
|
+
* answer crosses exactly as the host wrote it, down to the keys a client of
|
|
1687
|
+
* this version does not read.
|
|
1688
|
+
*/
|
|
1689
|
+
async #presetsList(): Promise<DispatchOutcome> {
|
|
1690
|
+
const call = await this.#unary('agentPresets', 'list')
|
|
1691
|
+
return call.ok ? { ok: true, r: call.value } : call
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
/**
|
|
1695
|
+
* Answer `session.create`: hand the client's request to the host unchanged.
|
|
1696
|
+
*
|
|
1697
|
+
* A preset instantiated as an Agent is a host decision about a body this
|
|
1698
|
+
* bridge does not model — the field names, the defaults and the refusals
|
|
1699
|
+
* belong to `SessionCreateRequest` and to the host that validates it — so the
|
|
1700
|
+
* payload and the answer cross verbatim. Nothing is required here, renamed, or
|
|
1701
|
+
* defaulted: a request the host rejects is rejected with the host's own code
|
|
1702
|
+
* and text.
|
|
1703
|
+
* @param request - the host's `SessionCreateRequest`, exactly as the client wrote it.
|
|
1704
|
+
*/
|
|
1705
|
+
async #sessionCreate(request: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1706
|
+
const call = await this.#unary('session', 'create', request)
|
|
1707
|
+
return call.ok ? { ok: true, r: call.value } : call
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
/**
|
|
1711
|
+
* Answer `session.fork`: branch one session into another that inherits it.
|
|
1712
|
+
*
|
|
1713
|
+
* Only the two keys protocol v1 names are read here. `sessionId` is required
|
|
1714
|
+
* and `atSeq` is the host's inclusive source-event cut, so a caller that
|
|
1715
|
+
* omitted it must not have one invented for it: the host reads an absent
|
|
1716
|
+
* `atSeq` as the newest finished turn, and a zero or a fractional number is
|
|
1717
|
+
* not a seq at all, which is refused here rather than forwarded for the host
|
|
1718
|
+
* to reject with a shape this bridge could have caught. Everything else —
|
|
1719
|
+
* whether this host forks at all, what the new session is called, which
|
|
1720
|
+
* synthetic events close an open cut — belongs to `session/fork`, so a host
|
|
1721
|
+
* refusal crosses with its own code and text.
|
|
1722
|
+
* @param payload - `{sessionId, atSeq?}`.
|
|
1723
|
+
*/
|
|
1724
|
+
async #sessionFork(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1725
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1726
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.fork requires sessionId')
|
|
1727
|
+
const atSeq = payload.atSeq === undefined ? undefined : seqNumber(payload.atSeq)
|
|
1728
|
+
if (payload.atSeq !== undefined && atSeq === undefined) {
|
|
1729
|
+
return refusal(CODE_INVALID_ARGS, 'session.fork atSeq must be a positive integer')
|
|
1730
|
+
}
|
|
1731
|
+
const call = await this.#unary('session', 'fork', {
|
|
1732
|
+
sessionId,
|
|
1733
|
+
...(atSeq === undefined ? {} : { atSeq }),
|
|
1734
|
+
})
|
|
1735
|
+
return call.ok ? { ok: true, r: call.value } : call
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/**
|
|
1739
|
+
* Answer `squads.state`: the host's squad domain as this deployment publishes
|
|
1740
|
+
* it.
|
|
1741
|
+
*
|
|
1742
|
+
* The read is the `dsh-agents` plugin's own `{teams, runs, host, presets?}`
|
|
1743
|
+
* document — reached over loopback, or read out of its ledger when loopback
|
|
1744
|
+
* cannot answer — mapped onto the frozen body: a definition keeps its identity,
|
|
1745
|
+
* its pins and its members, a run names the squad it belongs to, and both lose
|
|
1746
|
+
* the bookkeeping fields this channel does not publish. A body this build cannot
|
|
1747
|
+
* read is refused rather than repaired, and a host that serves no domain answers
|
|
1748
|
+
* `squads-unavailable` instead of an empty board.
|
|
1749
|
+
*/
|
|
1750
|
+
async #squadsState(): Promise<DispatchOutcome> {
|
|
1751
|
+
const read = await this.#squadState()
|
|
1752
|
+
return read.ok ? { ok: true, r: read.state } : read
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
/**
|
|
1756
|
+
* Answer `squads.list` or `squads.runs`: one half of the same read.
|
|
1757
|
+
*
|
|
1758
|
+
* Both commands read the domain once, exactly as `squads.state` does, and
|
|
1759
|
+
* publish the half they are named after. There is no second source: a squad
|
|
1760
|
+
* listing and a run listing can never disagree about a definition a launch
|
|
1761
|
+
* touched, because both are cut from one answer.
|
|
1762
|
+
* @param half - the body key this command publishes.
|
|
1763
|
+
*/
|
|
1764
|
+
async #squadsProjection(half: 'squads' | 'runs'): Promise<DispatchOutcome> {
|
|
1765
|
+
const read = await this.#squadState()
|
|
1766
|
+
if (!read.ok) return read
|
|
1767
|
+
return { ok: true, r: { [half]: read.state[half] } }
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
/**
|
|
1771
|
+
* Read the squad domain once.
|
|
1772
|
+
*
|
|
1773
|
+
* The transport answers the plugin's rows unread and this bridge maps them
|
|
1774
|
+
* here, so the ledger fallback and the loopback route are the same answer as far
|
|
1775
|
+
* as a client can tell.
|
|
1776
|
+
*/
|
|
1777
|
+
async #squadState(): Promise<{ readonly ok: true; readonly state: SquadsState } | CallFailure> {
|
|
1778
|
+
const transport = this.#options.squads
|
|
1779
|
+
if (transport === undefined) {
|
|
1780
|
+
return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
|
|
1781
|
+
}
|
|
1782
|
+
try {
|
|
1783
|
+
return { ok: true, state: squadsStateOf(await transport.state()) }
|
|
1784
|
+
} catch (error) {
|
|
1785
|
+
return this.#squadFailure(error)
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/**
|
|
1790
|
+
* Answer `squads.runMember`: launch one member session.
|
|
1791
|
+
*
|
|
1792
|
+
* Only the two names the command needs are read here. Which preset, permission,
|
|
1793
|
+
* model and brief that session is composed from is the definition's own, and
|
|
1794
|
+
* whether this host can launch at all is the transport's: an unknown squad or
|
|
1795
|
+
* member, an unusable preset and a squad that pins no workspace all cross as the
|
|
1796
|
+
* plugin's own code.
|
|
1797
|
+
* @param payload - `{squadId, memberId, firstMessage?}`.
|
|
1798
|
+
*/
|
|
1799
|
+
async #squadsRunMember(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1800
|
+
const transport = this.#options.squads
|
|
1801
|
+
if (transport === undefined) {
|
|
1802
|
+
return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
|
|
1803
|
+
}
|
|
1804
|
+
const request = parseSquadMemberRun(payload)
|
|
1805
|
+
if (request === undefined) return refusal(CODE_INVALID_ARGS, 'squads.runMember requires squadId and memberId')
|
|
1806
|
+
try {
|
|
1807
|
+
return { ok: true, r: { run: squadRunOf(await transport.runMember(request)) } }
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
return this.#squadFailure(error)
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
/**
|
|
1814
|
+
* Answer `squads.runSquad`: launch the Lead session of one whole squad.
|
|
1815
|
+
*
|
|
1816
|
+
* The goal travels as the plugin's own `goal` — it becomes part of the Lead's
|
|
1817
|
+
* system-prompt context rather than its first user message — so nothing about
|
|
1818
|
+
* what the squad must achieve is modelled here.
|
|
1819
|
+
* @param payload - `{squadId, goal?}`.
|
|
1820
|
+
*/
|
|
1821
|
+
async #squadsRunSquad(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1822
|
+
const transport = this.#options.squads
|
|
1823
|
+
if (transport === undefined) {
|
|
1824
|
+
return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
|
|
1825
|
+
}
|
|
1826
|
+
const request = parseSquadRun(payload)
|
|
1827
|
+
if (request === undefined) return refusal(CODE_INVALID_ARGS, 'squads.runSquad requires squadId')
|
|
1828
|
+
try {
|
|
1829
|
+
return { ok: true, r: { run: squadRunOf(await transport.runSquad(request)) } }
|
|
1830
|
+
} catch (error) {
|
|
1831
|
+
return this.#squadFailure(error)
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/**
|
|
1836
|
+
* Convert whatever the squad transport raised into a refusal that names a code.
|
|
1837
|
+
*
|
|
1838
|
+
* A refusal the transport built keeps its own code — that is how a domain
|
|
1839
|
+
* refusal and this bridge's two capability codes stay distinguishable. Anything
|
|
1840
|
+
* else is a host failure this channel could not attribute, and it is refused as
|
|
1841
|
+
* an unreachable domain rather than as an internal error: no squad answer was
|
|
1842
|
+
* read, which is exactly what `squads-unavailable` says.
|
|
1843
|
+
*/
|
|
1844
|
+
#squadFailure(error: unknown): CallFailure {
|
|
1845
|
+
if (isSquadRefusal(error)) return refusal(error.code, error.message)
|
|
1846
|
+
this.#options.log(`squad domain read failed: ${failureText(error)}`)
|
|
1847
|
+
return refusal(CODE_SQUADS_UNAVAILABLE, failureText(error))
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
/**
|
|
1851
|
+
* Answer `workspace.list`: the host's workspaces and its two global sets.
|
|
1852
|
+
*
|
|
1853
|
+
* A pure in-process read: `list()` answers a fresh array in registry order and
|
|
1854
|
+
* both sets are synchronous getters, so nothing here awaits, subscribes or
|
|
1855
|
+
* touches persistence, and a write this bridge forwarded a moment ago is
|
|
1856
|
+
* visible to the very next call. Nothing is sorted — the registry's own order
|
|
1857
|
+
* is the display order — and no row carries a workspace's `sessionIds`: the
|
|
1858
|
+
* roster already carries every session's `cwd`, a client groups for itself, and
|
|
1859
|
+
* that account would make one frame grow with the session count.
|
|
1860
|
+
*
|
|
1861
|
+
* A host that composes no registry is refused rather than answered with an
|
|
1862
|
+
* empty list: an empty list says "this host has no workspaces", which is a
|
|
1863
|
+
* different sentence from "there is nothing here to ask".
|
|
1864
|
+
*/
|
|
1865
|
+
#workspaceList(): DispatchOutcome {
|
|
1866
|
+
const listed = this.#options.sessionMeta.workspaceList()
|
|
1867
|
+
if (listed === undefined) return refusal(CODE_INTERNAL, 'this host composes no workspaceRegistry service')
|
|
1868
|
+
return { ok: true, r: listed }
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
/**
|
|
1872
|
+
* Answer `session.rename`: forward one `SessionRenameRequest` and hand back
|
|
1873
|
+
* the host's own `SessionRenameValue`.
|
|
1874
|
+
*
|
|
1875
|
+
* The write goes through the gateway — `session/rename`, never the title
|
|
1876
|
+
* service this process holds — because that endpoint restores a cold session
|
|
1877
|
+
* before it writes, so a client needs no resume path of its own. The title is
|
|
1878
|
+
* required and is text: an empty string is not a name anyone could have meant,
|
|
1879
|
+
* and it is refused here instead of being written. Everything after that is
|
|
1880
|
+
* the host's: the normalized title, the durable seq that committed it, and a
|
|
1881
|
+
* refusal such as `session/not-found` cross verbatim.
|
|
1882
|
+
* @param payload - `{sessionId, title}`.
|
|
1883
|
+
*/
|
|
1884
|
+
async #sessionRename(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1885
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1886
|
+
const title = stringArg(payload, 'title')
|
|
1887
|
+
if (sessionId === undefined || title === undefined) {
|
|
1888
|
+
return refusal(CODE_INVALID_ARGS, 'session.rename requires sessionId and title')
|
|
1889
|
+
}
|
|
1890
|
+
const call = await this.#unary('session', 'rename', { sessionId, title })
|
|
1891
|
+
return call.ok ? { ok: true, r: call.value } : call
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
/**
|
|
1895
|
+
* Forward one registry set mutation and answer `{ok:true}`.
|
|
1896
|
+
*
|
|
1897
|
+
* Three of the five session-admin writes are the same call under a different
|
|
1898
|
+
* endpoint name, so they share one body: `{sessionId}` in, one decided answer
|
|
1899
|
+
* out. Nothing is branched on — pin, unpin and unarchive take no second
|
|
1900
|
+
* argument to branch on — and the host's own set answer
|
|
1901
|
+
* (`WorkspacePinValue` / `WorkspaceArchiveValue`) is deliberately not
|
|
1902
|
+
* republished: a client that wants the new set reads `workspace.list`, the one
|
|
1903
|
+
* read that serves both. An archive's optional `stopActivity` is
|
|
1904
|
+
* `#sessionArchive`'s own concern.
|
|
1905
|
+
* @param method - the protocol method being answered, named in the refusal.
|
|
1906
|
+
* @param endpoint - the `workspace` registry method behind it.
|
|
1907
|
+
* @param payload - `{sessionId}`.
|
|
1908
|
+
*/
|
|
1909
|
+
async #sessionSetWrite(method: string, endpoint: string, payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1910
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1911
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, `${method} requires sessionId`)
|
|
1912
|
+
const call = await this.#unary('workspace', endpoint, { sessionId })
|
|
1913
|
+
return call.ok ? { ok: true, r: { ok: true } } : call
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
/**
|
|
1917
|
+
* Answer `session.archive`, whose request may ask the host to stop the
|
|
1918
|
+
* session's running work first.
|
|
1919
|
+
*
|
|
1920
|
+
* `stopActivity` is the host's own choice and only a boolean may cross: sent
|
|
1921
|
+
* without it, a session that is still running is refused by the host as
|
|
1922
|
+
* `workspace/session-active`; sent as `true`, the archive is written and that
|
|
1923
|
+
* work is stopped. Archiving is a session-level act — it never touches the
|
|
1924
|
+
* workspace the session belongs to — and the archived session keeps its slot,
|
|
1925
|
+
* so `session.unarchive` puts it back where it was. None of that is modelled
|
|
1926
|
+
* here.
|
|
1927
|
+
* @param payload - `{sessionId, stopActivity?}`.
|
|
1928
|
+
*/
|
|
1929
|
+
async #sessionArchive(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1930
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1931
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.archive requires sessionId')
|
|
1932
|
+
const stopActivity = payload.stopActivity
|
|
1933
|
+
if (stopActivity !== undefined && typeof stopActivity !== 'boolean') {
|
|
1934
|
+
return refusal(CODE_INVALID_ARGS, 'session.archive stopActivity must be a boolean when present')
|
|
1935
|
+
}
|
|
1936
|
+
const call = await this.#unary('workspace', 'archiveSession', { sessionId, ...(stopActivity === undefined ? {} : { stopActivity }) })
|
|
1937
|
+
return call.ok ? { ok: true, r: { ok: true } } : call
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
/**
|
|
1941
|
+
* Answer `session.commands`: one session's slash commands and skills, in one
|
|
1942
|
+
* directory.
|
|
1943
|
+
*
|
|
1944
|
+
* Both catalogs are read live and neither is modelled here: `commands/list`
|
|
1945
|
+
* is the host registry's own effective view for this Agent — a command
|
|
1946
|
+
* registered through an Agent-scoped child shadows the global one — and
|
|
1947
|
+
* `skills/list` is the catalog this session's cwd and preset select, so what
|
|
1948
|
+
* a phone lists is what the desktop composer would offer that same session. A
|
|
1949
|
+
* row crosses with the name and the summary the host publishes for it, plus
|
|
1950
|
+
* the whole draft line that invokes it, separator space included.
|
|
1951
|
+
*
|
|
1952
|
+
* Nothing is paged, re-sorted or cached: every command first, every skill
|
|
1953
|
+
* after, each in the host's own order, and the next call reads both again.
|
|
1954
|
+
* @param payload - `{sessionId}`.
|
|
1955
|
+
*/
|
|
1956
|
+
async #sessionCommands(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1957
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1958
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.commands requires sessionId')
|
|
1959
|
+
const commands = await this.#unary('commands', 'list', { agentId: sessionId })
|
|
1960
|
+
if (!commands.ok) return this.#commandsFailure('commands', 'list', commands)
|
|
1961
|
+
if (!Array.isArray(commands.value)) return refusal(CODE_INTERNAL, 'commands/list returned no command directory')
|
|
1962
|
+
const skills = await this.#unary('skills', 'list', { sessionId })
|
|
1963
|
+
if (!skills.ok) return this.#commandsFailure('skills', 'list', skills)
|
|
1964
|
+
if (!isRecord(skills.value) || !Array.isArray(skills.value.skills)) {
|
|
1965
|
+
return refusal(CODE_INTERNAL, 'skills/list returned no skill catalog')
|
|
1966
|
+
}
|
|
1967
|
+
return { ok: true, r: { sessionId, items: commandItems(commands.value, skills.value.skills) } }
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
/**
|
|
1971
|
+
* Answer `session.command`: run one draft line on the host and report whether
|
|
1972
|
+
* the host resolved it.
|
|
1973
|
+
*
|
|
1974
|
+
* The line crosses exactly as the client wrote it, because what a line means
|
|
1975
|
+
* belongs to the host: its parser decides whether the text is a slash command
|
|
1976
|
+
* at all, and its registry decides whether that name is one this Agent has. A
|
|
1977
|
+
* line the host resolves runs — this method does not pre-judge a command,
|
|
1978
|
+
* replay one, or refuse a line it does not recognise — and the answer is then
|
|
1979
|
+
* `matched: true`. A line the host resolves to nothing (no leading slash, an
|
|
1980
|
+
* unknown name, or a skill's `/name` gesture, which is prompt text rather than
|
|
1981
|
+
* a registry entry) answers `matched: false`, and nothing ran.
|
|
1982
|
+
*
|
|
1983
|
+
* A plain invocation carries no attachments: a draft line has none, the
|
|
1984
|
+
* endpoint requires the key, so an empty array is what crosses.
|
|
1985
|
+
* @param payload - `{sessionId, line}`.
|
|
1986
|
+
*/
|
|
1987
|
+
async #sessionCommand(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
1988
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
1989
|
+
const line = stringArg(payload, 'line')
|
|
1990
|
+
if (sessionId === undefined || line === undefined) {
|
|
1991
|
+
return refusal(CODE_INVALID_ARGS, 'session.command requires sessionId and line')
|
|
1992
|
+
}
|
|
1993
|
+
const call = await this.#unary('commands', 'execute', { agentId: sessionId, line, submittedAttachments: [] })
|
|
1994
|
+
if (!call.ok) return this.#commandsFailure('commands', 'execute', call)
|
|
1995
|
+
return { ok: true, r: { matched: call.value !== undefined } }
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
/**
|
|
1999
|
+
* Re-answer one command-channel failure.
|
|
2000
|
+
*
|
|
2001
|
+
* An endpoint this host does not serve at all is this bridge's own
|
|
2002
|
+
* `commands-unavailable`, so a phone stops offering the directory instead of
|
|
2003
|
+
* showing a call that fails every time; a call the host refused, and a channel
|
|
2004
|
+
* that is merely still activating, cross with the failure's own code and text.
|
|
2005
|
+
* @param namespace - the Remote namespace that failed.
|
|
2006
|
+
* @param method - the endpoint that failed.
|
|
2007
|
+
* @param failure - the refusal `#unary` produced.
|
|
2008
|
+
*/
|
|
2009
|
+
#commandsFailure(namespace: string, method: string, failure: CallFailure): CallFailure {
|
|
2010
|
+
if (!commandsUnavailable(failure.code)) return failure
|
|
2011
|
+
return refusal(CODE_COMMANDS_UNAVAILABLE, `this host serves no ${namespace}/${method} endpoint`)
|
|
2012
|
+
}
|
|
2013
|
+
|
|
826
2014
|
#approvalResolve(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
|
|
827
2015
|
const id = stringArg(payload, 'id')
|
|
828
2016
|
const decision = payload.decision
|
|
@@ -855,6 +2043,222 @@ export class BridgeConnection {
|
|
|
855
2043
|
return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
|
|
856
2044
|
}
|
|
857
2045
|
|
|
2046
|
+
/**
|
|
2047
|
+
* Answer one `question.list`: the questions this bridge is still holding.
|
|
2048
|
+
*
|
|
2049
|
+
* A pure read — it claims nothing, moves no deadline, triggers no `continued`
|
|
2050
|
+
* and writes no host state — because its whole purpose is to let a client that
|
|
2051
|
+
* was disconnected reconcile cards it already holds: a question missing from
|
|
2052
|
+
* this list is one nobody can answer any more, since the bridge withdraws every
|
|
2053
|
+
* claim when the last paired device leaves and the phone is not there to hear
|
|
2054
|
+
* it.
|
|
2055
|
+
*
|
|
2056
|
+
* Only a COMPLETE list may retire a card on the client, so a registry this
|
|
2057
|
+
* bridge cannot read answers `question-list-unavailable` rather than an empty
|
|
2058
|
+
* list: an unreadable set is not an empty one.
|
|
2059
|
+
* @param payload - must be the empty object: the held set is global, not scoped.
|
|
2060
|
+
*/
|
|
2061
|
+
#questionList(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
|
|
2062
|
+
if (Object.keys(payload).length > 0) {
|
|
2063
|
+
return refusal(CODE_INVALID_ARGS, 'question.list takes no arguments')
|
|
2064
|
+
}
|
|
2065
|
+
let questions: readonly ListedQuestion[]
|
|
2066
|
+
try {
|
|
2067
|
+
questions = this.#options.questions.listed()
|
|
2068
|
+
} catch (error) {
|
|
2069
|
+
this.#options.log(`question.list could not read the held questions: ${failureText(error)}`)
|
|
2070
|
+
return refusal(CODE_QUESTION_LIST_UNAVAILABLE, 'this bridge could not read the questions it is holding')
|
|
2071
|
+
}
|
|
2072
|
+
const answer: QuestionListPayload = { questions, complete: true }
|
|
2073
|
+
return { ok: true, r: answer }
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
/**
|
|
2077
|
+
* The body of `push.register` (protocol §28.3).
|
|
2078
|
+
*
|
|
2079
|
+
* A write, and the only one this channel has: the device's APNs registration
|
|
2080
|
+
* lands in its own row of the roster file, beside the identity it already
|
|
2081
|
+
* proved, so revoking the device revokes its notifications with it and no
|
|
2082
|
+
* second identity or second table exists.
|
|
2083
|
+
*
|
|
2084
|
+
* The answer is `{ok:true}` and nothing else. There is deliberately no echo of
|
|
2085
|
+
* the token and no "ready" flag: this bridge cannot know whether APNs will
|
|
2086
|
+
* accept the token, and a field claiming it did would be a lie a client might
|
|
2087
|
+
* render. A bridge with no signing key answers identically — a client has no
|
|
2088
|
+
* second code path for that difference.
|
|
2089
|
+
* @param payload - `{deviceToken, environment, bundle, liveActivityTokens?, locale?}`.
|
|
2090
|
+
*/
|
|
2091
|
+
async #pushRegister(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2092
|
+
const deviceToken = payload.deviceToken
|
|
2093
|
+
const environment = payload.environment
|
|
2094
|
+
const bundle = payload.bundle
|
|
2095
|
+
if (typeof deviceToken !== 'string' || deviceToken === '' || !/^[0-9a-fA-F]+$/.test(deviceToken)) {
|
|
2096
|
+
return refusal(CODE_INVALID_ARGS, 'deviceToken must be the hex string APNs handed the app')
|
|
2097
|
+
}
|
|
2098
|
+
if (environment !== 'sandbox' && environment !== 'production') {
|
|
2099
|
+
return refusal(CODE_INVALID_ARGS, 'environment must be "sandbox" or "production"')
|
|
2100
|
+
}
|
|
2101
|
+
if (typeof bundle !== 'string' || bundle === '') return refusal(CODE_INVALID_ARGS, 'bundle must be a non-empty string')
|
|
2102
|
+
const locale = optionalText(payload.locale)
|
|
2103
|
+
let liveActivityTokens: readonly PushLiveActivityToken[] | undefined
|
|
2104
|
+
if (payload.liveActivityTokens !== undefined) {
|
|
2105
|
+
const raw = payload.liveActivityTokens
|
|
2106
|
+
if (!Array.isArray(raw)) return refusal(CODE_INVALID_ARGS, 'liveActivityTokens must be an array')
|
|
2107
|
+
const collected: PushLiveActivityToken[] = []
|
|
2108
|
+
for (const entry of raw) {
|
|
2109
|
+
if (!isRecord(entry)) return refusal(CODE_INVALID_ARGS, 'each liveActivityTokens entry needs an activityId and a token')
|
|
2110
|
+
const activityId = entry.activityId
|
|
2111
|
+
const token = entry.token
|
|
2112
|
+
if (typeof activityId !== 'string' || activityId === '' || typeof token !== 'string' || token === '') {
|
|
2113
|
+
return refusal(CODE_INVALID_ARGS, 'each liveActivityTokens entry needs an activityId and a token')
|
|
2114
|
+
}
|
|
2115
|
+
// §29.9: a card names the session it belongs to. The key is optional —
|
|
2116
|
+
// a client that omits it is registered exactly as before — but a value
|
|
2117
|
+
// that is present has to be a session id, because a card carrying a
|
|
2118
|
+
// malformed address would be pushed to nobody while looking registered.
|
|
2119
|
+
const sessionId = entry.sessionId
|
|
2120
|
+
if (sessionId !== undefined && (typeof sessionId !== 'string' || sessionId === '')) {
|
|
2121
|
+
return refusal(CODE_INVALID_ARGS, 'a liveActivityTokens sessionId must be a non-empty string')
|
|
2122
|
+
}
|
|
2123
|
+
collected.push({ activityId, token, ...(sessionId === undefined ? {} : { sessionId }) })
|
|
2124
|
+
}
|
|
2125
|
+
liveActivityTokens = collected
|
|
2126
|
+
}
|
|
2127
|
+
const deviceId = this.#deviceId
|
|
2128
|
+
if (deviceId === undefined) return refusal(CODE_UNPAIRED, 'this connection is not paired')
|
|
2129
|
+
const registration: PushRegistration = {
|
|
2130
|
+
deviceToken,
|
|
2131
|
+
environment: environment as PushEnvironment,
|
|
2132
|
+
bundle,
|
|
2133
|
+
...(locale === undefined ? {} : { locale }),
|
|
2134
|
+
...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
|
|
2135
|
+
registeredAt: this.#options.now(),
|
|
2136
|
+
}
|
|
2137
|
+
try {
|
|
2138
|
+
const stored = await this.#options.roster.registerPush(deviceId, registration)
|
|
2139
|
+
if (!stored) return refusal(CODE_INTERNAL, 'this connection names no paired device')
|
|
2140
|
+
// The roster is the only place a standing watcher is armed from: the
|
|
2141
|
+
// session a card names gets a follow stream of this bridge's own, and it
|
|
2142
|
+
// keeps it until the last token for that session is gone.
|
|
2143
|
+
try {
|
|
2144
|
+
this.#options.onPushRegistered?.()
|
|
2145
|
+
} catch (error) {
|
|
2146
|
+
this.#options.log(`standing watchers could not be reconciled: ${failureText(error)}`)
|
|
2147
|
+
}
|
|
2148
|
+
} catch (error) {
|
|
2149
|
+
// Registration failing has to reach the client: it decides whether to
|
|
2150
|
+
// retry, and a token that never reached the disk is a device that will
|
|
2151
|
+
// never be notified.
|
|
2152
|
+
return refusal(CODE_INTERNAL, `could not write the device roster: ${failureText(error)}`)
|
|
2153
|
+
}
|
|
2154
|
+
return { ok: true, r: { ok: true } }
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
/**
|
|
2158
|
+
* 答一次 `usage.session`:一条会话的上下文窗口与下一次请求的组成估算。
|
|
2159
|
+
*
|
|
2160
|
+
* 两个读数各有自己的来源,也各有自己的缺席方式:`contextWindow` 只在宿主
|
|
2161
|
+
* 广播过 `request/context` 时出现,`composition` 只在观察到任何原文时出现,
|
|
2162
|
+
* 两项都没有就是空对象。会话本身不存在是另一种情况,回的是
|
|
2163
|
+
* `unknown-session`,而不是一个读不到任何东西的空对象;而「存在」由活会话
|
|
2164
|
+
* 存储、本进程观察到的事件与宿主名册三处中任意一处证明(见 `core/usage.ts`)。
|
|
2165
|
+
* @param payload - `{sessionId}`。
|
|
2166
|
+
*/
|
|
2167
|
+
async #usageSession(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2168
|
+
const sessionId = stringArg(payload, 'sessionId')
|
|
2169
|
+
if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'usage.session requires sessionId')
|
|
2170
|
+
const answer = await this.#options.usage.session(sessionId)
|
|
2171
|
+
if (answer === undefined) return refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`)
|
|
2172
|
+
return { ok: true, r: answer }
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
/**
|
|
2176
|
+
* 答一次 `usage.balance`:某条 provider 路由背后账户的余额。
|
|
2177
|
+
*
|
|
2178
|
+
* 判定与缓存全在 `core/usage.ts`:不是官方路由、不指向官方 origin、凭据拿
|
|
2179
|
+
* 不到,都不发上游请求,各自的理由按 `unsupported` 的三种取值过线。这里
|
|
2180
|
+
* 只转发,因为余额是账户的事实,本连接既不改写也不补默认值。
|
|
2181
|
+
* @param payload - `{provider}`。
|
|
2182
|
+
*/
|
|
2183
|
+
async #usageBalance(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2184
|
+
const provider = stringArg(payload, 'provider')
|
|
2185
|
+
if (provider === undefined) return refusal(CODE_INVALID_ARGS, 'usage.balance requires provider')
|
|
2186
|
+
return { ok: true, r: await this.#options.usage.balance(provider) }
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
/**
|
|
2190
|
+
* 答一次 `usage.stats`:宿主自己那份按天记的 token 台账的聚合。
|
|
2191
|
+
*
|
|
2192
|
+
* `days` 省略按 14,超出 60 按 60 收——收窗口的是 `core/usage-stats.ts`,不是
|
|
2193
|
+
* 协议:客户端给的天数只是「想看多深」,不该被当成一次分配。这里只拒绝根本
|
|
2194
|
+
* 不是数字的那种值,其余一律转发,包括读不到时那份 `unsupported`,
|
|
2195
|
+
* 因为「这台 Mac 没挂那个插件」不是一次失败。
|
|
2196
|
+
* @param payload - `{days?}`。
|
|
2197
|
+
*/
|
|
2198
|
+
async #usageStats(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2199
|
+
const days = payload.days
|
|
2200
|
+
if (days !== undefined && (typeof days !== 'number' || !Number.isFinite(days))) {
|
|
2201
|
+
return refusal(CODE_INVALID_ARGS, 'usage.stats requires days to be a number')
|
|
2202
|
+
}
|
|
2203
|
+
return { ok: true, r: await this.#options.usage.stats(days) }
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
/**
|
|
2207
|
+
* Answer one `jobs.list` and start watching that scope.
|
|
2208
|
+
*
|
|
2209
|
+
* The scope is the host registry's own: naming a session reads that session's
|
|
2210
|
+
* fenced set (its own jobs plus every unowned one), naming none reads the
|
|
2211
|
+
* unowned set. Neither is a global list, and this method never assembles one —
|
|
2212
|
+
* a cross-session view would be a second source of truth the host does not
|
|
2213
|
+
* have, and it would have to aggregate N fenced reads to fake it.
|
|
2214
|
+
*
|
|
2215
|
+
* Answering is also what subscribes: every later change of this scope arrives
|
|
2216
|
+
* as `jobs.changed` carrying the same payload, and a scope that was never
|
|
2217
|
+
* listed is never watched.
|
|
2218
|
+
* @param payload - `{}` for the unowned scope, or `{sessionId}` for one session's.
|
|
2219
|
+
*/
|
|
2220
|
+
async #jobsList(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
|
|
2221
|
+
const raw = payload.sessionId
|
|
2222
|
+
if (raw !== undefined && (typeof raw !== 'string' || raw === '')) {
|
|
2223
|
+
return refusal(CODE_INVALID_ARGS, 'jobs.list sessionId must be a non-empty string when present')
|
|
2224
|
+
}
|
|
2225
|
+
const sessionId = raw
|
|
2226
|
+
if (sessionId !== undefined) {
|
|
2227
|
+
// A job row names its owner and carries its label, so this read is fenced
|
|
2228
|
+
// by the same rule as following the session it belongs to: a delegated
|
|
2229
|
+
// child whose parent this connection may not read is not addressable here.
|
|
2230
|
+
const unfollowable = await this.#unfollowable(sessionId)
|
|
2231
|
+
if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
|
|
2232
|
+
}
|
|
2233
|
+
const roster = this.#options.jobs.read(sessionId)
|
|
2234
|
+
if (roster === undefined) {
|
|
2235
|
+
return refusal(CODE_JOBS_UNAVAILABLE, 'this host composes no background job registry')
|
|
2236
|
+
}
|
|
2237
|
+
this.#watchJobs(sessionId, roster)
|
|
2238
|
+
return { ok: true, r: roster }
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* Watch one job scope for this connection, once.
|
|
2243
|
+
*
|
|
2244
|
+
* The scope's first payload is the answer the client just received, so it is
|
|
2245
|
+
* seeded as already seen: a change frame only ever carries a set that differs
|
|
2246
|
+
* from the last one this connection was handed.
|
|
2247
|
+
*/
|
|
2248
|
+
#watchJobs(sessionId: string | undefined, payload: JobsPayload): void {
|
|
2249
|
+
const key = scopeKey(sessionId)
|
|
2250
|
+
this.#jobSeen.set(key, JSON.stringify(payload.jobs))
|
|
2251
|
+
if (this.#jobWatches.has(key)) return
|
|
2252
|
+
const dispose = this.#options.jobs.watch(sessionId, (changed) => {
|
|
2253
|
+
if (!this.declares(CAP_JOBS)) return
|
|
2254
|
+
const encoded = JSON.stringify(changed.jobs)
|
|
2255
|
+
if (this.#jobSeen.get(key) === encoded) return
|
|
2256
|
+
this.#jobSeen.set(key, encoded)
|
|
2257
|
+
this.#emit(TOPIC_JOBS_CHANGED, changed)
|
|
2258
|
+
})
|
|
2259
|
+
if (dispose !== undefined) this.#jobWatches.set(key, dispose)
|
|
2260
|
+
}
|
|
2261
|
+
|
|
858
2262
|
/**
|
|
859
2263
|
* Run one unary Remote call with the activation retry, converting a gateway
|
|
860
2264
|
* failure into a refusal that carries the gateway's own code.
|
|
@@ -898,10 +2302,20 @@ export class BridgeConnection {
|
|
|
898
2302
|
return parent === undefined ? sessionAddress(sessionId) : subagentAddress(parent, sessionId)
|
|
899
2303
|
}
|
|
900
2304
|
|
|
901
|
-
/**
|
|
2305
|
+
/**
|
|
2306
|
+
* Remember the durable parent of every delegated child a roster carried, and
|
|
2307
|
+
* which sessions that same roster authorizes this connection to read.
|
|
2308
|
+
*
|
|
2309
|
+
* A child is not authorized by being named: authorizing it on its own row
|
|
2310
|
+
* would let one refused read teach the connection to follow it on the retry.
|
|
2311
|
+
*/
|
|
902
2312
|
#rememberLineage(rows: readonly SessionRow[]): void {
|
|
903
2313
|
for (const row of rows) {
|
|
904
|
-
if (row.origin
|
|
2314
|
+
if (row.origin !== 'subagent') {
|
|
2315
|
+
this.#authorized.add(row.id)
|
|
2316
|
+
continue
|
|
2317
|
+
}
|
|
2318
|
+
if (row.parentSessionId !== undefined) this.#lineage.set(row.id, row.parentSessionId)
|
|
905
2319
|
}
|
|
906
2320
|
}
|
|
907
2321
|
|
|
@@ -916,11 +2330,32 @@ export class BridgeConnection {
|
|
|
916
2330
|
async #parentOf(sessionId: string): Promise<string | undefined> {
|
|
917
2331
|
const known = this.#lineage.get(sessionId)
|
|
918
2332
|
if (known !== undefined || this.#lineageRead) return known
|
|
919
|
-
const roster = await this.#
|
|
2333
|
+
const roster = await this.#readRoster()
|
|
920
2334
|
if (roster.ok) this.#lineageRead = true
|
|
921
2335
|
return this.#lineage.get(sessionId)
|
|
922
2336
|
}
|
|
923
2337
|
|
|
2338
|
+
/**
|
|
2339
|
+
* Whether this connection may follow one session at all.
|
|
2340
|
+
*
|
|
2341
|
+
* Following a delegated child is the one case that needs an answer before the
|
|
2342
|
+
* stream is asked for: relaxing the child gate must not become a channel to
|
|
2343
|
+
* any session a caller happens to name. A session this connection already
|
|
2344
|
+
* opened is authorized by that fact, an ordinary session the roster names is
|
|
2345
|
+
* authorized by the host's own roster, and a delegated child is authorized
|
|
2346
|
+
* only when the parent it hangs off is one of those. A session the roster does
|
|
2347
|
+
* not know at all keeps the old path — the harness itself answers for an id
|
|
2348
|
+
* this host does not have.
|
|
2349
|
+
* @returns the refusal to answer with, or undefined when the session may be followed.
|
|
2350
|
+
*/
|
|
2351
|
+
async #unfollowable(sessionId: string): Promise<string | undefined> {
|
|
2352
|
+
if (this.#authorized.has(sessionId)) return undefined
|
|
2353
|
+
const parent = await this.#parentOf(sessionId)
|
|
2354
|
+
if (parent === undefined) return undefined
|
|
2355
|
+
if (this.#authorized.has(parent)) return undefined
|
|
2356
|
+
return `session ${sessionId} is a delegated child whose parent ${parent} is not a session this connection may read`
|
|
2357
|
+
}
|
|
2358
|
+
|
|
924
2359
|
/**
|
|
925
2360
|
* Open one follow stream, resolving the address kind the harness demands.
|
|
926
2361
|
*
|
|
@@ -977,6 +2412,9 @@ export class BridgeConnection {
|
|
|
977
2412
|
await iterator.return?.()
|
|
978
2413
|
return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'session/follow returned no opening snapshot frame' }
|
|
979
2414
|
}
|
|
2415
|
+
// A stream that opened is proof this connection may read that session,
|
|
2416
|
+
// which is what lets a child of it be followed afterwards.
|
|
2417
|
+
this.#authorized.add(subscription.sessionId)
|
|
980
2418
|
void this.#drain(subscription, iterator)
|
|
981
2419
|
return { ok: true, baseline }
|
|
982
2420
|
} catch (error) {
|
|
@@ -986,13 +2424,27 @@ export class BridgeConnection {
|
|
|
986
2424
|
|
|
987
2425
|
/** Consume the rest of a follow stream, publishing every increment. */
|
|
988
2426
|
async #drain(subscription: Subscription, iterator: AsyncIterator<unknown>): Promise<void> {
|
|
2427
|
+
// Turn and step belong to this stream, not to the connection: a phone
|
|
2428
|
+
// following a parent and a child at once interleaves two turn sequences.
|
|
2429
|
+
const memory = {
|
|
2430
|
+
subagentThread: this.declares(CAP_SUBAGENT_THREAD),
|
|
2431
|
+
spawnCalls: new SpawnCallIndex(),
|
|
2432
|
+
}
|
|
989
2433
|
try {
|
|
990
2434
|
for (;;) {
|
|
991
2435
|
const next = await iterator.next()
|
|
992
2436
|
if (next.done === true) return
|
|
993
|
-
const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages)
|
|
2437
|
+
const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory)
|
|
994
2438
|
if (delta === undefined) continue
|
|
995
2439
|
this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
|
|
2440
|
+
// One turn ended, so a phone that is not holding this socket may want to
|
|
2441
|
+
// know. The call returns before anything is sent and swallows its own
|
|
2442
|
+
// failures: the frame above is already gone, and a notification is not
|
|
2443
|
+
// worth a delayed or aborted stream (protocol §28.5).
|
|
2444
|
+
if (delta.kind === 'turn-end') {
|
|
2445
|
+
this.#options.push?.notify(pushEventOfTurnEnd(delta.reason), subscription.sessionId)
|
|
2446
|
+
this.#options.liveActivity?.noteTurnEnd(subscription.sessionId, delta.reason)
|
|
2447
|
+
}
|
|
996
2448
|
}
|
|
997
2449
|
} catch (error) {
|
|
998
2450
|
if (!subscription.controller.signal.aborted) {
|