dsh-memu-memory 1.2.2 → 1.2.4

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 (58) hide show
  1. package/AGENTS.md +4 -1
  2. package/README.md +12 -16
  3. package/README.zh.md +13 -17
  4. package/docs/client-conventions.md +2 -0
  5. package/docs/contributing.md +7 -6
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +63 -1
  8. package/docs/host-api.md +19 -0
  9. package/docs/memory-semantics.md +10 -1
  10. package/docs/troubleshooting.md +77 -3
  11. package/lib/activity-log.js +1 -1
  12. package/lib/binding-diagnostics.js +1 -1
  13. package/lib/client.js +223 -19
  14. package/lib/cycle.js +9 -1
  15. package/lib/embedding-catalog.js +416 -138
  16. package/lib/embedding-download.js +36 -11
  17. package/lib/freshness.js +97 -0
  18. package/lib/graph.js +244 -2
  19. package/lib/inject.js +218 -11
  20. package/lib/local-embedding-manager.js +3 -2
  21. package/lib/local-embedding-protocol.js +40 -3
  22. package/lib/local-embedding-worker.js +36 -6
  23. package/lib/local-vector-service.js +18 -4
  24. package/lib/memory.js +83 -17
  25. package/lib/memu.js +15 -7
  26. package/lib/private.js +25 -5
  27. package/lib/rpc.js +17 -3
  28. package/lib/salient-wake.js +402 -0
  29. package/lib/state.js +173 -1
  30. package/package.json +3 -2
  31. package/scripts/drive-session.mjs +864 -0
  32. package/scripts/mock-llm.mjs +903 -0
  33. package/scripts/simulate-injection.mjs +298 -0
  34. package/tests/client-render.test.mjs +69 -2
  35. package/tests/consolidation-fork.test.mjs +14 -1
  36. package/tests/drive-session.test.mjs +152 -0
  37. package/tests/embedding-catalog.test.mjs +116 -8
  38. package/tests/embedding-download.test.mjs +97 -2
  39. package/tests/embedding-runtime.test.mjs +21 -13
  40. package/tests/entity-merge.test.mjs +261 -0
  41. package/tests/fixtures/mock-llm/reply.txt +1 -0
  42. package/tests/freshness.test.mjs +140 -0
  43. package/tests/help-page.test.mjs +4 -4
  44. package/tests/injection-chain.test.mjs +176 -0
  45. package/tests/injection-rollback.test.mjs +230 -0
  46. package/tests/local-embedding-env.test.mjs +51 -0
  47. package/tests/local-embedding-manager.test.mjs +18 -0
  48. package/tests/local-embedding-protocol.test.mjs +28 -2
  49. package/tests/local-embedding-worker.test.mjs +94 -0
  50. package/tests/mock-llm.test.mjs +225 -0
  51. package/tests/open-loop-date.test.mjs +406 -0
  52. package/tests/salient-wake.test.mjs +362 -0
  53. package/tests/settings-plumbing.test.mjs +76 -0
  54. package/tests/sidebar.test.mjs +5 -1
  55. package/tests/simulate-injection.test.mjs +76 -0
  56. package/tests/stubs/dsh-schedule.js +105 -0
  57. package/tests/vector-profile.test.mjs +28 -4
  58. package/tests/webui-auth.test.mjs +4 -0
