@theokit/agents 13.0.0-next.0 → 13.0.0-next.10

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/session.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-Z4QWC7IK.js";
7
7
 
8
8
  // src/session/session-lifecycle.ts
9
- import { readFileSync as readFileSync3, readdirSync, rmSync, statSync } from "fs";
9
+ import { closeSync, openSync, readFileSync as readFileSync3, readdirSync, readSync, rmSync, statSync } from "fs";
10
10
  import { join as join3 } from "path";
11
11
  import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
12
12
  import { classifySessionArtifact, forkTranscript, loadJsonl, sessionHasWriter, transcriptPath, transcriptRoot as transcriptRoot3 } from "@theokit/sdk/persistence";
@@ -133,12 +133,22 @@ var SessionInUseError = class extends TheokitAgentError2 {
133
133
  }
134
134
  sessionId;
135
135
  reason;
136
- registryRemoved;
136
+ registryOutcome;
137
137
  name = "SessionInUseError";
138
- constructor(sessionId, reason, registryRemoved = false) {
139
- super(`session "${sessionId}" is protected (${reason}). Deleting it would discard state something is still using. Stop the run, or pass { force: true } to delete anyway.` + (registryRemoved ? ` The registry entry was already removed before this was noticed \u2014 do not retry that half, only the transcript.` : "")), this.sessionId = sessionId, this.reason = reason, this.registryRemoved = registryRemoved;
138
+ constructor(sessionId, reason, registryOutcome) {
139
+ super(`session "${sessionId}" is protected (${reason}). Deleting it would discard state something is still using. Stop the run, or pass { force: true } to delete anyway.` + registryNote(registryOutcome)), this.sessionId = sessionId, this.reason = reason, this.registryOutcome = registryOutcome;
140
140
  }
141
141
  };
