@dosu/seshi-model 0.0.0-stage → 0.11.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/dist/index.js ADDED
@@ -0,0 +1,1553 @@
1
+ // packages/ts/model/src/api.ts
2
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 2048;
3
+ var EMPTY_PREFIX_SHA256 = "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945";
4
+ function isStub(metadata) {
5
+ return metadata.status === "stored" && metadata.head === undefined;
6
+ }
7
+ // packages/ts/model/src/canonical.ts
8
+ var PY_WHITESPACE = new Set([
9
+ 9,
10
+ 10,
11
+ 11,
12
+ 12,
13
+ 13,
14
+ 28,
15
+ 29,
16
+ 30,
17
+ 31,
18
+ 32,
19
+ 133,
20
+ 160,
21
+ 5760,
22
+ 8192,
23
+ 8193,
24
+ 8194,
25
+ 8195,
26
+ 8196,
27
+ 8197,
28
+ 8198,
29
+ 8199,
30
+ 8200,
31
+ 8201,
32
+ 8202,
33
+ 8232,
34
+ 8233,
35
+ 8239,
36
+ 8287,
37
+ 12288
38
+ ]);
39
+ function pyRstrip(s) {
40
+ let end = s.length;
41
+ while (end > 0 && PY_WHITESPACE.has(s.charCodeAt(end - 1)))
42
+ end--;
43
+ return end === s.length ? s : s.slice(0, end);
44
+ }
45
+ function canonicalText(text) {
46
+ return text.replaceAll(`\r
47
+ `, `
48
+ `).split(`
49
+ `).map(pyRstrip).join(`
50
+ `);
51
+ }
52
+ function stripNul(value) {
53
+ if (typeof value === "string")
54
+ return value.replaceAll("\x00", "");
55
+ if (Array.isArray(value))
56
+ return value.map(stripNul);
57
+ if (typeof value === "object" && value !== null) {
58
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, stripNul(v)]));
59
+ }
60
+ return value;
61
+ }
62
+ // packages/ts/model/src/errors.ts
63
+ class SessionRejected extends Error {
64
+ code;
65
+ constructor(code, message) {
66
+ super(message);
67
+ this.code = code;
68
+ this.name = "SessionRejected";
69
+ }
70
+ }
71
+
72
+ class IngestRejected extends SessionRejected {
73
+ code;
74
+ constructor(code, message) {
75
+ super(code, message);
76
+ this.code = code;
77
+ this.name = "IngestRejected";
78
+ }
79
+ }
80
+
81
+ class OffsetMismatch extends Error {
82
+ offset;
83
+ expected;
84
+ code = "offset_mismatch";
85
+ constructor(offset, expected) {
86
+ super(`chunk starts at byte ${offset}; the session's log ends at ${expected}`);
87
+ this.offset = offset;
88
+ this.expected = expected;
89
+ this.name = "OffsetMismatch";
90
+ }
91
+ }
92
+
93
+ class SessionConflict extends Error {
94
+ code = "conflict";
95
+ constructor(message) {
96
+ super(message);
97
+ this.name = "SessionConflict";
98
+ }
99
+ }
100
+
101
+ class Forbidden extends Error {
102
+ code = "forbidden";
103
+ constructor(message) {
104
+ super(message);
105
+ this.name = "Forbidden";
106
+ }
107
+ }
108
+
109
+ class Unauthorized extends Error {
110
+ code = "unauthorized";
111
+ constructor(message = "a valid token is required") {
112
+ super(message);
113
+ this.name = "Unauthorized";
114
+ }
115
+ }
116
+
117
+ class StoreError extends Error {
118
+ cause;
119
+ constructor(message, cause) {
120
+ super(message);
121
+ this.cause = cause;
122
+ this.name = "StoreError";
123
+ }
124
+ }
125
+ // packages/ts/model/src/generated/envelope.ts
126
+ var SCHEMA_ID = "seshi/envelope/1";
127
+ var JSON_SCHEMA = {
128
+ $id: "envelope.schema.json",
129
+ type: "object",
130
+ properties: {
131
+ schema: { const: "seshi/envelope/1" },
132
+ source: { $ref: "common.schema.json#/$defs/SourceKind" },
133
+ source_id: { $ref: "common.schema.json#/$defs/SourceId" },
134
+ format: { type: "string", minLength: 1 },
135
+ session_key: { type: "string", minLength: 1 },
136
+ payload: { $ref: "#/$defs/Payload" },
137
+ caller: { $ref: "#/$defs/Caller" },
138
+ claims: { $ref: "common.schema.json#/$defs/Claims" },
139
+ owner: { type: "string", minLength: 1 },
140
+ owner_basis: { $ref: "common.schema.json#/$defs/OwnerBasis" },
141
+ idempotency_key: { type: "string", minLength: 1, maxLength: 2048 },
142
+ provenance: { $ref: "common.schema.json#/$defs/SourceLocation" },
143
+ received_at: { $ref: "common.schema.json#/$defs/Timestamp" },
144
+ visibility: { $ref: "common.schema.json#/$defs/Visibility" },
145
+ replace: { type: "boolean" },
146
+ rebuild: { type: "boolean" },
147
+ shipped: { $ref: "#/$defs/ShippedPrefix" },
148
+ project: { type: "string" },
149
+ branch: { type: "string" },
150
+ parent_session_id: { type: "string" },
151
+ fork_of: { type: "string" },
152
+ retract_hash: { $ref: "common.schema.json#/$defs/Sha256" }
153
+ },
154
+ required: [
155
+ "schema",
156
+ "source",
157
+ "source_id",
158
+ "format",
159
+ "session_key",
160
+ "payload",
161
+ "caller",
162
+ "owner",
163
+ "owner_basis",
164
+ "idempotency_key",
165
+ "received_at"
166
+ ],
167
+ additionalProperties: false,
168
+ $defs: {
169
+ Payload: { oneOf: [{ $ref: "#/$defs/LogPayload" }, { $ref: "#/$defs/SpanPayload" }] },
170
+ LogPayload: {
171
+ type: "object",
172
+ properties: {
173
+ kind: { const: "log" },
174
+ encoding: { $ref: "common.schema.json#/$defs/LogEncoding" },
175
+ text: { type: "string" },
176
+ offset: { type: "integer", minimum: 0 }
177
+ },
178
+ required: ["kind", "encoding", "text", "offset"],
179
+ additionalProperties: false
180
+ },
181
+ SpanPayload: {
182
+ type: "object",
183
+ properties: {
184
+ kind: { const: "spans" },
185
+ spans: { type: "array", items: { type: "object" } },
186
+ resource: { type: "array", items: { type: "object" } }
187
+ },
188
+ required: ["kind", "spans"],
189
+ additionalProperties: false
190
+ },
191
+ ShippedPrefix: {
192
+ type: "object",
193
+ properties: {
194
+ records: { type: "integer", minimum: 0 },
195
+ prefix_sha256: { $ref: "common.schema.json#/$defs/Sha256" }
196
+ },
197
+ required: ["records", "prefix_sha256"],
198
+ additionalProperties: false
199
+ },
200
+ Caller: {
201
+ type: "object",
202
+ properties: {
203
+ kind: { $ref: "common.schema.json#/$defs/CallerKind" },
204
+ principal: { type: "string", minLength: 1 },
205
+ credential_id: { type: "string", minLength: 1 }
206
+ },
207
+ required: ["kind", "principal"],
208
+ additionalProperties: false
209
+ }
210
+ }
211
+ };
212
+ // packages/ts/model/src/parse.ts
213
+ import { createHash } from "node:crypto";
214
+
215
+ // packages/ts/model/src/generated/trace.ts
216
+ var SCHEMA_ID2 = "seshi/trace/1";
217
+ var JSON_SCHEMA2 = {
218
+ $id: "trace.schema.json",
219
+ type: "object",
220
+ properties: {
221
+ schema: { const: "seshi/trace/1" },
222
+ content_hash: { $ref: "common.schema.json#/$defs/Sha256" },
223
+ source: { type: "string", minLength: 1 },
224
+ agent: { type: "string", minLength: 1 },
225
+ project: { type: "string" },
226
+ branch: { type: "string" },
227
+ session_id: { type: ["string", "null"] },
228
+ started_at: { type: ["string", "null"] },
229
+ ended_at: { type: ["string", "null"] },
230
+ records: { type: "array", items: { $ref: "#/$defs/TraceRecord" } },
231
+ events: { type: "array", items: { $ref: "#/$defs/TraceEvent" } },
232
+ metadata: { $ref: "#/$defs/TraceMetadata" },
233
+ llm_calls: { type: "array", items: { $ref: "#/$defs/LlmCall" } },
234
+ provenance: { $ref: "common.schema.json#/$defs/Provenance" }
235
+ },
236
+ required: [
237
+ "schema",
238
+ "content_hash",
239
+ "source",
240
+ "agent",
241
+ "session_id",
242
+ "started_at",
243
+ "ended_at",
244
+ "records",
245
+ "events",
246
+ "metadata"
247
+ ],
248
+ additionalProperties: false,
249
+ $defs: {
250
+ TraceRecord: {
251
+ oneOf: [
252
+ { $ref: "#/$defs/TraceMetaRecord" },
253
+ { $ref: "#/$defs/TraceTextRecord" },
254
+ { $ref: "#/$defs/TraceAssistantRecord" },
255
+ { $ref: "#/$defs/TraceToolResultRecord" }
256
+ ]
257
+ },
258
+ TraceMetaRecord: {
259
+ type: "object",
260
+ properties: {
261
+ role: { const: "meta" },
262
+ source: { type: "string", minLength: 1 },
263
+ cwd: { type: "string" },
264
+ git_branch: { type: "string" },
265
+ model: { type: "string" },
266
+ agent_version: { type: "string" }
267
+ },
268
+ required: ["role", "source"],
269
+ additionalProperties: false
270
+ },
271
+ TraceTextRecord: {
272
+ type: "object",
273
+ properties: {
274
+ role: { enum: ["user", "system", "observation", "reasoning"] },
275
+ content: { type: "string" },
276
+ timestamp: { type: "string" },
277
+ id: { $ref: "#/$defs/RecordId" },
278
+ llm_call: { $ref: "#/$defs/LlmCallRef" },
279
+ synthetic: { const: true },
280
+ omitted: { type: "integer", minimum: 1 }
281
+ },
282
+ required: ["role", "content", "timestamp"],
283
+ additionalProperties: false
284
+ },
285
+ TraceAssistantRecord: {
286
+ type: "object",
287
+ properties: {
288
+ role: { const: "assistant" },
289
+ content: { type: ["string", "null"] },
290
+ tool_calls: { type: "array", items: { $ref: "#/$defs/TraceToolCall" } },
291
+ timestamp: { type: "string" },
292
+ id: { $ref: "#/$defs/RecordId" },
293
+ llm_call: { $ref: "#/$defs/LlmCallRef" }
294
+ },
295
+ required: ["role", "content", "timestamp"],
296
+ additionalProperties: false
297
+ },
298
+ TraceToolCall: {
299
+ type: "object",
300
+ properties: {
301
+ id: { type: "string", minLength: 1 },
302
+ name: { type: "string", minLength: 1 },
303
+ args: { type: "string" }
304
+ },
305
+ required: ["id", "name", "args"],
306
+ additionalProperties: false
307
+ },
308
+ TraceToolResultRecord: {
309
+ type: "object",
310
+ properties: {
311
+ role: { const: "tool" },
312
+ tool_call_id: { type: "string", minLength: 1 },
313
+ content: { type: "string" },
314
+ ok: { type: "boolean" },
315
+ timestamp: { type: "string" },
316
+ id: { $ref: "#/$defs/RecordId" },
317
+ withheld: { enum: ["sensitive-file", "secret-output", "review"] },
318
+ duration_ms: { type: "number", minimum: 0 }
319
+ },
320
+ required: ["role", "tool_call_id", "content", "timestamp"],
321
+ additionalProperties: false
322
+ },
323
+ RecordId: { type: "string", minLength: 1 },
324
+ LlmCallRef: { type: "string", minLength: 1 },
325
+ LlmCall: {
326
+ type: "object",
327
+ properties: {
328
+ id: { type: "string", minLength: 1 },
329
+ model: { type: "string" },
330
+ provider: { type: "string" },
331
+ started_at: { type: "string" },
332
+ ended_at: { type: "string" },
333
+ duration_ms: { type: "number", minimum: 0 },
334
+ usage: { $ref: "#/$defs/TokenUsage" },
335
+ stop_reason: { type: "string" },
336
+ request_id: { type: "string" },
337
+ parameters: {
338
+ type: "object",
339
+ additionalProperties: { type: ["string", "number", "boolean", "null"] }
340
+ },
341
+ error: { type: "string" }
342
+ },
343
+ required: ["id"],
344
+ additionalProperties: false
345
+ },
346
+ TokenUsage: {
347
+ type: "object",
348
+ properties: {
349
+ input_tokens: { type: "integer", minimum: 0 },
350
+ output_tokens: { type: "integer", minimum: 0 },
351
+ cache_read_input_tokens: { type: "integer", minimum: 0 },
352
+ cache_creation_input_tokens: { type: "integer", minimum: 0 },
353
+ reasoning_tokens: { type: "integer", minimum: 0 },
354
+ total_tokens: { type: "integer", minimum: 0 }
355
+ },
356
+ additionalProperties: false
357
+ },
358
+ EventRole: {
359
+ enum: ["user", "assistant", "tool_call", "tool_result", "system", "observation", "reasoning"]
360
+ },
361
+ TraceEvent: {
362
+ type: "object",
363
+ properties: {
364
+ index: { type: "integer", minimum: 0 },
365
+ role: { $ref: "#/$defs/EventRole" },
366
+ text: { type: "string" },
367
+ timestamp: { type: ["string", "null"] },
368
+ tool_name: { type: "string" },
369
+ tool_call_id: { type: "string" },
370
+ ok: { type: "boolean" }
371
+ },
372
+ required: ["index", "role", "text", "timestamp"],
373
+ additionalProperties: false
374
+ },
375
+ TraceMetadata: {
376
+ type: "object",
377
+ properties: {
378
+ cwd: { type: "string" },
379
+ git_branch: { type: "string" },
380
+ model: { type: "string" },
381
+ parent_session_id: { type: "string" },
382
+ continuation: { $ref: "common.schema.json#/$defs/Continuation" },
383
+ normalizer: { $ref: "common.schema.json#/$defs/Normalizer" }
384
+ },
385
+ additionalProperties: true
386
+ }
387
+ }
388
+ };
389
+
390
+ // packages/ts/model/src/schemas/trace.ts
391
+ var TRACE_SCHEMA = SCHEMA_ID2;
392
+
393
+ // packages/ts/model/src/schemas/trajectory.ts
394
+ class TrajectoryError extends Error {
395
+ constructor(message) {
396
+ super(message);
397
+ this.name = "TrajectoryError";
398
+ }
399
+ }
400
+ var SCOPE_COORDINATE = /^[^\x00-\x1f\x7f\u0085\u2028\u2029]*$/;
401
+ function isScopeCoordinate(value) {
402
+ return typeof value === "string" && SCOPE_COORDINATE.test(value);
403
+ }
404
+ var TEXT_ROLES = new Set(["user", "system", "observation", "reasoning"]);
405
+ function fail(index, message) {
406
+ throw new TrajectoryError(`record ${index}: ${message}`);
407
+ }
408
+ function requireString(index, record, key) {
409
+ const value = record[key];
410
+ if (typeof value !== "string")
411
+ fail(index, `${key} must be a string`);
412
+ return value;
413
+ }
414
+ function optionalString(index, record, key) {
415
+ const value = record[key];
416
+ if (value === undefined || value === null)
417
+ return;
418
+ if (typeof value !== "string")
419
+ fail(index, `${key} must be a string`);
420
+ return value;
421
+ }
422
+ function validateToolCall(index, value, at) {
423
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
424
+ fail(index, `tool_calls[${at}] must be an object`);
425
+ }
426
+ const call = value;
427
+ const id = requireString(index, call, "id");
428
+ const name = requireString(index, call, "name");
429
+ const args = requireString(index, call, "args");
430
+ if (id === "")
431
+ fail(index, `tool_calls[${at}].id must not be empty`);
432
+ if (name === "")
433
+ fail(index, `tool_calls[${at}].name must not be empty`);
434
+ return { id, name, args };
435
+ }
436
+ function nonEmptyOptional(index, record, key) {
437
+ const value = optionalString(index, record, key);
438
+ if (value === "")
439
+ fail(index, `${key} must not be empty`);
440
+ return value;
441
+ }
442
+ var WITHHELD = new Set(["sensitive-file", "secret-output", "review"]);
443
+ function injected(index, record) {
444
+ const out = {};
445
+ const synthetic = record.synthetic;
446
+ if (synthetic !== undefined && synthetic !== null) {
447
+ if (synthetic !== true)
448
+ fail(index, "synthetic must be true");
449
+ out.synthetic = true;
450
+ }
451
+ const omitted = record.omitted;
452
+ if (omitted !== undefined && omitted !== null) {
453
+ if (!Number.isInteger(omitted) || omitted < 1) {
454
+ fail(index, "omitted must be an integer ≥ 1");
455
+ }
456
+ out.omitted = omitted;
457
+ }
458
+ return out;
459
+ }
460
+ function extensions(index, record, role) {
461
+ const out = {};
462
+ if (role === "meta") {
463
+ const version = optionalString(index, record, "agent_version");
464
+ if (version !== undefined)
465
+ out.agent_version = version;
466
+ return out;
467
+ }
468
+ const id = nonEmptyOptional(index, record, "id");
469
+ if (id !== undefined)
470
+ out.id = id;
471
+ if (role !== "tool") {
472
+ const call = nonEmptyOptional(index, record, "llm_call");
473
+ if (call !== undefined)
474
+ out.llm_call = call;
475
+ if (role === "user")
476
+ Object.assign(out, injected(index, record));
477
+ return out;
478
+ }
479
+ const withheld = record.withheld;
480
+ if (withheld !== undefined && withheld !== null) {
481
+ if (typeof withheld !== "string" || !WITHHELD.has(withheld)) {
482
+ fail(index, "withheld must be sensitive-file, secret-output or review");
483
+ }
484
+ out.withheld = withheld;
485
+ }
486
+ const duration = record.duration_ms;
487
+ if (duration !== undefined && duration !== null) {
488
+ if (typeof duration !== "number" || !Number.isFinite(duration) || duration < 0) {
489
+ fail(index, "duration_ms must be a number ≥ 0");
490
+ }
491
+ out.duration_ms = duration;
492
+ }
493
+ return out;
494
+ }
495
+ function validateRecord(index, value, extended) {
496
+ const record = validateCore(index, value);
497
+ if (!extended)
498
+ return record;
499
+ return { ...record, ...extensions(index, value, record.role) };
500
+ }
501
+ function validateCore(index, value) {
502
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
503
+ fail(index, "must be an object");
504
+ }
505
+ const record = value;
506
+ const role = record.role;
507
+ if (role === "meta") {
508
+ const source = requireString(index, record, "source");
509
+ if (source === "" || !isScopeCoordinate(source))
510
+ fail(index, "source must be a scope coordinate");
511
+ const git_branch = optionalString(index, record, "git_branch");
512
+ if (git_branch !== undefined && !isScopeCoordinate(git_branch)) {
513
+ fail(index, "git_branch must be a scope coordinate");
514
+ }
515
+ const meta = { role, source };
516
+ const cwd = optionalString(index, record, "cwd");
517
+ const model = optionalString(index, record, "model");
518
+ if (cwd !== undefined)
519
+ meta.cwd = cwd;
520
+ if (git_branch !== undefined)
521
+ meta.git_branch = git_branch;
522
+ if (model !== undefined)
523
+ meta.model = model;
524
+ return meta;
525
+ }
526
+ if (typeof role === "string" && TEXT_ROLES.has(role)) {
527
+ return {
528
+ role,
529
+ content: requireString(index, record, "content"),
530
+ timestamp: requireString(index, record, "timestamp")
531
+ };
532
+ }
533
+ if (role === "assistant") {
534
+ const timestamp = requireString(index, record, "timestamp");
535
+ const calls = record.tool_calls;
536
+ if (calls !== undefined && calls !== null) {
537
+ if (!Array.isArray(calls))
538
+ fail(index, "tool_calls must be an array");
539
+ const content = record.content;
540
+ if (content !== null && content !== undefined && typeof content !== "string") {
541
+ fail(index, "content must be a string or null");
542
+ }
543
+ return {
544
+ role,
545
+ content: content ?? null,
546
+ tool_calls: calls.map((call, at) => validateToolCall(index, call, at)),
547
+ timestamp
548
+ };
549
+ }
550
+ const content = record.content;
551
+ if (content === null || content === undefined) {
552
+ return { role, content: null, timestamp };
553
+ }
554
+ if (typeof content !== "string")
555
+ fail(index, "content must be a string or null");
556
+ return { role, content, timestamp };
557
+ }
558
+ if (role === "tool") {
559
+ const tool_call_id = requireString(index, record, "tool_call_id");
560
+ if (tool_call_id === "")
561
+ fail(index, "tool_call_id must not be empty");
562
+ const result = {
563
+ role,
564
+ tool_call_id,
565
+ content: requireString(index, record, "content"),
566
+ timestamp: requireString(index, record, "timestamp")
567
+ };
568
+ const ok = record.ok;
569
+ if (ok !== undefined && ok !== null) {
570
+ if (typeof ok !== "boolean")
571
+ fail(index, "ok must be a boolean");
572
+ result.ok = ok;
573
+ }
574
+ return result;
575
+ }
576
+ fail(index, `unknown role ${JSON.stringify(role)}`);
577
+ }
578
+ function validateRecords(records) {
579
+ if (!Array.isArray(records))
580
+ throw new TrajectoryError("records must be an array");
581
+ return records.map((record, index) => validateRecord(index, record, false));
582
+ }
583
+ function validateTraceRecords(records) {
584
+ if (!Array.isArray(records))
585
+ throw new TrajectoryError("records must be an array");
586
+ return records.map((record, index) => validateRecord(index, record, true));
587
+ }
588
+
589
+ // packages/ts/model/src/parse.ts
590
+ function contentHash(source, events, continuation) {
591
+ const body = events.map((e) => `${e.role}\x1F${e.text}`).join("\x1E");
592
+ const head = continuation ? `${source}@${continuation.from_record}` : source;
593
+ return createHash("sha256").update(`${head}
594
+ ${body}`, "utf8").digest("hex");
595
+ }
596
+ function epochOf(value) {
597
+ const ms = Date.parse(value);
598
+ return Number.isNaN(ms) ? null : ms;
599
+ }
600
+ var USAGE_KEYS = [
601
+ "input_tokens",
602
+ "output_tokens",
603
+ "cache_read_input_tokens",
604
+ "cache_creation_input_tokens",
605
+ "reasoning_tokens",
606
+ "total_tokens"
607
+ ];
608
+ var CALL_STRINGS = [
609
+ "model",
610
+ "provider",
611
+ "started_at",
612
+ "ended_at",
613
+ "stop_reason",
614
+ "request_id",
615
+ "error"
616
+ ];
617
+ function checkLlmCall(value, index) {
618
+ const bad = (what) => {
619
+ throw new TrajectoryError(`llm call ${index}: ${what}`);
620
+ };
621
+ if (typeof value !== "object" || value === null || Array.isArray(value))
622
+ bad("must be an object");
623
+ const call = value;
624
+ if (typeof call.id !== "string" || call.id === "")
625
+ bad("needs an id");
626
+ const out = { id: call.id };
627
+ for (const key of CALL_STRINGS) {
628
+ const field = call[key];
629
+ if (field === undefined || field === null)
630
+ continue;
631
+ if (typeof field !== "string")
632
+ bad(`${key} must be a string`);
633
+ out[key] = field;
634
+ }
635
+ if (call.duration_ms !== undefined && call.duration_ms !== null) {
636
+ const ms = call.duration_ms;
637
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) {
638
+ bad("duration_ms must be a number ≥ 0");
639
+ }
640
+ out.duration_ms = ms;
641
+ }
642
+ if (call.usage !== undefined && call.usage !== null) {
643
+ if (typeof call.usage !== "object" || Array.isArray(call.usage))
644
+ bad("usage must be an object");
645
+ const usage = call.usage;
646
+ for (const key of Object.keys(usage)) {
647
+ if (!USAGE_KEYS.includes(key))
648
+ bad(`usage.${key} is not a token count`);
649
+ }
650
+ const counts = {};
651
+ for (const key of USAGE_KEYS) {
652
+ const n = usage[key];
653
+ if (n === undefined || n === null)
654
+ continue;
655
+ if (!Number.isInteger(n) || n < 0) {
656
+ bad(`usage.${key} must be a whole number ≥ 0`);
657
+ }
658
+ counts[key] = n;
659
+ }
660
+ out.usage = counts;
661
+ }
662
+ if (call.parameters !== undefined && call.parameters !== null) {
663
+ const params = call.parameters;
664
+ if (typeof params !== "object" || Array.isArray(params))
665
+ bad("parameters must be an object");
666
+ const kept = {};
667
+ for (const [key, v] of Object.entries(params)) {
668
+ if (v !== null && !["string", "number", "boolean"].includes(typeof v)) {
669
+ bad(`parameters.${key} must be a string, number, boolean or null`);
670
+ }
671
+ kept[key] = v;
672
+ }
673
+ out.parameters = kept;
674
+ }
675
+ return out;
676
+ }
677
+ function checkLlmCalls(input, records) {
678
+ const calls = input.map(checkLlmCall);
679
+ const ids = new Set;
680
+ for (const call of calls) {
681
+ if (ids.has(call.id))
682
+ throw new TrajectoryError(`llm call ${call.id} appears twice`);
683
+ ids.add(call.id);
684
+ }
685
+ records.forEach((record, index) => {
686
+ const ref = "llm_call" in record ? record.llm_call : undefined;
687
+ if (ref !== undefined && !ids.has(ref)) {
688
+ throw new TrajectoryError(`record ${index}: llm_call ${ref} is not in llm_calls`);
689
+ }
690
+ });
691
+ return calls;
692
+ }
693
+ function eventsOf(records) {
694
+ const events = [];
695
+ const toolNames = new Map;
696
+ for (const record of records.slice(1)) {
697
+ if (record.role === "meta") {
698
+ throw new TrajectoryError("only the first record may be a meta record");
699
+ }
700
+ const timestamp = epochOf(record.timestamp) === null ? null : record.timestamp;
701
+ const index = events.length;
702
+ switch (record.role) {
703
+ case "user":
704
+ case "system":
705
+ case "observation":
706
+ case "reasoning":
707
+ events.push({ index, role: record.role, text: canonicalText(record.content), timestamp });
708
+ break;
709
+ case "assistant": {
710
+ const calls = "tool_calls" in record ? record.tool_calls : undefined;
711
+ if (calls && calls.length > 0) {
712
+ for (const call of calls) {
713
+ toolNames.set(call.id, call.name);
714
+ events.push({
715
+ index: events.length,
716
+ role: "tool_call",
717
+ text: canonicalText(`${call.name} ${call.args}`),
718
+ timestamp,
719
+ tool_name: call.name,
720
+ tool_call_id: call.id
721
+ });
722
+ }
723
+ } else if (record.content) {
724
+ events.push({ index, role: "assistant", text: canonicalText(record.content), timestamp });
725
+ }
726
+ break;
727
+ }
728
+ case "tool": {
729
+ const event = {
730
+ index,
731
+ role: "tool_result",
732
+ text: canonicalText(record.content),
733
+ timestamp,
734
+ tool_call_id: record.tool_call_id
735
+ };
736
+ const name = toolNames.get(record.tool_call_id);
737
+ if (name !== undefined)
738
+ event.tool_name = name;
739
+ if (record.ok !== undefined)
740
+ event.ok = record.ok;
741
+ events.push(event);
742
+ break;
743
+ }
744
+ }
745
+ }
746
+ return events;
747
+ }
748
+ function conversationError(source, events) {
749
+ const roles = new Set(events.map((e) => e.role));
750
+ if (!roles.has("user"))
751
+ return "trajectory has no user records";
752
+ if (!source.startsWith("chat:") && !roles.has("assistant") && !roles.has("tool_call")) {
753
+ return "trajectory has no assistant records";
754
+ }
755
+ return null;
756
+ }
757
+ function parseTrace(input, options = {}) {
758
+ const records = validateTraceRecords(stripNul(input));
759
+ const first = records[0];
760
+ if (first?.role !== "meta") {
761
+ throw new TrajectoryError("first record must be the meta record");
762
+ }
763
+ const meta = first;
764
+ const given = options.llm_calls === undefined ? [] : stripNul(options.llm_calls);
765
+ if (!Array.isArray(given))
766
+ throw new TrajectoryError("llm_calls must be an array");
767
+ const llmCalls = checkLlmCalls(given, records);
768
+ const events = eventsOf(records);
769
+ const continuation = options.metadata?.continuation;
770
+ const problem = continuation ? null : conversationError(meta.source, events);
771
+ if (problem)
772
+ throw new TrajectoryError(problem);
773
+ const stamps = events.map((e) => e.timestamp === null ? null : epochOf(e.timestamp)).filter((ms) => ms !== null);
774
+ const at = (ms) => events.find((e) => e.timestamp !== null && epochOf(e.timestamp) === ms);
775
+ const started = stamps.length ? at(Math.min(...stamps)) : undefined;
776
+ const ended = stamps.length ? at(Math.max(...stamps)) : undefined;
777
+ const metadata = {};
778
+ if (meta.cwd !== undefined)
779
+ metadata.cwd = meta.cwd;
780
+ if (meta.git_branch !== undefined)
781
+ metadata.git_branch = meta.git_branch;
782
+ if (meta.model !== undefined)
783
+ metadata.model = meta.model;
784
+ Object.assign(metadata, options.metadata ?? {});
785
+ const trace = {
786
+ schema: TRACE_SCHEMA,
787
+ content_hash: contentHash(meta.source, events, continuation),
788
+ source: meta.source,
789
+ agent: options.agent ?? meta.source,
790
+ session_id: options.session_id ?? null,
791
+ started_at: started?.timestamp ?? null,
792
+ ended_at: ended?.timestamp ?? null,
793
+ records,
794
+ events,
795
+ metadata
796
+ };
797
+ if (options.project !== undefined)
798
+ trace.project = options.project;
799
+ if (options.branch !== undefined)
800
+ trace.branch = options.branch;
801
+ if (llmCalls.length > 0)
802
+ trace.llm_calls = llmCalls;
803
+ if (options.provenance !== undefined)
804
+ trace.provenance = options.provenance;
805
+ return trace;
806
+ }
807
+ // packages/ts/model/src/prefix-hash.ts
808
+ import { createHash as createHash2 } from "node:crypto";
809
+ function canonicalJson(value) {
810
+ if (Array.isArray(value))
811
+ return `[${value.map(canonicalJson).join(",")}]`;
812
+ if (typeof value === "object" && value !== null) {
813
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`);
814
+ return `{${entries.join(",")}}`;
815
+ }
816
+ return JSON.stringify(value);
817
+ }
818
+ function prefixSha256(records, count) {
819
+ return createHash2("sha256").update(canonicalJson(records.slice(0, count))).digest("hex");
820
+ }
821
+ var K = new Uint32Array([
822
+ 1116352408,
823
+ 1899447441,
824
+ 3049323471,
825
+ 3921009573,
826
+ 961987163,
827
+ 1508970993,
828
+ 2453635748,
829
+ 2870763221,
830
+ 3624381080,
831
+ 310598401,
832
+ 607225278,
833
+ 1426881987,
834
+ 1925078388,
835
+ 2162078206,
836
+ 2614888103,
837
+ 3248222580,
838
+ 3835390401,
839
+ 4022224774,
840
+ 264347078,
841
+ 604807628,
842
+ 770255983,
843
+ 1249150122,
844
+ 1555081692,
845
+ 1996064986,
846
+ 2554220882,
847
+ 2821834349,
848
+ 2952996808,
849
+ 3210313671,
850
+ 3336571891,
851
+ 3584528711,
852
+ 113926993,
853
+ 338241895,
854
+ 666307205,
855
+ 773529912,
856
+ 1294757372,
857
+ 1396182291,
858
+ 1695183700,
859
+ 1986661051,
860
+ 2177026350,
861
+ 2456956037,
862
+ 2730485921,
863
+ 2820302411,
864
+ 3259730800,
865
+ 3345764771,
866
+ 3516065817,
867
+ 3600352804,
868
+ 4094571909,
869
+ 275423344,
870
+ 430227734,
871
+ 506948616,
872
+ 659060556,
873
+ 883997877,
874
+ 958139571,
875
+ 1322822218,
876
+ 1537002063,
877
+ 1747873779,
878
+ 1955562222,
879
+ 2024104815,
880
+ 2227730452,
881
+ 2361852424,
882
+ 2428436474,
883
+ 2756734187,
884
+ 3204031479,
885
+ 3329325298
886
+ ]);
887
+ var H0 = new Uint32Array([
888
+ 1779033703,
889
+ 3144134277,
890
+ 1013904242,
891
+ 2773480762,
892
+ 1359893119,
893
+ 2600822924,
894
+ 528734635,
895
+ 1541459225
896
+ ]);
897
+ var rotr = (x, n) => x >>> n | x << 32 - n;
898
+
899
+ class ResumableSha256 {
900
+ h = new Uint32Array(H0);
901
+ block = new Uint8Array(64);
902
+ pending = 0;
903
+ total = 0;
904
+ w = new Uint32Array(64);
905
+ update(data) {
906
+ let i = 0;
907
+ while (i < data.length) {
908
+ const take = Math.min(64 - this.pending, data.length - i);
909
+ this.block.set(data.subarray(i, i + take), this.pending);
910
+ this.pending += take;
911
+ i += take;
912
+ if (this.pending === 64) {
913
+ this.compress(this.block);
914
+ this.pending = 0;
915
+ }
916
+ }
917
+ this.total += data.length;
918
+ return this;
919
+ }
920
+ digest() {
921
+ const copy = this.clone();
922
+ const bits = BigInt(copy.total) * 8n;
923
+ const tail = new Uint8Array(copy.pending <= 55 ? 64 - copy.pending : 128 - copy.pending);
924
+ tail[0] = 128;
925
+ new DataView(tail.buffer).setBigUint64(tail.length - 8, bits);
926
+ copy.update(tail);
927
+ return Array.from(copy.h, (v) => v.toString(16).padStart(8, "0")).join("");
928
+ }
929
+ export() {
930
+ const h = Array.from(this.h, (v) => v.toString(16).padStart(8, "0")).join("");
931
+ const pending = Array.from(this.block.subarray(0, this.pending), (b) => b.toString(16).padStart(2, "0")).join("");
932
+ return `${h}:${this.total}:${pending}`;
933
+ }
934
+ static resume(state) {
935
+ const match = /^([0-9a-f]{64}):(\d+):((?:[0-9a-f]{2}){0,63})$/.exec(state);
936
+ if (!match)
937
+ throw new Error("invalid sha256 state");
938
+ const hash = new ResumableSha256;
939
+ for (let i = 0;i < 8; i++)
940
+ hash.h[i] = Number.parseInt(match[1].slice(i * 8, i * 8 + 8), 16);
941
+ hash.total = Number(match[2]);
942
+ const pending = match[3];
943
+ hash.pending = pending.length / 2;
944
+ for (let i = 0;i < hash.pending; i++) {
945
+ hash.block[i] = Number.parseInt(pending.slice(i * 2, i * 2 + 2), 16);
946
+ }
947
+ if (hash.total % 64 !== hash.pending)
948
+ throw new Error("invalid sha256 state");
949
+ return hash;
950
+ }
951
+ clone() {
952
+ const copy = new ResumableSha256;
953
+ copy.h.set(this.h);
954
+ copy.block.set(this.block);
955
+ copy.pending = this.pending;
956
+ copy.total = this.total;
957
+ return copy;
958
+ }
959
+ compress(block) {
960
+ const { w, h } = this;
961
+ const view = new DataView(block.buffer, block.byteOffset, 64);
962
+ for (let i = 0;i < 16; i++)
963
+ w[i] = view.getUint32(i * 4);
964
+ for (let i = 16;i < 64; i++) {
965
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
966
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
967
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
968
+ }
969
+ let [a, b, c, d, e, f, g, hh] = h;
970
+ for (let i = 0;i < 64; i++) {
971
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
972
+ const ch = e & f ^ ~e & g;
973
+ const t1 = hh + S1 + ch + K[i] + w[i] >>> 0;
974
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
975
+ const maj = a & b ^ a & c ^ b & c;
976
+ const t2 = S0 + maj >>> 0;
977
+ hh = g;
978
+ g = f;
979
+ f = e;
980
+ e = d + t1 >>> 0;
981
+ d = c;
982
+ c = b;
983
+ b = a;
984
+ a = t1 + t2 >>> 0;
985
+ }
986
+ h[0] = h[0] + a >>> 0;
987
+ h[1] = h[1] + b >>> 0;
988
+ h[2] = h[2] + c >>> 0;
989
+ h[3] = h[3] + d >>> 0;
990
+ h[4] = h[4] + e >>> 0;
991
+ h[5] = h[5] + f >>> 0;
992
+ h[6] = h[6] + g >>> 0;
993
+ h[7] = h[7] + hh >>> 0;
994
+ }
995
+ }
996
+ var encoder = new TextEncoder;
997
+
998
+ class PrefixHash {
999
+ hash;
1000
+ count;
1001
+ constructor(hash, count) {
1002
+ this.hash = hash;
1003
+ this.count = count;
1004
+ }
1005
+ static empty() {
1006
+ return new PrefixHash(new ResumableSha256, 0);
1007
+ }
1008
+ static of(records) {
1009
+ const hash = PrefixHash.empty();
1010
+ for (const record of records)
1011
+ hash.append(record);
1012
+ return hash;
1013
+ }
1014
+ static resume(state) {
1015
+ const count = state.slice(0, Math.max(state.indexOf(":"), 0));
1016
+ if (!/^\d+$/.test(count))
1017
+ throw new Error("invalid prefix hash state");
1018
+ return new PrefixHash(ResumableSha256.resume(state.slice(count.length + 1)), Number(count));
1019
+ }
1020
+ get records() {
1021
+ return this.count;
1022
+ }
1023
+ append(record) {
1024
+ this.hash.update(encoder.encode(`${this.count === 0 ? "[" : ","}${canonicalJson(record)}`));
1025
+ this.count += 1;
1026
+ }
1027
+ digest() {
1028
+ const copy = ResumableSha256.resume(this.hash.export());
1029
+ return copy.update(encoder.encode(this.count === 0 ? "[]" : "]")).digest();
1030
+ }
1031
+ export() {
1032
+ return `${this.count}:${this.hash.export()}`;
1033
+ }
1034
+ }
1035
+ // packages/ts/model/src/schemas/otlp.ts
1036
+ var OTLP_TRACE_SCHEMA = "seshi/trace-otlp/1";
1037
+ // packages/ts/model/src/schemas/renders.ts
1038
+ var RENDER_FORMATS = ["seshi", "letta", "otlp", "atif"];
1039
+ function isRenderFormat(value) {
1040
+ return typeof value === "string" && RENDER_FORMATS.includes(value);
1041
+ }
1042
+ var LETTA_TRACE_SCHEMA = "sessionstorage/trace/1";
1043
+ // packages/ts/model/src/generated/change.ts
1044
+ var SCHEMA_ID3 = "seshi/change/1";
1045
+ var JSON_SCHEMA3 = {
1046
+ $id: "change.schema.json",
1047
+ type: "object",
1048
+ properties: {
1049
+ schema: { const: "seshi/change/1" },
1050
+ kind: { enum: ["published", "tombstone", "visibility_changed"] },
1051
+ at: { $ref: "common.schema.json#/$defs/Timestamp" },
1052
+ owner: { type: "string", minLength: 1 },
1053
+ archive_id: { $ref: "common.schema.json#/$defs/Sha256" },
1054
+ session_id: { type: "string" },
1055
+ content_hash: { oneOf: [{ $ref: "common.schema.json#/$defs/Sha256" }, { type: "null" }] },
1056
+ continuation: { $ref: "common.schema.json#/$defs/Continuation" },
1057
+ replace: { const: true },
1058
+ writer: { $ref: "common.schema.json#/$defs/Writer" },
1059
+ owner_basis: { $ref: "common.schema.json#/$defs/OwnerBasis" },
1060
+ reason: { enum: ["deleted", "retracted", "redacted"] },
1061
+ visibility: { $ref: "common.schema.json#/$defs/Visibility" }
1062
+ },
1063
+ required: ["schema", "kind", "at", "owner", "archive_id", "session_id", "content_hash", "writer"],
1064
+ additionalProperties: false
1065
+ };
1066
+
1067
+ // packages/ts/model/src/generated/metadata.ts
1068
+ var SCHEMA_ID4 = "seshi/metadata/1";
1069
+ var JSON_SCHEMA4 = {
1070
+ $id: "metadata.schema.json",
1071
+ type: "object",
1072
+ properties: {
1073
+ schema: { const: "seshi/metadata/1" },
1074
+ owner: { type: "string", minLength: 1 },
1075
+ archive_id: { $ref: "common.schema.json#/$defs/Sha256" },
1076
+ session_id: { type: "string" },
1077
+ agent: { type: "string" },
1078
+ source: { type: "string" },
1079
+ project: { type: "string" },
1080
+ branch: { type: "string" },
1081
+ parent_session_id: { type: "string" },
1082
+ status: { enum: ["stored", "redacted"] },
1083
+ head: { $ref: "common.schema.json#/$defs/Sha256" },
1084
+ traces: { type: "array", items: { $ref: "#/$defs/SessionTraceRef" } },
1085
+ normalized: { $ref: "#/$defs/NormalizedState" },
1086
+ dropped_prefix: { $ref: "#/$defs/DroppedPrefix" },
1087
+ withheld_calls: {
1088
+ type: "object",
1089
+ additionalProperties: { enum: ["sensitive-file", "secret-output"] }
1090
+ },
1091
+ applied: { type: "array", items: { $ref: "#/$defs/AppliedEnvelope" } },
1092
+ writer: { $ref: "common.schema.json#/$defs/Writer" },
1093
+ owner_basis: { $ref: "common.schema.json#/$defs/OwnerBasis" },
1094
+ visibility: { $ref: "common.schema.json#/$defs/Visibility" },
1095
+ claims: { $ref: "common.schema.json#/$defs/Claims" },
1096
+ redaction: { $ref: "common.schema.json#/$defs/RedactionSummary" },
1097
+ provenance: { $ref: "common.schema.json#/$defs/Provenance" },
1098
+ origin_agent: { type: "string" },
1099
+ native_session_id: { type: "string" },
1100
+ normalizer: { $ref: "common.schema.json#/$defs/Normalizer" },
1101
+ retract_hash: { $ref: "common.schema.json#/$defs/Sha256" },
1102
+ active_at: { $ref: "common.schema.json#/$defs/Timestamp" },
1103
+ created_at: { $ref: "common.schema.json#/$defs/Timestamp" },
1104
+ updated_at: { $ref: "common.schema.json#/$defs/Timestamp" }
1105
+ },
1106
+ required: [
1107
+ "schema",
1108
+ "owner",
1109
+ "archive_id",
1110
+ "session_id",
1111
+ "agent",
1112
+ "status",
1113
+ "traces",
1114
+ "writer",
1115
+ "owner_basis",
1116
+ "visibility",
1117
+ "created_at",
1118
+ "updated_at"
1119
+ ],
1120
+ additionalProperties: false,
1121
+ $defs: {
1122
+ SessionTraceRef: {
1123
+ type: "object",
1124
+ properties: {
1125
+ content_hash: { $ref: "common.schema.json#/$defs/Sha256" },
1126
+ created_at: { $ref: "common.schema.json#/$defs/Timestamp" },
1127
+ records: { type: "integer", minimum: 0 },
1128
+ continuation: { $ref: "common.schema.json#/$defs/Continuation" },
1129
+ rule_set: { $ref: "common.schema.json#/$defs/Sha256" }
1130
+ },
1131
+ required: ["content_hash", "created_at", "records"],
1132
+ additionalProperties: false
1133
+ },
1134
+ NormalizedState: {
1135
+ type: "object",
1136
+ properties: {
1137
+ bytes: { type: "integer", minimum: 0 },
1138
+ records: { type: "integer", minimum: 0 },
1139
+ prefix_sha256: { $ref: "common.schema.json#/$defs/Sha256" },
1140
+ hash_state: { type: "string" }
1141
+ },
1142
+ required: ["bytes", "records", "prefix_sha256", "hash_state"],
1143
+ additionalProperties: false
1144
+ },
1145
+ DroppedPrefix: {
1146
+ type: "object",
1147
+ properties: {
1148
+ bytes: { type: "integer", minimum: 0 },
1149
+ records: { type: "integer", minimum: 0 },
1150
+ prefix_sha256: { $ref: "common.schema.json#/$defs/Sha256" }
1151
+ },
1152
+ required: ["bytes", "records", "prefix_sha256"],
1153
+ additionalProperties: false
1154
+ },
1155
+ AppliedEnvelope: {
1156
+ type: "object",
1157
+ properties: {
1158
+ idempotency_key: { type: "string", minLength: 1, maxLength: 2048 },
1159
+ at: { $ref: "common.schema.json#/$defs/Timestamp" },
1160
+ status: { enum: ["stored", "duplicate", "unchanged", "dropped"] },
1161
+ content_hash: { $ref: "common.schema.json#/$defs/Sha256" },
1162
+ records: { type: "integer", minimum: 0 },
1163
+ events: { type: "integer", minimum: 0 },
1164
+ records_total: { type: "integer", minimum: 0 },
1165
+ prefix_sha256: { $ref: "common.schema.json#/$defs/Sha256" },
1166
+ bytes_total: { type: "integer", minimum: 0 }
1167
+ },
1168
+ required: [
1169
+ "idempotency_key",
1170
+ "at",
1171
+ "status",
1172
+ "records_total",
1173
+ "prefix_sha256",
1174
+ "bytes_total"
1175
+ ],
1176
+ additionalProperties: false
1177
+ }
1178
+ }
1179
+ };
1180
+
1181
+ // packages/ts/model/src/schemas/store.ts
1182
+ var METADATA_SCHEMA = SCHEMA_ID4;
1183
+ var CHANGE_SCHEMA = SCHEMA_ID3;
1184
+ var LAYOUT_SCHEMA = "seshi/layout/2";
1185
+ var LAYOUT_SCHEMA_V1 = "seshi/layout/1";
1186
+ var LAYOUT_SCHEMAS = [LAYOUT_SCHEMA_V1, LAYOUT_SCHEMA];
1187
+ var LEGACY_LAYOUT_SCHEMA = "sessionstorage/layout/1";
1188
+ var UPLOAD_SOURCE = "upload";
1189
+ function localWriter(owner, kind = "local") {
1190
+ return { kind, principal: owner, source_id: UPLOAD_SOURCE };
1191
+ }
1192
+ // packages/ts/model/src/generated/common.ts
1193
+ var JSON_SCHEMA5 = {
1194
+ $id: "common.schema.json",
1195
+ $defs: {
1196
+ Sha256: { type: "string", pattern: "^[0-9a-f]{64}$" },
1197
+ Timestamp: { type: "string", format: "date-time" },
1198
+ SourceKind: {
1199
+ type: "string",
1200
+ enum: ["upload", "hook", "otlp", "datadog", "s3", "cursor-cloud"]
1201
+ },
1202
+ SourceId: { type: "string", pattern: "^[a-z0-9]+(-[a-z0-9]+)*$" },
1203
+ CallerKind: {
1204
+ type: "string",
1205
+ enum: ["person", "device", "service", "admin", "static", "local"]
1206
+ },
1207
+ Writer: {
1208
+ type: "object",
1209
+ properties: {
1210
+ kind: { $ref: "#/$defs/CallerKind" },
1211
+ principal: { type: "string", minLength: 1 },
1212
+ credential_id: { type: "string", minLength: 1 },
1213
+ source_id: { $ref: "#/$defs/SourceId" }
1214
+ },
1215
+ required: ["kind", "principal", "source_id"],
1216
+ additionalProperties: false
1217
+ },
1218
+ OwnerBasis: { type: "string", enum: ["verified", "claimed", "service"] },
1219
+ LogEncoding: { enum: ["jsonl", "json"] },
1220
+ Visibility: { type: "string", enum: ["org", "owner"] },
1221
+ Claims: {
1222
+ type: "object",
1223
+ properties: {
1224
+ email: { type: "string" },
1225
+ name: { type: "string" },
1226
+ username: { type: "string" },
1227
+ git_email: { type: "string" },
1228
+ git_name: { type: "string" },
1229
+ account_ids: { type: "object", additionalProperties: { type: "string" } }
1230
+ },
1231
+ additionalProperties: false
1232
+ },
1233
+ SourceLocation: {
1234
+ type: "object",
1235
+ properties: {
1236
+ object_key: { type: "string" },
1237
+ etag: { type: "string" },
1238
+ cursor: { type: "string" }
1239
+ },
1240
+ additionalProperties: false
1241
+ },
1242
+ Provenance: {
1243
+ type: "object",
1244
+ properties: {
1245
+ source: { $ref: "#/$defs/SourceKind" },
1246
+ source_id: { $ref: "#/$defs/SourceId" },
1247
+ format: { type: "string", minLength: 1 },
1248
+ location: { $ref: "#/$defs/SourceLocation" }
1249
+ },
1250
+ required: ["source", "source_id"],
1251
+ additionalProperties: false
1252
+ },
1253
+ Normalizer: {
1254
+ type: "object",
1255
+ properties: {
1256
+ name: { type: "string", minLength: 1 },
1257
+ version: { type: "string", minLength: 1 },
1258
+ format_version: { type: "string", minLength: 1 }
1259
+ },
1260
+ required: ["name", "version"],
1261
+ additionalProperties: false
1262
+ },
1263
+ Continuation: {
1264
+ type: "object",
1265
+ properties: {
1266
+ from_record: { type: "integer", minimum: 0 },
1267
+ prefix_sha256: { $ref: "#/$defs/Sha256" }
1268
+ },
1269
+ required: ["from_record", "prefix_sha256"],
1270
+ additionalProperties: false
1271
+ },
1272
+ RedactionSummary: {
1273
+ type: "object",
1274
+ properties: {
1275
+ rule_set: { $ref: "#/$defs/Sha256" },
1276
+ counts: { type: "object", additionalProperties: { type: "integer", minimum: 0 } }
1277
+ },
1278
+ required: ["rule_set", "counts"],
1279
+ additionalProperties: false
1280
+ }
1281
+ }
1282
+ };
1283
+
1284
+ // packages/ts/model/src/generated/layout.ts
1285
+ var JSON_SCHEMA6 = {
1286
+ $id: "layout.schema.json",
1287
+ type: "object",
1288
+ properties: {
1289
+ schema: { enum: ["seshi/layout/1", "seshi/layout/2"] },
1290
+ trace_schema: { const: "seshi/trace/1" },
1291
+ deployment_id: { type: "string", minLength: 1 },
1292
+ org: { type: "string", minLength: 1 },
1293
+ created_at: { $ref: "common.schema.json#/$defs/Timestamp" },
1294
+ created_by: { type: "string" },
1295
+ mode: { enum: ["server", "serverless"] },
1296
+ min_version: { type: "string", pattern: "^\\d+\\.\\d+\\.\\d+$" },
1297
+ mode_changed_at: { $ref: "common.schema.json#/$defs/Timestamp" },
1298
+ mode_changed_by: { type: "string" }
1299
+ },
1300
+ required: ["schema", "trace_schema", "deployment_id", "created_at", "created_by"],
1301
+ additionalProperties: false
1302
+ };
1303
+
1304
+ // packages/ts/model/src/schemas/validate.ts
1305
+ var KNOWN = new Set([
1306
+ "$id",
1307
+ "$ref",
1308
+ "$defs",
1309
+ "type",
1310
+ "const",
1311
+ "enum",
1312
+ "oneOf",
1313
+ "anyOf",
1314
+ "items",
1315
+ "properties",
1316
+ "required",
1317
+ "additionalProperties",
1318
+ "pattern",
1319
+ "format",
1320
+ "minLength",
1321
+ "maxLength",
1322
+ "minimum",
1323
+ "maximum",
1324
+ "minItems",
1325
+ "maxItems"
1326
+ ]);
1327
+ var FILES = new Map([JSON_SCHEMA3, JSON_SCHEMA5, JSON_SCHEMA, JSON_SCHEMA6, JSON_SCHEMA4, JSON_SCHEMA2].map((s) => [s.$id, s]));
1328
+ var MAX_PROBLEMS = 20;
1329
+ var DATE_TIME = /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
1330
+ function typeOf(value) {
1331
+ if (value === null)
1332
+ return "null";
1333
+ if (Array.isArray(value))
1334
+ return "array";
1335
+ return typeof value;
1336
+ }
1337
+ function hasType(value, type) {
1338
+ switch (type) {
1339
+ case "integer":
1340
+ return typeof value === "number" && Number.isInteger(value);
1341
+ case "number":
1342
+ return typeof value === "number" && Number.isFinite(value);
1343
+ case "object":
1344
+ return typeOf(value) === "object";
1345
+ default:
1346
+ return typeOf(value) === type;
1347
+ }
1348
+ }
1349
+ function same(a, b) {
1350
+ if (a === b)
1351
+ return true;
1352
+ if (typeOf(a) !== typeOf(b) || typeof a !== "object" || a === null)
1353
+ return false;
1354
+ if (Array.isArray(a)) {
1355
+ const other = b;
1356
+ return a.length === other.length && a.every((v, i) => same(v, other[i]));
1357
+ }
1358
+ const ka = Object.keys(a);
1359
+ const kb = Object.keys(b);
1360
+ return ka.length === kb.length && ka.every((k) => same(a[k], b[k]));
1361
+ }
1362
+ function segment(key) {
1363
+ return `/${String(key).replaceAll("~", "~0").replaceAll("/", "~1")}`;
1364
+ }
1365
+
1366
+ class Checker {
1367
+ problems = [];
1368
+ resolve(ref, file) {
1369
+ const match = /^([a-z-]+\.schema\.json)?#\/\$defs\/([A-Za-z0-9]+)$/.exec(ref);
1370
+ const target = match?.[1] ?? file;
1371
+ const schema = match ? FILES.get(target)?.$defs?.[match[2]] : undefined;
1372
+ if (!schema)
1373
+ throw new Error(`${file}: unsupported or dangling $ref ${ref}`);
1374
+ return { schema, file: target };
1375
+ }
1376
+ add(path, message) {
1377
+ if (this.problems.length < MAX_PROBLEMS)
1378
+ this.problems.push(`${path || "/"}: ${message}`);
1379
+ }
1380
+ matches(value, schema, file) {
1381
+ const probe = new Checker;
1382
+ probe.check(value, schema, file, "");
1383
+ return probe.problems.length === 0;
1384
+ }
1385
+ check(value, schema, file, path) {
1386
+ for (const k of Object.keys(schema)) {
1387
+ if (!KNOWN.has(k))
1388
+ throw new Error(`${file}: unsupported keyword ${k}`);
1389
+ }
1390
+ if (schema.$ref !== undefined) {
1391
+ const { schema: target, file: in_ } = this.resolve(schema.$ref, file);
1392
+ this.check(value, target, in_, path);
1393
+ }
1394
+ if (schema.const !== undefined && !same(value, schema.const)) {
1395
+ this.add(path, `must be ${JSON.stringify(schema.const)}`);
1396
+ return;
1397
+ }
1398
+ if (schema.enum !== undefined && !schema.enum.some((v) => same(value, v))) {
1399
+ this.add(path, `must be one of ${schema.enum.map((v) => JSON.stringify(v)).join(", ")}`);
1400
+ return;
1401
+ }
1402
+ if (schema.oneOf !== undefined) {
1403
+ const n = schema.oneOf.filter((s) => this.matches(value, s, file)).length;
1404
+ if (n !== 1) {
1405
+ this.add(path, n === 0 ? "matches none of its alternatives" : "matches more than one");
1406
+ return;
1407
+ }
1408
+ }
1409
+ if (schema.anyOf !== undefined && !schema.anyOf.some((s) => this.matches(value, s, file))) {
1410
+ this.add(path, "matches none of its alternatives");
1411
+ return;
1412
+ }
1413
+ if (schema.type !== undefined) {
1414
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
1415
+ if (!types.some((t) => hasType(value, t))) {
1416
+ this.add(path, `must be ${types.join(" or ")}, not ${typeOf(value)}`);
1417
+ return;
1418
+ }
1419
+ }
1420
+ if (typeof value === "string")
1421
+ this.string(value, schema, path);
1422
+ if (typeof value === "number")
1423
+ this.number(value, schema, path);
1424
+ if (Array.isArray(value))
1425
+ this.array(value, schema, file, path);
1426
+ else if (typeOf(value) === "object") {
1427
+ this.object(value, schema, file, path);
1428
+ }
1429
+ }
1430
+ string(value, schema, path) {
1431
+ const length = [...value].length;
1432
+ if (schema.minLength !== undefined && length < schema.minLength) {
1433
+ this.add(path, `must be at least ${schema.minLength} characters`);
1434
+ }
1435
+ if (schema.maxLength !== undefined && length > schema.maxLength) {
1436
+ this.add(path, `must be at most ${schema.maxLength} characters`);
1437
+ }
1438
+ if (schema.pattern !== undefined && !new RegExp(schema.pattern, "u").test(value)) {
1439
+ this.add(path, `must match ${schema.pattern}`);
1440
+ }
1441
+ if (schema.format === "date-time" && (!DATE_TIME.test(value) || Number.isNaN(Date.parse(value)))) {
1442
+ this.add(path, "must be an RFC 3339 date-time");
1443
+ }
1444
+ }
1445
+ number(value, schema, path) {
1446
+ if (schema.minimum !== undefined && value < schema.minimum) {
1447
+ this.add(path, `must be >= ${schema.minimum}`);
1448
+ }
1449
+ if (schema.maximum !== undefined && value > schema.maximum) {
1450
+ this.add(path, `must be <= ${schema.maximum}`);
1451
+ }
1452
+ }
1453
+ array(value, schema, file, path) {
1454
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
1455
+ this.add(path, `must have at least ${schema.minItems} items`);
1456
+ }
1457
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {
1458
+ this.add(path, `must have at most ${schema.maxItems} items`);
1459
+ }
1460
+ if (schema.items) {
1461
+ const items = schema.items;
1462
+ value.forEach((item, i) => {
1463
+ this.check(item, items, file, path + segment(i));
1464
+ });
1465
+ }
1466
+ }
1467
+ object(value, schema, file, path) {
1468
+ for (const name of schema.required ?? []) {
1469
+ if (!(name in value))
1470
+ this.add(path, `is missing ${name}`);
1471
+ }
1472
+ const props = schema.properties ?? {};
1473
+ for (const [name, item] of Object.entries(value)) {
1474
+ const prop = props[name];
1475
+ if (prop)
1476
+ this.check(item, prop, file, path + segment(name));
1477
+ else if (schema.additionalProperties === false) {
1478
+ this.add(path + segment(name), "is not allowed");
1479
+ } else if (typeof schema.additionalProperties === "object") {
1480
+ this.check(item, schema.additionalProperties, file, path + segment(name));
1481
+ }
1482
+ }
1483
+ }
1484
+ }
1485
+ function schemaProblems(file, value) {
1486
+ const schema = FILES.get(file);
1487
+ if (!schema)
1488
+ throw new Error(`no schema ${file}`);
1489
+ const checker = new Checker;
1490
+ checker.check(value, schema, file, "");
1491
+ return checker.problems;
1492
+ }
1493
+ // packages/ts/model/src/search.ts
1494
+ var SEARCH_SORTS = ["relevance", "recent"];
1495
+ // packages/ts/model/package.json
1496
+ var package_default = {
1497
+ name: "@dosu/seshi-model",
1498
+ version: "0.11.0",
1499
+ private: true,
1500
+ description: "Layer 0: the trace, stored-object, session API and format adapter types; canonical text and hashing; trajectory-v1 validation. Its version is the release's (what traces record as their normalizer and /healthz reports).",
1501
+ type: "module",
1502
+ exports: {
1503
+ ".": {
1504
+ bun: "./src/index.ts"
1505
+ }
1506
+ },
1507
+ dependencies: {
1508
+ "@letta-ai/trajectory": "^0.3.0"
1509
+ }
1510
+ };
1511
+
1512
+ // packages/ts/model/src/version.ts
1513
+ var VERSION = package_default.version;
1514
+ export {
1515
+ CHANGE_SCHEMA,
1516
+ EMPTY_PREFIX_SHA256,
1517
+ SCHEMA_ID as ENVELOPE_SCHEMA,
1518
+ Forbidden,
1519
+ IngestRejected,
1520
+ LAYOUT_SCHEMA,
1521
+ LAYOUT_SCHEMAS,
1522
+ LAYOUT_SCHEMA_V1,
1523
+ LEGACY_LAYOUT_SCHEMA,
1524
+ LETTA_TRACE_SCHEMA,
1525
+ MAX_IDEMPOTENCY_KEY_LENGTH,
1526
+ METADATA_SCHEMA,
1527
+ OTLP_TRACE_SCHEMA,
1528
+ OffsetMismatch,
1529
+ PrefixHash,
1530
+ RENDER_FORMATS,
1531
+ ResumableSha256,
1532
+ SEARCH_SORTS,
1533
+ SessionConflict,
1534
+ SessionRejected,
1535
+ StoreError,
1536
+ TRACE_SCHEMA,
1537
+ TrajectoryError,
1538
+ UPLOAD_SOURCE,
1539
+ Unauthorized,
1540
+ VERSION,
1541
+ canonicalJson,
1542
+ canonicalText,
1543
+ isRenderFormat,
1544
+ isScopeCoordinate,
1545
+ isStub,
1546
+ localWriter,
1547
+ parseTrace,
1548
+ prefixSha256,
1549
+ schemaProblems,
1550
+ stripNul,
1551
+ validateRecords,
1552
+ validateTraceRecords
1553
+ };