@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.
Files changed (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
package/src/core/wire.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * - `session/list` is the only endpoint whose single parameter is named
11
11
  * `_request` (the underscore is part of the wire name);
12
- * - three endpoints take NO parameters at all and must be called with `{}`;
12
+ * - four endpoints take NO parameters at all and must be called with `{}`;
13
13
  * - every other endpoint names its single parameter `request`.
14
14
  * @module dsh-remote-bridge/core/wire
15
15
  */
@@ -111,6 +111,8 @@ export interface WireRow {
111
111
  */
112
112
  export const WIRE_TABLE: readonly WireRow[] = [
113
113
  { namespace: 'session', method: 'list', wire: '_request' },
114
+ { namespace: 'session', method: 'create', wire: 'request' },
115
+ { namespace: 'session', method: 'fork', wire: 'request' },
114
116
  { namespace: 'session', method: 'page', wire: 'request' },
115
117
  { namespace: 'session', method: 'follow', wire: 'request' },
116
118
  { namespace: 'session', method: 'prompt', wire: 'request' },
@@ -119,7 +121,17 @@ export const WIRE_TABLE: readonly WireRow[] = [
119
121
  { namespace: 'session', method: 'projections', wire: 'request' },
120
122
  { namespace: 'session', method: 'modelCatalog', wire: 'none' },
121
123
  { namespace: 'session', method: 'selectModel', wire: 'request' },
124
+ { namespace: 'session', method: 'rename', wire: 'request' },
125
+ { namespace: 'workspace', method: 'pinSession', wire: 'request' },
126
+ { namespace: 'workspace', method: 'unpinSession', wire: 'request' },
127
+ { namespace: 'workspace', method: 'archiveSession', wire: 'request' },
128
+ { namespace: 'workspace', method: 'unarchiveSession', wire: 'request' },
129
+ { namespace: 'agentPresets', method: 'list', wire: 'none' },
130
+ { namespace: 'commands', method: 'list', wire: { names: ['agentId'] } },
131
+ { namespace: 'commands', method: 'execute', wire: { names: ['agentId', 'line', 'submittedAttachments'] } },
132
+ { namespace: 'skills', method: 'list', wire: 'request' },
122
133
  { namespace: 'userQuestions', method: 'answer', wire: { names: ['agentId', 'callId', 'answer'] } },
134
+ { namespace: 'userQuestions', method: 'attachWait', wire: { names: ['agentId', 'callId'] } },
123
135
  { namespace: 'pluginInventory', method: 'list', wire: 'none' },
124
136
  { namespace: 'pluginManager', method: 'listPlugins', wire: 'none' },
125
137
  ]
@@ -27,6 +27,15 @@ export const CLOSE_PROTOCOL_ERROR = 1002
27
27
  export const CLOSE_UNSUPPORTED_DATA = 1003
28
28
  /** Close code for a message past the size this bridge will carry. */
29
29
  export const CLOSE_TOO_LARGE = 1009
30
+ /**
31
+ * Close code for a peer that stopped answering: a liveness ping went out and no
32
+ * frame at all came back before its deadline.
33
+ *
34
+ * It is an application-range code (4000-4999), so a client can tell a peer that
35
+ * went silent from a protocol fault, from a frame this bridge will not carry,
36
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
37
+ */
38
+ export const CLOSE_LIVENESS_TIMEOUT = 4000
30
39
 
31
40
  /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
32
41
  export function webSocketAccept(secWebSocketKey: string): string {
@@ -115,6 +124,11 @@ export function encodeTextFrame(text: string): Buffer {
115
124
  return encodeServerFrame(OPCODE_TEXT, Buffer.from(text, 'utf8'))
116
125
  }
117
126
 
127
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
128
+ export function encodeBinaryFrame(payload: Buffer): Buffer {
129
+ return encodeServerFrame(OPCODE_BINARY, payload)
130
+ }
131
+
118
132
  /** Encode one close frame with a code and a short reason. */
119
133
  export function encodeCloseFrame(code: number, reason: string): Buffer {
120
134
  const text = Buffer.from(reason, 'utf8').subarray(0, 123)
@@ -0,0 +1,320 @@
1
+ /**
2
+ * The APNs client this bridge sends notifications through.
3
+ *
4
+ * Written against `node:http2` and `node:crypto` and nothing else: the provider
5
+ * API is one POST per notification behind an ES256 JWT, which is small enough
6
+ * that a dependency would cost more than it saves, and this package's whole
7
+ * install surface is one browser library.
8
+ *
9
+ * Two facts about the credential shape everything here:
10
+ *
11
+ * - the signing key is an Apple `.p8` on this machine, named by an environment
12
+ * variable. It never enters this repository, the roster file, a log line or a
13
+ * wire frame; only the JWT derived from it leaves the process.
14
+ * - a bridge with no key is a bridge with the channel OFF. {@link apnsConfigFromEnv}
15
+ * answers undefined, no sender is constructed, and every notification path is
16
+ * a no-op — the existing protocol runs byte for byte as it did before (§28).
17
+ * @module dsh-remote-bridge/host/apns
18
+ */
19
+
20
+ import { createPrivateKey, sign, type KeyObject } from 'node:crypto'
21
+ import { readFile } from 'node:fs/promises'
22
+ import { connect, type ClientHttp2Session } from 'node:http2'
23
+ import type { LiveActivityAddress, LiveActivityNotification, LiveActivitySender } from '../core/liveactivity.ts'
24
+ import type { PushAddress, PushNotification, PushSendResult, PushSender } from '../core/push.ts'
25
+
26
+ /** Production APNs authority. */
27
+ export const APNS_PRODUCTION_AUTHORITY = 'api.push.apple.com'
28
+ /** Development APNs authority; a build signed for development must use it. */
29
+ export const APNS_SANDBOX_AUTHORITY = 'api.sandbox.push.apple.com'
30
+ /** Path prefix of one device delivery. */
31
+ export const APNS_DEVICE_PATH = '/3/device/'
32
+ /**
33
+ * The topic suffix a Live Activity push needs.
34
+ *
35
+ * A Live Activity is addressed under the app bundle's own topic with this
36
+ * suffix appended (§29); the bare bundle is the alert channel's topic, and
37
+ * sending a card there is delivered as an alert the App cannot decode.
38
+ */
39
+ export const APNS_LIVE_ACTIVITY_TOPIC_SUFFIX = '.push-type.liveactivity'
40
+ /**
41
+ * How long one signed provider token is reused.
42
+ *
43
+ * Apple rejects a token older than an hour and throttles a provider that mints
44
+ * one per request, so the token is refreshed well inside that window.
45
+ */
46
+ export const APNS_TOKEN_TTL_MS = 45 * 60 * 1000
47
+ /** How long one delivery may take before it is abandoned. */
48
+ export const APNS_TIMEOUT_MS = 10_000
49
+ /** Environment variables this bridge reads its credential from. */
50
+ export const APNS_ENV = {
51
+ keyFile: 'DSH_REMOTE_BRIDGE_APNS_KEY_FILE',
52
+ keyId: 'DSH_REMOTE_BRIDGE_APNS_KEY_ID',
53
+ teamId: 'DSH_REMOTE_BRIDGE_APNS_TEAM_ID',
54
+ } as const
55
+
56
+ /** The credential this bridge signs with. */
57
+ export interface ApnsConfig {
58
+ /** Absolute path of the `.p8` private key. */
59
+ readonly keyFile: string
60
+ /** The key id Apple issued for that file. */
61
+ readonly keyId: string
62
+ /** The Apple Developer team id, which is the token's `iss`. */
63
+ readonly teamId: string
64
+ }
65
+
66
+ /**
67
+ * Read the APNs credential from the environment.
68
+ * @param env - the environment to read; defaults to this process's.
69
+ * @returns the credential, or undefined when any part of it is missing — which
70
+ * is how the channel stays off by default.
71
+ */
72
+ export function apnsConfigFromEnv(env: NodeJS.ProcessEnv = process.env): ApnsConfig | undefined {
73
+ const keyFile = env[APNS_ENV.keyFile]?.trim()
74
+ const keyId = env[APNS_ENV.keyId]?.trim()
75
+ const teamId = env[APNS_ENV.teamId]?.trim()
76
+ if (keyFile === undefined || keyFile === '' || keyId === undefined || keyId === '' || teamId === undefined || teamId === '') return undefined
77
+ return { keyFile, keyId, teamId }
78
+ }
79
+
80
+ /** @returns the base64url text of one buffer, without padding. */
81
+ export function base64Url(value: Buffer | string): string {
82
+ return Buffer.from(value).toString('base64url')
83
+ }
84
+
85
+ /**
86
+ * Sign one APNs provider token.
87
+ *
88
+ * Header and claims are exactly what Apple accepts and nothing more: `alg`,
89
+ * `kid` and `iss`, `iat`. APNs rejects a token carrying any other claim, so
90
+ * this is not a place to add a convenient `exp` beside it.
91
+ * @param input - the key, its id, the team id, and the issue time.
92
+ * @returns the compact JWT.
93
+ */
94
+ export function es256Jwt(input: {
95
+ readonly key: KeyObject
96
+ readonly keyId: string
97
+ readonly teamId: string
98
+ readonly issuedAt?: number
99
+ }): string {
100
+ const header = base64Url(JSON.stringify({ alg: 'ES256', kid: input.keyId }))
101
+ const claims = base64Url(JSON.stringify({ iss: input.teamId, iat: Math.floor((input.issuedAt ?? Date.now()) / 1000) }))
102
+ const signingInput = `${header}.${claims}`
103
+ // ES256 is ECDSA over P-256 with SHA-256, and APNs wants the raw r||s pair
104
+ // rather than a DER sequence: 'ieee-p1363' is that encoding.
105
+ const signature = sign('sha256', Buffer.from(signingInput, 'utf8'), { key: input.key, dsaEncoding: 'ieee-p1363' })
106
+ return `${signingInput}.${base64Url(signature)}`
107
+ }
108
+
109
+ /** What one delivery's HTTP/2 request looks like. */
110
+ export interface ApnsRequestSpec {
111
+ readonly authority: string
112
+ readonly path: string
113
+ readonly headers: Readonly<Record<string, string>>
114
+ }
115
+
116
+ /**
117
+ * The request one notification becomes.
118
+ *
119
+ * `apns-topic` is the registration's own bundle id and `apns-push-type` is
120
+ * always `alert`: this channel only ever sends a user-visible notification, and
121
+ * a body typed as anything else would be dropped by the system for having an
122
+ * alert payload.
123
+ * @param target - the device being notified.
124
+ * @param jwt - the provider token.
125
+ * @returns the authority, path and headers of the POST.
126
+ */
127
+ export function apnsRequestSpec(target: PushAddress, jwt: string): ApnsRequestSpec {
128
+ return {
129
+ authority: target.environment === 'production' ? APNS_PRODUCTION_AUTHORITY : APNS_SANDBOX_AUTHORITY,
130
+ path: `${APNS_DEVICE_PATH}${target.deviceToken}`,
131
+ headers: {
132
+ authorization: `bearer ${jwt}`,
133
+ 'apns-topic': target.bundle,
134
+ 'apns-push-type': 'alert',
135
+ 'apns-priority': '10',
136
+ 'content-type': 'application/json',
137
+ },
138
+ }
139
+ }
140
+
141
+ /**
142
+ * The topic one Live Activity push is addressed under.
143
+ * @param bundle - the app bundle the device registered with.
144
+ * @returns the bundle plus the Live Activity suffix, appended once.
145
+ */
146
+ export function liveActivityTopicOf(bundle: string): string {
147
+ return bundle.endsWith(APNS_LIVE_ACTIVITY_TOPIC_SUFFIX) ? bundle : `${bundle}${APNS_LIVE_ACTIVITY_TOPIC_SUFFIX}`
148
+ }
149
+
150
+ /**
151
+ * The request one Live Activity push becomes.
152
+ *
153
+ * Three headers differ from the alert request beside it, and each of them is a
154
+ * rule rather than a preference: the push type is `liveactivity`, the topic is
155
+ * the app bundle's Live Activity topic, and the expiration is `0` — a card
156
+ * update that could not be delivered now must never be delivered later, because
157
+ * it would overwrite the present with the past (§29).
158
+ * @param target - the card being pushed to.
159
+ * @param jwt - the provider token.
160
+ * @returns the authority, path and headers of the POST.
161
+ */
162
+ export function liveActivityRequestSpec(target: LiveActivityAddress, jwt: string): ApnsRequestSpec {
163
+ return {
164
+ authority: target.environment === 'production' ? APNS_PRODUCTION_AUTHORITY : APNS_SANDBOX_AUTHORITY,
165
+ path: `${APNS_DEVICE_PATH}${target.token}`,
166
+ headers: {
167
+ authorization: `bearer ${jwt}`,
168
+ 'apns-topic': liveActivityTopicOf(target.bundle),
169
+ 'apns-push-type': 'liveactivity',
170
+ 'apns-priority': '10',
171
+ 'apns-expiration': '0',
172
+ 'content-type': 'application/json',
173
+ },
174
+ }
175
+ }
176
+
177
+ /** The reason APNs named, or its raw answer when it named none. */
178
+ function apnsReason(text: string): string {
179
+ try {
180
+ const parsed: unknown = JSON.parse(text)
181
+ if (typeof parsed === 'object' && parsed !== null) {
182
+ const reason = (parsed as { reason?: unknown }).reason
183
+ if (typeof reason === 'string' && reason !== '') return reason
184
+ }
185
+ } catch {
186
+ // Not JSON: the body itself is the answer, and it is all there is.
187
+ }
188
+ return text.slice(0, 200)
189
+ }
190
+
191
+ export interface ApnsSenderOptions {
192
+ readonly config: ApnsConfig
193
+ readonly log?: (message: string) => void
194
+ /** Clock the token lifetime is measured against; the wall clock by default. */
195
+ readonly now?: () => number
196
+ readonly timeoutMs?: number
197
+ /** The HTTP/2 dial, injectable so the failure paths need no network. */
198
+ readonly connect?: (authority: string) => ClientHttp2Session
199
+ }
200
+
201
+ /**
202
+ * The APNs delivery half of the push channel.
203
+ *
204
+ * Every method resolves: a delivery that failed is a {@link PushSendResult} with
205
+ * `ok: false`, never a rejection, because both callers sit on frame paths that
206
+ * must not learn about APNs at all.
207
+ */
208
+ export class ApnsSender implements PushSender, LiveActivitySender {
209
+ readonly #config: ApnsConfig
210
+ readonly #log: (message: string) => void
211
+ readonly #now: () => number
212
+ readonly #timeoutMs: number
213
+ readonly #dial: (authority: string) => ClientHttp2Session
214
+ #key: Promise<KeyObject> | undefined
215
+ #token: { readonly value: string; readonly mintedAt: number } | undefined
216
+
217
+ constructor(options: ApnsSenderOptions) {
218
+ this.#config = options.config
219
+ this.#log = options.log ?? (() => undefined)
220
+ this.#now = options.now ?? (() => Date.now())
221
+ this.#timeoutMs = options.timeoutMs ?? APNS_TIMEOUT_MS
222
+ this.#dial = options.connect ?? (authority => connect(`https://${authority}`))
223
+ }
224
+
225
+ /** Deliver one notification, or report why it did not arrive. */
226
+ async send(target: PushAddress, notification: PushNotification): Promise<PushSendResult> {
227
+ let jwt: string
228
+ try {
229
+ jwt = await this.#providerToken()
230
+ } catch (error) {
231
+ return { ok: false, reason: `signing key unusable: ${String(error)}` }
232
+ }
233
+ return await this.#post(apnsRequestSpec(target, jwt), JSON.stringify(notification))
234
+ }
235
+
236
+ /**
237
+ * Deliver one Live Activity push, or report why it did not arrive.
238
+ *
239
+ * The same provider token, the same transport and the same "resolve, never
240
+ * reject" rule as {@link send}; only the request's headers and the body differ,
241
+ * and both are built outside this class so the contract stays assertable.
242
+ */
243
+ async sendLiveActivity(target: LiveActivityAddress, notification: LiveActivityNotification): Promise<PushSendResult> {
244
+ let jwt: string
245
+ try {
246
+ jwt = await this.#providerToken()
247
+ } catch (error) {
248
+ return { ok: false, reason: `signing key unusable: ${String(error)}` }
249
+ }
250
+ return await this.#post(liveActivityRequestSpec(target, jwt), JSON.stringify(notification))
251
+ }
252
+
253
+ /**
254
+ * POST one already-built body to APNs.
255
+ *
256
+ * One HTTP/2 session per delivery, closed as soon as the answer is in: the
257
+ * provider API has no session to keep warm, and one left open would outlive the
258
+ * caller that wanted it. Every failure resolves, because both callers sit on
259
+ * frame paths that must not learn about APNs at all.
260
+ * @param spec - the authority, path and headers of the delivery.
261
+ * @param body - the JSON body to send.
262
+ * @returns whether APNs accepted it, and why not when it did not.
263
+ */
264
+ async #post(spec: ApnsRequestSpec, body: string): Promise<PushSendResult> {
265
+ const authority = spec.authority
266
+ return await new Promise<PushSendResult>((resolve) => {
267
+ let settled = false
268
+ let timer: NodeJS.Timeout | undefined
269
+ const finish = (result: PushSendResult): void => {
270
+ if (settled) return
271
+ settled = true
272
+ if (timer !== undefined) clearTimeout(timer)
273
+ try {
274
+ session.close()
275
+ } catch {
276
+ // A session already gone is the outcome we wanted anyway.
277
+ }
278
+ resolve(result)
279
+ }
280
+ let session: ClientHttp2Session
281
+ try {
282
+ session = this.#dial(authority)
283
+ } catch (error) {
284
+ resolve({ ok: false, reason: `connect failed: ${String(error)}` })
285
+ return
286
+ }
287
+ timer = setTimeout(() => { finish({ ok: false, reason: `no answer within ${this.#timeoutMs} ms` }) }, this.#timeoutMs)
288
+ timer.unref?.()
289
+ session.on('error', (error: Error) => { finish({ ok: false, reason: String(error) }) })
290
+ session.on('close', () => { finish({ ok: false, reason: 'the connection closed before APNs answered' }) })
291
+ let status = 0
292
+ let text = ''
293
+ try {
294
+ const stream = session.request({ ':method': 'POST', ':path': spec.path, ...spec.headers })
295
+ stream.setEncoding('utf8')
296
+ stream.on('response', (headers) => { status = Number(headers[':status'] ?? 0) })
297
+ stream.on('data', (chunk: string) => { text += chunk })
298
+ stream.on('error', (error: Error) => { finish({ ok: false, reason: String(error) }) })
299
+ stream.on('end', () => {
300
+ finish(status === 200 ? { ok: true, status } : { ok: false, status, reason: apnsReason(text) })
301
+ })
302
+ stream.end(body)
303
+ } catch (error) {
304
+ finish({ ok: false, reason: `request failed: ${String(error)}` })
305
+ }
306
+ })
307
+ }
308
+
309
+ /** @returns the cached provider token, minting one when it has aged out. */
310
+ async #providerToken(): Promise<string> {
311
+ const now = this.#now()
312
+ if (this.#token !== undefined && now - this.#token.mintedAt < APNS_TOKEN_TTL_MS) return this.#token.value
313
+ this.#key ??= readFile(this.#config.keyFile, 'utf8').then(pem => createPrivateKey({ key: pem, format: 'pem' }))
314
+ const key = await this.#key
315
+ const value = es256Jwt({ key, keyId: this.#config.keyId, teamId: this.#config.teamId, issuedAt: now })
316
+ this.#token = { value, mintedAt: now }
317
+ this.#log(`minted an APNs provider token for key ${this.#config.keyId}`)
318
+ return value
319
+ }
320
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The read-only ledger fallback of the squads channel.
3
+ *
4
+ * `dsh-agents` is the only writer of this document, and this bridge reads the
5
+ * same bytes under the same rules: a document of an unknown generation, a
6
+ * revision that is not a whole number, or a team/run set this build cannot read
7
+ * is refused rather than repaired. Nothing here writes, locks, creates or
8
+ * quarantines anything — a Host whose loopback route cannot answer still shows
9
+ * the user's own definitions, and never edits them from behind the plugin's back.
10
+ *
11
+ * The rows themselves are mapped by `core/squads.ts`, exactly as a loopback
12
+ * answer is: the two paths meet in one mapping, so a fallback body cannot drift
13
+ * from a served one.
14
+ * @module dsh-remote-bridge/host/squads-ledger
15
+ */
16
+
17
+ import { readFile } from 'node:fs/promises'
18
+ import { join } from 'node:path'
19
+ import { CODE_SQUADS_UNAVAILABLE } from '../core/protocol.ts'
20
+ import { SquadRefusal } from '../core/squads.ts'
21
+
22
+ /** Ledger file name inside the plugin's own directory. */
23
+ export const SQUAD_LEDGER_FILE = 'ledger.json'
24
+
25
+ /** Owner lock beside it; it is what carries the owning pid. */
26
+ export const SQUAD_LEDGER_LOCK_FILE = 'ledger.json.lock'
27
+
28
+ /** The one ledger generation this build reads. */
29
+ export const SQUAD_LEDGER_SCHEMA_VERSION = 1
30
+
31
+ /** One state document read off the ledger, in the plugin's own key names. */
32
+ export interface SquadLedgerDocument {
33
+ teams: readonly unknown[]
34
+ runs: readonly unknown[]
35
+ host: { ownerPid?: number }
36
+ }
37
+
38
+ /** The plugin's own code for a ledger this build cannot read. */
39
+ const CODE_LEDGER_CORRUPT = 'ledger-corrupt'
40
+
41
+ function record(value: unknown): Record<string, unknown> | undefined {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined
43
+ }
44
+
45
+ function messageOf(error: unknown): string {
46
+ return error instanceof Error ? error.message : String(error)
47
+ }
48
+
49
+ function corrupt(reason: string): SquadRefusal {
50
+ return new SquadRefusal(CODE_LEDGER_CORRUPT, 'the dsh-agents ledger ' + reason)
51
+ }
52
+
53
+ /**
54
+ * Read the owning pid from the ledger lock.
55
+ *
56
+ * The lock is the plugin's own record of who is writing; a missing or unreadable
57
+ * one leaves the pid absent, because a channel with no owner to name is not a
58
+ * failure of the read.
59
+ * @param directory - the plugin-owned directory.
60
+ * @returns `{ownerPid}` when the lock names one, or an empty object.
61
+ */
62
+ async function ownerOf(directory: string): Promise<{ ownerPid?: number }> {
63
+ try {
64
+ const parsed = record(JSON.parse(await readFile(join(directory, SQUAD_LEDGER_LOCK_FILE), 'utf8')))
65
+ const pid = parsed?.pid
66
+ return typeof pid === 'number' && Number.isInteger(pid) && pid > 0 ? { ownerPid: pid } : {}
67
+ } catch {
68
+ return {}
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Read the ledger document without touching it.
74
+ * @param directory - the plugin-owned directory (`$DSH_HOME/dsh-agents`).
75
+ * @returns the definitions and runs as stored, plus the owning pid when the lock
76
+ * names one.
77
+ * @throws {SquadRefusal} `squads-unavailable` when there is no readable ledger, or
78
+ * the plugin's own `ledger-corrupt` when the bytes are not the document this
79
+ * build reads.
80
+ */
81
+ export async function readSquadLedger(directory: string): Promise<SquadLedgerDocument> {
82
+ const file = join(directory, SQUAD_LEDGER_FILE)
83
+ let text: string
84
+ try {
85
+ text = await readFile(file, 'utf8')
86
+ } catch (error) {
87
+ throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain over loopback and holds no ledger at ' + file + ': ' + messageOf(error))
88
+ }
89
+ let parsed: unknown
90
+ try {
91
+ parsed = JSON.parse(text)
92
+ } catch (error) {
93
+ throw corrupt('at ' + file + ' is not valid JSON: ' + messageOf(error))
94
+ }
95
+ const document = record(parsed)
96
+ if (document === undefined) throw corrupt('is not a JSON object')
97
+ if (document.schemaVersion !== SQUAD_LEDGER_SCHEMA_VERSION) {
98
+ throw corrupt('declares generation ' + String(document.schemaVersion) + ', and this build reads ' + String(SQUAD_LEDGER_SCHEMA_VERSION))
99
+ }
100
+ if (typeof document.revision !== 'number' || !Number.isInteger(document.revision) || document.revision < 0) {
101
+ throw corrupt('carries no usable revision')
102
+ }
103
+ if (!Array.isArray(document.teams) || !Array.isArray(document.runs)) throw corrupt('holds no team/run arrays')
104
+ return { teams: document.teams, runs: document.runs, host: await ownerOf(directory) }
105
+ }