-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsessionService.ts
More file actions
799 lines (748 loc) · 34.9 KB
/
Copy pathsessionService.ts
File metadata and controls
799 lines (748 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
import { createHash, randomUUID } from "node:crypto";
import type { EvidenceEvent } from "../types.js";
import { openSessionEventStore } from "../persistence/openSessionEventStore.js";
import type { SessionEventStore } from "../persistence/sessionEventStore.js";
import { sha256Hex } from "../utils/hash.js";
import type { ConversationHistory } from "./surfaceProjection.js";
import { describeLiveEntries, prepareSurfaceCompaction, type LiveSurfaceEntry } from "./surfaceCompaction.js";
import { createSessionProjections, type SessionProjections } from "./projection/sessionProjections.js";
import { SessionEventWriter } from "./sessionSpine.js";
export { NATIVE_TRUST_TIER } from "./sessionSpine.js";
import type { RequestHeaderMeta } from "./requestHeaderMeta.js";
import { buildRequestOutcomeMeta, requestOutcomeEventType } from "./requestOutcomeMeta.js";
import type { RequestOutcomeParams } from "./requestOutcomeMeta.js";
import { assertToolSchemaCommitted } from "./toolSchemaCommitment.js";
import { buildStepEndMeta, buildTurnEndMeta } from "./turnLifecycleMeta.js";
import { buildApprovalRow } from "./approvalEventMeta.js";
import { buildLoopEventRow } from "./loopEventMeta.js";
import { assertNativeImageBytes, snapshotNativeImages } from "../attachments/nativeImageInput.js";
import { assertNativeAudioBytes, snapshotNativeAudio, NATIVE_AUDIO_INPUT_FORMAT } from "../attachments/nativeAudioInput.js";
import { snapshotRecordedGeminiPart } from "./geminiPartMeta.js";
import type { LoopEventRecord } from "./loopEventMeta.js";
import { SessionSpillPolicy } from "./spill/spillPolicy.js";
import { attachmentPayloadRoute } from "./sessionPayloadCap.js";
import { SPILL_COMMITMENT_EVENT_TYPE, spillCommitmentMeta, spillCommitmentNameSeed, type SpillCommitmentSubject } from "./spill/spillInput.js";
import { SessionSpillStore } from "./spill/spillStore.js";
import { SPILL_META_KEY, type SpillPolicyConfig, type SpillRef } from "./spill/spillTypes.js";
import type {
ApprovalRecord,
AssistantBlockInput,
RequestHeaderParams,
SandboxModeInput,
SealRef,
SessionCloseParams,
SessionEventRef,
SessionOpenParams,
StepEndParams,
StepRef,
ToolCallInput,
ToolResultInput,
TurnEndParams,
TurnRef,
TurnStartParams
} from "./sessionApiTypes.js";
// A monitor digest is a 64-char lowercase hex sha256. compositionDigest is
// already one in normal use; anything else is hashed so the sessions row's
// binary_sha256 column is always well-formed.
function normalizeSha256(value: string): string {
return /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : sha256Hex(value);
}
// SessionService is the SINGLE WRITER for one session's spine. It owns the
// per-session head (seq + prevSessionEventHash) in memory and the current
// turn/step counters, appends every session event through the signed,
// hash-chained persistence seam, and applies the coalescing / step-boundary
// batching policy. Every method below is synchronous: the store contract is
// synchronous, and the coalescer's back-pressure is expressed by a synchronous
// call that does not return until its bytes are flushed — the queue bound IS the
// "model-visible ⊆ logged" bound.
// The parameter and result shapes live in ./sessionApiTypes.js — see its header
// for why the split exists and why PreparedRequest stayed here. Only the result
// type every caller of this module already handles is re-exported: mirroring the
// whole list here gave the shapes two import paths and therefore two places to
// drift, and nothing outside this file used the mirror.
export type { SessionEventRef } from "./sessionApiTypes.js";
// Module-private brand token. A PreparedRequest can only be minted by code in
// THIS module — in practice only by recordRequestHeader, after its request/header
// row is committed and signed. External code cannot name this symbol, so it
// cannot construct a PreparedRequest through the type system, and the runtime
// guard rejects any attempt that tried.
const PREPARED_REQUEST_BRAND: unique symbol = Symbol("amc.session.preparedRequest");
/**
* The bytes destined for a model, obtainable ONLY after they were logged.
*
* This is the STRUCTURAL half of "model-visible ⇒ logged ⇒ signed". A caller
* that holds a PreparedRequest necessarily holds proof that recordRequestHeader
* already committed a signed request/header event naming requestDigest =
* sha256(the bytes) — because that method is the only mint. The guarantee does
* NOT rest on the invariants harness, which defaults to OFF under NODE_ENV=
* production and, in this tree, is not installed by any boot path
* (installInvariants is exported from @amc/core but nothing here calls it). Where
* a host does install ctx.invariants and registerSessionInvariants, those
* companions are a dev-time backstop that catches structural mistakes; they are
* not what makes this hold.
*
* Known limit (see design risks): a deliberate `as` cast, or a plugin that calls
* a provider SDK directly rather than through this seam, is outside what a brand
* can enforce. Closing that is a P3.0/P3.1 credentials-seam question.
*/
export class PreparedRequest {
readonly headerEventId: string;
readonly headerEventHash: string;
readonly requestDigest: string;
private readonly requestBytes: Buffer;
constructor(
brand: typeof PREPARED_REQUEST_BRAND,
init: {
readonly headerEventId: string;
readonly headerEventHash: string;
readonly requestDigest: string;
readonly requestBytes: Buffer;
}
) {
if (brand !== PREPARED_REQUEST_BRAND) {
throw new Error("PreparedRequest is not constructible outside SessionService");
}
this.headerEventId = init.headerEventId;
this.headerEventHash = init.headerEventHash;
this.requestDigest = init.requestDigest;
this.requestBytes = init.requestBytes;
}
// The exact bytes to transmit. Reachable only from an instance this module
// minted, i.e. only once the request/header row committing to requestDigest is
// durable and signed. Returns a copy so a holder cannot mutate the logged bytes.
toBytes(): Buffer {
return Buffer.from(this.requestBytes);
}
}
export class SessionService extends SessionEventWriter {
// The surface fold runs through the projection registry rather than direct
// calls, so repeated projectHistory() resumes from the cached prefix instead
// of re-parsing every row's meta_json. Public and per-service: the cache is
// keyed to ONE log, and a composed runtime registers its own units here.
readonly projections: SessionProjections = createSessionProjections();
// `store` is injectable so a caller (a test, a conformance run, a composed
// service) can pin a backend without going through workspace configuration.
// Left absent, the workspace's own pinned backend is opened.
constructor(workspace: string, store?: SessionEventStore, spillConfig: Partial<SpillPolicyConfig> = {}) {
super(workspace, store ?? openSessionEventStore(workspace), spillConfig);
}
open(params: SessionOpenParams): SessionEventRef {
if (this.sessionIdValue !== null) {
throw new Error("SessionService.open called twice");
}
const sessionId = params.sessionId ?? randomUUID();
this.sessionIdValue = sessionId;
this.runtime = params.runtime ?? "amc";
this.spill = new SessionSpillPolicy(new SessionSpillStore(this.workspace, sessionId), this.spillConfig);
// Seed the per-session head from any rows already carrying this session id. A
// fresh session has none, leaving seq=0 / prevHash=SESSION_GENESIS; a resumed
// one picks up exactly where its last committed event left off.
this.seedHead(sessionId);
// The sessions row must exist before any event references it, or verification
// reports "references missing session". A natively-run agent has no separate
// binary, so binary_path records the agent id and binary_sha256 the
// composition it ran under.
this.store.startSession({
sessionId,
runtime: params.runtime ?? "amc",
binaryPath: params.agentId,
binarySha256: normalizeSha256(params.compositionDigest)
});
return this.appendSessionEvent({
eventType: "session/open",
typeMeta: {
runtime: params.runtime ?? "amc",
agentId: params.agentId,
harnessVersion: params.harnessVersion,
compositionDigest: params.compositionDigest,
policyDigest: params.policyDigest,
...(params.parent === undefined ? {} : { parentSession: { ...params.parent } })
},
surface: { op: "none" },
turn: null,
step: null
});
}
startTurn(params: TurnStartParams): TurnRef {
this.ensureUsable();
if (this.currentTurn !== null) {
throw new Error("SessionService.startTurn called while a turn is open");
}
const turn = ++this.turnNo;
this.currentTurn = turn;
this.currentStep = null;
this.stepNo = 0;
this.window.openTurn();
const ref = this.appendSessionEvent({
eventType: "turn/start",
typeMeta: { turn, trigger: params.trigger },
surface: { op: "none" },
turn,
step: null
});
return { ...ref, turn };
}
// Closes the turn this service is driving. `origin: "live"` is what makes a
// cancellation here spell itself as a cancel WITH a cause and never as the
// "interrupted" a crash leaves behind — the loop cannot disguise a stop as a
// death, because buildTurnEndMeta refuses to write one.
endTurn(params: TurnEndParams): TurnRef {
const turn = this.requireTurn();
const ref = this.appendSessionEvent({
eventType: "turn/end",
typeMeta: buildTurnEndMeta(
{ turn, reason: params.reason, cancelCause: params.cause ?? null, recovery: null },
"live"
),
surface: { op: "none" },
turn,
step: null
});
this.currentStep = null;
return { ...ref, turn };
}
// The turn seal is an ordinary evidence event whose meta commits to the turn's
// window; the row's own writer_sig IS the seal signature, so there is no
// separate seal type or signature scheme. Verification recomputes the window
// root from the stored rows and never trusts the value the seal carries.
sealTurn(): SealRef {
const turn = this.requireTurn();
const sealed = this.window.seal();
const { merkleRoot: windowMerkleRoot, sealChainIndex } = sealed;
const ref = this.appendSessionEvent({
eventType: "turn/seal",
typeMeta: {
turn,
window_first_event_id: sealed.firstEventId,
window_last_event_id: sealed.lastEventId,
window_event_count: sealed.eventCount,
window_merkle_root: windowMerkleRoot,
prev_seal_event_id: sealed.prevSealEventId,
prev_seal_merkle_root: sealed.prevSealMerkleRoot,
seal_chain_index: sealChainIndex
},
surface: { op: "none" },
turn,
step: null
});
this.window.recordSeal(ref.eventId, ref.eventHash, windowMerkleRoot);
this.currentTurn = null;
this.currentStep = null;
return { ...ref, turn, windowMerkleRoot, sealChainIndex };
}
startStep(): StepRef {
const turn = this.requireTurn();
const step = ++this.stepNo;
this.currentStep = step;
const ref = this.appendSessionEvent({
eventType: "step/start",
typeMeta: { turn, step },
surface: { op: "none" },
turn,
step
});
return { ...ref, turn, step };
}
// The step boundary is the crash-loss bound: every event recorded during the
// step is durably committed by the time this returns, so a crash can lose at
// most the un-recorded tail of the in-flight step, never a completed one.
endStep(params: StepEndParams): StepRef {
const turn = this.requireTurn();
const step = this.requireStep();
const ref = this.appendSessionEvent({
eventType: "step/end",
typeMeta: buildStepEndMeta({
turn,
step,
stopReason: params.stopReason,
// Passed straight through, null included: a step that reported no usage
// records none rather than a fabricated zero.
usage: params.usage,
recoveredBy: null
}),
surface: { op: "none" },
turn,
step
});
this.currentStep = null;
return { ...ref, turn, step };
}
// The single seam through which a request reaches a model. It commits a signed
// request/header event that names requestDigest = sha256(exact bytes to be
// sent), and only THEN mints the PreparedRequest carrying those bytes. Because
// PreparedRequest cannot be constructed outside this module, a caller cannot
// transmit to a model without that committed, signed row — the property is
// structural, not a runtime check that production can turn off.
recordRequestHeader(params: RequestHeaderParams): PreparedRequest {
this.ensureUsable();
// Checked BEFORE the header is appended: an unbacked tool-schema commitment
// must not be able to reach the log at all, not merely be unlikely to.
if (params.toolSchema !== null) {
assertToolSchemaCommitted(this.readEvents(), params.toolSchema, this.sessionId);
}
const requestBytes =
typeof params.requestBytes === "string" ? Buffer.from(params.requestBytes, "utf8") : params.requestBytes;
const requestDigest = sha256Hex(requestBytes);
// Annotated, so a field derivation reads cannot go missing here silently.
// The LITERAL ORDER below is the hash pre-image order (see requestHeaderMeta).
const typeMeta: RequestHeaderMeta = {
model: params.model,
providerId: params.providerId,
params: params.params,
encoderId: params.encoderId,
encoderVersion: params.encoderVersion,
systemPromptEventId: params.systemPromptEventId,
toolSchemaEventId: params.toolSchema?.eventId ?? null,
toolSchemaSha256: params.toolSchema?.payloadSha256 ?? null,
projectionCutoffEventId: params.projectionCutoffEventId,
projectionDigest: params.projectionDigest,
sourceEventIds: [...params.sourceEventIds],
requestDigest
};
const ref = this.appendSessionEvent({
eventType: "request/header",
typeMeta: { ...typeMeta },
surface: { op: "none" },
turn: this.currentTurn,
step: this.currentStep
});
// The row is now durable and signed; only now are the bytes released.
return new PreparedRequest(PREPARED_REQUEST_BRAND, {
headerEventId: ref.eventId,
headerEventHash: ref.eventHash,
requestDigest,
requestBytes
});
}
// The other half of the send path: what came back. One row per dispatch,
// recorded AFTER the stream terminated, naming the request/header row it
// settles. Without it a session records what a model was asked and never what
// it answered — see ./requestOutcomeMeta.ts for the shape and for why the
// retry verdict is recorded beside the provider's facts rather than inside
// them.
recordRequestOutcome(params: RequestOutcomeParams): SessionEventRef {
return this.appendSessionEvent({
eventType: requestOutcomeEventType(params),
typeMeta: { ...buildRequestOutcomeMeta(params, this.currentTurn, this.currentStep) },
surface: { op: "none" },
turn: this.currentTurn,
step: this.currentStep
});
}
// The projected conversation the model would see, folded ONLY from this
// session's committed rows (re-read from evidence_events), never from an
// in-memory buffer. Reading model-visible history therefore cannot outrun the
// log: every part it contains is the payload of a row that is already durable
// and signed. This is the "projected history" half of the same structural
// property recordRequestHeader gives the request path.
projectHistory(): ConversationHistory {
this.ensureUsable();
return this.projections.surface.evaluate(this.store.readSessionEvents(this.sessionId)).value;
}
// This session's committed rows, in commit order. Read-only, and re-read from
// the store rather than served from a buffer, for the same reason
// projectHistory() is: a caller building a request from these rows is building
// it from what is durable, not from what this process happens to remember.
readEvents(): readonly EvidenceEvent[] {
this.ensureUsable();
return this.store.readSessionEvents(this.sessionId);
}
// Commit the EXACT tool-schema bytes a request will carry, giving the header's
// `toolSchemaSha256` a durable referent. Surface op is `none` because the tool
// schema is part of the request envelope, not of the conversation — see
// ./toolSchemaCommitment.ts for the full argument and for the alternative
// (a spill-style side file) that was rejected.
recordToolSchema(schemaBytes: string | Buffer): SessionEventRef {
this.ensureUsable();
const bytes = typeof schemaBytes === "string" ? Buffer.from(schemaBytes, "utf8") : schemaBytes;
return this.appendSessionEvent({
eventType: "request/tools",
typeMeta: { turn: this.currentTurn, step: this.currentStep, toolSchemaSha256: sha256Hex(bytes) },
surface: { op: "none" },
turn: this.currentTurn,
step: this.currentStep,
payload: bytes
});
}
recordSystemPrompt(text: string): SessionEventRef {
return this.recordContent({
eventType: "system/prompt",
content: text,
slot: "system",
role: "system",
kind: "text",
buildMeta: () => ({}),
turn: this.currentTurn,
step: this.currentStep
});
}
recordUserMessage(text: string, provenance?: {
readonly sourceInputEventId: string;
readonly sourceInputFormat: "amc-image-input@2" | "amc-audio-input@1";
readonly sourceContentIndex: number;
}): SessionEventRef {
if (provenance !== undefined && (!["amc-image-input@2", NATIVE_AUDIO_INPUT_FORMAT].includes(provenance.sourceInputFormat)
|| typeof provenance.sourceInputEventId !== "string" || !provenance.sourceInputEventId
|| !Number.isSafeInteger(provenance.sourceContentIndex) || provenance.sourceContentIndex < 0)) {
throw new Error("Ordered text provenance requires its source inbox, format and nonnegative content index.");
}
return this.recordContent({
eventType: "user/message",
content: text,
slot: "user",
role: "user",
kind: "text",
buildMeta: () => provenance === undefined ? {} : ({ sourceInputEventId: provenance.sourceInputEventId,
sourceInputFormat: provenance.sourceInputFormat, sourceContentIndex: provenance.sourceContentIndex }),
turn: this.currentTurn,
step: this.currentStep
});
}
recordAssistantBlock(block: AssistantBlockInput): SessionEventRef {
const gemini = block.gemini === undefined ? undefined : snapshotRecordedGeminiPart(block.gemini, block.blockKind, block.content);
const turn = this.currentTurn;
const step = this.currentStep;
return this.recordContent({
eventType: "assistant/block",
content: block.content,
slot: `assistant:${block.blockIndex}`,
role: "assistant",
kind: block.blockKind,
buildMeta: () => ({
turn,
step,
blockIndex: block.blockIndex,
blockKind: block.blockKind,
stopReason: block.stopReason,
...(gemini === undefined ? {} : { gemini })
}),
turn,
step
});
}
/**
* Record a file the user attached, addressed by its own content.
*
* The bytes ARE the address: the row's `payload_sha256` is what the surface
* part points at, which is the same invariant every other projected part
* obeys. Attaching identical bytes under two names therefore yields one
* address, and the row is the only copy.
*
* Its own event type rather than a `user/message`, because a reader needs to
* tell what a person typed from what a person handed over -- and because an
* attachment is gated on the way in (see ../attachments/attachmentIngest.ts)
* while a typed message is not.
*/
recordUserAttachment(params: {
readonly filename: string;
readonly content: string | Buffer;
readonly kind: "text" | "image" | "audio";
readonly mimeType: string;
readonly sourceInputEventId?: string;
readonly sourceInputIndex?: number;
readonly sourceInputFormat?: "amc-image-input@2" | "amc-audio-input@1";
readonly sourceContentIndex?: number;
}): SessionEventRef {
const turn = this.currentTurn;
const step = this.currentStep;
const bytes = typeof params.content === "string"
? Buffer.from(params.content, "utf8")
: Buffer.from(params.content);
if ((params.sourceInputEventId !== undefined || params.sourceInputIndex !== undefined)
&& ((params.kind !== "image" && params.kind !== "audio") || typeof params.sourceInputEventId !== "string" || !params.sourceInputEventId
|| !Number.isSafeInteger(params.sourceInputIndex) || params.sourceInputIndex! < 0)) {
throw new Error("Image input provenance requires a source inbox row and nonnegative image index together.");
}
if ((params.sourceInputFormat !== undefined || params.sourceContentIndex !== undefined)
&& ((params.sourceInputFormat !== "amc-image-input@2" && params.sourceInputFormat !== NATIVE_AUDIO_INPUT_FORMAT) || params.sourceInputEventId === undefined
|| !Number.isSafeInteger(params.sourceContentIndex) || params.sourceContentIndex! < 0)) {
throw new Error("Ordered image provenance requires its source inbox, format and nonnegative content index.");
}
// Above the per-event cap, validated image/text bytes spill (./spill/spillInput.ts): commitment row first, then the object.
const what = `Attachment ${JSON.stringify(params.filename)}`;
const route = attachmentPayloadRoute(this.workspace, what, params.kind, bytes.byteLength);
if (params.kind === "image") {
assertNativeImageBytes(bytes, params.mimeType);
snapshotNativeImages([{ filename: params.filename, bytes, mediaType: params.mimeType }]);
}
if (params.kind === "audio") {
if (params.sourceInputFormat !== NATIVE_AUDIO_INPUT_FORMAT || params.sourceInputEventId === undefined
|| !Number.isSafeInteger(params.sourceContentIndex) || !Number.isSafeInteger(params.sourceInputIndex)) {
throw new Error("Audio attachments require original signed audio inbox/order provenance.");
}
assertNativeAudioBytes(bytes, params.mimeType);
snapshotNativeAudio({ filename: params.filename, bytes, mediaType: params.mimeType });
}
const retained = route.spill ? this.retainOversizeInput(what, bytes, route.cap, { subject: "user/attachment", filename: params.filename }) : null;
return this.recordContent({
eventType: "user/attachment",
content: retained === null ? bytes : retained.descriptor,
// Names BOTH: the digest of the ORIGINAL bytes makes the slot content-addressed, the filename
// keeps it legible to a person reading the log.
slot: `attachment:${params.filename}:${sha256Hex(bytes).slice(0, 12)}`,
role: "user",
kind: params.kind,
buildMeta: () => ({
turn,
step,
filename: params.filename,
mimeType: params.mimeType,
bytes: bytes.byteLength,
...(params.sourceInputEventId === undefined ? {} : { sourceInputEventId: params.sourceInputEventId, sourceInputIndex: params.sourceInputIndex }),
...(params.sourceInputFormat === undefined ? {} : { sourceInputFormat: params.sourceInputFormat, sourceContentIndex: params.sourceContentIndex }),
...(retained === null ? {} : { [SPILL_META_KEY]: retained.ref })
}),
turn,
step
});
}
retainOversizeInput(what: string, bytes: Buffer, cap: number, subject: SpillCommitmentSubject): { readonly ref: SpillRef; readonly descriptor: Buffer } { // Commitment row durable BEFORE the object (./spill/spillInput.ts).
return this.requireSpill().retainInput({ nameSeed: spillCommitmentNameSeed(subject), content: bytes }, { what, cap }, (ref) => void this.appendSessionEvent({ eventType: SPILL_COMMITMENT_EVENT_TYPE,
surface: { op: "none" }, turn: this.currentTurn, step: this.currentStep, typeMeta: { turn: this.currentTurn, step: this.currentStep, ...spillCommitmentMeta(subject), [SPILL_META_KEY]: ref } }));
}
recordToolCall(call: ToolCallInput): SessionEventRef {
const gemini = call.gemini === undefined ? undefined : snapshotRecordedGeminiPart(call.gemini, "tool_use", call.args,
{ id: call.toolCallId, wireName: call.providerName?.wireName ?? call.toolName });
// Recorded (and therefore durably committed) BEFORE the caller performs the
// tool side effect, so no model-visible dispatch precedes its log entry.
const turn = this.currentTurn;
const step = this.currentStep;
return this.recordContent({
eventType: "tool/call",
content: call.args,
slot: `tool_use:${call.toolCallId}`,
role: "assistant",
kind: "tool_use",
buildMeta: (argsSha256) => ({
turn,
step,
toolCallId: call.toolCallId,
toolName: call.toolName,
argsSha256,
dispatch: call.dispatch,
parentToken: call.parentToken,
...(call.providerName === undefined ? {} : { providerName: call.providerName }),
...(gemini === undefined ? {} : { gemini })
}),
turn,
step
});
}
/**
* Stable addresses of the current conversation entries. Compaction appends a
* loop/compact row whose payload becomes visible; original signed rows remain
* untouched. Origins survive later replacements of the same live entry.
*/
liveSurfaceEntries(): readonly LiveSurfaceEntry[] {
this.ensureUsable();
return describeLiveEntries(this.readEvents());
}
/** Replace one origin without changing its role, kind or tool-result identity. */
compactSurfaceEntry(params: {
readonly originEventId: string; readonly replacement: string; readonly reason: string;
/** Deprecated compatibility input. Savings are always measured from stored bytes. */
readonly replacedBytes?: number;
}): SessionEventRef {
return this.commitSurfaceCompaction({ origins: [params.originEventId], mode: "replace", replacement: params.replacement, reason: params.reason });
}
/** Summarize one contiguous live range in a single append, retaining raw evidence. */
compactSurfaceRange(params: {
readonly originEventIds: readonly string[]; readonly replacement: string; readonly reason: string;
readonly summaryRole?: "user" | "assistant";
}): SessionEventRef {
return this.commitSurfaceCompaction({ origins: params.originEventIds, mode: "summarize", replacement: params.replacement,
reason: params.reason, ...(params.summaryRole === undefined ? {} : { summaryRole: params.summaryRole }) });
}
dropSurfaceEntry(params: { readonly originEventId: string; readonly reason: string }): SessionEventRef {
return this.dropSurfaceRange({ originEventIds: [params.originEventId], reason: params.reason });
}
/** Complete tool pairs can be removed atomically; partial pairs refuse. */
dropSurfaceRange(params: { readonly originEventIds: readonly string[]; readonly reason: string }): SessionEventRef {
return this.commitSurfaceCompaction({ origins: params.originEventIds, mode: "drop", reason: params.reason });
}
compactToolResult(params: {
readonly toolCallId: string; readonly replacement: string; readonly reason: string;
/** Deprecated: deliberately ignored, never used to claim savings. */
readonly replacedBytes?: number;
}): SessionEventRef {
const entry = this.liveSurfaceEntries().find(candidate => candidate.slot === `tool_result:${params.toolCallId}` && candidate.kind === "tool_result");
if (!entry) throw new Error(`cannot compact ${params.toolCallId}: no live tool result is on this session's surface`);
return this.compactSurfaceEntry({ originEventId: entry.originEventId, replacement: params.replacement, reason: params.reason });
}
private commitSurfaceCompaction(params: Parameters<typeof prepareSurfaceCompaction>[2]): SessionEventRef {
this.ensureUsable();
if (this.currentStep !== null) throw new Error("compaction is allowed only between steps, never during an in-flight model/tool step");
const prepared = prepareSurfaceCompaction(this.workspace, this.readEvents(), params);
return this.appendSessionEvent({ eventType: "loop/compact", typeMeta: {
turn: this.currentTurn, step: this.currentStep, ...prepared.typeMeta
}, surface: prepared.surface, payload: prepared.payload, turn: this.currentTurn, step: this.currentStep });
}
// Spill oversized tool output before it becomes either model-visible or logged;
// the full payload commitment remains in the signed spill metadata.
recordToolResult(result: ToolResultInput): SessionEventRef {
this.ensureUsable();
const turn = this.currentTurn;
const step = this.currentStep;
const full = typeof result.content === "string" ? Buffer.from(result.content, "utf8") : Buffer.from(result.content);
const outcome = this.requireSpill().apply({ nameSeed: result.toolCallId, content: full }, (ref) => {
this.appendSessionEvent({
eventType: "tool/spill-commitment",
typeMeta: { turn, step, toolCallId: result.toolCallId, [SPILL_META_KEY]: ref },
surface: { op: "none" },
turn,
step
});
});
return this.recordContent({
eventType: "tool/result",
content: outcome.content,
slot: `tool_result:${result.toolCallId}`,
role: "tool",
kind: "tool_result",
buildMeta: () => ({
turn,
step,
toolCallId: result.toolCallId,
outcome: result.outcome,
exitCode: result.exitCode,
timedOut: result.timedOut,
denied: result.denied,
[SPILL_META_KEY]: outcome.ref
}),
turn,
step
});
}
// The approval audit pair. BOTH halves are turn-enclosed, and `requireTurn` is
// what enforces it rather than a comment asking callers to be careful.
//
// WHY A TURN IS REQUIRED. The turn is this log's commit and replay boundary:
// its `turn/seal` commits to a Merkle root over exactly the events inside its
// window. An approval row appended between turns is in no window, so it is
// covered by no seal — the one row an auditor most needs sealed would be the
// one row that is not. The answer row was additionally being written with
// `turn: null, step: null`, so even the pair's own halves could land in
// different windows. Both now carry the same open turn and step, so the whole
// decision sits inside one sealed window.
//
// The refusal is deliberately loud. An asker that has no turn open is asking
// outside the lifetime of the work the answer would authorize, and the honest
// response to that is to fail, never to log it somewhere weaker.
recordApproval(record: ApprovalRecord): SessionEventRef {
const turn = this.requireTurn();
const step = this.currentStep;
const row = buildApprovalRow(record, turn, step);
return this.appendSessionEvent({
eventType: row.eventType,
typeMeta: row.meta,
surface: { op: "none" },
turn,
step
});
}
// The agent loop's own control rows — its inbox splices, its cancellations,
// its pre-step vetoes. One method over a closed union rather than one method
// per row, because these are the loop's bookkeeping rather than conversation
// content: their shapes live together in ./loopEventMeta.ts, which is also
// what keeps their hash pre-image order in one place. Surface op is always
// `none` — a queued message becomes model-visible only when a step claims it
// and records a `user/message`.
recordLoopEvent(record: LoopEventRecord): SessionEventRef {
this.ensureUsable();
const row = buildLoopEventRow(record);
return this.appendSessionEvent({
eventType: row.eventType,
typeMeta: row.meta,
surface: { op: "none" },
turn: this.currentTurn,
step: this.currentStep,
...(row.payload === null ? {} : { payload: row.payload })
});
}
/**
* Record a scoreable projection row into this session's spine.
*
* THE RULE THIS EXISTS TO ENFORCE: a projection row belongs to the session
* whose turn caused the fact it projects, and it goes through the session's
* own writer -- never through `openLedger().appendEvidenceBatch`. Two writers
* bypassed that (`agentToolset`'s record callback and
* `delegationEvidenceWriter`), which put rows with NO SESSION ENVELOPE inside
* sessions that have a spine. Two consequences followed, and only one of them
* was obvious:
*
* `sessionRootDescriptor` refuses to anchor such a session, because "the
* session root would cover less than the session does" -- a correct refusal,
* so every session that called a tool became unanchorable.
*
* And a row written after the session was sealed makes the seal's committed
* final hash false, which `verifyLedgerIntegrity` reports workspace-wide.
* That is not a hidden cost: `assurance/assuranceRunner.ts` turns it into
* `status: "INVALID"`, and `evidence/auditPacket.ts` ships it to a customer
* as `integrity/ledger-verify.json`.
*
* The union is closed to the three projection types on purpose. This is not a
* general escape hatch into the spine: a caller wanting to record conversation
* or lifecycle has a named method for it, and widening this one would make
* "what may enter the spine" a question with no answer.
*/
recordProjectedEvidence(row: {
readonly eventType: "audit" | "metric" | "stdout";
readonly payload: string;
readonly meta: Record<string, unknown>;
}): SessionEventRef {
this.ensureUsable();
return this.appendSessionEvent({
eventType: row.eventType,
typeMeta: row.meta,
// Projection rows are evidence about the turn, not content the model sees.
surface: { op: "none" },
turn: this.currentTurn,
step: this.currentStep,
payload: row.payload
});
}
recordSandboxMode(input: SandboxModeInput): SessionEventRef {
this.ensureUsable();
return this.appendSessionEvent({
eventType: "sandbox/mode",
typeMeta: {
turn: this.currentTurn,
backend: input.backend,
mode: input.mode,
policyDigest: input.policyDigest
},
surface: { op: "none" },
turn: this.currentTurn,
step: null
});
}
close(params: SessionCloseParams): SessionEventRef {
this.ensureUsable();
const sessionId = this.sessionId;
// finalEventId names the last event of the session, which is this close event
// itself; its id is minted up front so the meta can commit to it.
const closeId = randomUUID();
const ref = this.appendSessionEvent({
eventType: "session/close",
typeMeta: {
reason: params.reason,
turnCount: this.turnNo,
sealCount: this.window.sealCount,
sessionMerkleRoot: this.window.sessionMerkleRoot(),
finalEventId: closeId
},
surface: { op: "none" },
turn: null,
step: null,
id: closeId
});
// sealSession is NOT idempotent — the contract makes a second seal throw on
// every backend — so it runs exactly once, guarded by `closed`. The sealed
// final hash then equals this close event's hash (it is the last event), so
// the seal and the close event cross-check.
this.store.sealSession(sessionId);
this.closed = true;
this.store.close();
return ref;
}
}