@@ -0,0 +1,864 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * EVALUATION ONLY — drive one bound conversation through the public Session
4
+ * remote for work order B. Never imported by runtime code.
5
+ *
6
+ * Public request shape (verified against the host source on 2026-11-01):
7
+ *
8
+ * packages/api/session-controller/src/types.ts
9
+ * interface SessionPromptRequest {
10
+ * requestId: SessionRequestId
11
+ * sessionId: SessionId
12
+ * mode: 'queue' | 'steer'
13
+ * content: readonly PromptContentPart[] // {type:'text', text}
14
+ * clientTimeZone?: string // 'UTC' or a valid IANA name
15
+ * }
16
+ *
17
+ * packages/api/session-controller/src/index.ts
18
+ * @Remote('prompt') prompt(request, signal) -> { accepted: true }
19
+ *
20
+ * Transport rule
21
+ * --------------
22
+ * The generated client calls this unary method through the Connection RPC
23
+ * carrier; its documented wire form is (docs/api-gateway.md):
24
+ *
25
+ * POST <base>/api/session/prompt
26
+ * {
27
+ * "type": "client-request",
28
+ * "rpcId": "<connection correlation id>",
29
+ * "method": "session/prompt",
30
+ * "payload": { "args": { "request": <SessionPromptRequest> } }
31
+ * }
32
+ * ->
33
+ * { "type": "server-response", "rpcId": "<same>", "result": { "ok": true, "value": { "accepted": true } } }
34
+ *
35
+ * There is no stream-carrier form for this method: the API Gateway rejects a
36
+ * unary method opened through /api/remote.mux with gateway/signature-invalid.
37
+ *
38
+ * Work order B forbids silently calling the shared /api route. Therefore this
39
+ * script deliberately REFUSES to send anything unless --allow-api-route is
40
+ * passed together with --base. Without that explicit opt-in it prints the exact
41
+ * requests as a manual fallback and exits non-zero (code 3). This is not a
42
+ * missing feature; it is the rule.
43
+ *
44
+ * Authentication assumption: the Host's /api route is behind its persistent
45
+ * browser authentication (connection.admit() returns 401 without a valid
46
+ * cookie). If the target Host enforces it, pass --cookie-file with the single
47
+ * Cookie header value copied from the authenticated browser session. This
48
+ * harness never prints or stores that value, and it sends no other credentials.
49
+ * A non-loopback --base would additionally need the Host's trustedHosts setup;
50
+ * the harness warns but does not bypass it.
51
+ *
52
+ * Completion is observed from the public persisted session log
53
+ * (<DSH_HOME>/sessions/<project>/<sessionId>/session.v4.jsonl.zstd), the same
54
+ * artifact docs/host-api.md §6.8 describes. No private endpoint and no plugin
55
+ * RPC is called. A turn counts as done only when a turn/end for this prompt
56
+ * reports reason.kind === 'completed'.
57
+ *
58
+ * Usage:
59
+ * node scripts/drive-session.mjs --session <id> --turns 50 \
60
+ * --base http://127.0.0.1:<host-gateway-port> --allow-api-route \
61
+ * --requests-out ./requests.jsonl
62
+ * node scripts/drive-session.mjs --session <id> --turns 5 --dry-run
63
+ *
64
+ * Exit codes:
65
+ * 0 all requested turns completed
66
+ * 1 a turn or the transport failed (the first failure stops the run)
67
+ * 2 usage error
68
+ * 3 manual fallback: nothing was sent (no approved transport)
69
+ * 4 preflight failure: the session log needed to observe turn/end is absent
70
+ */
71
+ import crypto from 'node:crypto'
72
+ import fs from 'node:fs'
73
+ import os from 'node:os'
74
+ import path from 'node:path'
75
+ import zlib from 'node:zlib'
76
+ import { pathToFileURL } from 'node:url'
77
+
78
+ const EXIT_OK = 0
79
+ const EXIT_FAILED = 1
80
+ const EXIT_USAGE = 2
81
+ const EXIT_MANUAL = 3
82
+ const EXIT_PREFLIGHT = 4
83
+
84
+ const DEFAULT_TURNS = 50
85
+ const DEFAULT_TIMEOUT_MS = 180_000
86
+ const DEFAULT_POLL_MS = 400
87
+
88
+ /**
89
+ * Neutral prompts used only when neither --prompt nor --text-file is supplied.
90
+ * They contain no user data and are cycled to reach --turns.
91
+ */
92
+ const DEFAULT_PROMPTS = Object.freeze([
93
+ '今天有点累,随便聊聊吧。',
94
+ '你还记得我昨天提到的那件事吗?',
95
+ '帮我把今天要做的事理一理。',
96
+ '我们上次说到哪儿了?',
97
+ '明天有什么安排吗?',
98
+ '我想起一个很久以前的小事。',
99
+ '给我讲讲你最近在忙什么。',
100
+ '如果要去一个陌生的城市,你会先做什么?',
101
+ '今天天气怎么样?凭记忆回答就好。',
102
+ '晚安,明天见。',
103
+ ])
104
+
105
+ const USAGE = `EVALUATION ONLY — drive one conversation through the public Session prompt remote.
106
+
107
+ Usage:
108
+ node scripts/drive-session.mjs --session <id> [options] [--prompt <text> ...]
109
+
110
+ Required:
111
+ --session <id> Target SessionId (the conversation must already be
112
+ bound to the test library).
113
+
114
+ Transport:
115
+ --base <url> Host gateway base, e.g. http://127.0.0.1:3000
116
+ (the Host's own port, not the mock LLM port).
117
+ --allow-api-route Explicitly permit the documented public Connection RPC
118
+ carrier POST <base>/api/session/prompt. Without this
119
+ flag and --base, nothing is sent: the script prints a
120
+ manual fallback and exits 3 (work order B rule).
121
+ --cookie-file <p> File holding one Cookie header value for /api. The
122
+ Host browser-authenticates /api, so a real Host
123
+ usually returns 401 without it. The value is never
124
+ printed or stored by this script.
125
+
126
+ Turns:
127
+ --turns <n> Number of prompts. Default: ${DEFAULT_TURNS}.
128
+ --prompt <text> One prompt; repeatable. Positional text after options
129
+ is also accepted as prompts.
130
+ --text-file <p> .json array of strings / {text|prompt|content} objects,
131
+ or one prompt per non-empty line. Optional: without it
132
+ the built-in neutral prompts are cycled.
133
+ --interval-ms <n> Wait between completed turns. Default: 0.
134
+ --timeout-ms <n> Per-turn send + completion budget. Default: ${DEFAULT_TIMEOUT_MS}.
135
+ --poll-ms <n> Session-log poll interval. Default: ${DEFAULT_POLL_MS}.
136
+ --client-time-zone <iana> IANA name sent as clientTimeZone. Default: system zone.
137
+
138
+ Observation:
139
+ --session-log <p> Exact session log path (skips discovery).
140
+ --dsh-home <p> DSH home used for discovery. Default: $DSH_HOME or ~/.dsh.
141
+
142
+ Output:
143
+ --requests-out <p> Write the exact request objects as JSONL before sending.
144
+ This file contains the prompt text; delete it after use
145
+ and do not commit it.
146
+ --dry-run Print the requests and exit 0 without sending.
147
+ -h, --help Show this text.
148
+
149
+ Public request sent for every turn:
150
+ sessionController.prompt({
151
+ requestId: '<unique per turn>',
152
+ sessionId: '<--session>',
153
+ mode: 'queue',
154
+ content: [{ type: 'text', text: '<prompt>' }],
155
+ clientTimeZone: '<IANA>'
156
+ })
157
+
158
+ The run stops on the first failure. A timeout or a non-completed turn/end is a
159
+ failure and is not counted as a valid turn. No /api call is made without
160
+ --allow-api-route.
161
+ `
162
+
163
+ function failUsage(message) {
164
+ console.error('drive-session: ' + message + '\n')
165
+ console.error(USAGE)
166
+ return EXIT_USAGE
167
+ }
168
+
169
+ function parseArgs(argv) {
170
+ const options = {
171
+ base: null,
172
+ session: null,
173
+ turns: DEFAULT_TURNS,
174
+ intervalMs: 0,
175
+ timeoutMs: DEFAULT_TIMEOUT_MS,
176
+ pollMs: DEFAULT_POLL_MS,
177
+ textFile: null,
178
+ prompts: [],
179
+ clientTimeZone: null,
180
+ sessionLog: null,
181
+ dshHome: null,
182
+ requestsOut: null,
183
+ cookieFile: null,
184
+ allowApiRoute: false,
185
+ dryRun: false,
186
+ help: false,
187
+ }
188
+ const take = (index, name) => {
189
+ const value = argv[index]
190
+ if (value === undefined || value.startsWith('--')) throw new Error(name + ' requires a value')
191
+ return value
192
+ }
193
+ for (let i = 0; i < argv.length; i += 1) {
194
+ const token = argv[i]
195
+ if (token === '-h') {
196
+ options.help = true
197
+ continue
198
+ }
199
+ if (!token.startsWith('--')) {
200
+ options.prompts.push(token)
201
+ continue
202
+ }
203
+ const eq = token.indexOf('=')
204
+ const name = eq === -1 ? token : token.slice(0, eq)
205
+ const inline = eq === -1 ? null : token.slice(eq + 1)
206
+ switch (name) {
207
+ case '--help':
208
+ options.help = true
209
+ break
210
+ case '--base':
211
+ options.base = inline ?? take(++i, '--base')
212
+ break
213
+ case '--session':
214
+ options.session = inline ?? take(++i, '--session')
215
+ break
216
+ case '--turns':
217
+ options.turns = positiveInt(inline ?? take(++i, '--turns'), '--turns')
218
+ break
219
+ case '--interval-ms':
220
+ options.intervalMs = nonNegativeInt(inline ?? take(++i, '--interval-ms'), '--interval-ms')
221
+ break
222
+ case '--timeout-ms':
223
+ options.timeoutMs = positiveInt(inline ?? take(++i, '--timeout-ms'), '--timeout-ms')
224
+ break
225
+ case '--poll-ms':
226
+ options.pollMs = positiveInt(inline ?? take(++i, '--poll-ms'), '--poll-ms')
227
+ break
228
+ case '--text-file':
229
+ options.textFile = inline ?? take(++i, '--text-file')
230
+ break
231
+ case '--prompt':
232
+ options.prompts.push(inline ?? take(++i, '--prompt'))
233
+ break
234
+ case '--client-time-zone':
235
+ options.clientTimeZone = inline ?? take(++i, '--client-time-zone')
236
+ break
237
+ case '--session-log':
238
+ options.sessionLog = inline ?? take(++i, '--session-log')
239
+ break
240
+ case '--dsh-home':
241
+ options.dshHome = inline ?? take(++i, '--dsh-home')
242
+ break
243
+ case '--requests-out':
244
+ options.requestsOut = inline ?? take(++i, '--requests-out')
245
+ break
246
+ case '--cookie-file':
247
+ options.cookieFile = inline ?? take(++i, '--cookie-file')
248
+ break
249
+ case '--allow-api-route':
250
+ if (inline !== null) throw new Error('--allow-api-route does not take a value')
251
+ options.allowApiRoute = true
252
+ break
253
+ case '--dry-run':
254
+ if (inline !== null) throw new Error('--dry-run does not take a value')
255
+ options.dryRun = true
256
+ break
257
+ default:
258
+ throw new Error('unknown option: ' + token)
259
+ }
260
+ }
261
+ return options
262
+ }
263
+
264
+ function positiveInt(value, name) {
265
+ const number = Number(value)
266
+ if (!Number.isSafeInteger(number) || number <= 0) throw new Error(name + ' must be a positive integer')
267
+ return number
268
+ }
269
+
270
+ function nonNegativeInt(value, name) {
271
+ const number = Number(value)
272
+ if (!Number.isSafeInteger(number) || number < 0) throw new Error(name + ' must be a non-negative integer')
273
+ return number
274
+ }
275
+
276
+ function defaultClientTimeZone() {
277
+ try {
278
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
279
+ return typeof zone === 'string' && zone ? zone : 'UTC'
280
+ } catch {
281
+ return 'UTC'
282
+ }
283
+ }
284
+
285
+ function readTextFilePrompts(file) {
286
+ const raw = fs.readFileSync(file, 'utf8')
287
+ if (path.extname(file).toLowerCase() === '.json') {
288
+ let value
289
+ try { value = JSON.parse(raw) } catch (error) { throw new Error('--text-file is not valid JSON: ' + error.message) }
290
+ if (!Array.isArray(value)) throw new Error('--text-file JSON must be an array')
291
+ const prompts = value.map((item, index) => textOfPromptItem(item, index)).filter(Boolean)
292
+ if (prompts.length === 0) throw new Error('--text-file JSON array contains no prompts')
293
+ return prompts
294
+ }
295
+ const prompts = raw.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith('#'))
296
+ if (prompts.length === 0) throw new Error('--text-file contains no non-empty lines')
297
+ return prompts
298
+ }
299
+
300
+ function textOfPromptItem(item, index) {
301
+ if (typeof item === 'string') return item.trim()
302
+ if (!item || typeof item !== 'object') throw new Error('--text-file item ' + (index + 1) + ' is not a string or object')
303
+ const candidate = item.text ?? item.prompt ?? item.content
304
+ if (typeof candidate === 'string') return candidate.trim()
305
+ if (Array.isArray(candidate)) {
306
+ const text = candidate
307
+ .map((part) => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : ''))
308
+ .filter(Boolean)
309
+ .join('\n')
310
+ .trim()
311
+ if (text) return text
312
+ }
313
+ throw new Error('--text-file item ' + (index + 1) + ' has no text/prompt/content string')
314
+ }
315
+
316
+ function resolvePrompts(options) {
317
+ const prompts = [...options.prompts]
318
+ if (options.textFile) prompts.push(...readTextFilePrompts(options.textFile))
319
+ const list = prompts.length > 0 ? prompts.map((text) => String(text).trim()).filter(Boolean) : [...DEFAULT_PROMPTS]
320
+ if (list.length === 0) throw new Error('no prompts resolved')
321
+ return list
322
+ }
323
+
324
+ function buildRequests({ sessionId, turns, prompts, clientTimeZone }) {
325
+ const runId = 'memu-eval-' + new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)
326
+ + '-' + crypto.randomBytes(2).toString('hex')
327
+ const requests = []
328
+ for (let turn = 1; turn <= turns; turn += 1) {
329
+ const text = prompts[(turn - 1) % prompts.length]
330
+ // One identity, generated once: the log matcher and the wire request must
331
+ // agree, and a retried request must not reuse it.
332
+ const requestId = runId + '-' + String(turn).padStart(3, '0') + '-' + crypto.randomBytes(2).toString('hex')
333
+ requests.push({
334
+ turn,
335
+ requestId,
336
+ request: {
337
+ requestId,
338
+ sessionId,
339
+ mode: 'queue',
340
+ content: [{ type: 'text', text }],
341
+ clientTimeZone,
342
+ },
343
+ })
344
+ }
345
+ return requests
346
+ }
347
+
348
+ function writeRequests(file, requests) {
349
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true })
350
+ const body = requests.map((item) => JSON.stringify({ turn: item.turn, requestId: item.requestId, request: item.request })).join('\n') + '\n'
351
+ fs.writeFileSync(file, body, 'utf8')
352
+ }
353
+
354
+ function printManualFallback({ reason, requests, requestsOut }) {
355
+ const sample = requests[0]?.request
356
+ console.error('MANUAL FALLBACK — nothing was sent.')
357
+ console.error('')
358
+ console.error('Reason: ' + reason)
359
+ console.error('')
360
+ console.error('This harness only calls the public remote below, and it will not touch the')
361
+ console.error('shared /api route on its own:')
362
+ console.error('')
363
+ console.error(' sessionController.prompt({')
364
+ console.error(' requestId, sessionId, mode: \'queue\',')
365
+ console.error(' content: [{ type: \'text\', text }], clientTimeZone')
366
+ console.error(' })')
367
+ console.error('')
368
+ console.error('Deliver each request with an approved client that can call that remote, then')
369
+ console.error('read the mock-llm JSONL log with:')
370
+ console.error('')
371
+ console.error(' node scripts/mock-llm.mjs --report <mock-llm.jsonl> > mock-llm-report-YYYY-MM-DD.md')
372
+ console.error('')
373
+ console.error('If you explicitly accept the documented public Connection RPC carrier, re-run with:')
374
+ console.error('')
375
+ console.error(' --base <host gateway> --allow-api-route')
376
+ console.error('')
377
+ console.error('That carrier is POST <base>/api/session/prompt with a client-request envelope;')
378
+ console.error('it is the same public remote the official browser client uses, not a private')
379
+ console.error('endpoint. Without the opt-in flag this driver refuses to POST /api.')
380
+ console.error('The Host browser-authenticates /api: add --cookie-file <path> (one Cookie')
381
+ console.error('header value) if the carrier answers 401/403.')
382
+ if (requestsOut) console.error('')
383
+ if (requestsOut) console.error('All ' + requests.length + ' request objects were written to ' + path.resolve(requestsOut) + '.')
384
+ else if (requests.length > 5) console.error('Rerun with --requests-out <path> to write all ' + requests.length + ' request objects as JSONL.')
385
+ console.error('')
386
+ if (!requestsOut && requests.length <= 5) {
387
+ for (const item of requests) {
388
+ console.error('turn ' + item.turn + ':')
389
+ console.error(JSON.stringify(item.request, null, 2))
390
+ }
391
+ } else {
392
+ console.error('First request (' + requests.length + ' total):')
393
+ console.error(JSON.stringify(sample, null, 2))
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Encode one Session id as the persistence layer does (host format.ts
399
+ * encodeSegment). Kept local so the harness imports no host or plugin code.
400
+ */
401
+ function encodeSegment(raw) {
402
+ let out = ''
403
+ for (let i = 0; i < raw.length; i += 1) {
404
+ const ch = String.fromCharCode(raw.charCodeAt(i))
405
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
406
+ else out += '~' + raw.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0')
407
+ }
408
+ return out
409
+ }
410
+
411
+ const LOG_SUFFIXES = ['session.v4.jsonl.zstd', 'session.v4.jsonl', 'session.jsonl.zstd', 'session.jsonl']
412
+
413
+ function locateSessionLog({ explicit, dshHome, sessionId }) {
414
+ if (explicit) {
415
+ const resolved = path.resolve(explicit)
416
+ return fs.existsSync(resolved) ? resolved : null
417
+ }
418
+ const root = path.join(dshHome, 'sessions')
419
+ let projects
420
+ try { projects = fs.readdirSync(root, { withFileTypes: true }) } catch { return null }
421
+ const encoded = encodeSegment(sessionId)
422
+ for (const project of projects) {
423
+ if (!project.isDirectory()) continue
424
+ for (const dirName of [sessionId, encoded]) {
425
+ const dir = path.join(root, project.name, dirName)
426
+ for (const suffix of LOG_SUFFIXES) {
427
+ const candidate = path.join(dir, suffix)
428
+ if (fs.existsSync(candidate)) return candidate
429
+ }
430
+ }
431
+ }
432
+ return null
433
+ }
434
+
435
+ const ZSTD_MAGIC = 0xFD2FB528
436
+
437
+ /**
438
+ * Locate complete Zstandard frames in a concatenated log.
439
+ *
440
+ * Mirrors the structural scan in the host's session-persistence-jsonl package
441
+ * (src/zstd.ts) because Node's one-shot decompressor stops after the first
442
+ * frame and this harness must not import host packages. The final frame may be
443
+ * torn while the host is writing; it is left for the next poll.
444
+ */
445
+ function scanZstdFrames(buffer) {
446
+ const frames = []
447
+ let offset = 0
448
+ while (offset < buffer.length) {
449
+ const start = offset
450
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
451
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error('corrupt session log: bad zstd magic at byte ' + offset)
452
+ offset += 4
453
+ if (offset === buffer.length) return { frames, tornStart: start }
454
+ const descriptor = buffer.readUInt8(offset)
455
+ offset += 1
456
+ if ((descriptor & 0x18) !== 0) throw new Error('corrupt session log: reserved frame-header bit')
457
+ const contentSizeFlag = descriptor >>> 6
458
+ const singleSegment = (descriptor & 0x20) !== 0
459
+ const checksum = (descriptor & 0x04) !== 0
460
+ const dictionaryFlag = descriptor & 0x03
461
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
462
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
463
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
464
+ if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start }
465
+ offset += remainingHeaderBytes
466
+ for (;;) {
467
+ if (buffer.length - offset < 3) return { frames, tornStart: start }
468
+ const blockHeader = buffer.readUIntLE(offset, 3)
469
+ offset += 3
470
+ const lastBlock = (blockHeader & 1) !== 0
471
+ const blockType = (blockHeader >>> 1) & 0x03
472
+ const blockSize = blockHeader >>> 3
473
+ if (blockType === 0x03) throw new Error('corrupt session log: reserved block type')
474
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
475
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
476
+ offset += payloadBytes
477
+ if (lastBlock) break
478
+ }
479
+ if (checksum) {
480
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
481
+ offset += 4
482
+ }
483
+ frames.push({ start, end: offset })
484
+ }
485
+ return { frames }
486
+ }
487
+
488
+ function readSessionEvents(file) {
489
+ const raw = fs.readFileSync(file)
490
+ let text
491
+ if (file.endsWith('.zstd')) {
492
+ const { frames } = scanZstdFrames(raw)
493
+ const parts = []
494
+ for (const frame of frames) {
495
+ try {
496
+ parts.push(zlib.zstdDecompressSync(raw.subarray(frame.start, frame.end)))
497
+ } catch (error) {
498
+ throw new Error('cannot decompress session log frame at byte ' + frame.start + ': ' + error.message)
499
+ }
500
+ }
501
+ text = Buffer.concat(parts).toString('utf8')
502
+ } else {
503
+ text = raw.toString('utf8')
504
+ }
505
+ const events = []
506
+ for (const line of text.split(/\r?\n/)) {
507
+ if (!line.trim()) continue
508
+ try {
509
+ const value = JSON.parse(line)
510
+ if (value && typeof value === 'object') events.push(value)
511
+ } catch {
512
+ // The host appends complete JSON lines; a torn line is retried next poll.
513
+ }
514
+ }
515
+ return events
516
+ }
517
+
518
+ /**
519
+ * Index of the durable user/message that claims this requestId.
520
+ *
521
+ * The inbox `agent/inbox/spliced` event proves admission but not that a turn
522
+ * consumed the prompt, so it is deliberately not used as the anchor. A
523
+ * `user/message` appears inside the turn that actually claims the prompt, which
524
+ * is what lets the wait below pair it with the right turn/end.
525
+ */
526
+ function promptClaimIndex(events, requestId) {
527
+ for (let i = events.length - 1; i >= 0; i -= 1) {
528
+ const event = events[i]
529
+ if (event?.type === 'user/message' && event?.data?.source?.rpcId === requestId) return i
530
+ }
531
+ return -1
532
+ }
533
+
534
+ /** Whether the host durably admitted this requestId (before a turn claims it). */
535
+ function promptAdmitted(events, requestId) {
536
+ return events.some((event) => event?.type === 'agent/inbox/spliced'
537
+ && Array.isArray(event?.data?.inserted)
538
+ && event.data.inserted.some((item) => item?.source?.rpcId === requestId))
539
+ }
540
+
541
+ /** Turn number of the `turn/start` that encloses one claimed user message. */
542
+ function enclosingTurn(events, claimIndex) {
543
+ for (let i = claimIndex - 1; i >= 0; i -= 1) {
544
+ const event = events[i]
545
+ if (event?.type === 'turn/start') {
546
+ const turn = Number(event?.data?.turn)
547
+ return Number.isSafeInteger(turn) ? turn : null
548
+ }
549
+ if (event?.type === 'turn/end') return null
550
+ }
551
+ return null
552
+ }
553
+
554
+ /**
555
+ * Read the public session log until the prompt's own turn/end appears.
556
+ *
557
+ * A queued prompt may be claimed in the middle of an existing long turn, so the
558
+ * enclosing turn is read from the log instead of assuming a fresh turn starts.
559
+ * Only `reason.kind === 'completed'` counts as success.
560
+ *
561
+ * @returns {{state:'completed'|'failed'|'timeout', reason:string, waitedMs:number}}
562
+ */
563
+ async function waitForTurn({ logPath, requestId, timeoutMs, pollMs }) {
564
+ const started = Date.now()
565
+ const deadline = started + timeoutMs
566
+ let admitted = false
567
+ let lastReadError = null
568
+ while (Date.now() < deadline) {
569
+ try {
570
+ const events = readSessionEvents(logPath)
571
+ if (!admitted && promptAdmitted(events, requestId)) admitted = true
572
+ const claim = promptClaimIndex(events, requestId)
573
+ if (claim >= 0) {
574
+ const turn = enclosingTurn(events, claim)
575
+ for (let i = claim + 1; i < events.length; i += 1) {
576
+ const event = events[i]
577
+ if (event?.type !== 'turn/end') continue
578
+ const endedTurn = Number(event?.data?.turn)
579
+ if (turn !== null && Number.isSafeInteger(endedTurn) && endedTurn !== turn) {
580
+ return {
581
+ state: 'failed',
582
+ reason: 'turn/end turn=' + endedTurn + ' does not match the claiming turn=' + turn,
583
+ waitedMs: Date.now() - started,
584
+ }
585
+ }
586
+ const reason = event?.data?.reason?.kind
587
+ if (reason === 'completed') {
588
+ return { state: 'completed', reason: 'completed', waitedMs: Date.now() - started }
589
+ }
590
+ return {
591
+ state: 'failed',
592
+ reason: 'turn/end reason=' + String(reason || 'unknown'),
593
+ waitedMs: Date.now() - started,
594
+ }
595
+ }
596
+ }
597
+ lastReadError = null
598
+ } catch (error) {
599
+ lastReadError = error?.message || String(error)
600
+ }
601
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))))
602
+ }
603
+ if (lastReadError) {
604
+ return { state: 'timeout', reason: 'cannot read session log: ' + lastReadError, waitedMs: timeoutMs }
605
+ }
606
+ return {
607
+ state: 'timeout',
608
+ reason: admitted ? 'prompt was admitted but no turn claimed it before the deadline' : 'prompt not observed in the session log',
609
+ waitedMs: timeoutMs,
610
+ }
611
+ }
612
+
613
+ function joinUrl(base, suffix) {
614
+ return String(base).replace(/\/+$/, '') + suffix
615
+ }
616
+
617
+ /**
618
+ * The Connection RPC carrier wraps each Remote method parameter by **name**, so a
619
+ * single-argument remote must go out as `{ args: { request: <SessionPromptRequest> } }`.
620
+ * Sending the request fields directly is rejected before the host ever sees them
621
+ * (`gateway/arguments-invalid: missing "request"`) — which is what this file did until it
622
+ * actually met a real host.
623
+ */
624
+ export function buildPromptEnvelope(request, rpcId = crypto.randomUUID()) {
625
+ return {
626
+ type: 'client-request',
627
+ rpcId,
628
+ method: 'session/prompt',
629
+ payload: { args: { request } },
630
+ }
631
+ }
632
+
633
+ async function sendPrompt({ base, request, timeoutMs, cookie }) {
634
+ const url = joinUrl(base, '/api/session/prompt')
635
+ const envelope = buildPromptEnvelope(request)
636
+ const headers = { 'content-type': 'application/json' }
637
+ if (cookie) headers.cookie = cookie
638
+ let response
639
+ try {
640
+ response = await fetch(url, {
641
+ method: 'POST',
642
+ headers,
643
+ body: JSON.stringify(envelope),
644
+ signal: AbortSignal.timeout(Math.min(timeoutMs, 2_147_483_647)),
645
+ })
646
+ } catch (error) {
647
+ throw new Error('transport failure for ' + url + ': ' + (error?.message || error))
648
+ }
649
+ const text = await response.text()
650
+ if (!response.ok) {
651
+ const hint = response.status === 401 || response.status === 403
652
+ ? ' (the Host authenticates /api; pass --cookie-file with the browser session cookie)'
653
+ : ''
654
+ throw new Error('HTTP ' + response.status + ' from ' + url + hint + ': ' + text.slice(0, 240))
655
+ }
656
+ let body
657
+ try {
658
+ body = JSON.parse(text)
659
+ } catch {
660
+ throw new Error('response is not JSON (expected a Connection RPC envelope)')
661
+ }
662
+ if (!body || body.type !== 'server-response' || body.rpcId !== envelope.rpcId) {
663
+ throw new Error('response is not the matching Connection RPC envelope')
664
+ }
665
+ if (!body.result || body.result.ok !== true) {
666
+ const failure = body.result?.error || {}
667
+ throw new Error('session/prompt rejected: ' + String(failure.code || 'unknown') + ': ' + String(failure.message || 'no message'))
668
+ }
669
+ if (body.result.value?.accepted !== true) {
670
+ throw new Error('session/prompt did not return { accepted: true }')
671
+ }
672
+ return { rpcId: envelope.rpcId }
673
+ }
674
+
675
+ function isLoopbackHost(hostname) {
676
+ return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1'
677
+ }
678
+
679
+ async function main(argv = process.argv.slice(2)) {
680
+ let options
681
+ try {
682
+ options = parseArgs(argv)
683
+ } catch (error) {
684
+ return failUsage(error.message)
685
+ }
686
+ if (options.help) {
687
+ process.stdout.write(USAGE)
688
+ return EXIT_OK
689
+ }
690
+ if (!options.session || !String(options.session).trim()) {
691
+ return failUsage('--session is required')
692
+ }
693
+ if (options.base) {
694
+ let parsed
695
+ try { parsed = new URL(options.base) } catch { return failUsage('--base is not a valid URL') }
696
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return failUsage('--base must be http(s)')
697
+ if (!isLoopbackHost(parsed.hostname)) {
698
+ console.error('drive-session: warning: --base is not loopback (' + parsed.hostname + '); the harness sends no credentials, so an authenticated host will reject it')
699
+ }
700
+ }
701
+
702
+ const clientTimeZone = options.clientTimeZone || defaultClientTimeZone()
703
+ let prompts
704
+ try {
705
+ prompts = resolvePrompts(options)
706
+ } catch (error) {
707
+ return failUsage(error.message)
708
+ }
709
+ const requests = buildRequests({
710
+ sessionId: String(options.session).trim(),
711
+ turns: options.turns,
712
+ prompts,
713
+ clientTimeZone,
714
+ })
715
+
716
+ let cookie = null
717
+ if (options.cookieFile) {
718
+ try {
719
+ cookie = fs.readFileSync(options.cookieFile, 'utf8').trim()
720
+ } catch (error) {
721
+ return failUsage('cannot read --cookie-file: ' + error.message)
722
+ }
723
+ if (!cookie || /[\r\n]/.test(cookie)) {
724
+ return failUsage('--cookie-file must contain exactly one Cookie header value (no line breaks)')
725
+ }
726
+ }
727
+
728
+ if (options.requestsOut) {
729
+ try { writeRequests(options.requestsOut, requests) } catch (error) {
730
+ console.error('drive-session: cannot write --requests-out: ' + error.message)
731
+ return EXIT_FAILED
732
+ }
733
+ }
734
+
735
+ if (options.dryRun) {
736
+ for (const item of requests) {
737
+ process.stdout.write(JSON.stringify({ turn: item.turn, request: item.request }) + '\n')
738
+ }
739
+ console.log('drive-session: dry run — ' + requests.length + ' request(s) generated, nothing sent')
740
+ return EXIT_OK
741
+ }
742
+
743
+ if (!options.allowApiRoute) {
744
+ printManualFallback({
745
+ reason: 'no approved public-remote carrier. Work order B forbids silently POSTing /api.',
746
+ requests,
747
+ requestsOut: options.requestsOut,
748
+ })
749
+ return EXIT_MANUAL
750
+ }
751
+ if (!options.base) {
752
+ printManualFallback({
753
+ reason: '--allow-api-route needs --base <host gateway>; there is nowhere to send the public remote.',
754
+ requests,
755
+ requestsOut: options.requestsOut,
756
+ })
757
+ return EXIT_MANUAL
758
+ }
759
+
760
+ const dshHome = options.dshHome || process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
761
+ const sessionLog = locateSessionLog({
762
+ explicit: options.sessionLog,
763
+ dshHome,
764
+ sessionId: String(options.session).trim(),
765
+ })
766
+ if (!sessionLog) {
767
+ console.error('drive-session: preflight failed — no session log for ' + options.session)
768
+ console.error(' looked under: ' + path.join(dshHome, 'sessions'))
769
+ console.error(' Pass --session-log <path> with the exact session.v4.jsonl.zstd file,')
770
+ console.error(' or --dsh-home <path> if DSH_HOME is not ' + dshHome + '.')
771
+ console.error(' Nothing was sent: without the public session log a turn cannot be observed as completed.')
772
+ return EXIT_PREFLIGHT
773
+ }
774
+ try {
775
+ readSessionEvents(sessionLog)
776
+ } catch (error) {
777
+ console.error('drive-session: preflight failed — cannot read ' + sessionLog + ': ' + error.message)
778
+ console.error(' Nothing was sent.')
779
+ return EXIT_PREFLIGHT
780
+ }
781
+
782
+ console.log('drive-session: ' + requests.length + ' turn(s) → session ' + options.session)
783
+ console.log(' base: ' + joinUrl(options.base, '/api/session/prompt') + ' (explicit --allow-api-route)')
784
+ console.log(' session log: ' + sessionLog)
785
+ console.log(' clientTimeZone: ' + clientTimeZone)
786
+ console.log(' cookie: ' + (cookie ? 'supplied via --cookie-file (not printed)' : 'none (a Host with browser auth will answer 401)'))
787
+ if (options.requestsOut) console.log(' requests: ' + path.resolve(options.requestsOut))
788
+
789
+ const started = Date.now()
790
+ let completed = 0
791
+ let failed = 0
792
+ let lastFailure = null
793
+ for (const item of requests) {
794
+ const turnStarted = Date.now()
795
+ try {
796
+ await sendPrompt({ base: options.base, request: item.request, timeoutMs: options.timeoutMs, cookie })
797
+ } catch (error) {
798
+ failed += 1
799
+ lastFailure = { turn: item.turn, stage: 'send', reason: error.message }
800
+ console.error('turn ' + item.turn + '/' + requests.length + ' SEND FAILED: ' + error.message)
801
+ break
802
+ }
803
+ // One per-turn budget: admission time is charged against completion time.
804
+ const remaining = Math.max(1_000, options.timeoutMs - (Date.now() - turnStarted))
805
+ const waited = await waitForTurn({
806
+ logPath: sessionLog,
807
+ requestId: item.request.requestId,
808
+ timeoutMs: remaining,
809
+ pollMs: options.pollMs,
810
+ })
811
+ if (waited.state !== 'completed') {
812
+ failed += 1
813
+ lastFailure = { turn: item.turn, stage: 'wait', reason: waited.state + ': ' + waited.reason }
814
+ console.error('turn ' + item.turn + '/' + requests.length + ' WAIT FAILED: ' + waited.state + ' (' + waited.reason + ')')
815
+ break
816
+ }
817
+ completed += 1
818
+ const elapsed = Date.now() - turnStarted
819
+ console.log('turn ' + item.turn + '/' + requests.length + ' completed in ' + elapsed + 'ms (requestId ' + item.request.requestId + ')')
820
+ if (options.intervalMs > 0 && item.turn < requests.length) {
821
+ await new Promise((resolve) => setTimeout(resolve, options.intervalMs))
822
+ }
823
+ }
824
+
825
+ const totalMs = Date.now() - started
826
+ console.log('')
827
+ console.log('summary: sent+completed=' + completed + ' failed=' + failed + ' requested=' + requests.length + ' elapsed=' + totalMs + 'ms')
828
+ if (lastFailure) {
829
+ console.log('first failure: turn ' + lastFailure.turn + ' (' + lastFailure.stage + ') ' + lastFailure.reason)
830
+ return EXIT_FAILED
831
+ }
832
+ if (completed !== requests.length) {
833
+ console.log('run stopped before every requested turn completed')
834
+ return EXIT_FAILED
835
+ }
836
+ console.log('all requested turns completed')
837
+ return EXIT_OK
838
+ }
839
+
840
+ const invokedDirectly = process.argv[1]
841
+ ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
842
+ : false
843
+ if (invokedDirectly) {
844
+ main().then((code) => { process.exitCode = typeof code === 'number' ? code : EXIT_FAILED }).catch((error) => {
845
+ console.error('drive-session: ' + (error?.stack || error))
846
+ process.exitCode = EXIT_FAILED
847
+ })
848
+ }
849
+
850
+ export {
851
+ DEFAULT_PROMPTS,
852
+ buildRequests,
853
+ encodeSegment,
854
+ enclosingTurn,
855
+ locateSessionLog,
856
+ parseArgs,
857
+ promptAdmitted,
858
+ promptClaimIndex,
859
+ readSessionEvents,
860
+ scanZstdFrames,
861
+ sendPrompt,
862
+ textOfPromptItem,
863
+ waitForTurn,
864
+ }