@theokit/sdk 4.30.0 → 4.31.1

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/{agent-Ekv8y7_c.d.ts → agent-BJbGi8-R.d.ts} +1 -1
  3. package/dist/{agent-LD76RI74.cjs → agent-BKNJIOEY.cjs} +9 -9
  4. package/dist/{agent-LD76RI74.cjs.map → agent-BKNJIOEY.cjs.map} +1 -1
  5. package/dist/{agent-Bzg2_uGr.d.cts → agent-CbZPGFfM.d.cts} +1 -1
  6. package/dist/{agent-7YUGJJTU.js → agent-HW7OY2W3.js} +8 -8
  7. package/dist/{agent-7YUGJJTU.js.map → agent-HW7OY2W3.js.map} +1 -1
  8. package/dist/agent.d.ts +15 -2
  9. package/dist/{chunk-ISZ3MBUD.js → chunk-CCRWSZ2F.js} +57 -20
  10. package/dist/chunk-CCRWSZ2F.js.map +1 -0
  11. package/dist/chunk-CJVMDRQB.cjs +169 -0
  12. package/dist/chunk-CJVMDRQB.cjs.map +1 -0
  13. package/dist/{chunk-YU6KON2I.cjs → chunk-E2YEDATX.cjs} +6 -6
  14. package/dist/{chunk-YU6KON2I.cjs.map → chunk-E2YEDATX.cjs.map} +1 -1
  15. package/dist/{chunk-NG6B2PMA.cjs → chunk-GQBXBHZ2.cjs} +5 -5
  16. package/dist/{chunk-NG6B2PMA.cjs.map → chunk-GQBXBHZ2.cjs.map} +1 -1
  17. package/dist/{chunk-2HRYBRD7.cjs → chunk-IOOSAZZH.cjs} +8 -9
  18. package/dist/chunk-IOOSAZZH.cjs.map +1 -0
  19. package/dist/{chunk-2MF3IE2D.cjs → chunk-NZCFLEHO.cjs} +136 -25
  20. package/dist/chunk-NZCFLEHO.cjs.map +1 -0
  21. package/dist/{chunk-U6QGZHPN.js → chunk-RPKTXBPK.js} +5 -6
  22. package/dist/chunk-RPKTXBPK.js.map +1 -0
  23. package/dist/{chunk-GWMQ5CS3.cjs → chunk-S6F3FKFR.cjs} +87 -50
  24. package/dist/chunk-S6F3FKFR.cjs.map +1 -0
  25. package/dist/{chunk-SQLZ7ONU.js → chunk-SJLOIZ4Z.js} +4 -4
  26. package/dist/{chunk-SQLZ7ONU.js.map → chunk-SJLOIZ4Z.js.map} +1 -1
  27. package/dist/{chunk-4SXHEZIV.cjs → chunk-U2FO3MRG.cjs} +9 -3
  28. package/dist/chunk-U2FO3MRG.cjs.map +1 -0
  29. package/dist/chunk-UAYYNWYJ.js +163 -0
  30. package/dist/chunk-UAYYNWYJ.js.map +1 -0
  31. package/dist/{chunk-ZZWTY3RX.js → chunk-VGUOUAM2.js} +9 -4
  32. package/dist/chunk-VGUOUAM2.js.map +1 -0
  33. package/dist/{chunk-5YCAR23S.js → chunk-WYPHQ7NM.js} +3 -3
  34. package/dist/{chunk-5YCAR23S.js.map → chunk-WYPHQ7NM.js.map} +1 -1
  35. package/dist/{chunk-NRSH7RJY.js → chunk-XDNGF5BY.js} +133 -22
  36. package/dist/chunk-XDNGF5BY.js.map +1 -0
  37. package/dist/{compact-session-OO7NVWPB.cjs → compact-session-42BK7RE3.cjs} +12 -12
  38. package/dist/{compact-session-OO7NVWPB.cjs.map → compact-session-42BK7RE3.cjs.map} +1 -1
  39. package/dist/{compact-session-OO2GD76G.js → compact-session-QMBOCFVQ.js} +4 -4
  40. package/dist/{compact-session-OO2GD76G.js.map → compact-session-QMBOCFVQ.js.map} +1 -1
  41. package/dist/{cron-D0Z29gI-.d.ts → cron-BU9qD5B6.d.ts} +2 -2
  42. package/dist/{cron-CjzvXGT2.d.cts → cron-BwojPwEs.d.cts} +2 -2
  43. package/dist/cron.cjs +8 -8
  44. package/dist/cron.d.cts +3 -3
  45. package/dist/cron.d.ts +3 -3
  46. package/dist/cron.js +7 -7
  47. package/dist/{errors-DHZtSNnj.d.ts → errors-Cua4WC9H.d.ts} +1 -1
  48. package/dist/{errors-BdL-buYn.d.cts → errors-DyVbXdR4.d.cts} +1 -1
  49. package/dist/errors.d.cts +2 -2
  50. package/dist/errors.d.ts +2 -2
  51. package/dist/eval.cjs +11 -12
  52. package/dist/eval.cjs.map +1 -1
  53. package/dist/eval.js +7 -8
  54. package/dist/eval.js.map +1 -1
  55. package/dist/fs-session-store-IIP7ZBYE.cjs +17 -0
  56. package/dist/{fs-session-store-KAUQYSGI.cjs.map → fs-session-store-IIP7ZBYE.cjs.map} +1 -1
  57. package/dist/fs-session-store-T7YPW5A4.js +8 -0
  58. package/dist/{fs-session-store-ZKB5NN37.js.map → fs-session-store-T7YPW5A4.js.map} +1 -1
  59. package/dist/index.cjs +29 -29
  60. package/dist/index.d.cts +23 -10
  61. package/dist/index.d.ts +23 -10
  62. package/dist/index.js +9 -9
  63. package/dist/{inject-session-6MJUSGZP.cjs → inject-session-6ZMCA2NE.cjs} +6 -6
  64. package/dist/{inject-session-6MJUSGZP.cjs.map → inject-session-6ZMCA2NE.cjs.map} +1 -1
  65. package/dist/{inject-session-KOFHS5K3.js → inject-session-YA3GQE4G.js} +4 -4
  66. package/dist/{inject-session-KOFHS5K3.js.map → inject-session-YA3GQE4G.js.map} +1 -1
  67. package/dist/internal/llm/abort-error.d.ts +1 -0
  68. package/dist/internal/llm/retrying-client.d.ts +53 -0
  69. package/dist/internal/llm/transport-error.d.ts +9 -0
  70. package/dist/internal/persistence/index.cjs +18 -19
  71. package/dist/internal/persistence/index.cjs.map +1 -1
  72. package/dist/internal/persistence/index.js +1 -2
  73. package/dist/internal/persistence/index.js.map +1 -1
  74. package/dist/internal/persistence/session-transcript.d.cts +13 -1
  75. package/dist/internal/persistence/session-transcript.d.ts +13 -1
  76. package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +1 -1
  77. package/dist/persistence.cjs +17 -14
  78. package/dist/persistence.cjs.map +1 -1
  79. package/dist/persistence.d.cts +1 -1
  80. package/dist/persistence.d.ts +1 -1
  81. package/dist/persistence.js +2 -3
  82. package/dist/persistence.js.map +1 -1
  83. package/dist/{run-OJbGyweZ.d.cts → run-CwEJtLPE.d.cts} +8 -0
  84. package/dist/{run-OJbGyweZ.d.ts → run-CwEJtLPE.d.ts} +8 -0
  85. package/dist/server/errors-envelope.d.cts +3 -3
  86. package/dist/server/errors-envelope.d.ts +3 -3
  87. package/dist/{session-transcript-T7LGJUGW.js → session-transcript-5VZUWEJ5.js} +3 -3
  88. package/dist/{session-transcript-T7LGJUGW.js.map → session-transcript-5VZUWEJ5.js.map} +1 -1
  89. package/dist/session-transcript-T4SB66I7.cjs +50 -0
  90. package/dist/{session-transcript-LPNZR3YS.cjs.map → session-transcript-T4SB66I7.cjs.map} +1 -1
  91. package/dist/subagents-loader.d.cts +2 -2
  92. package/dist/subagents-loader.d.ts +2 -2
  93. package/dist/types/agent-prims.d.ts +8 -0
  94. package/package.json +1 -1
  95. package/dist/chunk-2HRYBRD7.cjs.map +0 -1
  96. package/dist/chunk-2MF3IE2D.cjs.map +0 -1
  97. package/dist/chunk-4SXHEZIV.cjs.map +0 -1
  98. package/dist/chunk-C7PICHRF.cjs +0 -68
  99. package/dist/chunk-C7PICHRF.cjs.map +0 -1
  100. package/dist/chunk-GWMQ5CS3.cjs.map +0 -1
  101. package/dist/chunk-HK7ZHSAX.cjs +0 -85
  102. package/dist/chunk-HK7ZHSAX.cjs.map +0 -1
  103. package/dist/chunk-HZQEDNF6.js +0 -66
  104. package/dist/chunk-HZQEDNF6.js.map +0 -1
  105. package/dist/chunk-ISZ3MBUD.js.map +0 -1
  106. package/dist/chunk-NRSH7RJY.js.map +0 -1
  107. package/dist/chunk-R6ZP6KNB.js +0 -80
  108. package/dist/chunk-R6ZP6KNB.js.map +0 -1
  109. package/dist/chunk-U6QGZHPN.js.map +0 -1
  110. package/dist/chunk-ZZWTY3RX.js.map +0 -1
  111. package/dist/fs-session-store-KAUQYSGI.cjs +0 -17
  112. package/dist/fs-session-store-ZKB5NN37.js +0 -8
  113. package/dist/session-transcript-LPNZR3YS.cjs +0 -46
