dsh-memu-memory 1.2.2 → 1.2.3
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/AGENTS.md +3 -1
- package/README.md +12 -4
- package/README.zh.md +13 -5
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +7 -6
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +20 -0
- package/docs/host-api.md +19 -0
- package/docs/memory-semantics.md +10 -1
- package/docs/troubleshooting.md +36 -3
- package/lib/activity-log.js +1 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +152 -9
- package/lib/cycle.js +9 -1
- package/lib/freshness.js +97 -0
- package/lib/graph.js +244 -2
- package/lib/inject.js +119 -8
- package/lib/memory.js +83 -17
- package/lib/rpc.js +13 -2
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +92 -1
- package/package.json +1 -1
- package/scripts/drive-session.mjs +853 -0
- package/scripts/mock-llm.mjs +903 -0
- package/tests/client-render.test.mjs +13 -1
- package/tests/entity-merge.test.mjs +261 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/help-page.test.mjs +4 -4
- package/tests/injection-chain.test.mjs +176 -0
- package/tests/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/webui-auth.test.mjs +4 -0
|
@@ -0,0 +1,853 @@
|
|
|
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": { <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
|
+
async function sendPrompt({ base, request, timeoutMs, cookie }) {
|
|
618
|
+
const url = joinUrl(base, '/api/session/prompt')
|
|
619
|
+
const rpcId = crypto.randomUUID()
|
|
620
|
+
const envelope = {
|
|
621
|
+
type: 'client-request',
|
|
622
|
+
rpcId,
|
|
623
|
+
method: 'session/prompt',
|
|
624
|
+
payload: { args: request },
|
|
625
|
+
}
|
|
626
|
+
const headers = { 'content-type': 'application/json' }
|
|
627
|
+
if (cookie) headers.cookie = cookie
|
|
628
|
+
let response
|
|
629
|
+
try {
|
|
630
|
+
response = await fetch(url, {
|
|
631
|
+
method: 'POST',
|
|
632
|
+
headers,
|
|
633
|
+
body: JSON.stringify(envelope),
|
|
634
|
+
signal: AbortSignal.timeout(Math.min(timeoutMs, 2_147_483_647)),
|
|
635
|
+
})
|
|
636
|
+
} catch (error) {
|
|
637
|
+
throw new Error('transport failure for ' + url + ': ' + (error?.message || error))
|
|
638
|
+
}
|
|
639
|
+
const text = await response.text()
|
|
640
|
+
if (!response.ok) {
|
|
641
|
+
const hint = response.status === 401 || response.status === 403
|
|
642
|
+
? ' (the Host authenticates /api; pass --cookie-file with the browser session cookie)'
|
|
643
|
+
: ''
|
|
644
|
+
throw new Error('HTTP ' + response.status + ' from ' + url + hint + ': ' + text.slice(0, 240))
|
|
645
|
+
}
|
|
646
|
+
let body
|
|
647
|
+
try {
|
|
648
|
+
body = JSON.parse(text)
|
|
649
|
+
} catch {
|
|
650
|
+
throw new Error('response is not JSON (expected a Connection RPC envelope)')
|
|
651
|
+
}
|
|
652
|
+
if (!body || body.type !== 'server-response' || body.rpcId !== rpcId) {
|
|
653
|
+
throw new Error('response is not the matching Connection RPC envelope')
|
|
654
|
+
}
|
|
655
|
+
if (!body.result || body.result.ok !== true) {
|
|
656
|
+
const failure = body.result?.error || {}
|
|
657
|
+
throw new Error('session/prompt rejected: ' + String(failure.code || 'unknown') + ': ' + String(failure.message || 'no message'))
|
|
658
|
+
}
|
|
659
|
+
if (body.result.value?.accepted !== true) {
|
|
660
|
+
throw new Error('session/prompt did not return { accepted: true }')
|
|
661
|
+
}
|
|
662
|
+
return { rpcId }
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function isLoopbackHost(hostname) {
|
|
666
|
+
return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1'
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async function main(argv = process.argv.slice(2)) {
|
|
670
|
+
let options
|
|
671
|
+
try {
|
|
672
|
+
options = parseArgs(argv)
|
|
673
|
+
} catch (error) {
|
|
674
|
+
return failUsage(error.message)
|
|
675
|
+
}
|
|
676
|
+
if (options.help) {
|
|
677
|
+
process.stdout.write(USAGE)
|
|
678
|
+
return EXIT_OK
|
|
679
|
+
}
|
|
680
|
+
if (!options.session || !String(options.session).trim()) {
|
|
681
|
+
return failUsage('--session is required')
|
|
682
|
+
}
|
|
683
|
+
if (options.base) {
|
|
684
|
+
let parsed
|
|
685
|
+
try { parsed = new URL(options.base) } catch { return failUsage('--base is not a valid URL') }
|
|
686
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return failUsage('--base must be http(s)')
|
|
687
|
+
if (!isLoopbackHost(parsed.hostname)) {
|
|
688
|
+
console.error('drive-session: warning: --base is not loopback (' + parsed.hostname + '); the harness sends no credentials, so an authenticated host will reject it')
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const clientTimeZone = options.clientTimeZone || defaultClientTimeZone()
|
|
693
|
+
let prompts
|
|
694
|
+
try {
|
|
695
|
+
prompts = resolvePrompts(options)
|
|
696
|
+
} catch (error) {
|
|
697
|
+
return failUsage(error.message)
|
|
698
|
+
}
|
|
699
|
+
const requests = buildRequests({
|
|
700
|
+
sessionId: String(options.session).trim(),
|
|
701
|
+
turns: options.turns,
|
|
702
|
+
prompts,
|
|
703
|
+
clientTimeZone,
|
|
704
|
+
})
|
|
705
|
+
|
|
706
|
+
let cookie = null
|
|
707
|
+
if (options.cookieFile) {
|
|
708
|
+
try {
|
|
709
|
+
cookie = fs.readFileSync(options.cookieFile, 'utf8').trim()
|
|
710
|
+
} catch (error) {
|
|
711
|
+
return failUsage('cannot read --cookie-file: ' + error.message)
|
|
712
|
+
}
|
|
713
|
+
if (!cookie || /[\r\n]/.test(cookie)) {
|
|
714
|
+
return failUsage('--cookie-file must contain exactly one Cookie header value (no line breaks)')
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
if (options.requestsOut) {
|
|
719
|
+
try { writeRequests(options.requestsOut, requests) } catch (error) {
|
|
720
|
+
console.error('drive-session: cannot write --requests-out: ' + error.message)
|
|
721
|
+
return EXIT_FAILED
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (options.dryRun) {
|
|
726
|
+
for (const item of requests) {
|
|
727
|
+
process.stdout.write(JSON.stringify({ turn: item.turn, request: item.request }) + '\n')
|
|
728
|
+
}
|
|
729
|
+
console.log('drive-session: dry run — ' + requests.length + ' request(s) generated, nothing sent')
|
|
730
|
+
return EXIT_OK
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
if (!options.allowApiRoute) {
|
|
734
|
+
printManualFallback({
|
|
735
|
+
reason: 'no approved public-remote carrier. Work order B forbids silently POSTing /api.',
|
|
736
|
+
requests,
|
|
737
|
+
requestsOut: options.requestsOut,
|
|
738
|
+
})
|
|
739
|
+
return EXIT_MANUAL
|
|
740
|
+
}
|
|
741
|
+
if (!options.base) {
|
|
742
|
+
printManualFallback({
|
|
743
|
+
reason: '--allow-api-route needs --base <host gateway>; there is nowhere to send the public remote.',
|
|
744
|
+
requests,
|
|
745
|
+
requestsOut: options.requestsOut,
|
|
746
|
+
})
|
|
747
|
+
return EXIT_MANUAL
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const dshHome = options.dshHome || process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
751
|
+
const sessionLog = locateSessionLog({
|
|
752
|
+
explicit: options.sessionLog,
|
|
753
|
+
dshHome,
|
|
754
|
+
sessionId: String(options.session).trim(),
|
|
755
|
+
})
|
|
756
|
+
if (!sessionLog) {
|
|
757
|
+
console.error('drive-session: preflight failed — no session log for ' + options.session)
|
|
758
|
+
console.error(' looked under: ' + path.join(dshHome, 'sessions'))
|
|
759
|
+
console.error(' Pass --session-log <path> with the exact session.v4.jsonl.zstd file,')
|
|
760
|
+
console.error(' or --dsh-home <path> if DSH_HOME is not ' + dshHome + '.')
|
|
761
|
+
console.error(' Nothing was sent: without the public session log a turn cannot be observed as completed.')
|
|
762
|
+
return EXIT_PREFLIGHT
|
|
763
|
+
}
|
|
764
|
+
try {
|
|
765
|
+
readSessionEvents(sessionLog)
|
|
766
|
+
} catch (error) {
|
|
767
|
+
console.error('drive-session: preflight failed — cannot read ' + sessionLog + ': ' + error.message)
|
|
768
|
+
console.error(' Nothing was sent.')
|
|
769
|
+
return EXIT_PREFLIGHT
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
console.log('drive-session: ' + requests.length + ' turn(s) → session ' + options.session)
|
|
773
|
+
console.log(' base: ' + joinUrl(options.base, '/api/session/prompt') + ' (explicit --allow-api-route)')
|
|
774
|
+
console.log(' session log: ' + sessionLog)
|
|
775
|
+
console.log(' clientTimeZone: ' + clientTimeZone)
|
|
776
|
+
console.log(' cookie: ' + (cookie ? 'supplied via --cookie-file (not printed)' : 'none (a Host with browser auth will answer 401)'))
|
|
777
|
+
if (options.requestsOut) console.log(' requests: ' + path.resolve(options.requestsOut))
|
|
778
|
+
|
|
779
|
+
const started = Date.now()
|
|
780
|
+
let completed = 0
|
|
781
|
+
let failed = 0
|
|
782
|
+
let lastFailure = null
|
|
783
|
+
for (const item of requests) {
|
|
784
|
+
const turnStarted = Date.now()
|
|
785
|
+
try {
|
|
786
|
+
await sendPrompt({ base: options.base, request: item.request, timeoutMs: options.timeoutMs, cookie })
|
|
787
|
+
} catch (error) {
|
|
788
|
+
failed += 1
|
|
789
|
+
lastFailure = { turn: item.turn, stage: 'send', reason: error.message }
|
|
790
|
+
console.error('turn ' + item.turn + '/' + requests.length + ' SEND FAILED: ' + error.message)
|
|
791
|
+
break
|
|
792
|
+
}
|
|
793
|
+
// One per-turn budget: admission time is charged against completion time.
|
|
794
|
+
const remaining = Math.max(1_000, options.timeoutMs - (Date.now() - turnStarted))
|
|
795
|
+
const waited = await waitForTurn({
|
|
796
|
+
logPath: sessionLog,
|
|
797
|
+
requestId: item.request.requestId,
|
|
798
|
+
timeoutMs: remaining,
|
|
799
|
+
pollMs: options.pollMs,
|
|
800
|
+
})
|
|
801
|
+
if (waited.state !== 'completed') {
|
|
802
|
+
failed += 1
|
|
803
|
+
lastFailure = { turn: item.turn, stage: 'wait', reason: waited.state + ': ' + waited.reason }
|
|
804
|
+
console.error('turn ' + item.turn + '/' + requests.length + ' WAIT FAILED: ' + waited.state + ' (' + waited.reason + ')')
|
|
805
|
+
break
|
|
806
|
+
}
|
|
807
|
+
completed += 1
|
|
808
|
+
const elapsed = Date.now() - turnStarted
|
|
809
|
+
console.log('turn ' + item.turn + '/' + requests.length + ' completed in ' + elapsed + 'ms (requestId ' + item.request.requestId + ')')
|
|
810
|
+
if (options.intervalMs > 0 && item.turn < requests.length) {
|
|
811
|
+
await new Promise((resolve) => setTimeout(resolve, options.intervalMs))
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const totalMs = Date.now() - started
|
|
816
|
+
console.log('')
|
|
817
|
+
console.log('summary: sent+completed=' + completed + ' failed=' + failed + ' requested=' + requests.length + ' elapsed=' + totalMs + 'ms')
|
|
818
|
+
if (lastFailure) {
|
|
819
|
+
console.log('first failure: turn ' + lastFailure.turn + ' (' + lastFailure.stage + ') ' + lastFailure.reason)
|
|
820
|
+
return EXIT_FAILED
|
|
821
|
+
}
|
|
822
|
+
if (completed !== requests.length) {
|
|
823
|
+
console.log('run stopped before every requested turn completed')
|
|
824
|
+
return EXIT_FAILED
|
|
825
|
+
}
|
|
826
|
+
console.log('all requested turns completed')
|
|
827
|
+
return EXIT_OK
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
const invokedDirectly = process.argv[1]
|
|
831
|
+
? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
|
|
832
|
+
: false
|
|
833
|
+
if (invokedDirectly) {
|
|
834
|
+
main().then((code) => { process.exitCode = typeof code === 'number' ? code : EXIT_FAILED }).catch((error) => {
|
|
835
|
+
console.error('drive-session: ' + (error?.stack || error))
|
|
836
|
+
process.exitCode = EXIT_FAILED
|
|
837
|
+
})
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
export {
|
|
841
|
+
DEFAULT_PROMPTS,
|
|
842
|
+
buildRequests,
|
|
843
|
+
encodeSegment,
|
|
844
|
+
enclosingTurn,
|
|
845
|
+
locateSessionLog,
|
|
846
|
+
parseArgs,
|
|
847
|
+
promptAdmitted,
|
|
848
|
+
promptClaimIndex,
|
|
849
|
+
readSessionEvents,
|
|
850
|
+
scanZstdFrames,
|
|
851
|
+
textOfPromptItem,
|
|
852
|
+
waitForTurn,
|
|
853
|
+
}
|