@namzu/sdk 20.4.0 → 21.0.0
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/CHANGELOG.md +179 -0
- package/dist/bridge/sse/mapper.d.ts +19 -0
- package/dist/bridge/sse/mapper.d.ts.map +1 -1
- package/dist/bridge/sse/mapper.js +9 -1
- package/dist/bridge/sse/mapper.js.map +1 -1
- package/dist/contracts/schemas.d.ts +10 -10
- package/dist/manager/run/persistence.d.ts +26 -0
- package/dist/manager/run/persistence.d.ts.map +1 -1
- package/dist/manager/run/persistence.js +40 -0
- package/dist/manager/run/persistence.js.map +1 -1
- package/dist/public-runtime.d.ts +4 -0
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +16 -0
- package/dist/public-runtime.js.map +1 -1
- package/dist/run/drain.d.ts +194 -0
- package/dist/run/drain.d.ts.map +1 -0
- package/dist/run/drain.js +228 -0
- package/dist/run/drain.js.map +1 -0
- package/dist/run/index.d.ts +2 -0
- package/dist/run/index.d.ts.map +1 -1
- package/dist/run/index.js +1 -0
- package/dist/run/index.js.map +1 -1
- package/dist/runtime/query/events.d.ts +12 -0
- package/dist/runtime/query/events.d.ts.map +1 -1
- package/dist/runtime/query/events.js +61 -3
- package/dist/runtime/query/events.js.map +1 -1
- package/dist/runtime/query/index.d.ts +36 -0
- package/dist/runtime/query/index.d.ts.map +1 -1
- package/dist/runtime/query/index.js +32 -0
- package/dist/runtime/query/index.js.map +1 -1
- package/dist/runtime/query/resume-run.d.ts +25 -0
- package/dist/runtime/query/resume-run.d.ts.map +1 -1
- package/dist/runtime/query/resume-run.js +15 -3
- package/dist/runtime/query/resume-run.js.map +1 -1
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/index.js.map +1 -1
- package/dist/store/run/conformance.d.ts +159 -0
- package/dist/store/run/conformance.d.ts.map +1 -0
- package/dist/store/run/conformance.js +451 -0
- package/dist/store/run/conformance.js.map +1 -0
- package/dist/store/run/disk.d.ts +30 -2
- package/dist/store/run/disk.d.ts.map +1 -1
- package/dist/store/run/disk.js +101 -0
- package/dist/store/run/disk.js.map +1 -1
- package/dist/store/run/memory.d.ts +5 -4
- package/dist/store/run/memory.d.ts.map +1 -1
- package/dist/store/run/memory.js +30 -1
- package/dist/store/run/memory.js.map +1 -1
- package/dist/types/doctor/check.d.ts +28 -2
- package/dist/types/doctor/check.d.ts.map +1 -1
- package/dist/types/run/event-cursor.d.ts +90 -0
- package/dist/types/run/event-cursor.d.ts.map +1 -0
- package/dist/types/run/event-cursor.js +47 -0
- package/dist/types/run/event-cursor.js.map +1 -0
- package/dist/types/run/events.d.ts +71 -1
- package/dist/types/run/events.d.ts.map +1 -1
- package/dist/types/run/events.js.map +1 -1
- package/dist/types/run/index.d.ts +1 -0
- package/dist/types/run/index.d.ts.map +1 -1
- package/dist/types/run/index.js +1 -0
- package/dist/types/run/index.js.map +1 -1
- package/dist/types/run/store.d.ts +41 -1
- package/dist/types/run/store.d.ts.map +1 -1
- package/package.json +6 -1
- package/src/bridge/sse/mapper.ts +28 -1
- package/src/manager/run/persistence.ts +43 -0
- package/src/public-runtime.ts +22 -0
- package/src/run/drain.ts +393 -0
- package/src/run/index.ts +3 -0
- package/src/runtime/query/events.ts +68 -4
- package/src/runtime/query/index.ts +87 -0
- package/src/runtime/query/resume-run.ts +67 -12
- package/src/store/index.ts +1 -1
- package/src/store/run/conformance.ts +705 -0
- package/src/store/run/disk.ts +106 -2
- package/src/store/run/memory.ts +35 -5
- package/src/types/doctor/check.ts +28 -2
- package/src/types/run/event-cursor.ts +118 -0
- package/src/types/run/events.ts +80 -3
- package/src/types/run/index.ts +1 -0
- package/src/types/run/store.ts +43 -1
package/src/store/run/disk.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { appendFile, mkdir, readFile, readdir, unlink } from 'node:fs/promises'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import type { CheckpointId, IterationCheckpoint } from '../../types/hitl/index.js'
|
|
4
|
-
import type { Run, RunEvent, RunStoreConfig } from '../../types/run/index.js'
|
|
5
|
-
import type { CompletedToolRecord, RunStore } from '../../types/run/store.js'
|
|
4
|
+
import type { PersistedRunEvent, Run, RunEvent, RunStoreConfig } from '../../types/run/index.js'
|
|
5
|
+
import type { CompletedToolRecord, ReadRunEventsOptions, RunStore } from '../../types/run/store.js'
|
|
6
6
|
import { atomicWriteFile } from '../../utils/atomic-write.js'
|
|
7
7
|
import { type Logger, getRootLogger } from '../../utils/logger.js'
|
|
8
8
|
import { defineSchema, migrate, stamp } from '../schema.js'
|
|
@@ -51,6 +51,7 @@ export class RunDiskStore implements RunStore {
|
|
|
51
51
|
this.runDir = join(this.baseDir, runId)
|
|
52
52
|
}
|
|
53
53
|
await mkdir(this.runDir, { recursive: true })
|
|
54
|
+
await healTornTranscript(this.runDir)
|
|
54
55
|
this.log.info(`Run directory created: ${this.runDir}`)
|
|
55
56
|
return this.runDir
|
|
56
57
|
}
|
|
@@ -66,6 +67,10 @@ export class RunDiskStore implements RunStore {
|
|
|
66
67
|
await appendFile(join(dir, 'transcript.jsonl'), line, 'utf-8')
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
async readEvents(options?: ReadRunEventsOptions): Promise<readonly PersistedRunEvent[]> {
|
|
71
|
+
return readRunEventsIn(this.requireInit(), options)
|
|
72
|
+
}
|
|
73
|
+
|
|
69
74
|
/**
|
|
70
75
|
* Every tool call this run has already finished, keyed by `toolUseId`.
|
|
71
76
|
*
|
|
@@ -296,6 +301,105 @@ export class RunDiskStore implements RunStore {
|
|
|
296
301
|
}
|
|
297
302
|
}
|
|
298
303
|
|
|
304
|
+
/**
|
|
305
|
+
* Every durable event under one run directory, oldest first.
|
|
306
|
+
*
|
|
307
|
+
* A free function for the same reason {@link readCheckpointsIn} is one: a
|
|
308
|
+
* caller catching up on a run this process never started would otherwise have
|
|
309
|
+
* to bind a {@link RunDiskStore} to read it, and binding one CREATES the
|
|
310
|
+
* directory. A read that mints an empty run directory then answers "no events"
|
|
311
|
+
* is indistinguishable from a run that genuinely has none.
|
|
312
|
+
*
|
|
313
|
+
* ## Unsequenced lines take their position
|
|
314
|
+
*
|
|
315
|
+
* A transcript written before events were numbered carries no `seq` at all.
|
|
316
|
+
* Numbering those lines by their 1-based position is what keeps their evidence
|
|
317
|
+
* reachable: a legacy run of five lines reads back as 1..5, seeds the emitter
|
|
318
|
+
* at 5, and its next event is 6 — continuous, and stable on every later read.
|
|
319
|
+
* Skipping them instead would erase a run's whole history from a catch-up, and
|
|
320
|
+
* synthesising nothing at all would put the emitter back at 1 on top of a log
|
|
321
|
+
* that already has five entries.
|
|
322
|
+
*
|
|
323
|
+
* A damaged line is skipped rather than refused, which is the one place this
|
|
324
|
+
* differs from the checkpoint reader next door, and deliberately: a checkpoint
|
|
325
|
+
* is read to RESUME from, so a damaged one must stop the resume, while the
|
|
326
|
+
* transcript is read to REPORT from, and dropping every event after a torn line
|
|
327
|
+
* would be a larger loss than the torn line itself. The position count still
|
|
328
|
+
* advances over it, so the numbering of the events after it is unchanged.
|
|
329
|
+
*/
|
|
330
|
+
export async function readRunEventsIn(
|
|
331
|
+
runDir: string,
|
|
332
|
+
options?: ReadRunEventsOptions,
|
|
333
|
+
): Promise<readonly PersistedRunEvent[]> {
|
|
334
|
+
let raw: string
|
|
335
|
+
try {
|
|
336
|
+
raw = await readFile(join(runDir, 'transcript.jsonl'), 'utf-8')
|
|
337
|
+
} catch (err) {
|
|
338
|
+
if (isFileNotFound(err)) return []
|
|
339
|
+
throw err
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const sinceSeq = options?.sinceSeq ?? 0
|
|
343
|
+
const events: PersistedRunEvent[] = []
|
|
344
|
+
let position = 0
|
|
345
|
+
|
|
346
|
+
for (const line of raw.split('\n')) {
|
|
347
|
+
if (line.length === 0) continue
|
|
348
|
+
position += 1
|
|
349
|
+
|
|
350
|
+
let parsed: Record<string, unknown>
|
|
351
|
+
try {
|
|
352
|
+
parsed = JSON.parse(line) as Record<string, unknown>
|
|
353
|
+
} catch {
|
|
354
|
+
continue
|
|
355
|
+
}
|
|
356
|
+
if (parsed === null || typeof parsed !== 'object' || typeof parsed.type !== 'string') continue
|
|
357
|
+
|
|
358
|
+
const seq = typeof parsed.seq === 'number' ? parsed.seq : position
|
|
359
|
+
if (seq <= sinceSeq) continue
|
|
360
|
+
|
|
361
|
+
events.push({
|
|
362
|
+
...parsed,
|
|
363
|
+
seq,
|
|
364
|
+
// Stamped by `appendEvent` since long before it was declared. A line
|
|
365
|
+
// that predates even that gets the only honest answer available:
|
|
366
|
+
// zero, which sorts before every real moment and cannot be mistaken
|
|
367
|
+
// for one.
|
|
368
|
+
timestamp: typeof parsed.timestamp === 'number' ? parsed.timestamp : 0,
|
|
369
|
+
} as unknown as PersistedRunEvent)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return events
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Terminate a transcript whose last line was cut off mid-write.
|
|
377
|
+
*
|
|
378
|
+
* A process killed during `appendFile` leaves a fragment with no newline. The
|
|
379
|
+
* next append lands on the same line, so the fragment and a WHOLE, correct
|
|
380
|
+
* event merge into one unparsable line — and the reader skips it. The event was
|
|
381
|
+
* written, the emitter counted it as durable, and it is gone.
|
|
382
|
+
*
|
|
383
|
+
* Ending the fragment is enough. It stays unreadable and is skipped as it
|
|
384
|
+
* always was; everything appended after it survives, which is the difference
|
|
385
|
+
* between losing one event and losing one event plus the next.
|
|
386
|
+
*
|
|
387
|
+
* Called from `initRun`, which is the only moment the store knows nothing is
|
|
388
|
+
* mid-write.
|
|
389
|
+
*/
|
|
390
|
+
async function healTornTranscript(runDir: string): Promise<void> {
|
|
391
|
+
const path = join(runDir, 'transcript.jsonl')
|
|
392
|
+
let raw: string
|
|
393
|
+
try {
|
|
394
|
+
raw = await readFile(path, 'utf-8')
|
|
395
|
+
} catch (err) {
|
|
396
|
+
if (isFileNotFound(err)) return
|
|
397
|
+
throw err
|
|
398
|
+
}
|
|
399
|
+
if (raw.length === 0 || raw.endsWith('\n')) return
|
|
400
|
+
await appendFile(path, '\n', 'utf-8')
|
|
401
|
+
}
|
|
402
|
+
|
|
299
403
|
/**
|
|
300
404
|
* Every checkpoint stored under one run directory, ascending by `createdAt`.
|
|
301
405
|
*
|
package/src/store/run/memory.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Run } from '../../types/run/entity.js'
|
|
2
|
-
import type { RunEvent } from '../../types/run/events.js'
|
|
3
|
-
import type { CompletedToolRecord, RunStore } from '../../types/run/store.js'
|
|
2
|
+
import type { PersistedRunEvent, RunEvent } from '../../types/run/events.js'
|
|
3
|
+
import type { CompletedToolRecord, ReadRunEventsOptions, RunStore } from '../../types/run/store.js'
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Process-local {@link RunStore}: a run's evidence with no filesystem.
|
|
@@ -22,9 +22,21 @@ export class InMemoryRunStore implements RunStore {
|
|
|
22
22
|
private meta: Run | null = null
|
|
23
23
|
private messages: Run['messages'] = []
|
|
24
24
|
private report: string | null = null
|
|
25
|
-
private
|
|
25
|
+
private events: PersistedRunEvent[] = []
|
|
26
26
|
|
|
27
27
|
async initRun(runId: string, parentRunId?: string): Promise<string | null> {
|
|
28
|
+
// Rebinding to a DIFFERENT run starts that run's evidence empty. The disk
|
|
29
|
+
// store gets this for free — a different id is a different directory —
|
|
30
|
+
// and this one has to say it, because one instance reused for a replay
|
|
31
|
+
// fork otherwise reports the origin run's events, its messages and its
|
|
32
|
+
// report as the new run's own. Evidence attributed to the wrong run is
|
|
33
|
+
// worse than none: it is wrong and it looks right.
|
|
34
|
+
if (this.runId !== null && this.runId !== runId) {
|
|
35
|
+
this.meta = null
|
|
36
|
+
this.messages = []
|
|
37
|
+
this.report = null
|
|
38
|
+
this.events = []
|
|
39
|
+
}
|
|
28
40
|
this.runId = runId
|
|
29
41
|
this.parentRunId = parentRunId
|
|
30
42
|
// No location, and that is the honest answer rather than a defect.
|
|
@@ -68,7 +80,25 @@ export class InMemoryRunStore implements RunStore {
|
|
|
68
80
|
// line — a parity test compares the two read-backs, and a timestamp
|
|
69
81
|
// present in one medium and absent in the other would make identical
|
|
70
82
|
// runs look different depending on where they were recorded.
|
|
71
|
-
|
|
83
|
+
//
|
|
84
|
+
// An unsequenced event takes its position in the log, which is the same
|
|
85
|
+
// rule the disk reader applies to a line written before events were
|
|
86
|
+
// numbered. Nothing in the kernel appends unsequenced today; the rule is
|
|
87
|
+
// here so the two backends cannot answer differently if something does.
|
|
88
|
+
this.events.push({
|
|
89
|
+
...event,
|
|
90
|
+
seq: event.seq ?? this.events.length + 1,
|
|
91
|
+
timestamp: Date.now(),
|
|
92
|
+
} as unknown as PersistedRunEvent)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async readEvents(options?: ReadRunEventsOptions): Promise<readonly PersistedRunEvent[]> {
|
|
96
|
+
this.requireInit()
|
|
97
|
+
const sinceSeq = options?.sinceSeq ?? 0
|
|
98
|
+
// Copied, not sliced by reference, for the same reason `writeRunMeta`
|
|
99
|
+
// clones: a caller holding the array must not be able to reach into the
|
|
100
|
+
// log through it.
|
|
101
|
+
return this.events.filter((event) => event.seq > sinceSeq).map((event) => ({ ...event }))
|
|
72
102
|
}
|
|
73
103
|
|
|
74
104
|
async writeReport(content: string): Promise<string | null> {
|
|
@@ -114,7 +144,7 @@ export class InMemoryRunStore implements RunStore {
|
|
|
114
144
|
meta: Run | null
|
|
115
145
|
messages: Run['messages']
|
|
116
146
|
report: string | null
|
|
117
|
-
events: readonly
|
|
147
|
+
events: readonly PersistedRunEvent[]
|
|
118
148
|
} {
|
|
119
149
|
return { meta: this.meta, messages: this.messages, report: this.report, events: this.events }
|
|
120
150
|
}
|
|
@@ -1,4 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* What a check concluded.
|
|
3
|
+
*
|
|
4
|
+
* `skipped` and `inconclusive` are the two ways a check produces no verdict,
|
|
5
|
+
* and they are separate because a caller acts on them differently.
|
|
6
|
+
*
|
|
7
|
+
* - `skipped` — the check LOOKED and there was nothing here to check: an
|
|
8
|
+
* optional package is not installed, a registry the check reads has no
|
|
9
|
+
* auto-discovery to read, nothing is configured yet. A permanent or
|
|
10
|
+
* by-design absence, and an ordinary state of a healthy machine.
|
|
11
|
+
* - `inconclusive` — the check DID NOT ANSWER: it timed out, it was aborted,
|
|
12
|
+
* the thing it reads threw. Nothing is known either way, and that is itself
|
|
13
|
+
* a gap in the report worth acting on.
|
|
14
|
+
*
|
|
15
|
+
* The word used to cover both, so `namzu doctor` could not tell "healthy" from
|
|
16
|
+
* "did not manage to look", and neither could anything reading its exit code.
|
|
17
|
+
*/
|
|
18
|
+
export type DoctorStatus = 'pass' | 'fail' | 'inconclusive' | 'warn' | 'skipped'
|
|
2
19
|
|
|
3
20
|
export type DoctorCategory =
|
|
4
21
|
| 'sandbox'
|
|
@@ -47,7 +64,16 @@ export interface DoctorReport {
|
|
|
47
64
|
readonly fail: number
|
|
48
65
|
readonly inconclusive: number
|
|
49
66
|
readonly warn: number
|
|
67
|
+
readonly skipped: number
|
|
68
|
+
/** Every other count sums to this. A reader may rely on that. */
|
|
50
69
|
readonly total: number
|
|
51
70
|
}
|
|
52
|
-
|
|
71
|
+
/**
|
|
72
|
+
* `69` is sysexits `EX_UNAVAILABLE`, whose own definition ends "a catchall
|
|
73
|
+
* when something you wanted to do doesn't work, but you don't know why".
|
|
74
|
+
* That is `inconclusive`. It is not `2`, which this report already spends on
|
|
75
|
+
* "nothing was registered", and not `70`, which says the CLI is broken and
|
|
76
|
+
* is worth a bug report.
|
|
77
|
+
*/
|
|
78
|
+
readonly exit: 0 | 1 | 2 | 69 | 70
|
|
53
79
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a reconnecting consumer left off, and whether the kernel can honour it.
|
|
3
|
+
*
|
|
4
|
+
* The shortfall is a VALUE here, not a sentence in a document. A consumer that
|
|
5
|
+
* asks for everything after sequence 400 and silently receives a splice from a
|
|
6
|
+
* different generation of the run is wrong and has no way to find out; a
|
|
7
|
+
* consumer handed `{ status: 'unavailable', reason: 'cursor_ahead' }` re-derives
|
|
8
|
+
* from the transcript and is right. That is refuse-do-not-degrade applied to a
|
|
9
|
+
* subscription rather than to a capability.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ClaimFence } from './checkpoint-store.js'
|
|
13
|
+
import type { PersistedRunEvent } from './events.js'
|
|
14
|
+
|
|
15
|
+
/** What a consumer holds when it comes back. */
|
|
16
|
+
export interface RunEventCursor {
|
|
17
|
+
/**
|
|
18
|
+
* The last `seq` the consumer actually received, from the envelope. Zero —
|
|
19
|
+
* or the field absent — means "from the beginning".
|
|
20
|
+
*/
|
|
21
|
+
readonly sinceSeq: number
|
|
22
|
+
/**
|
|
23
|
+
* The `generation` carried on the events the consumer received, when they
|
|
24
|
+
* carried one.
|
|
25
|
+
*
|
|
26
|
+
* Compared for equality only. Absent on both sides is not a match and not a
|
|
27
|
+
* mismatch: it is an unfenced run, where the sequence is the only evidence
|
|
28
|
+
* available and the log persisting is the assumption.
|
|
29
|
+
*/
|
|
30
|
+
readonly generation?: ClaimFence
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Why a cursor could not be honoured. */
|
|
34
|
+
export type RunEventReplayRefusal =
|
|
35
|
+
/**
|
|
36
|
+
* The consumer claims to have seen more than the log holds.
|
|
37
|
+
*
|
|
38
|
+
* The ordinary cause is not a lying client: it is a log that did not
|
|
39
|
+
* survive. An in-memory run store on a restarted process seeds at zero
|
|
40
|
+
* while the consumer still holds 400, and this is the verdict that says so
|
|
41
|
+
* instead of reporting a serene "you are up to date".
|
|
42
|
+
*/
|
|
43
|
+
| 'cursor_ahead'
|
|
44
|
+
/**
|
|
45
|
+
* The run has been taken over since. The consumer's sequence numbers were
|
|
46
|
+
* minted under an older claim and address a different sequence space, so
|
|
47
|
+
* they are not comparable — not merely stale.
|
|
48
|
+
*/
|
|
49
|
+
| 'generation_changed'
|
|
50
|
+
/**
|
|
51
|
+
* The store answered, and its oldest available event is above the one after
|
|
52
|
+
* the cursor. A pruning or windowed backend, caught at the boundary rather
|
|
53
|
+
* than delivered as a continuous stream with a hole in it.
|
|
54
|
+
*/
|
|
55
|
+
| 'gap'
|
|
56
|
+
|
|
57
|
+
/** What came of a cursor. */
|
|
58
|
+
export type RunEventReplay =
|
|
59
|
+
/** The cursor is already at the log's head. Nothing was missed. */
|
|
60
|
+
| { readonly status: 'complete' }
|
|
61
|
+
/** Contiguous from `sinceSeq + 1`, oldest first. */
|
|
62
|
+
| { readonly status: 'replayed'; readonly events: readonly PersistedRunEvent[] }
|
|
63
|
+
/** Nothing is delivered. The consumer re-derives from the transcript. */
|
|
64
|
+
| { readonly status: 'unavailable'; readonly reason: RunEventReplayRefusal }
|
|
65
|
+
|
|
66
|
+
/** The log's present state, as the store reports it. */
|
|
67
|
+
export interface RunEventLogHead {
|
|
68
|
+
/** Highest sequence in the log; zero when it is empty. */
|
|
69
|
+
readonly lastSeq: number
|
|
70
|
+
/** The fence the run is being written under, when it holds a claim. */
|
|
71
|
+
readonly generation?: ClaimFence
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Decide what a cursor is owed, given what the log holds.
|
|
76
|
+
*
|
|
77
|
+
* Pure, and ordered deliberately: a takeover invalidates the sequence space, so
|
|
78
|
+
* comparing sequences across generations would be arithmetic on two different
|
|
79
|
+
* scales. The generation check therefore runs FIRST, before the numbers are
|
|
80
|
+
* allowed to mean anything.
|
|
81
|
+
*
|
|
82
|
+
* `events` is what the store returned for `{ sinceSeq: cursor.sinceSeq }`. It is
|
|
83
|
+
* passed in rather than fetched here so this stays a function of its arguments
|
|
84
|
+
* — the property "no gap, no duplicate" is decidable from the three inputs, and
|
|
85
|
+
* a test can drive every branch without a store.
|
|
86
|
+
*/
|
|
87
|
+
export function resolveRunEventReplay(
|
|
88
|
+
cursor: RunEventCursor,
|
|
89
|
+
head: RunEventLogHead,
|
|
90
|
+
events: readonly PersistedRunEvent[],
|
|
91
|
+
): RunEventReplay {
|
|
92
|
+
// Both sides must carry one for a mismatch to mean anything. An unfenced run
|
|
93
|
+
// has no generation to disagree with, and treating "absent" as a distinct
|
|
94
|
+
// value would refuse every run that never took a claim — which is most of
|
|
95
|
+
// them.
|
|
96
|
+
if (
|
|
97
|
+
cursor.generation !== undefined &&
|
|
98
|
+
head.generation !== undefined &&
|
|
99
|
+
cursor.generation !== head.generation
|
|
100
|
+
) {
|
|
101
|
+
return { status: 'unavailable', reason: 'generation_changed' }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (cursor.sinceSeq > head.lastSeq) {
|
|
105
|
+
return { status: 'unavailable', reason: 'cursor_ahead' }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (cursor.sinceSeq === head.lastSeq) return { status: 'complete' }
|
|
109
|
+
|
|
110
|
+
// The log says there is something above the cursor, so an empty answer is
|
|
111
|
+
// the store contradicting its own head rather than "nothing to send".
|
|
112
|
+
const first = events[0]
|
|
113
|
+
if (!first || first.seq !== cursor.sinceSeq + 1) {
|
|
114
|
+
return { status: 'unavailable', reason: 'gap' }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return { status: 'replayed', events }
|
|
118
|
+
}
|
package/src/types/run/events.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type {
|
|
|
15
15
|
import type { PlanStep } from '../plan/index.js'
|
|
16
16
|
import type { PluginHookEvent, PluginHookResult } from '../plugin/index.js'
|
|
17
17
|
import type { TaskStatus } from '../task/index.js'
|
|
18
|
+
import type { ClaimFence } from './checkpoint-store.js'
|
|
18
19
|
import type { Lineage } from './lineage.js'
|
|
19
20
|
import type { MessageStopReason, StopReason } from './stop-reason.js'
|
|
20
21
|
import type {
|
|
@@ -43,6 +44,57 @@ interface RunEventEnvelope {
|
|
|
43
44
|
*/
|
|
44
45
|
schemaVersion?: 3
|
|
45
46
|
lineage?: Lineage
|
|
47
|
+
/**
|
|
48
|
+
* This event's position in its OWN run's durable event log, from 1.
|
|
49
|
+
*
|
|
50
|
+
* **Present means recorded.** The emitter takes a candidate number, appends
|
|
51
|
+
* the event stamped with it, and only then advances the counter and hands
|
|
52
|
+
* the event to the live stream — so a `seq` a consumer can see is a `seq`
|
|
53
|
+
* the log contains. That is what makes it usable as a cursor: reconnect,
|
|
54
|
+
* ask for everything above it, and nothing is missed and nothing arrives
|
|
55
|
+
* twice.
|
|
56
|
+
*
|
|
57
|
+
* **Absent means not recoverable**, and three different things arrive that
|
|
58
|
+
* way:
|
|
59
|
+
*
|
|
60
|
+
* - the high-frequency events {@link isEphemeralEvent} names, which are
|
|
61
|
+
* deliberately never persisted;
|
|
62
|
+
* - an event whose durable write FAILED — it still reaches the live
|
|
63
|
+
* stream, unstamped, because losing the news of a failure is worse than
|
|
64
|
+
* delivering it without a cursor;
|
|
65
|
+
* - the delegation lifecycle events (`agent_pending`, `agent_completed`,
|
|
66
|
+
* `agent_failed`, `agent_canceled` and the three sub-session variants),
|
|
67
|
+
* which the agent manager hands straight to a host's listener without
|
|
68
|
+
* passing through the run's event translator at all. They are not in any
|
|
69
|
+
* run's log, and the missing `seq` is how a consumer learns that rather
|
|
70
|
+
* than discovering it after a reconnect.
|
|
71
|
+
*
|
|
72
|
+
* **Per run, not per stream.** A parent's listener also receives its
|
|
73
|
+
* children's events, each numbered in its own run's log, so a consumer
|
|
74
|
+
* keeps one cursor per `runId`. The SSE mapper carries the pair as
|
|
75
|
+
* `<runId>:<seq>` for exactly this reason.
|
|
76
|
+
*
|
|
77
|
+
* Monotonic under a single writer. The run store takes no claim fence
|
|
78
|
+
* today (see `QueryParams.claimFence`), so two workers that both took one
|
|
79
|
+
* run can both append — `generation` is what makes that detectable.
|
|
80
|
+
*/
|
|
81
|
+
seq?: number
|
|
82
|
+
/**
|
|
83
|
+
* The claim fence the run was being written under, when it holds a claim.
|
|
84
|
+
*
|
|
85
|
+
* A sequence alone lies across a takeover: a client at seq 400 reconnects
|
|
86
|
+
* to a run whose store lost its log, the new writer starts at 1, and the
|
|
87
|
+
* client's cursor silently addresses a different sequence space. The fence
|
|
88
|
+
* is already the arbiter of who may write and it only increases, so
|
|
89
|
+
* carrying it here makes a takeover ORDERED rather than merely
|
|
90
|
+
* distinguishable.
|
|
91
|
+
*
|
|
92
|
+
* Absent when the run was written unfenced, which is every run that took no
|
|
93
|
+
* claim. A cursor then relies on the log persisting — the disk store's
|
|
94
|
+
* does, an in-memory store's does not, and `cursor_ahead` is the verdict
|
|
95
|
+
* that catches the difference.
|
|
96
|
+
*/
|
|
97
|
+
generation?: ClaimFence
|
|
46
98
|
}
|
|
47
99
|
|
|
48
100
|
type CoreRunEvent =
|
|
@@ -679,12 +731,37 @@ type CoreRunEvent =
|
|
|
679
731
|
*/
|
|
680
732
|
export type RunEvent =
|
|
681
733
|
| (CoreRunEvent & RunEventEnvelope)
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
734
|
+
// Intersected so `seq` is READABLE on every member of the union — TypeScript
|
|
735
|
+
// refuses a property access on a union where one member lacks the field, and
|
|
736
|
+
// a consumer holding a cursor has to be able to ask any event for its
|
|
737
|
+
// number. These three never carry one, and that is the answer rather than an
|
|
738
|
+
// omission: they are emitted straight to a host's listener and reach no run's
|
|
739
|
+
// durable log.
|
|
740
|
+
| (SubsessionSpawnedEvent & RunEventEnvelope)
|
|
741
|
+
| (SubsessionMessagedEvent & RunEventEnvelope)
|
|
742
|
+
| (SubsessionIdledEvent & RunEventEnvelope)
|
|
685
743
|
|
|
686
744
|
export type RunEventListener = (event: RunEvent) => void | Promise<void>
|
|
687
745
|
|
|
746
|
+
/**
|
|
747
|
+
* A run event as the durable log gives it back.
|
|
748
|
+
*
|
|
749
|
+
* `seq` and `timestamp` are REQUIRED here and optional on the live envelope,
|
|
750
|
+
* which is the whole difference between the two types: a recorded event has a
|
|
751
|
+
* position and a moment, and a live one may be neither recorded nor
|
|
752
|
+
* recoverable.
|
|
753
|
+
*
|
|
754
|
+
* `timestamp` is not new — both store implementations have always stamped it
|
|
755
|
+
* on write. It was simply never declared anywhere, so the field was persisted
|
|
756
|
+
* by two writers, typed by neither, and read by nobody. Declaring it is what
|
|
757
|
+
* lets the read-back stop casting.
|
|
758
|
+
*/
|
|
759
|
+
export type PersistedRunEvent = RunEvent & {
|
|
760
|
+
readonly seq: number
|
|
761
|
+
/** Epoch ms at which the store recorded the event. */
|
|
762
|
+
readonly timestamp: number
|
|
763
|
+
}
|
|
764
|
+
|
|
688
765
|
/**
|
|
689
766
|
* Event types whose volume makes durable persistence wasteful.
|
|
690
767
|
*
|
package/src/types/run/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ export * from './stop-reason.js'
|
|
|
4
4
|
export * from './config.js'
|
|
5
5
|
export * from './checkpoint-store.js'
|
|
6
6
|
export * from './store.js'
|
|
7
|
+
export * from './event-cursor.js'
|
|
7
8
|
export * from './entity.js'
|
|
8
9
|
export * from './replay.js'
|
|
9
10
|
// Domain `RunStatus` (session-hierarchy.md §4.6 state machine). Safe to
|
package/src/types/run/store.ts
CHANGED
|
@@ -28,7 +28,19 @@
|
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
import type { Run } from './entity.js'
|
|
31
|
-
import type { RunEvent } from './events.js'
|
|
31
|
+
import type { PersistedRunEvent, RunEvent } from './events.js'
|
|
32
|
+
|
|
33
|
+
/** What a caller asks the log for. See {@link RunStore.readEvents}. */
|
|
34
|
+
export interface ReadRunEventsOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Return only events ABOVE this sequence — strictly greater, never equal.
|
|
37
|
+
*
|
|
38
|
+
* The exclusive boundary is what makes a cursor round-trip: a consumer that
|
|
39
|
+
* last saw `seq: 12` passes 12 and receives 13 onward, so nothing is
|
|
40
|
+
* delivered twice. Absent means the whole log.
|
|
41
|
+
*/
|
|
42
|
+
readonly sinceSeq?: number
|
|
43
|
+
}
|
|
32
44
|
|
|
33
45
|
/**
|
|
34
46
|
* One finished tool call, recovered from the run's own transcript.
|
|
@@ -71,6 +83,36 @@ export interface RunStore {
|
|
|
71
83
|
*/
|
|
72
84
|
appendEvent(event: RunEvent): Promise<void>
|
|
73
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Read the run's durable event log back, oldest first.
|
|
88
|
+
*
|
|
89
|
+
* Required, unlike {@link RunStore.addToIndex}, and the asymmetry is the
|
|
90
|
+
* point: a store that records a transcript it cannot read back is
|
|
91
|
+
* write-only evidence, which is the defect the whole contract exists to
|
|
92
|
+
* fix one level up. It is also what a reconnecting consumer catches up
|
|
93
|
+
* through — "refresh the page and keep watching the answer arrive" is this
|
|
94
|
+
* method plus a cursor and nothing else.
|
|
95
|
+
*
|
|
96
|
+
* Three obligations, each of which a consumer relies on:
|
|
97
|
+
*
|
|
98
|
+
* 1. **Ascending by `seq`, in the order the events were appended.** Do not
|
|
99
|
+
* sort a log back into order — a log that needs sorting was written by
|
|
100
|
+
* two processes, and hiding that produces a plausible transcript of a
|
|
101
|
+
* run that never happened.
|
|
102
|
+
* 2. **`sinceSeq` is exclusive.** See {@link ReadRunEventsOptions}.
|
|
103
|
+
* 3. **Contiguous, or honestly short.** A backend that prunes may return a
|
|
104
|
+
* first event above `sinceSeq + 1`; that is a gap, the caller detects
|
|
105
|
+
* it, and the reconnect is refused rather than spliced. Do NOT
|
|
106
|
+
* manufacture placeholders to close it.
|
|
107
|
+
*
|
|
108
|
+
* High-frequency events never enter the log (see
|
|
109
|
+
* {@link RunStore.appendEvent}), so what a late subscriber recovers is
|
|
110
|
+
* message-granular, not keystroke-granular. Aggregated assistant text,
|
|
111
|
+
* every tool result and the full message list are all intact; the deltas
|
|
112
|
+
* that composed them are not, and are not meant to be.
|
|
113
|
+
*/
|
|
114
|
+
readEvents(options?: ReadRunEventsOptions): Promise<readonly PersistedRunEvent[]>
|
|
115
|
+
|
|
74
116
|
/**
|
|
75
117
|
* Persist the run's final report. Returns a location, or `null` when the
|
|
76
118
|
* backend has none. See {@link RunStore.initRun}.
|