@@ -54,7 +54,19 @@ export declare class SessionTranscript {
54
54
  * Returns them in root→leaf (chronological replay) order.
55
55
  */
56
56
  export declare function reconstructMessages(records: readonly SessionRecord[]): LlmMessage[];
57
- /** Default transcript base dir. `~/.theokit` isolates our sessions; set to `~/.claude` for CLI interop. */
57
+ /**
58
+ * Raiz do estado de transcript.
59
+ *
60
+ * `THEOKIT_HOME` vence; o fallback é `~/.theokit`. Home-ancorado de propósito, e NÃO
61
+ * `getTheokitHome(cwd)` de `paths.ts`: aquele faz fallback para `<cwd>/.theokit`, e trocar
62
+ * por ele moveria o transcript de todo mundo que **não** define a variável. O irmão com a
63
+ * forma certa é `catalog-source-models-dev.ts` (M94 ADR-2).
64
+ *
65
+ * Antes do M94 esta função ignorava a env, então quem a definia tinha o estado partido em
66
+ * dois em silêncio — as sessões continuavam em `~/.theokit` enquanto o resto do SDK migrava.
67
+ */
68
+ export declare function transcriptRoot(): string;
69
+ /** @deprecated Use {@link transcriptRoot}. Mantido como alias — mesmo valor. */
58
70
  export declare function defaultBaseDir(): string;
59
71
  /**
60
72
  * Expand a leading `~` / `~/` to the user's home dir. `node:path` does NOT expand `~`, so a
@@ -54,7 +54,19 @@ export declare class SessionTranscript {
54
54
  * Returns them in root→leaf (chronological replay) order.
55
55
  */
56
56
  export declare function reconstructMessages(records: readonly SessionRecord[]): LlmMessage[];
57
- /** Default transcript base dir. `~/.theokit` isolates our sessions; set to `~/.claude` for CLI interop. */
57
+ /**
58
+ * Raiz do estado de transcript.
59
+ *
60
+ * `THEOKIT_HOME` vence; o fallback é `~/.theokit`. Home-ancorado de propósito, e NÃO
61
+ * `getTheokitHome(cwd)` de `paths.ts`: aquele faz fallback para `<cwd>/.theokit`, e trocar
62
+ * por ele moveria o transcript de todo mundo que **não** define a variável. O irmão com a
63
+ * forma certa é `catalog-source-models-dev.ts` (M94 ADR-2).
64
+ *
65
+ * Antes do M94 esta função ignorava a env, então quem a definia tinha o estado partido em
66
+ * dois em silêncio — as sessões continuavam em `~/.theokit` enquanto o resto do SDK migrava.
67
+ */
68
+ export declare function transcriptRoot(): string;
69
+ /** @deprecated Use {@link transcriptRoot}. Mantido como alias — mesmo valor. */
58
70
  export declare function defaultBaseDir(): string;
59
71
  /**
60
72
  * Expand a leading `~` / `~/` to the user's home dir. `node:path` does NOT expand `~`, so a
@@ -1 +1 @@
1
- export {};
1
+ export declare function runPostRunLifecycle(inputs: PostRunLifecycleInputs): Promise<void>;
@@ -1,11 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkHK7ZHSAX_cjs = require('./chunk-HK7ZHSAX.cjs');
4
3
  var chunkPNVDQL5Y_cjs = require('./chunk-PNVDQL5Y.cjs');
5
- var chunkC7PICHRF_cjs = require('./chunk-C7PICHRF.cjs');
4
+ var chunkCJVMDRQB_cjs = require('./chunk-CJVMDRQB.cjs');
6
5
  var chunkJD74LN7R_cjs = require('./chunk-JD74LN7R.cjs');
7
6
  var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
8
- var chunk4SXHEZIV_cjs = require('./chunk-4SXHEZIV.cjs');
7
+ var chunkU2FO3MRG_cjs = require('./chunk-U2FO3MRG.cjs');
9
8
  var chunkTIZ4TS5V_cjs = require('./chunk-TIZ4TS5V.cjs');
10
9
  var chunkA44COQJJ_cjs = require('./chunk-A44COQJJ.cjs');
11
10
  require('./chunk-BEURCLDV.cjs');
@@ -110,29 +109,29 @@ function readJsonlTail(path, options = {}) {
110
109
  return options._stats === true ? Object.assign(out, { bytesRead }) : out;
111
110
  }
112
111
 
112
+ Object.defineProperty(exports, "PersistenceSchema", {
113
+ enumerable: true,
114
+ get: function () { return chunkPNVDQL5Y_cjs.PersistenceSchema; }
115
+ });
113
116
  Object.defineProperty(exports, "JsonlParseError", {
114
117
  enumerable: true,
115
- get: function () { return chunkHK7ZHSAX_cjs.JsonlParseError; }
118
+ get: function () { return chunkCJVMDRQB_cjs.JsonlParseError; }
116
119
  });
117
120
  Object.defineProperty(exports, "appendJsonl", {
118
121
  enumerable: true,
119
- get: function () { return chunkHK7ZHSAX_cjs.appendJsonl; }
122
+ get: function () { return chunkCJVMDRQB_cjs.appendJsonl; }
120
123
  });
121
124
  Object.defineProperty(exports, "loadJsonl", {
122
125
  enumerable: true,
123
- get: function () { return chunkHK7ZHSAX_cjs.loadJsonl; }
126
+ get: function () { return chunkCJVMDRQB_cjs.loadJsonl; }
124
127
  });
125
128
  Object.defineProperty(exports, "readJsonlIds", {
126
129
  enumerable: true,
127
- get: function () { return chunkHK7ZHSAX_cjs.readJsonlIds; }
128
- });
129
- Object.defineProperty(exports, "PersistenceSchema", {
130
- enumerable: true,
131
- get: function () { return chunkPNVDQL5Y_cjs.PersistenceSchema; }
130
+ get: function () { return chunkCJVMDRQB_cjs.readJsonlIds; }
132
131
  });
133
132
  Object.defineProperty(exports, "withFileLock", {
134
133
  enumerable: true,
135
- get: function () { return chunkC7PICHRF_cjs.withFileLock; }
134
+ get: function () { return chunkCJVMDRQB_cjs.withFileLock; }
136
135
  });
137
136
  Object.defineProperty(exports, "applyWalWithFallback", {
138
137
  enumerable: true,
@@ -156,11 +155,15 @@ Object.defineProperty(exports, "withCwdMutex", {
156
155
  });
157
156
  Object.defineProperty(exports, "encodeProjectDir", {
158
157
  enumerable: true,
159
- get: function () { return chunk4SXHEZIV_cjs.encodeProjectDir; }
158
+ get: function () { return chunkU2FO3MRG_cjs.encodeProjectDir; }
160
159
  });
161
160
  Object.defineProperty(exports, "transcriptPath", {
162
161
  enumerable: true,
163
- get: function () { return chunk4SXHEZIV_cjs.transcriptPath; }
162
+ get: function () { return chunkU2FO3MRG_cjs.transcriptPath; }
163
+ });
164
+ Object.defineProperty(exports, "transcriptRoot", {
165
+ enumerable: true,
166
+ get: function () { return chunkU2FO3MRG_cjs.transcriptRoot; }
164
167
  });
165
168
  Object.defineProperty(exports, "atomicWriteJson", {
166
169
  enumerable: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-writer.ts","../src/internal/persistence/transcript-ops.ts"],"names":["TheokitAgentError","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AAc,MAAM,IAAI,CAAA;AAEtD,EAAA,IAAI,GAAA,GAAM,MAAA;AACV,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,MAAM,WAAW,OAAA,CAAQ,WAAA;AACzB,IAAA,MAAM,GAAA,GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAC,CAAA;AACzD,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, openSync, rmSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n const lockPath = `${sessionPath}.lock`;\n let fd: number;\n try {\n fd = openSync(lockPath, \"wx\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new SessionBusyError(sessionPath);\n }\n throw err;\n }\n closeSync(fd);\n\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n };\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee.\n const fd = openSync(dst, \"wx\");\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Lê chunks de trás para frente até acumular linhas completas suficientes.\n *\n * Extraído de `readJsonlTail` porque o laço de leitura e a seleção de registros são duas\n * responsabilidades — e juntas passavam do teto de complexidade. A primeira linha do buffer pode\n * estar cortada ao meio quando a leitura parou antes do início do arquivo; por isso ela é descartada.\n */\nfunction lerCaudaBruta(path: string, want: number): { linhas: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (naoVazias(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const linhas = naoVazias(tail);\n return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };\n}\n\n/** Linhas com conteúdo, na ordem do arquivo. */\nfunction naoVazias(texto: string): string[] {\n return texto.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { linhas, bytesRead } = lerCaudaBruta(path, want);\n\n let sel = linhas;\n if (options.sinceMarker !== undefined) {\n const marcador = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marcador));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-writer.ts","../src/internal/persistence/transcript-ops.ts"],"names":["TheokitAgentError","openSync","closeSync","rmSync","readFileSync","writeSync","statSync","readSync"],"mappings":";;;;;;;;;;;;AA0CO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAeA,eAAsB,qBAAqB,WAAA,EAAkD;AAC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,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, openSync, rmSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n const lockPath = `${sessionPath}.lock`;\n let fd: number;\n try {\n fd = openSync(lockPath, \"wx\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new SessionBusyError(sessionPath);\n }\n throw err;\n }\n closeSync(fd);\n\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n };\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee.\n const fd = openSync(dst, \"wx\");\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Lê chunks de trás para frente até acumular linhas completas suficientes.\n *\n * Extraído de `readJsonlTail` porque o laço de leitura e a seleção de registros são duas\n * responsabilidades — e juntas passavam do teto de complexidade. A primeira linha do buffer pode\n * estar cortada ao meio quando a leitura parou antes do início do arquivo; por isso ela é descartada.\n */\nfunction lerCaudaBruta(path: string, want: number): { linhas: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (naoVazias(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const linhas = naoVazias(tail);\n return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };\n}\n\n/** Linhas com conteúdo, na ordem do arquivo. */\nfunction naoVazias(texto: string): string[] {\n return texto.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { linhas, bytesRead } = lerCaudaBruta(path, want);\n\n let sel = linhas;\n if (options.sinceMarker !== undefined) {\n const marcador = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marcador));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
@@ -21,7 +21,7 @@ export { withFileLock } from "./internal/persistence/file-lock.js";
21
21
  export { sanitizeFts5Query } from "./internal/persistence/fts5-sanitize.js";
22
22
  export { appendJsonl, JsonlParseError, loadJsonl, readJsonlIds, } from "./internal/persistence/jsonl.js";
23
23
  export { PersistenceSchema } from "./internal/persistence/persistence-schema.js";
24
- export { encodeProjectDir, transcriptPath, } from "./internal/persistence/session-transcript.js";
24
+ export { encodeProjectDir, transcriptPath, transcriptRoot, } from "./internal/persistence/session-transcript.js";
25
25
  export { acquireSessionWriter, SessionBusyError, type SessionWriterLease, } from "./internal/persistence/session-writer.js";
26
26
  export type { OpenSqliteResilientOptions, ResilientSqliteDb, } from "./internal/persistence/sqlite-open.js";
27
27
  export { isCorruptionError, openSqliteResilient } from "./internal/persistence/sqlite-open.js";
@@ -21,7 +21,7 @@ export { withFileLock } from "./internal/persistence/file-lock.js";
21
21
  export { sanitizeFts5Query } from "./internal/persistence/fts5-sanitize.js";
22
22
  export { appendJsonl, JsonlParseError, loadJsonl, readJsonlIds, } from "./internal/persistence/jsonl.js";
23
23
  export { PersistenceSchema } from "./internal/persistence/persistence-schema.js";
24
- export { encodeProjectDir, transcriptPath, } from "./internal/persistence/session-transcript.js";
24
+ export { encodeProjectDir, transcriptPath, transcriptRoot, } from "./internal/persistence/session-transcript.js";
25
25
  export { acquireSessionWriter, SessionBusyError, type SessionWriterLease, } from "./internal/persistence/session-writer.js";
26
26
  export type { OpenSqliteResilientOptions, ResilientSqliteDb, } from "./internal/persistence/sqlite-open.js";
27
27
  export { isCorruptionError, openSqliteResilient } from "./internal/persistence/sqlite-open.js";
@@ -1,9 +1,8 @@
1
- export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds } from './chunk-R6ZP6KNB.js';
2
1
  export { PersistenceSchema } from './chunk-CAH3G4IS.js';
3
- export { withFileLock } from './chunk-HZQEDNF6.js';
2
+ export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds, withFileLock } from './chunk-UAYYNWYJ.js';
4
3
  export { applyWalWithFallback, isCorruptionError, openSqliteResilient, sanitizeFts5Query } from './chunk-77FOZCOT.js';
5
4
  export { withCwdMutex } from './chunk-2XLKLVVR.js';
6
- export { encodeProjectDir, transcriptPath } from './chunk-ZZWTY3RX.js';
5
+ export { encodeProjectDir, transcriptPath, transcriptRoot } from './chunk-VGUOUAM2.js';
7
6
  export { atomicWriteJson, atomicWriteText, replaceFileAtomic } from './chunk-S2BBRVQX.js';
8
7
  import { TheokitAgentError } from './chunk-WLKFWQSJ.js';
9
8
  import './chunk-JTFYYKDT.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/persistence/session-writer.ts","../src/internal/persistence/transcript-ops.ts"],"names":["openSync","closeSync"],"mappings":";;;;;;;;;;;AA0CO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAeA,eAAsB,qBAAqB,WAAA,EAAkD;AAC3F,EAAA,MAAM,QAAA,GAAW,GAAG,WAAW,CAAA,KAAA,CAAA;AAC/B,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,I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,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.js","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, openSync, rmSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n const lockPath = `${sessionPath}.lock`;\n let fd: number;\n try {\n fd = openSync(lockPath, \"wx\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new SessionBusyError(sessionPath);\n }\n throw err;\n }\n closeSync(fd);\n\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n };\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee.\n const fd = openSync(dst, \"wx\");\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Lê chunks de trás para frente até acumular linhas completas suficientes.\n *\n * Extraído de `readJsonlTail` porque o laço de leitura e a seleção de registros são duas\n * responsabilidades — e juntas passavam do teto de complexidade. A primeira linha do buffer pode\n * estar cortada ao meio quando a leitura parou antes do início do arquivo; por isso ela é descartada.\n */\nfunction lerCaudaBruta(path: string, want: number): { linhas: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (naoVazias(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const linhas = naoVazias(tail);\n return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };\n}\n\n/** Linhas com conteúdo, na ordem do arquivo. */\nfunction naoVazias(texto: string): string[] {\n return texto.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { linhas, bytesRead } = lerCaudaBruta(path, want);\n\n let sel = linhas;\n if (options.sinceMarker !== undefined) {\n const marcador = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marcador));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/persistence/session-writer.ts","../src/internal/persistence/transcript-ops.ts"],"names":["openSync","closeSync"],"mappings":";;;;;;;;;;AA0CO,IAAM,gBAAA,GAAN,cAA+B,iBAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAeA,eAAsB,qBAAqB,WAAA,EAAkD;AAC3F,EAAA,MAAM,QAAA,GAAW,GAAG,WAAW,CAAA,KAAA,CAAA;AAC/B,EAAA,IAAI,EAAA;AACJ,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,QAAA,CAAS,UAAU,IAAI,CAAA;AAAA,EAC9B,SAAS,GAAA,EAAK;AACZ,IAAA,IAAK,GAAA,CAA8B,SAAS,QAAA,EAAU;AACpD,MAAA,MAAM,IAAI,iBAAiB,WAAW,CAAA;AAAA,IACxC;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACA,EAAA,SAAA,CAAU,EAAE,CAAA;AAEZ,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC;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SAAS,aAAA,CACd,IAAA,EACA,OAAA,GAAgC,EAAC,EAC5B;AACL,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,iBAAA;AAC1C,EAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAU,GAAI,aAAA,CAAc,MAAM,IAAI,CAAA;AAEtD,EAAA,IAAI,GAAA,GAAM,MAAA;AACV,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,MAAM,WAAW,OAAA,CAAQ,WAAA;AACzB,IAAA,MAAM,GAAA,GAAM,IAAI,aAAA,CAAc,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAC,CAAA;AACzD,IAAA,IAAI,OAAO,CAAA,EAAG,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,MAAM,CAAC,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,MAAA,CAAO,SAAS,IAAI,CAAA,QAAS,GAAA,CAAI,KAAA,CAAM,CAAC,IAAI,CAAA;AAEhD,EAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,CAAC,MAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAM,CAAA;AAC7C,EAAA,OAAO,OAAA,CAAQ,WAAW,IAAA,GAAQ,MAAA,CAAO,OAAO,GAAA,EAAK,EAAE,SAAA,EAAW,CAAA,GAAY,GAAA;AAChF","file":"persistence.js","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, openSync, rmSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — another process already holds the writer lease for this session.\n *\n * Carries `sessionPath` because knowing WHICH session is busy is what lets the caller decide between\n * forking and waiting for the user to close the TUI (`rules/error-handling.md § 2` — context enough\n * to act on).\n */\nexport class SessionBusyError extends TheokitAgentError {\n override readonly name = \"SessionBusyError\";\n\n constructor(readonly sessionPath: string) {\n super(\n `another process is already writing this session: ${sessionPath}. ` +\n \"Fork it to a new id instead of appending — two writers interleave lines into a sequence \" +\n \"that parses but is not what either process wrote.\",\n { code: \"session_busy\", isRetryable: false },\n );\n }\n}\n\n/** A held writer lease. `release()` is idempotent. */\nexport interface SessionWriterLease {\n readonly sessionPath: string;\n release(): Promise<void>;\n}\n\n/**\n * Take the exclusive writer lease for `sessionPath`, or reject with {@link SessionBusyError}.\n *\n * The lock is a sibling `.lock` file created with `wx` — the same file-existence primitive the\n * SDK's `withFileLock` builds on. Exclusivity comes from the filesystem, so it holds across\n * processes, not just across async tasks in one process.\n */\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n const lockPath = `${sessionPath}.lock`;\n let fd: number;\n try {\n fd = openSync(lockPath, \"wx\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new SessionBusyError(sessionPath);\n }\n throw err;\n }\n closeSync(fd);\n\n let released = false;\n return {\n sessionPath,\n release: async (): Promise<void> => {\n if (released) return;\n released = true;\n rmSync(lockPath, { force: true });\n },\n };\n}\n","/**\n * M81 — transcript operations the consumer was doing by hand INSIDE the framework's own store.\n *\n * ## What this replaces\n *\n * `agents/lib/session/backtrack.ts:188` (agent-builder) wrote straight into the session store with a\n * bare `writeFileSync` — no atomicity, no lock, no API. 243 lines re-implementing parse, cut and\n * write for a format the framework owns. The consumer is not at fault: nothing here was reachable.\n *\n * ## The rule that travels WITH the operation\n *\n * `rules/audit-trail-rotation.md § Session transcripts (M60)` defines a NEVER-delete list — the live\n * pointer, the most recent transcript, and any active registry entry. That rule lived in the\n * CONSUMER. Moving the operation here without moving the rule would ship an API able to destroy\n * exactly what the rule protects — the same shape of defect as M80's `reconcileUpdateGoalStatus`:\n * critical knowledge outside the module that needs it, applied by convention.\n *\n * So `forkTranscript` takes `liveSessionPaths` and refuses, with a TYPED error, to write over any of\n * them. The caller supplies the list because only the caller knows which session is live; the\n * enforcement lives here because that is where the write happens.\n *\n * @internal\n */\n\nimport { closeSync, openSync, readFileSync, readSync, statSync, writeSync } from \"node:fs\";\n\nimport { TheokitAgentError } from \"../../errors.js\";\n\n/**\n * M81 — the target is a protected session (live pointer / most-recent transcript / active entry).\n *\n * Typed rather than a bare `Error` because the caller must distinguish \"this session is protected\"\n * from \"the disk is full\": the first is a correct refusal, the second is an incident.\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n\n constructor(readonly path: string) {\n super(\n `refusing to write over a live session transcript: ${path}. ` +\n \"Fork to a new id instead — the live pointer, the most recent transcript and any active \" +\n \"registry entry are never overwritten (audit-trail rotation, M60).\",\n { code: \"live_session_protected\", isRetryable: false },\n );\n }\n}\n\n/** Options for {@link forkTranscript}. */\nexport interface ForkTranscriptOptions {\n /** Keep records `[0, beforeRecordIndex)`. Omit to copy the whole transcript. */\n readonly beforeRecordIndex?: number;\n /**\n * Paths that must never be written over — the live pointer, the most recent transcript, any active\n * registry entry. The caller supplies them because only the caller knows which session is live.\n */\n readonly liveSessionPaths?: readonly string[];\n}\n\n/**\n * Copy `src` into `dst`, keeping the first `beforeRecordIndex` records. The SOURCE is never touched.\n *\n * Atomicity comes from `wx` (exclusive create): two concurrent forks to the same destination cannot\n * both succeed — the loser gets `EEXIST` rather than writing over a half-written file. That is also\n * why an existing destination is a refusal, not a silent overwrite: losing a transcript without an\n * error is the worst failure mode for an operation that touches user sessions.\n */\nexport function forkTranscript(\n src: string,\n dst: string,\n options: ForkTranscriptOptions = {},\n): void {\n for (const live of options.liveSessionPaths ?? []) {\n if (live === dst) throw new LiveSessionError(dst);\n }\n\n const lines = readFileSync(src, \"utf8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n const kept =\n options.beforeRecordIndex === undefined ? lines : lines.slice(0, options.beforeRecordIndex);\n const body = kept.length > 0 ? `${kept.join(\"\\n\")}\\n` : \"\";\n\n // `wx` — fails with EEXIST instead of truncating. The exclusivity IS the concurrency guarantee.\n const fd = openSync(dst, \"wx\");\n try {\n writeSync(fd, body);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Options for {@link readJsonlTail}. */\nexport interface ReadJsonlTailOptions {\n /** Maximum records to return, counted from the END. */\n readonly maxRecords?: number;\n /** Stop once a line contains this marker (exclusive). */\n readonly sinceMarker?: string;\n /** Test-only: also report how many bytes were read, to prove the read is not whole-file. */\n readonly _stats?: boolean;\n}\n\nconst TAIL_CHUNK = 64 * 1024;\n\n/**\n * Lê chunks de trás para frente até acumular linhas completas suficientes.\n *\n * Extraído de `readJsonlTail` porque o laço de leitura e a seleção de registros são duas\n * responsabilidades — e juntas passavam do teto de complexidade. A primeira linha do buffer pode\n * estar cortada ao meio quando a leitura parou antes do início do arquivo; por isso ela é descartada.\n */\nfunction lerCaudaBruta(path: string, want: number): { linhas: string[]; bytesRead: number } {\n const size = statSync(path).size;\n const fd = openSync(path, \"r\");\n let bytesRead = 0;\n let tail = \"\";\n let pos = size;\n try {\n while (pos > 0) {\n const len = Math.min(TAIL_CHUNK, pos);\n pos -= len;\n const buf = Buffer.alloc(len);\n readSync(fd, buf, 0, len, pos);\n bytesRead += len;\n tail = buf.toString(\"utf8\") + tail;\n if (naoVazias(tail).length > want) break;\n }\n } finally {\n closeSync(fd);\n }\n const linhas = naoVazias(tail);\n return { linhas: pos > 0 ? linhas.slice(1) : linhas, bytesRead };\n}\n\n/** Linhas com conteúdo, na ordem do arquivo. */\nfunction naoVazias(texto: string): string[] {\n return texto.split(\"\\n\").filter((l) => l.trim().length > 0);\n}\n\n/**\n * Read the LAST records of a JSONL file without loading the whole thing.\n *\n * Reads fixed-size chunks backwards from EOF until enough newlines have been seen. A session\n * transcript grows without bound; loading megabytes to show the last three turns is the cost this\n * exists to avoid — and a `slice` over a full read would be that same cost with a better name.\n */\nexport function readJsonlTail<T = Record<string, unknown>>(\n path: string,\n options: ReadJsonlTailOptions = {},\n): T[] {\n const want = options.maxRecords ?? Number.POSITIVE_INFINITY;\n const { linhas, bytesRead } = lerCaudaBruta(path, want);\n\n let sel = linhas;\n if (options.sinceMarker !== undefined) {\n const marcador = options.sinceMarker;\n const idx = sel.findLastIndex((l) => l.includes(marcador));\n if (idx >= 0) sel = sel.slice(idx + 1);\n }\n if (Number.isFinite(want)) sel = sel.slice(-want);\n\n const out = sel.map((l) => JSON.parse(l) as T);\n return options._stats === true ? (Object.assign(out, { bytesRead }) as T[]) : out;\n}\n"]}
@@ -376,6 +376,14 @@ interface ModelParameterValue {
376
376
  interface ModelSelection {
377
377
  id: string;
378
378
  params?: ModelParameterValue[];
379
+ /**
380
+ * M94 — janela de contexto do modelo, em tokens. Vira o `override` do resolvedor de janela.
381
+ *
382
+ * Existe para modelos SEM entrada de catálogo: sem ela, um modelo de 400k era orçado contra o
383
+ * piso de 128k e compactava ~3× mais do que precisava. Um valor acima do que o catálogo conhece
384
+ * é clampeado — declarar 10M não estoura o provider.
385
+ */
386
+ contextWindow?: number;
379
387
  }
380
388
  /**
381
389
  * SE12 — a read-only, text-only projection of one turn of the run's conversation,
@@ -376,6 +376,14 @@ interface ModelParameterValue {
376
376
  interface ModelSelection {
377
377
  id: string;
378
378
  params?: ModelParameterValue[];
379
+ /**
380
+ * M94 — janela de contexto do modelo, em tokens. Vira o `override` do resolvedor de janela.
381
+ *
382
+ * Existe para modelos SEM entrada de catálogo: sem ela, um modelo de 400k era orçado contra o
383
+ * piso de 128k e compactava ~3× mais do que precisava. Um valor acima do que o catálogo conhece
384
+ * é clampeado — declarar 10M não estoura o provider.
385
+ */
386
+ contextWindow?: number;
379
387
  }
380
388
  /**
381
389
  * SE12 — a read-only, text-only projection of one turn of the run's conversation,
@@ -1,6 +1,6 @@
1
- import { T as TheokitAgentError } from '../errors-BdL-buYn.cjs';
2
- export { M as MemoryAdapterError } from '../errors-BdL-buYn.cjs';
3
- import '../run-OJbGyweZ.cjs';
1
+ import { T as TheokitAgentError } from '../errors-DyVbXdR4.cjs';
2
+ export { M as MemoryAdapterError } from '../errors-DyVbXdR4.cjs';
3
+ import '../run-CwEJtLPE.cjs';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { T as TheokitAgentError } from '../errors-DHZtSNnj.js';
2
- export { M as MemoryAdapterError } from '../errors-DHZtSNnj.js';
3
- import '../run-OJbGyweZ.js';
1
+ import { T as TheokitAgentError } from '../errors-Cua4WC9H.js';
2
+ export { M as MemoryAdapterError } from '../errors-Cua4WC9H.js';
3
+ import '../run-CwEJtLPE.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,5 +1,5 @@
1
- export { SessionTranscript, defaultBaseDir, encodeProjectDir, expandTilde, readTranscript, reconstructMessages, safeSessionId, transcriptPath, writeTranscript } from './chunk-ZZWTY3RX.js';
1
+ export { SessionTranscript, defaultBaseDir, encodeProjectDir, expandTilde, readTranscript, reconstructMessages, safeSessionId, transcriptPath, transcriptRoot, writeTranscript } from './chunk-VGUOUAM2.js';
2
2
  import './chunk-S2BBRVQX.js';
3
3
  import './chunk-JTFYYKDT.js';
4
- //# sourceMappingURL=session-transcript-T7LGJUGW.js.map
5
- //# sourceMappingURL=session-transcript-T7LGJUGW.js.map
4
+ //# sourceMappingURL=session-transcript-5VZUWEJ5.js.map
5
+ //# sourceMappingURL=session-transcript-5VZUWEJ5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"session-transcript-T7LGJUGW.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"session-transcript-5VZUWEJ5.js"}
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ var chunkU2FO3MRG_cjs = require('./chunk-U2FO3MRG.cjs');
4
+ require('./chunk-TIZ4TS5V.cjs');
5
+ require('./chunk-BEURCLDV.cjs');
6
+
7
+
8
+
9
+ Object.defineProperty(exports, "SessionTranscript", {
10
+ enumerable: true,
11
+ get: function () { return chunkU2FO3MRG_cjs.SessionTranscript; }
12
+ });
13
+ Object.defineProperty(exports, "defaultBaseDir", {
14
+ enumerable: true,
15
+ get: function () { return chunkU2FO3MRG_cjs.defaultBaseDir; }
16
+ });
17
+ Object.defineProperty(exports, "encodeProjectDir", {
18
+ enumerable: true,
19
+ get: function () { return chunkU2FO3MRG_cjs.encodeProjectDir; }
20
+ });
21
+ Object.defineProperty(exports, "expandTilde", {
22
+ enumerable: true,
23
+ get: function () { return chunkU2FO3MRG_cjs.expandTilde; }
24
+ });
25
+ Object.defineProperty(exports, "readTranscript", {
26
+ enumerable: true,
27
+ get: function () { return chunkU2FO3MRG_cjs.readTranscript; }
28
+ });
29
+ Object.defineProperty(exports, "reconstructMessages", {
30
+ enumerable: true,
31
+ get: function () { return chunkU2FO3MRG_cjs.reconstructMessages; }
32
+ });
33
+ Object.defineProperty(exports, "safeSessionId", {
34
+ enumerable: true,
35
+ get: function () { return chunkU2FO3MRG_cjs.safeSessionId; }
36
+ });
37
+ Object.defineProperty(exports, "transcriptPath", {
38
+ enumerable: true,
39
+ get: function () { return chunkU2FO3MRG_cjs.transcriptPath; }
40
+ });
41
+ Object.defineProperty(exports, "transcriptRoot", {
42
+ enumerable: true,
43
+ get: function () { return chunkU2FO3MRG_cjs.transcriptRoot; }
44
+ });
45
+ Object.defineProperty(exports, "writeTranscript", {
46
+ enumerable: true,
47
+ get: function () { return chunkU2FO3MRG_cjs.writeTranscript; }
48
+ });
49
+ //# sourceMappingURL=session-transcript-T4SB66I7.cjs.map
50
+ //# sourceMappingURL=session-transcript-T4SB66I7.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"session-transcript-LPNZR3YS.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"session-transcript-T4SB66I7.cjs"}
@@ -1,5 +1,5 @@
1
- import { a as AgentDefinition } from './agent-Bzg2_uGr.cjs';
2
- import './run-OJbGyweZ.cjs';
1
+ import { a as AgentDefinition } from './agent-CbZPGFfM.cjs';
2
+ import './run-CwEJtLPE.cjs';
3
3
  import 'zod';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { a as AgentDefinition } from './agent-Ekv8y7_c.js';
2
- import './run-OJbGyweZ.js';
1
+ import { a as AgentDefinition } from './agent-BJbGi8-R.js';
2
+ import './run-CwEJtLPE.js';
3
3
  import 'zod';
4
4
 
5
5
  /**
@@ -29,6 +29,14 @@ export interface ModelParameterValue {
29
29
  export interface ModelSelection {
30
30
  id: string;
31
31
  params?: ModelParameterValue[];
32
+ /**
33
+ * M94 — janela de contexto do modelo, em tokens. Vira o `override` do resolvedor de janela.
34
+ *
35
+ * Existe para modelos SEM entrada de catálogo: sem ela, um modelo de 400k era orçado contra o
36
+ * piso de 128k e compactava ~3× mais do que precisava. Um valor acima do que o catálogo conhece
37
+ * é clampeado — declarar 10M não estoura o provider.
38
+ */
39
+ contextWindow?: number;
32
40
  }
33
41
  /**
34
42
  * SE12 — a read-only, text-only projection of one turn of the run's conversation,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "4.30.0",
3
+ "version": "4.31.1",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheodev/theokit-sdk#readme",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":["readTranscript","transcriptPath","path","mkdir","dirname","withFileLock","writeTranscript"],"mappings":";;;;;;;AA6CO,IAAM,iBAAN,MAA6C;AAAA,EACzC,QAAA;AAAA,EACA,IAAA;AAAA,EAET,YAAY,OAAA,EAAgC;AAC1C,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,GAAA;AAAA,EACtB;AAAA,EAEA,MAAM,YAAY,OAAA,EAA2C;AAC3D,IAAA,OAAOA,iCAAeC,gCAAA,CAAe,IAAA,CAAK,UAAU,IAAA,CAAK,IAAA,EAAM,OAAO,CAAC,CAAA;AAAA,EACzE;AAAA,EAEA,MAAM,aAAA,CAAc,OAAA,EAAiB,OAAA,EAAkD;AAErF,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAMC,SAAOD,gCAAA,CAAe,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,MAAM,OAAO,CAAA;AAE7D,IAAA,MAAME,eAAMC,YAAA,CAAQF,MAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAMG,8BAAA,CAAaH,QAAM,YAAY;AACnC,MAAA,MAAM,KAAA,GAAQ,MAAMF,gCAAA,CAAeE,MAAI,CAAA;AACvC,MAAA,MAAMI,kCAAgBJ,MAAA,EAAM,CAAC,GAAG,KAAA,EAAO,GAAG,OAAO,CAAC,CAAA;AAAA,IACpD,CAAC,CAAA;AAAA,EACH;AACF","file":"chunk-2HRYBRD7.cjs","sourcesContent":["/**\n * SE41 — `FsSessionStore`, the DEFAULT reference implementation of the pluggable\n * {@link SessionStore} seam. It reads and append-writes the native Claude-shaped\n * `.jsonl` transcript at `<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl` — the\n * exact on-disk format SE40 introduced (the file the Claude Code CLI can\n * `--continue`). Omitting `local.sessionStore` resolves to this store, so the\n * default persistence path is byte-identical to SE40 behavior.\n *\n * `readRecords` is `readTranscript(transcriptPath(...))` (a missing session →\n * `[]`, not an error — a fresh agent has no history). `appendRecords` is a TRUE\n * append: it reads the prior records, concatenates the new-turn delta, and\n * rewrites the whole line set atomically under the SE40 cross-process file lock\n * (`writeTranscript` never shrinks — the native format is an append-only\n * `parentUuid` DAG). The parent dir is created BEFORE acquiring the lock because\n * the lock's companion `<path>.lock` file needs an existing parent dir (the SE40\n * `mkdir(dirname)`-before-lock fix).\n *\n * @internal\n */\n\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport {\n readTranscript,\n type SessionRecord,\n transcriptPath,\n writeTranscript,\n} from \"./session-transcript.js\";\n\n/** Options identifying the on-disk transcript location for the FS default store. */\nexport interface FsSessionStoreOptions {\n /** Transcript base dir (`~/.theokit` default, `~/.claude` for CLI interop) — already `~`-expanded. */\n baseDir: string;\n /** The workspace cwd whose encoded form is the transcript project dir. */\n cwd: string;\n}\n\n/**\n * The default `SessionStore` — reads/append-writes the native `.jsonl` transcript.\n *\n * @internal\n */\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n\n constructor(options: FsSessionStoreOptions) {\n this.#baseDir = options.baseDir;\n this.#cwd = options.cwd;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n return readTranscript(transcriptPath(this.#baseDir, this.#cwd, agentId));\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n // Empty delta → nothing to persist (avoids an unnecessary lock + rewrite).\n if (records.length === 0) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n // mkdir BEFORE the lock: withFileLock's companion `<path>.lock` needs the parent dir.\n await mkdir(dirname(path), { recursive: true });\n await withFileLock(path, async () => {\n const prior = await readTranscript(path);\n await writeTranscript(path, [...prior, ...records]);\n });\n }\n}\n"]}