142
+ function registryNote(outcome) {
143
+ if (outcome === "removed") {
144
+ return ` The registry entry was already removed before this was noticed \u2014 do not retry that half, only the transcript.`;
145
+ }
146
+ if (outcome === "unconfirmed") {
147
+ return ` The registry removal was already attempted and reported nothing, so whether the entry is gone is unknown \u2014 verify it before retrying.`;
148
+ }
149
+ return "";
150
+ }
151
+ __name(registryNote, "registryNote");
142
152
  function listSessions(cwd, root = transcriptRoot3()) {
143
153
  const dir = projectDirFor(cwd, root);
144
154
  let entries;
@@ -161,8 +171,10 @@ function listSessions(cwd, root = transcriptRoot3()) {
161
171
  }
162
172
  const kind = classifySessionArtifact(entry, isDirectory);
163
173
  if (kind !== "transcript") continue;
174
+ const id = sessionIdOf(path);
164
175
  found.push({
165
- id: entry.replace(/\.jsonl$/, ""),
176
+ id,
177
+ idSource: id === void 0 ? "unavailable" : "transcript",
166
178
  transcript: path,
167
179
  modifiedAt
168
180
  });
@@ -170,21 +182,48 @@ function listSessions(cwd, root = transcriptRoot3()) {
170
182
  return found.sort((a, b) => b.modifiedAt.getTime() - a.modifiedAt.getTime());
171
183
  }
172
184
  __name(listSessions, "listSessions");
173
- function protectedTranscripts(cwd, root = transcriptRoot3()) {
185
+ function sessionIdOf(path) {
186
+ let fd;
187
+ try {
188
+ fd = openSync(path, "r");
189
+ const buffer = Buffer.alloc(FIRST_RECORD_BYTES);
190
+ const read = readSync(fd, buffer, 0, FIRST_RECORD_BYTES, 0);
191
+ const newline = buffer.indexOf(10);
192
+ const end = newline === -1 || newline > read ? read : newline;
193
+ const first = JSON.parse(buffer.toString("utf8", 0, end));
194
+ if (typeof first === "object" && first !== null) {
195
+ const id = first.sessionId;
196
+ if (typeof id === "string" && id.length > 0) return id;
197
+ }
198
+ } catch {
199
+ } finally {
200
+ if (fd !== void 0) closeSync(fd);
201
+ }
202
+ return void 0;
203
+ }
204
+ __name(sessionIdOf, "sessionIdOf");
205
+ var FIRST_RECORD_BYTES = 64 * 1024;
206
+ function protectedTranscriptPaths(cwd, root = transcriptRoot3()) {
174
207
  const protectedBy = /* @__PURE__ */ new Map();
175
208
  const sessions = listSessions(cwd, root);
176
209
  const pointer = readPointer(cwd, root);
177
- if (pointer !== void 0) protectedBy.set(pointer, "resumable session pointer");
178
- if (sessions.length > 0 && !protectedBy.has(sessions[0].id)) {
179
- protectedBy.set(sessions[0].id, "most recent session");
210
+ if (pointer !== void 0) {
211
+ protectedBy.set(transcriptPath(root, cwd, pointer), "resumable session pointer");
212
+ }
213
+ if (sessions.length > 0 && !protectedBy.has(sessions[0].transcript)) {
214
+ protectedBy.set(sessions[0].transcript, "most recent session");
180
215
  }
181
216
  for (const session of sessions) {
182
217
  const hasWriter = sessionHasWriter(session.transcript);
183
- if (hasWriter) protectedBy.set(session.id, "active writer lease");
218
+ if (hasWriter) protectedBy.set(session.transcript, "active writer lease");
184
219
  }
185
220
  return protectedBy;
186
221
  }
187
- __name(protectedTranscripts, "protectedTranscripts");
222
+ __name(protectedTranscriptPaths, "protectedTranscriptPaths");
223
+ function transcriptOf(id, cwd, root = transcriptRoot3()) {
224
+ return transcriptPath(root, cwd, id);
225
+ }
226
+ __name(transcriptOf, "transcriptOf");
188
227
  function readPointer(cwd, root) {
189
228
  try {
190
229
  const id = readFileSync3(sessionPointerPath(cwd, root), "utf8").trim();
@@ -197,27 +236,29 @@ __name(readPointer, "readPointer");
197
236
  async function deleteSession(sessionId, options) {
198
237
  const root = options.root ?? transcriptRoot3();
199
238
  if (options.force !== true) {
200
- const reason = protectedTranscripts(options.cwd, root).get(sessionId);
239
+ const reason = protectedTranscriptPaths(options.cwd, root).get(transcriptOf(sessionId, options.cwd, root));
201
240
  if (reason !== void 0) throw new SessionInUseError(sessionId, reason);
202
241
  }
203
- let registryRemoved = false;
242
+ let registryOutcome = "not-attempted";
204
243
  let registryError;
205
244
  if (options.removeFromRegistry !== void 0) {
206
245
  try {
207
246
  const outcome = await awaitRegistryRemoval(options.removeFromRegistry(sessionId), sessionId, options.registryTimeoutMs);
208
- registryRemoved = outcome !== false;
247
+ if (outcome === false) registryOutcome = "nothing-to-remove";
248
+ else if (outcome === void 0) registryOutcome = "unconfirmed";
249
+ else registryOutcome = "removed";
209
250
  } catch (error) {
210
251
  return {
211
- registryRemoved: false,
252
+ registryOutcome: "failed",
212
253
  transcriptRemoved: false,
213
254
  registryError: error
214
255
  };
215
256
  }
216
257
  }
217
258
  if (options.force !== true) {
218
- const nowProtected = protectedTranscripts(options.cwd, root).get(sessionId);
259
+ const nowProtected = protectedTranscriptPaths(options.cwd, root).get(transcriptOf(sessionId, options.cwd, root));
219
260
  if (nowProtected !== void 0) {
220
- throw new SessionInUseError(sessionId, nowProtected, registryRemoved);
261
+ throw new SessionInUseError(sessionId, nowProtected, registryOutcome);
221
262
  }
222
263
  }
223
264
  let transcriptRemoved = false;
@@ -227,7 +268,7 @@ async function deleteSession(sessionId, options) {
227
268
  } catch {
228
269
  }
229
270
  return {
230
- registryRemoved,
271
+ registryOutcome,
231
272
  transcriptRemoved,
232
273
  registryError
233
274
  };
@@ -251,7 +292,7 @@ function forkBeforeUserTurn(srcId, newId, nth, options) {
251
292
  forkTranscript(src, dst, {
252
293
  beforeRecordIndex: selected.index,
253
294
  liveSessionPaths: [
254
- ...protectedTranscripts(options.cwd, root).keys()
295
+ ...protectedTranscriptPaths(options.cwd, root).keys()
255
296
  ].map((id) => transcriptPath(root, options.cwd, id))
256
297
  });
257
298
  return {
@@ -297,7 +338,7 @@ __name(reachableUserTurns, "reachableUserTurns");
297
338
  // src/session/gc/transcript-gc.ts
298
339
  import { rmSync as rmSync2 } from "fs";
299
340
  import { TheokitAgentError as TheokitAgentError3 } from "@theokit/sdk/errors";
300
- import { transcriptPath as transcriptPath2, transcriptRoot as transcriptRoot4 } from "@theokit/sdk/persistence";
341
+ import { transcriptRoot as transcriptRoot4 } from "@theokit/sdk/persistence";
301
342
  var FLOOR = {
302
343
  keepLast: 1,
303
344
  maxAgeDays: 1
@@ -327,7 +368,7 @@ var GCFloorError = class extends TheokitAgentError3 {
327
368
  super(`transcript GC: \`${field}\` must be at least ${String(FLOOR[field])}, received ${String(received)}. This is refused rather than clamped: a policy silently replaced by a different one is a policy nobody reviewed.`), this.field = field, this.received = received;
328
369
  }
329
370
  };
330
- function resolveProtection(builtin, provider) {
371
+ function resolveProtection(builtin, provider, cwd, root) {
331
372
  if (provider === void 0) return builtin;
332
373
  let extra;
333
374
  try {
@@ -335,8 +376,9 @@ function resolveProtection(builtin, provider) {
335
376
  } catch (cause) {
336
377
  throw new GCProtectionUnavailableError(cause);
337
378
  }
338
- const union = new Map(extra);
339
- for (const [id, reason] of builtin) union.set(id, reason);
379
+ const union = /* @__PURE__ */ new Map();
380
+ for (const [id, reason] of extra) union.set(transcriptOf(id, cwd, root), reason);
381
+ for (const [path, reason] of builtin) union.set(path, reason);
340
382
  return union;
341
383
  }
342
384
  __name(resolveProtection, "resolveProtection");
@@ -351,11 +393,11 @@ function planTranscriptGC(options) {
351
393
  const now = options.now ?? Date.now();
352
394
  const cutoff = now - options.maxAgeDays * 864e5;
353
395
  const sessions = listSessions(options.cwd, root);
354
- const protectedBy = resolveProtection(protectedTranscripts(options.cwd, root), options.protectedIds);
396
+ const protectedBy = resolveProtection(protectedTranscriptPaths(options.cwd, root), options.protectedIds, options.cwd, root);
355
397
  const candidates = [];
356
398
  const kept = [];
357
399
  for (const [index, session] of sessions.entries()) {
358
- const protection = protectedBy.get(session.id);
400
+ const protection = protectedBy.get(session.transcript);
359
401
  if (protection !== void 0) {
360
402
  kept.push({
361
403
  id: session.id,
@@ -399,33 +441,62 @@ function planTranscriptGC(options) {
399
441
  };
400
442
  }
401
443
  __name(planTranscriptGC, "planTranscriptGC");
444
+ async function releaseFromRegistry(candidate, options) {
445
+ if (candidate.id === void 0) {
446
+ return {
447
+ note: {
448
+ id: void 0,
449
+ message: UNNAMEABLE_COLLECTION
450
+ },
451
+ unlink: true
452
+ };
453
+ }
454
+ if (options.removeFromRegistry === void 0) return {
455
+ unlink: true
456
+ };
457
+ try {
458
+ await awaitRegistryRemoval(options.removeFromRegistry(candidate.id), candidate.id, options.registryTimeoutMs);
459
+ return {
460
+ unlink: true
461
+ };
462
+ } catch (error) {
463
+ return {
464
+ note: {
465
+ id: candidate.id,
466
+ message: `registry removal failed, transcript kept: ${error.message}`
467
+ },
468
+ unlink: false
469
+ };
470
+ }
471
+ }
472
+ __name(releaseFromRegistry, "releaseFromRegistry");
473
+ var UNNAMEABLE_COLLECTION = "transcript collected without a registry removal: its session id could not be read, and a fabricated one would name no session";
474
+ function recordRemoval(candidate, removed, orphaned) {
475
+ if (candidate.id === void 0) orphaned.push(candidate.transcript);
476
+ else removed.push(candidate.id);
477
+ }
478
+ __name(recordRemoval, "recordRemoval");
402
479
  async function runTranscriptGC(plan, options) {
403
480
  const removed = [];
481
+ const orphaned = [];
404
482
  const errors = [];
405
- const protectedNow = options.apply ? resolveProtection(protectedTranscripts(plan.cwd, plan.root), options.protectedIds) : /* @__PURE__ */ new Map();
483
+ const protectedNow = options.apply ? resolveProtection(protectedTranscriptPaths(plan.cwd, plan.root), options.protectedIds, plan.cwd, plan.root) : /* @__PURE__ */ new Map();
406
484
  for (const candidate of plan.candidates) {
407
- if (protectedNow.has(candidate.id)) continue;
485
+ if (protectedNow.has(candidate.transcript)) continue;
408
486
  if (!options.apply) {
409
- removed.push(candidate.id);
487
+ if (candidate.id === void 0) orphaned.push(candidate.transcript);
488
+ else removed.push(candidate.id);
410
489
  continue;
411
490
  }
412
- if (options.removeFromRegistry !== void 0) {
413
- try {
414
- await awaitRegistryRemoval(options.removeFromRegistry(candidate.id), candidate.id, options.registryTimeoutMs);
415
- } catch (error) {
416
- errors.push({
417
- id: candidate.id,
418
- message: `registry removal failed, transcript kept: ${error.message}`
419
- });
420
- continue;
421
- }
422
- }
491
+ const registry = await releaseFromRegistry(candidate, options);
492
+ if (registry.note !== void 0) errors.push(registry.note);
493
+ if (!registry.unlink) continue;
423
494
  try {
424
- rmSync2(transcriptPath2(plan.root, plan.cwd, candidate.id));
425
- removed.push(candidate.id);
495
+ rmSync2(candidate.transcript);
496
+ recordRemoval(candidate, removed, orphaned);
426
497
  } catch (error) {
427
498
  if (error.code === "ENOENT") {
428
- removed.push(candidate.id);
499
+ recordRemoval(candidate, removed, orphaned);
429
500
  continue;
430
501
  }
431
502
  errors.push({
@@ -437,6 +508,7 @@ async function runTranscriptGC(plan, options) {
437
508
  return {
438
509
  dryRun: !options.apply,
439
510
  removed,
511
+ orphaned,
440
512
  errors
441
513
  };
442
514
  }
@@ -461,13 +533,13 @@ function transcriptRootHint(found, previousRoot, env = process.env) {
461
533
  __name(transcriptRootHint, "transcriptRootHint");
462
534
 
463
535
  // src/session/thread-history.ts
464
- import { loadJsonl as loadJsonl2, transcriptPath as transcriptPath3, transcriptRoot as transcriptRoot5 } from "@theokit/sdk/persistence";
536
+ import { loadJsonl as loadJsonl2, transcriptPath as transcriptPath2, transcriptRoot as transcriptRoot5 } from "@theokit/sdk/persistence";
465
537
  var ABSENT = {
466
538
  state: "absent",
467
539
  messages: []
468
540
  };
469
541
  function readThreadHistory(sessionId, options) {
470
- const path = transcriptPath3(options.root ?? transcriptRoot5(), options.cwd, sessionId);
542
+ const path = transcriptPath2(options.root ?? transcriptRoot5(), options.cwd, sessionId);
471
543
  try {
472
544
  return {
473
545
  state: "present",
@@ -686,12 +758,13 @@ export {
686
758
  projectDirFor,
687
759
  projectDirMatches,
688
760
  projectsRoot,
689
- protectedTranscripts,
761
+ protectedTranscriptPaths,
690
762
  readThreadHistory,
691
763
  recordProjectDir,
692
764
  resolveProjectDir,
693
765
  runTranscriptGC,
694
766
  sessionPointerPath,
767
+ transcriptOf,
695
768
  transcriptRootHint
696
769
  };
697
770
  //# sourceMappingURL=session.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/session/session-lifecycle.ts","../src/session/gc/registry-remover.ts","../src/session/project-index.ts","../src/session/session-pointer.ts","../src/session/gc/transcript-gc.ts","../src/session/transcript-root-hint.ts","../src/session/thread-history.ts","../src/session/liveness-oracle.ts"],"mappings":";;;;;;;;AAKA,SAASA,gBAAAA,eAAcC,aAAaC,QAAQC,gBAAgB;AAC5D,SAASC,QAAAA,aAAY;AAErB,SAASC,qBAAAA,0BAAyB;AAClC,SACEC,yBACAC,gBACAC,WACAC,kBACAC,gBACAC,kBAAAA,uBACK;;;ACEP,SAASC,yBA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AI/D,kBAAiB+D,SAAAA,MAAe5B,KAAM;AAE1C,YAAM+B,MAAMtD,MAAMmD,SAAAA;AAClB,UAAI,WAAWG,KAAK;AAClB,eAAO;UAAEhD,UAAU;UAAgBC,QAAQ,kBAAkB4C,SAAAA,KAAcG,IAAIlD,KAAK;QAAG;MACzF;AACA,UAAIkD,IAAIjD,OAAO;AACb,eAAO;UAAEC,UAAU;UAASC,QAAQ,sBAAsB4C,SAAAA;UAAa9D,KAAK8D;QAAU;MACxF;IACF;AAUA,WAAOpC,aAAa,IAChB;MAAET,UAAU;MAAgBC,QAAQ;IAA0B,IAC9D;MACED,UAAU;MACVC,QAAQ;IACV;EACN,GA/BmB;AAiCnB,aAAWgB,QAAQZ,SAAS;AAC1B,QAAII,aAAa,GAAG;AAClBF,UAAI0C,IAAIhC,MAAM;QAAEjB,UAAU;QAAgBC,QAAQ;MAA0B,CAAA;AAC5E;IACF;AAGA,UAAMiD,WAAWlC,YAAYC,IAAAA;AAC7B,QAAIiC,SAAS5B,SAAS,cAAc;AAElCf,UAAI0C,IAAIhC,MAAM;QACZjB,UAAU;QACVC,QAAQ,kBAAkBK,KAAKa,YAAY,IAAIF,IAAAA,KAASiC,SAASpD,KAAK;MACxE,CAAA;AACA;IACF;AACA,QAAIoD,SAAS5B,SAAS,SAAS;AAC7Bf,UAAI0C,IACFhC,MACAzB,wBAAwB0D,SAASzD,MAAMC,OAAO,MAAMe,YAAY,CAAA,CAAA;AAElE;IACF;AAEA,UAAMiC,OAAOH,UAAAA;AACbhC,QAAI0C,IACFhC,MACAqB,qBAAqBpC,SACjBuC,WAAWxB,MAAMyB,IAAAA,IACjB;MAAE1C,UAAU;MAAgBC,QAAQqC;IAAiB,CAAA;EAE7D;AAEA,SAAO/B;AACT;AA1KgBH;","names":["readFileSync","readdirSync","rmSync","statSync","join","TheokitAgentError","classifySessionArtifact","forkTranscript","loadJsonl","sessionHasWriter","transcriptPath","transcriptRoot","TheokitAgentError","SessionRegistryRemoverError","TheokitAgentError","name","sessionId","timeoutMs","String","DEFAULT_REGISTRY_TIMEOUT_MS","isThenable","value","then","awaitRegistryRemoval","outcome","Number","isFinite","timer","Promise","race","_resolve","reject","setTimeout","undefined","clearTimeout","readFileSync","writeFileSync","join","encodeProjectDir","transcriptRoot","CWD_SIDECAR","projectsRoot","root","transcriptRoot","join","projectDirFor","cwd","encodeProjectDir","recordProjectDir","sidecar","ensureSecureDir","writeFileSync","resolveProjectDir","encodedName","raw","readFileSync","trim","length","undefined","projectDirMatches","readFileSync","join","atomicWriteText","transcriptRoot","POINTER","sessionPointerPath","cwd","root","transcriptRoot","join","projectDirFor","loadOrCreateSessionId","mintId","existing","readFileSync","trim","length","sessionId","resumed","persistSessionId","target","ensureSecureDir","atomicWriteText","persisted","SessionInUseError","TheokitAgentError","name","sessionId","reason","registryRemoved","listSessions","cwd","root","transcriptRoot","dir","projectDirFor","entries","readdirSync","found","entry","path","join","isDirectory","modifiedAt","stats","statSync","mtime","kind","classifySessionArtifact","push","id","replace","transcript","sort","a","b","getTime","protectedTranscripts","protectedBy","Map","sessions","pointer","readPointer","undefined","set","length","has","session","hasWriter","sessionHasWriter","readFileSync","sessionPointerPath","trim","deleteSession","options","force","get","registryError","removeFromRegistry","outcome","awaitRegistryRemoval","registryTimeoutMs","error","transcriptRemoved","nowProtected","rmSync","transcriptPath","forkBeforeUserTurn","srcId","newId","nth","Number","isInteger","String","src","dst","turns","reachableUserTurns","selected","forkTranscript","beforeRecordIndex","index","liveSessionPaths","keys","map","recordIndex","selectedText","text","GOAL_CONTINUATION_MARKER","textOfRecord","record","message","content","filter","block","type","isGenuineUserTurn","startsWith","records","loadJsonl","floor","i","subtype","rmSync","TheokitAgentError","transcriptPath","transcriptRoot","FLOOR","keepLast","maxAgeDays","GCProtectionUnavailableError","TheokitAgentError","name","reason","Error","message","String","code","isRetryable","cause","GCFloorError","field","received","resolveProtection","builtin","provider","undefined","extra","union","Map","id","set","planTranscriptGC","options","Number","isFinite","root","transcriptRoot","now","Date","cutoff","sessions","listSessions","cwd","protectedBy","protectedTranscripts","protectedIds","candidates","kept","index","session","entries","protection","get","push","age","modifiedAt","getTime","isNaN","transcript","runTranscriptGC","plan","removed","errors","protectedNow","apply","candidate","has","removeFromRegistry","awaitRegistryRemoval","registryTimeoutMs","error","rmSync","transcriptPath","dryRun","readdirSync","transcriptRootHint","found","previousRoot","env","process","undefined","current","THEOKIT_HOME","trim","length","projects","readdirSync","projectsRoot","String","loadJsonl","transcriptPath","transcriptRoot","ABSENT","state","messages","readThreadHistory","sessionId","options","path","transcriptPath","root","transcriptRoot","cwd","loadJsonl","err","isNotFound","reason","messageOf","code","Error","message","String","TheokitAgentError","DEFAULT_TRANSCRIPT_SAMPLES","encodeProjectDir","cwd","replace","LivenessBudgetError","TheokitAgentError","budget","String","assertUsableBudget","Number","isInteger","verdictFromRecordedCwds","cwds","probe","budgetLeft","unprobeable","at","error","found","liveness","reason","undefined","join","classifyProjects","encoded","opts","out","Map","remaining","path","answer","fs","exists","Error","message","recordedCwd","name","dir","projectsRoot","entries","listEntries","kind","samples","transcriptSamples","file","filter","f","endsWith","slice","record","JSON","parse","firstLine","length","includes","push","candidates","enumerationError","enumerate","candidatePaths","searchPool","pool","seen","Set","candidate","has","add","hit","set","recorded"]}
1
+ {"version":3,"sources":["../src/session/session-lifecycle.ts","../src/session/gc/registry-remover.ts","../src/session/project-index.ts","../src/session/session-pointer.ts","../src/session/gc/transcript-gc.ts","../src/session/transcript-root-hint.ts","../src/session/thread-history.ts","../src/session/liveness-oracle.ts"],"mappings":";;;;;;;;AAKA,SAASA,WAAWC,UAAUC,gBAAAA,eAAcC,aAAaC,UAAUC,QAAQC,gBAAgB;AAC3F,SAASC,QAAAA,aAAY;AAErB,SAASC,qBAAAA,0BAAyB;AAClC,SACEC,yBACAC,gBACAC,WACAC,kBACAC,gBACAC,kBAAAA,uBACK;;;ACEP,SAASC,yBAAyB;AAQ3B,IAAMC,8BAAN,cAA0CC,kBAAAA;EA1BjD,OA0B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AA;AAC7B,QAAIiC,SAAS5B,SAAS,cAAc;AAElCf,UAAI0C,IAAIhC,MAAM;QACZjB,UAAU;QACVC,QAAQ,kBAAkBK,KAAKa,YAAY,IAAIF,IAAAA,KAASiC,SAASpD,KAAK;MACxE,CAAA;AACA;IACF;AACA,QAAIoD,SAAS5B,SAAS,SAAS;AAC7Bf,UAAI0C,IACFhC,MACAzB,wBAAwB0D,SAASzD,MAAMC,OAAO,MAAMe,YAAY,CAAA,CAAA;AAElE;IACF;AAEA,UAAMiC,OAAOH,UAAAA;AACbhC,QAAI0C,IACFhC,MACAqB,qBAAqBpC,SACjBuC,WAAWxB,MAAMyB,IAAAA,IACjB;MAAE1C,UAAU;MAAgBC,QAAQqC;IAAiB,CAAA;EAE7D;AAEA,SAAO/B;AACT;AA1KgBH;","names":["closeSync","openSync","readFileSync","readdirSync","readSync","rmSync","statSync","join","TheokitAgentError","classifySessionArtifact","forkTranscript","loadJsonl","sessionHasWriter","transcriptPath","transcriptRoot","TheokitAgentError","SessionRegistryRemoverError","TheokitAgentError","name","sessionId","timeoutMs","String","DEFAULT_REGISTRY_TIMEOUT_MS","isThenable","value","then","awaitRegistryRemoval","outcome","Number","isFinite","timer","Promise","race","_resolve","reject","setTimeout","undefined","clearTimeout","readFileSync","writeFileSync","join","encodeProjectDir","transcriptRoot","CWD_SIDECAR","projectsRoot","root","transcriptRoot","join","projectDirFor","cwd","encodeProjectDir","recordProjectDir","sidecar","ensureSecureDir","writeFileSync","resolveProjectDir","encodedName","raw","readFileSync","trim","length","undefined","projectDirMatches","readFileSync","join","atomicWriteText","transcriptRoot","POINTER","sessionPointerPath","cwd","root","transcriptRoot","join","projectDirFor","loadOrCreateSessionId","mintId","existing","readFileSync","trim","length","sessionId","resumed","persistSessionId","target","ensureSecureDir","atomicWriteText","persisted","SessionInUseError","TheokitAgentError","name","sessionId","reason","registryOutcome","registryNote","outcome","listSessions","cwd","root","transcriptRoot","dir","projectDirFor","entries","readdirSync","found","entry","path","join","isDirectory","modifiedAt","stats","statSync","mtime","kind","classifySessionArtifact","id","sessionIdOf","push","idSource","undefined","transcript","sort","a","b","getTime","fd","openSync","buffer","Buffer","alloc","FIRST_RECORD_BYTES","read","readSync","newline","indexOf","end","first","JSON","parse","toString","length","closeSync","protectedTranscriptPaths","protectedBy","Map","sessions","pointer","readPointer","set","transcriptPath","has","session","hasWriter","sessionHasWriter","transcriptOf","readFileSync","sessionPointerPath","trim","deleteSession","options","force","get","registryError","removeFromRegistry","awaitRegistryRemoval","registryTimeoutMs","error","transcriptRemoved","nowProtected","rmSync","forkBeforeUserTurn","srcId","newId","nth","Number","isInteger","String","src","dst","turns","reachableUserTurns","selected","forkTranscript","beforeRecordIndex","index","liveSessionPaths","keys","map","recordIndex","selectedText","text","GOAL_CONTINUATION_MARKER","textOfRecord","record","message","content","filter","block","type","isGenuineUserTurn","startsWith","records","loadJsonl","floor","i","subtype","rmSync","TheokitAgentError","transcriptRoot","FLOOR","keepLast","maxAgeDays","GCProtectionUnavailableError","TheokitAgentError","name","reason","Error","message","String","code","isRetryable","cause","GCFloorError","field","received","resolveProtection","builtin","provider","cwd","root","undefined","extra","union","Map","id","set","transcriptOf","path","planTranscriptGC","options","Number","isFinite","transcriptRoot","now","Date","cutoff","sessions","listSessions","protectedBy","protectedTranscriptPaths","protectedIds","candidates","kept","index","session","entries","protection","get","transcript","push","age","modifiedAt","getTime","isNaN","releaseFromRegistry","candidate","note","UNNAMEABLE_COLLECTION","unlink","removeFromRegistry","awaitRegistryRemoval","registryTimeoutMs","error","recordRemoval","removed","orphaned","runTranscriptGC","plan","errors","protectedNow","apply","has","registry","rmSync","dryRun","readdirSync","transcriptRootHint","found","previousRoot","env","process","undefined","current","THEOKIT_HOME","trim","length","projects","readdirSync","projectsRoot","String","loadJsonl","transcriptPath","transcriptRoot","ABSENT","state","messages","readThreadHistory","sessionId","options","path","transcriptPath","root","transcriptRoot","cwd","loadJsonl","err","isNotFound","reason","messageOf","code","Error","message","String","TheokitAgentError","DEFAULT_TRANSCRIPT_SAMPLES","encodeProjectDir","cwd","replace","LivenessBudgetError","TheokitAgentError","budget","String","assertUsableBudget","Number","isInteger","verdictFromRecordedCwds","cwds","probe","budgetLeft","unprobeable","at","error","found","liveness","reason","undefined","join","classifyProjects","encoded","opts","out","Map","remaining","path","answer","fs","exists","Error","message","recordedCwd","name","dir","projectsRoot","entries","listEntries","kind","samples","transcriptSamples","file","filter","f","endsWith","slice","record","JSON","parse","firstLine","length","includes","push","candidates","enumerationError","enumerate","candidatePaths","searchPool","pool","seen","Set","candidate","has","add","hit","set","recorded"]}
@@ -0,0 +1,181 @@
1
+ import { TrustPosture, SettingSource } from '@theokit/sdk';
2
+ import { TheokitAgentError } from '@theokit/sdk/errors';
3
+
4
+ /**
5
+ * M68 — the trust gate for `settingSources`.
6
+ *
7
+ * ## The defect this module closes
8
+ *
9
+ * `settingSources` enables on-disk config discovery. `'user'` reads `~/.theokit/` — the operator's
10
+ * own machine, which no third party controls. `'project'` reads `<cwd>/.theokit/`, **including
11
+ * `hooks.json`, which executes shell**.
12
+ *
13
+ * The previous API took `readonly SettingSource[]`, and its JSDoc justified the risk this way:
14
+ * *"it is opt-in because `.theokit/` is the app's own repo (informed consent)"*. That premise holds
15
+ * for a web app whose `cwd` is its own deploy. It does **not** hold for the class of product this
16
+ * framework addresses — an agent whose `cwd` is a repository the user just cloned. There `.theokit/`
17
+ * is attacker-controlled content, and enabling `'project'` is remote code execution on the first
18
+ * `build()`.
19
+ *
20
+ * Documenting it did not prevent it. The measured consumer (TheoCode) did not trust the API: it
21
+ * gated from the outside, with a `posture.allows` of its own (`chat.ts:386`, comment B-008). It
22
+ * already **had** the right decision and could not pass it through, because the API only accepted
23
+ * strings. The gate existed on its side and evaporated at the boundary.
24
+ *
25
+ * ## The evidence is the SDK's, not one invented here
26
+ *
27
+ * `TrustPosture` is `@theokit/sdk`'s own trust primitive, and `recordWiring`'s doc says *"a posture
28
+ * is the only thing in this package that retains a capability"*. A bespoke type would make two trust
29
+ * grammars coexist and drift apart (ADR 0063).
30
+ */
31
+ /**
32
+ * The framework's capability vocabulary — deliberately a single name (ADR 0065).
33
+ *
34
+ * `allows` is all-or-nothing in the SDK: every declared `K` gets the same boolean. A finer
35
+ * vocabulary (`hooks`, `skills`, `subagents`, `mcp`) would promise the consumer it can gate one
36
+ * without gating the other, and the primitive does not deliver that. An API that suggests a
37
+ * distinction the runtime does not make teaches the wrong thing, and the error only surfaces when
38
+ * somebody depends on the distinction.
39
+ */
40
+ type SettingSourceCapability = 'projectSettings';
41
+ /** Authorization to read config from the working directory. Requires the posture, never a claim. */
42
+ interface ProjectSettingsGrant {
43
+ /**
44
+ * Typically the output of `resolveTrustPosture` — which is what gives it `source` (`'env' |
45
+ * 'store' | 'default'`) and therefore a refusal that says WHERE the decision came from instead of
46
+ * merely denying.
47
+ */
48
+ readonly trustedBy: TrustPosture<SettingSourceCapability>;
49
+ }
50
+ /**
51
+ * Which on-disk config roots the agent may read.
52
+ *
53
+ * The asymmetry is the design: `user` is a boolean because `~/.theokit/` belongs to the operator;
54
+ * `project` requires evidence because `<cwd>/.theokit/` may not. Omitting a root is not enabling it
55
+ * — never "enabling without a gate". The asymmetry is inherited from the SDK itself, whose
56
+ * `TrustPostureInput.envOverride` documents that `false` and `undefined` both mean "the operator did
57
+ * not turn it on", not "turned it off".
58
+ */
59
+ interface SettingSourcesSelection {
60
+ /** `~/.theokit/` — the operator's machine. No gate: no third party controls it. */
61
+ readonly user?: boolean;
62
+ /** `<cwd>/.theokit/` — controlled by whoever wrote the open repository. Requires evidence. */
63
+ readonly project?: ProjectSettingsGrant;
64
+ /**
65
+ * `<cwd>/.claude/` — a FOREIGN configuration dialect, read only once declared
66
+ * (`usetheokit/theokit-sdk#524`).
67
+ *
68
+ * ## Two questions, and which half of this field answers each
69
+ *
70
+ * The SDK's docblock separates them, and the separation is the whole point of `compatSources`:
71
+ * a trust gate answers *"do I trust the code in this directory?"*; importing another product's
72
+ * configuration answers *"do I want it imported into this one?"*. They come apart in the ordinary
73
+ * case, because `.claude/` is populated in exactly the repository one trusts most — for a
74
+ * different tool, by a teammate who never heard of this runtime.
75
+ *
76
+ * So the two are answered by two different things here, and it matters which:
77
+ *
78
+ * | Question | Answered by |
79
+ * |---|---|
80
+ * | do I want the foreign dialect imported? | **declaring this field at all** — omitting is not enabling |
81
+ * | do I trust this directory's code to run? | the `TrustPosture` inside the grant |
82
+ *
83
+ * ## Why the grant is `ProjectSettingsGrant` and not a vocabulary of its own
84
+ *
85
+ * Not because the two questions are the same — they are not. Because a separate grant could not
86
+ * carry the distinction even if it existed: `TrustPosture.allows` is `Record<K, boolean>` and the
87
+ * SDK documents every value as moving together with the level, so a `'foreignDialects'` capability
88
+ * beside `'projectSettings'` would promise an operator they can grant one and withhold the other,
89
+ * and `resolveTrustPosture` would hand back the same boolean for both. That is precisely the
90
+ * failure ADR 0065 exists to prevent, and inventing the second name would commit it while looking
91
+ * like rigour.
92
+ *
93
+ * The consent half is therefore carried by the declaration, which is a real and sufficient
94
+ * boundary: an operator who trusts a repository completely still reads no `.claude/` until they
95
+ * write this field. What the grant adds on top is stricter than the SDK — there, listing a dialect
96
+ * is enough — and the extra strictness is deliberate: this reads a `hooks.json` that executes
97
+ * shell out of a directory that usually arrived with the clone.
98
+ */
99
+ readonly claudeCode?: ProjectSettingsGrant & {
100
+ /**
101
+ * #686 — WHICH surfaces of the foreign root to import. Absent means all of them, which is what
102
+ * every caller before this meant and still means.
103
+ *
104
+ * The distinction is the reason the grant exists. `.claude/` usually arrives with the clone and
105
+ * its `hooks.json` executes shell, so "take the skills, refuse the hooks" is the ordinary thing
106
+ * to want — and before this the only choices were all of it or none of it.
107
+ *
108
+ * Requires `@theokit/sdk >= 5.4.0`, which is where the narrowed form landed. On an older SDK the
109
+ * runtime drops an unrecognised shape in SILENCE, so declaring it there would import nothing at
110
+ * all rather than importing less — refused at resolve time instead.
111
+ */
112
+ readonly import?: readonly CompatSurface[];
113
+ };
114
+ }
115
+ /**
116
+ * The surfaces a foreign configuration root can contribute.
117
+ *
118
+ * Written out rather than imported, for the same reason as the `claude-code` literal below:
119
+ * `CompatSurface` does not exist in `@theokit/sdk@4.52.1`, this package's declared floor, and a gate
120
+ * that cannot build against its own minimum dependency is worse than a constant that has been
121
+ * checked. Verified against the published 5.4.0 `.d.ts`, where the union is
122
+ * `"hooks" | "plugins" | "skills" | "subagents"` — note `subagents`, not `agents`.
123
+ */
124
+ type CompatSurface = 'commands' | 'hooks' | 'plugins' | 'skills' | 'subagents';
125
+ /** What `resolveCompatSources` returns: the whole root, or the root narrowed to some surfaces. */
126
+ type ResolvedCompatSource = 'claude-code' | {
127
+ readonly kind: 'claude-code';
128
+ readonly import: readonly CompatSurface[];
129
+ };
130
+ /**
131
+ * Refusal to read the working directory for lack of trust.
132
+ *
133
+ * Descends from `TheokitAgentError` because typed errors are an unbreakable rule here — and because
134
+ * `isTransientError` only sees this hierarchy. A class extending plain `Error` would be invisible to
135
+ * the predicate that separates recoverable from unrecoverable (the defect M67 fixed in five
136
+ * classes).
137
+ */
138
+ declare class UntrustedSettingSourceError extends TheokitAgentError {
139
+ /** Where the trust decision came from: `'env' | 'store' | 'default'`. */
140
+ readonly trustSource: string;
141
+ /** The refused capability. */
142
+ readonly capability: SettingSourceCapability;
143
+ readonly name = "UntrustedSettingSourceError";
144
+ constructor(message: string,
145
+ /** Where the trust decision came from: `'env' | 'store' | 'default'`. */
146
+ trustSource: string,
147
+ /** The refused capability. */
148
+ capability: SettingSourceCapability);
149
+ }
150
+ /**
151
+ * Translate the declared selection into the `SettingSource`s the SDK accepts, refusing what the
152
+ * posture does not authorize.
153
+ *
154
+ * Refuses rather than ignores (ADR 0064). Ignoring would leave the product running in the belief
155
+ * that the repository's hooks are active — a silent failure mode, on the wrong side. The SDK already
156
+ * picked that side for the same problem: `recordWiring` throws `UngatedCapabilityError` when
157
+ * somebody registers a capability the posture does not gate.
158
+ *
159
+ * @throws {UntrustedSettingSourceError} when `project` is requested and the posture does not grant it.
160
+ */
161
+ declare function resolveSettingSources(selection: SettingSourcesSelection | undefined): readonly SettingSource[];
162
+ /**
163
+ * The foreign configuration dialects this layer forwards, once the posture authorises them.
164
+ *
165
+ * ## Why it is a separate function and the same vocabulary
166
+ *
167
+ * Separate because the SDK takes them on a separate option (`local.compatSources`); the same
168
+ * `ProjectSettingsGrant` because the thing being authorised is identical — reading a `hooks.json`
169
+ * that executes shell out of a directory the operator does not necessarily control.
170
+ *
171
+ * ## What it deliberately does NOT do
172
+ *
173
+ * Validate the source NAME. The SDK DROPS an unrecognised name rather than turning it into
174
+ * `<cwd>/<name>`, so a typo fails closed there; turning that into a throw here would convert a safe
175
+ * default into a crash. This gate decides authorisation, never vocabulary.
176
+ *
177
+ * @throws {UntrustedSettingSourceError} when a source is requested and the posture does not grant it.
178
+ */
179
+ declare function resolveCompatSources(selection: SettingSourcesSelection | undefined): readonly ResolvedCompatSource[];
180
+
181
+ export { type CompatSurface as C, type ProjectSettingsGrant as P, type ResolvedCompatSource as R, type SettingSourcesSelection as S, UntrustedSettingSourceError as U, type SettingSourceCapability as a, resolveSettingSources as b, resolveCompatSources as r };
package/dist/testing.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { AgentOutputEvent } from '@theokit/presenter';
2
2
  import { WireChunk } from '@theokit/presenter/wire';
3
- import { A as AgentDefinition } from './define-agent-BL3jMyJi.js';
3
+ import { A as AgentDefinition } from './define-agent-Dp6e7chT.js';
4
4
  import '@theokit/sdk';
5
5
  import 'zod';
6
- import './agent-compiler-uhleFZj_.js';
6
+ import './agent-compiler-CvYfM-0t.js';
7
7
  import '@theokit/sdk/errors';
8
8
  import './types-C16Wuh9E.js';
9
+ import './setting-sources-gate-tadmHT0c.js';
9
10
  import './hook-handlers-Cw2FsnE5.js';
10
11
 
11
12
  /**
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  compileAgentDefinition
3
- } from "./chunk-OAQEWLQJ.js";
3
+ } from "./chunk-43O2CCZR.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-Z4QWC7IK.js";
package/dist/tools.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  export { CatastrophicCommandError, CommandPolicy, ContextMatchError, ContextMatchReason, CreateApplyPatchToolOptions, CreateBraveWebSearchAdapterOptions, CreateCurrentTimeToolOptions, CreateEditFileToolOptions, CreateGenericHttpSearchAdapterOptions, CreateGitDiffToolOptions, CreateGitStatusToolOptions, CreateGlobToolOptions, CreateInteractiveShellToolOptions, CreateListDirToolOptions, CreateReadFileToolOptions, CreateRunVitestToolOptions, CreateSearchTextToolOptions, CreateShellToolOptions, CreateViewImageToolOptions, CreateWebFetchToolOptions, CreateWebSearchToolOptions, CreateWriteFileToolOptions, DEFAULT_MAX_IMAGE_BYTES, DEFAULT_TOOL_GUIDANCE, EnvContextOptions, PlanModeTool, PlanModeToolOptions, PlanModeToolWithStore, PlanNode, QuestionTool, QuestionToolOptions, ReadTracker, ReasoningTools, RedirectBlockedError, RepoMapOptions, ResolveAndScreenOptions, ScreenedFetchOptions, SessionArtifactStore, SessionArtifactStoreOptions, SsrfBlockedError, TodoItem, TodolistTool, ToolGuidanceMap, TruncationMode, TruncationOptions, TruncationResult, VitestSummary, WebSearchCallback, WebSearchResult, buildEnvContext, buildRepoMap, catastrophicShellReason, commandDenialReason, createApplyPatchTool, createBraveWebSearchAdapter, createCurrentTimeTool, createEditFileTool, createGenericHttpSearchAdapter, createGitDiffTool, createGitStatusTool, createGlobTool, createInteractiveShellTool, createListDirTool, createPlanModeTool, createQuestionTool, createReadFileTool, createRunVitestTool, createSearchTextTool, createSessionArtifactStore, createShellTool, createTodolistTool, createUpdatePlanTool, createViewImageTool, createWebFetchTool, createWebSearchTool, createWriteFileTool, createWriteStdinTool, denyCatastrophicCommands, formatCode, formatDiff, formatError, formatFileList, injectGuidance, isBlockedIp, isCommandAllowed, renderToolList, replaceUnique, resolveAndScreen, screenedFetch, todoItemsToPlanNodes, truncateOutput, withDefaultGuidance, withDescription, withName, withShellExitGuidance, withToolResultGuidance } from '@theokit/sdk-tools';
2
2
  import * as _theokit_sdk from '@theokit/sdk';
3
3
  import { TheokitAgentError } from '@theokit/sdk/errors';
4
- import { D as DelegationTarget, a as DelegateOptions } from './delegation-scoring--OiOTcAW.js';
4
+ import { D as DelegationTarget, a as DelegateOptions } from './delegation-scoring-BZdtCdMN.js';
5
5
  import '@theokit/sdk/retry';
6
- import './agent-compiler-uhleFZj_.js';
6
+ import './agent-compiler-CvYfM-0t.js';
7
7
  import './types-C16Wuh9E.js';
8
8
  import 'zod';
9
+ import './setting-sources-gate-tadmHT0c.js';
9
10
  import '@theokit/presenter/wire';
10
11
  import './hook-handlers-Cw2FsnE5.js';
11
12