@theokit/sdk 4.31.0 → 4.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/dist/{agent-Bzg2_uGr.d.cts → agent-DGv1-d81.d.cts} +52 -2
- package/dist/{agent-6GQBOHHA.cjs → agent-ES57DGAT.cjs} +9 -9
- package/dist/{agent-6GQBOHHA.cjs.map → agent-ES57DGAT.cjs.map} +1 -1
- package/dist/{agent-DY5LGZ5E.js → agent-FBFPSBTX.js} +8 -8
- package/dist/{agent-DY5LGZ5E.js.map → agent-FBFPSBTX.js.map} +1 -1
- package/dist/{agent-Ekv8y7_c.d.ts → agent-SmxntivO.d.ts} +52 -2
- package/dist/{chunk-VUXLNVX7.js → chunk-334WDVFZ.js} +4 -4
- package/dist/{chunk-VUXLNVX7.js.map → chunk-334WDVFZ.js.map} +1 -1
- package/dist/{chunk-WQEQCJTZ.cjs → chunk-CJVMDRQB.cjs} +26 -3
- package/dist/chunk-CJVMDRQB.cjs.map +1 -0
- package/dist/{chunk-UKNMWCPZ.cjs → chunk-CVSNCUBU.cjs} +133 -70
- package/dist/chunk-CVSNCUBU.cjs.map +1 -0
- package/dist/{chunk-4SXHEZIV.cjs → chunk-DQSILMWU.cjs} +9 -3
- package/dist/chunk-DQSILMWU.cjs.map +1 -0
- package/dist/{chunk-PORDVVJS.js → chunk-EIPSZ4GA.js} +4 -4
- package/dist/chunk-EIPSZ4GA.js.map +1 -0
- package/dist/{chunk-4JWZRASX.js → chunk-HBTEK5LK.js} +3 -3
- package/dist/{chunk-4JWZRASX.js.map → chunk-HBTEK5LK.js.map} +1 -1
- package/dist/{chunk-U447MTG4.cjs → chunk-HCXDDR6P.cjs} +8 -8
- package/dist/chunk-HCXDDR6P.cjs.map +1 -0
- package/dist/{chunk-XJT5VACT.cjs → chunk-I4QDIQ45.cjs} +6 -6
- package/dist/{chunk-XJT5VACT.cjs.map → chunk-I4QDIQ45.cjs.map} +1 -1
- package/dist/{chunk-CYTAM3E6.cjs → chunk-JPG7NMNH.cjs} +75 -58
- package/dist/chunk-JPG7NMNH.cjs.map +1 -0
- package/dist/{chunk-FZ75EZR5.js → chunk-NI4PAMJQ.js} +45 -28
- package/dist/chunk-NI4PAMJQ.js.map +1 -0
- package/dist/{chunk-FDGRQQWX.cjs → chunk-OQX2DG36.cjs} +5 -5
- package/dist/{chunk-FDGRQQWX.cjs.map → chunk-OQX2DG36.cjs.map} +1 -1
- package/dist/{chunk-TLG444A6.js → chunk-SQVQH4EK.js} +130 -67
- package/dist/chunk-SQVQH4EK.js.map +1 -0
- package/dist/{chunk-ICSCKB3N.js → chunk-UAYYNWYJ.js} +27 -4
- package/dist/chunk-UAYYNWYJ.js.map +1 -0
- package/dist/{chunk-ZZWTY3RX.js → chunk-WPBTPSKQ.js} +9 -4
- package/dist/chunk-WPBTPSKQ.js.map +1 -0
- package/dist/{compact-session-2BFNMENR.cjs → compact-session-OKXLKJIS.cjs} +12 -12
- package/dist/{compact-session-2BFNMENR.cjs.map → compact-session-OKXLKJIS.cjs.map} +1 -1
- package/dist/{compact-session-2JONXHLR.js → compact-session-UHGMWPMW.js} +4 -4
- package/dist/{compact-session-2JONXHLR.js.map → compact-session-UHGMWPMW.js.map} +1 -1
- package/dist/{cron-CjzvXGT2.d.cts → cron-BiK_aNJI.d.cts} +2 -2
- package/dist/{cron-D0Z29gI-.d.ts → cron-Dx7B-3WB.d.ts} +2 -2
- package/dist/cron.cjs +8 -8
- package/dist/cron.d.cts +3 -3
- package/dist/cron.d.ts +3 -3
- package/dist/cron.js +7 -7
- package/dist/{errors-DHZtSNnj.d.ts → errors-Cua4WC9H.d.ts} +1 -1
- package/dist/{errors-BdL-buYn.d.cts → errors-DyVbXdR4.d.cts} +1 -1
- package/dist/errors.d.cts +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/eval.cjs +11 -11
- package/dist/eval.js +7 -7
- package/dist/fs-session-store-2J5JOXC2.js +8 -0
- package/dist/{fs-session-store-7AEI4STY.js.map → fs-session-store-2J5JOXC2.js.map} +1 -1
- package/dist/fs-session-store-DNAJ6RQG.cjs +17 -0
- package/dist/{fs-session-store-26WVVMC4.cjs.map → fs-session-store-DNAJ6RQG.cjs.map} +1 -1
- package/dist/index.cjs +50 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -8
- package/dist/index.d.ts +23 -8
- package/dist/index.js +30 -10
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-MIFEKATN.cjs → inject-session-24FJ65LP.cjs} +6 -6
- package/dist/{inject-session-MIFEKATN.cjs.map → inject-session-24FJ65LP.cjs.map} +1 -1
- package/dist/{inject-session-NNSCCIVP.js → inject-session-JXQO33T3.js} +4 -4
- package/dist/{inject-session-NNSCCIVP.js.map → inject-session-JXQO33T3.js.map} +1 -1
- package/dist/internal/llm/abort-error.d.ts +1 -0
- package/dist/internal/llm/retrying-client.d.ts +27 -3
- package/dist/internal/llm/transport-error.d.ts +9 -0
- package/dist/internal/persistence/index.cjs +6 -6
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/persistence/session-transcript.d.cts +13 -1
- package/dist/internal/persistence/session-transcript.d.ts +13 -1
- package/dist/internal/runtime/lifecycle/post-run-lifecycle.d.ts +1 -1
- package/dist/persistence.cjs +13 -9
- package/dist/persistence.d.cts +2 -1
- package/dist/persistence.d.ts +2 -1
- package/dist/persistence.js +2 -2
- package/dist/{run-OJbGyweZ.d.ts → run-CwEJtLPE.d.cts} +8 -0
- package/dist/{run-OJbGyweZ.d.cts → run-CwEJtLPE.d.ts} +8 -0
- package/dist/server/errors-envelope.d.cts +3 -3
- package/dist/server/errors-envelope.d.ts +3 -3
- package/dist/session-transcript-F5OXXO6G.cjs +50 -0
- package/dist/{session-transcript-LPNZR3YS.cjs.map → session-transcript-F5OXXO6G.cjs.map} +1 -1
- package/dist/{session-transcript-T7LGJUGW.js → session-transcript-QS6CXHHD.js} +3 -3
- package/dist/{session-transcript-T7LGJUGW.js.map → session-transcript-QS6CXHHD.js.map} +1 -1
- package/dist/subagents-loader.d.cts +2 -2
- package/dist/subagents-loader.d.ts +2 -2
- package/dist/types/agent-prims.d.ts +8 -0
- package/dist/types/session-record.d.ts +51 -1
- package/package.json +1 -1
- package/dist/chunk-4SXHEZIV.cjs.map +0 -1
- package/dist/chunk-CYTAM3E6.cjs.map +0 -1
- package/dist/chunk-FZ75EZR5.js.map +0 -1
- package/dist/chunk-ICSCKB3N.js.map +0 -1
- package/dist/chunk-PORDVVJS.js.map +0 -1
- package/dist/chunk-TLG444A6.js.map +0 -1
- package/dist/chunk-U447MTG4.cjs.map +0 -1
- package/dist/chunk-UKNMWCPZ.cjs.map +0 -1
- package/dist/chunk-WQEQCJTZ.cjs.map +0 -1
- package/dist/chunk-ZZWTY3RX.js.map +0 -1
- package/dist/fs-session-store-26WVVMC4.cjs +0 -17
- package/dist/fs-session-store-7AEI4STY.js +0 -8
- package/dist/session-transcript-LPNZR3YS.cjs +0 -46
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.32.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- M94 — publica quatro resolvedores que o SDK já conhecia internamente.
|
|
8
|
+
|
|
9
|
+
- **`transcriptRoot()` é exportado e honra `THEOKIT_HOME`.** Antes, a raiz do transcript ignorava a variável enquanto os stores irmãos a respeitavam: quem a definia tinha o estado partido em dois em silêncio, e as sessões antigas sumiam da listagem sem erro. O fallback continua sendo `~/.theokit` — deliberadamente **não** o resolvedor cwd-ancorado de `paths.ts`, cuja troca moveria o transcript de quem **não** define a variável.
|
|
10
|
+
- **`ModelSelection.contextWindow` atravessa até o orçamento de compactação.** O resolvedor aceitava um `override` desde a versão anterior e nenhum caminho de produção o passava: um modelo de 400k sem entrada de catálogo era orçado contra o piso de 128k e compactava cerca de três vezes mais do que precisava. Um valor acima do que o catálogo conhece continua sendo limitado.
|
|
11
|
+
- **`SessionRecord.message` deixa de ser `Record<string, unknown>`.** O novo `TranscriptMessage` descreve a forma que o escritor sempre produziu. **Não** se chama `SessionMessage`: esse nome já existe com forma incompatível, e reaproveitá-lo repetiria uma quebra silenciosa anterior. A leitura do disco segue tolerante — o que muda é o tipo.
|
|
12
|
+
- **`Provider.forModel(modelId)`** dá um dono único à gramática `provider/modelo`. Um id sem barra devolve `undefined` em vez de casar parcialmente, para que quem chama possa distinguir "modelo não-roteável" de "caminho default".
|
|
13
|
+
|
|
14
|
+
Nota de rótulo: `4.31.1` já continha, por engano, parte destas adições — foi publicado como patch quando o correto era minor. Nada quebra (adições são compatíveis), e esta versão declara a superfície corretamente.
|
|
15
|
+
|
|
16
|
+
## 4.31.1
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- M93 — oito correções da revisão adversarial.
|
|
21
|
+
|
|
22
|
+
- **O retry deixa de reexecutar um stream já parcialmente consumido.** Uma falha depois do primeiro evento reexecutava o turno inteiro, duplicando texto e blocos `tool_use` — exatamente no cenário que motivou o retry (429 depois de várias tool calls).
|
|
23
|
+
- **O transcript volta a nascer `0600`.** A troca para append incremental perdeu o modo explícito e, sob `umask 022`, o arquivo — que carrega conteúdo em trânsito — nascia legível por outros.
|
|
24
|
+
- **Um append sobre arquivo truncado por crash não engole mais o registro novo.**
|
|
25
|
+
- **Erro transitório passa a ser decidido pelo status estruturado, não pelo texto da mensagem.** A heurística anterior classificava `ECONNREFUSED …:443` como não-transitório porque a porta casava o padrão de "4xx": o retry ficava desligado justamente para falha de rede.
|
|
26
|
+
- **Falha de socket passa a ser tipada nos transportes Anthropic e OpenAI.** Sem isso, o erro cru escapava e nenhuma política de retry o reconhecia.
|
|
27
|
+
- **`CredentialPoolExhaustedError` e circuito aberto deixam de ser reexecutados.** O pool já gastou o próprio orçamento; reexecutar por cima triplicava a espera e desfazia o fail-fast do circuit breaker.
|
|
28
|
+
- Cancelamento (`AbortError`) nunca é confundido com falha de rede.
|
|
29
|
+
|
|
3
30
|
## 4.31.0
|
|
4
31
|
|
|
5
32
|
### Minor Changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as ModelSelection, ac as SDKUserMessage, ae as SendOptions, b as Run, G as GenerateOptions, n as GenerateRunResult, _ as RunToCompletionOptions, $ as RunToCompletionResult, S as SDKMessage, al as StreamToCompletionResult, C as CustomTool, c as PermissionMode, a as McpServerConfig, P as Processor } from './run-
|
|
1
|
+
import { M as ModelSelection, ac as SDKUserMessage, ae as SendOptions, b as Run, G as GenerateOptions, n as GenerateRunResult, _ as RunToCompletionOptions, $ as RunToCompletionResult, S as SDKMessage, al as StreamToCompletionResult, C as CustomTool, c as PermissionMode, a as McpServerConfig, P as Processor } from './run-CwEJtLPE.cjs';
|
|
2
2
|
import * as zod from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -16,6 +16,49 @@ import * as zod from 'zod';
|
|
|
16
16
|
* @public
|
|
17
17
|
*/
|
|
18
18
|
/** One transcript record (one JSONL line). `message` absent on `system` (compact_boundary) records. */
|
|
19
|
+
/** Um bloco de conteúdo dentro de {@link TranscriptMessage}. */
|
|
20
|
+
type TranscriptBlock = {
|
|
21
|
+
type: "text";
|
|
22
|
+
text: string;
|
|
23
|
+
} | {
|
|
24
|
+
type: "thinking";
|
|
25
|
+
thinking?: string;
|
|
26
|
+
signature?: string;
|
|
27
|
+
} | {
|
|
28
|
+
type: "tool_use";
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
input: unknown;
|
|
32
|
+
} | {
|
|
33
|
+
type: "tool_result";
|
|
34
|
+
tool_use_id: string;
|
|
35
|
+
content: unknown;
|
|
36
|
+
is_error?: boolean;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* O corpo de mensagem de um {@link SessionRecord}.
|
|
40
|
+
*
|
|
41
|
+
* **NÃO se chama `SessionMessage`** — esse nome já existe em `internal/session/session-types.ts` com
|
|
42
|
+
* a forma `{role, text}`, incompatível com esta. Repropor um nome exportado com forma nova é
|
|
43
|
+
* precisamente a quebra silenciosa que o M91 custou dois patches para desfazer.
|
|
44
|
+
*
|
|
45
|
+
* O parse do disco continua **tolerante** (`readTranscript` pula linha malformada): o que muda aqui
|
|
46
|
+
* é o **tipo**, não a leniência — registros gravados por versões anteriores continuam legíveis.
|
|
47
|
+
*
|
|
48
|
+
* @public
|
|
49
|
+
*/
|
|
50
|
+
interface TranscriptMessage {
|
|
51
|
+
role: "user" | "assistant";
|
|
52
|
+
content: TranscriptBlock[];
|
|
53
|
+
/**
|
|
54
|
+
* Os três campos abaixo aparecem **só** no registro de assistant, e vêm do escritor
|
|
55
|
+
* (`SessionTranscript.appendAssistant`). Declarados opcionais porque o registro de user não os
|
|
56
|
+
* tem — medido no próprio escritor, não presumido.
|
|
57
|
+
*/
|
|
58
|
+
id?: string;
|
|
59
|
+
type?: "message";
|
|
60
|
+
model?: string;
|
|
61
|
+
}
|
|
19
62
|
interface SessionRecord {
|
|
20
63
|
type: "user" | "assistant" | "system";
|
|
21
64
|
uuid: string;
|
|
@@ -31,7 +74,14 @@ interface SessionRecord {
|
|
|
31
74
|
preTokens: number;
|
|
32
75
|
trigger: string;
|
|
33
76
|
};
|
|
34
|
-
|
|
77
|
+
/**
|
|
78
|
+
* O corpo da mensagem, na forma que o escritor de transcript de fato grava.
|
|
79
|
+
*
|
|
80
|
+
* M94 — era `Record<string, unknown>`, e o consumidor recuperava o tipo com cast a cada leitura.
|
|
81
|
+
* A forma **sempre foi fixa** (`SessionTranscript.appendToolResults` / `#push` a produzem); só não
|
|
82
|
+
* estava declarada. Segue opcional porque registros de sistema não carregam mensagem.
|
|
83
|
+
*/
|
|
84
|
+
message?: TranscriptMessage;
|
|
35
85
|
}
|
|
36
86
|
|
|
37
87
|
/**
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkJPG7NMNH_cjs = require('./chunk-JPG7NMNH.cjs');
|
|
4
4
|
require('./chunk-BV2MWEMV.cjs');
|
|
5
5
|
require('./chunk-MZ5ZRORA.cjs');
|
|
6
|
-
require('./chunk-
|
|
6
|
+
require('./chunk-I4QDIQ45.cjs');
|
|
7
7
|
require('./chunk-BUUUWQMB.cjs');
|
|
8
|
-
require('./chunk-
|
|
9
|
-
require('./chunk-
|
|
8
|
+
require('./chunk-HCXDDR6P.cjs');
|
|
9
|
+
require('./chunk-CVSNCUBU.cjs');
|
|
10
10
|
require('./chunk-LUSXDZPV.cjs');
|
|
11
11
|
require('./chunk-IT3PWBW4.cjs');
|
|
12
12
|
require('./chunk-JLMXKTBX.cjs');
|
|
@@ -21,10 +21,10 @@ require('./chunk-YPEPCZHF.cjs');
|
|
|
21
21
|
require('./chunk-VJ26EKGJ.cjs');
|
|
22
22
|
require('./chunk-GIW4L6HY.cjs');
|
|
23
23
|
require('./chunk-7S7KKUO6.cjs');
|
|
24
|
-
require('./chunk-
|
|
24
|
+
require('./chunk-CJVMDRQB.cjs');
|
|
25
25
|
require('./chunk-JD74LN7R.cjs');
|
|
26
26
|
require('./chunk-YLQQX5W2.cjs');
|
|
27
|
-
require('./chunk-
|
|
27
|
+
require('./chunk-DQSILMWU.cjs');
|
|
28
28
|
require('./chunk-ANIZEWTU.cjs');
|
|
29
29
|
require('./chunk-WJVHMTKB.cjs');
|
|
30
30
|
require('./chunk-TIZ4TS5V.cjs');
|
|
@@ -44,7 +44,7 @@ require('./chunk-BEURCLDV.cjs');
|
|
|
44
44
|
|
|
45
45
|
Object.defineProperty(exports, "Agent", {
|
|
46
46
|
enumerable: true,
|
|
47
|
-
get: function () { return
|
|
47
|
+
get: function () { return chunkJPG7NMNH_cjs.Agent; }
|
|
48
48
|
});
|
|
49
|
-
//# sourceMappingURL=agent-
|
|
50
|
-
//# sourceMappingURL=agent-
|
|
49
|
+
//# sourceMappingURL=agent-ES57DGAT.cjs.map
|
|
50
|
+
//# sourceMappingURL=agent-ES57DGAT.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-ES57DGAT.cjs"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export { Agent } from './chunk-
|
|
1
|
+
export { Agent } from './chunk-NI4PAMJQ.js';
|
|
2
2
|
import './chunk-2SFBB54R.js';
|
|
3
3
|
import './chunk-HRA3CPGG.js';
|
|
4
|
-
import './chunk-
|
|
4
|
+
import './chunk-334WDVFZ.js';
|
|
5
5
|
import './chunk-K2BQQ445.js';
|
|
6
|
-
import './chunk-
|
|
7
|
-
import './chunk-
|
|
6
|
+
import './chunk-EIPSZ4GA.js';
|
|
7
|
+
import './chunk-SQVQH4EK.js';
|
|
8
8
|
import './chunk-6CLRANZA.js';
|
|
9
9
|
import './chunk-EEZ7CFMM.js';
|
|
10
10
|
import './chunk-XAUBQMQU.js';
|
|
@@ -19,10 +19,10 @@ import './chunk-UJ7IQJAG.js';
|
|
|
19
19
|
import './chunk-7AD3ZTZL.js';
|
|
20
20
|
import './chunk-V4XRLPEF.js';
|
|
21
21
|
import './chunk-5PZMMF4H.js';
|
|
22
|
-
import './chunk-
|
|
22
|
+
import './chunk-UAYYNWYJ.js';
|
|
23
23
|
import './chunk-77FOZCOT.js';
|
|
24
24
|
import './chunk-2XLKLVVR.js';
|
|
25
|
-
import './chunk-
|
|
25
|
+
import './chunk-WPBTPSKQ.js';
|
|
26
26
|
import './chunk-BXV2QUIC.js';
|
|
27
27
|
import './chunk-4VPXM6UU.js';
|
|
28
28
|
import './chunk-S2BBRVQX.js';
|
|
@@ -37,5 +37,5 @@ import './chunk-POQT2OIF.js';
|
|
|
37
37
|
import './chunk-FKCC2MED.js';
|
|
38
38
|
import './chunk-WLKFWQSJ.js';
|
|
39
39
|
import './chunk-JTFYYKDT.js';
|
|
40
|
-
//# sourceMappingURL=agent-
|
|
41
|
-
//# sourceMappingURL=agent-
|
|
40
|
+
//# sourceMappingURL=agent-FBFPSBTX.js.map
|
|
41
|
+
//# sourceMappingURL=agent-FBFPSBTX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-FBFPSBTX.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as ModelSelection, ac as SDKUserMessage, ae as SendOptions, b as Run, G as GenerateOptions, n as GenerateRunResult, _ as RunToCompletionOptions, $ as RunToCompletionResult, S as SDKMessage, al as StreamToCompletionResult, C as CustomTool, c as PermissionMode, a as McpServerConfig, P as Processor } from './run-
|
|
1
|
+
import { M as ModelSelection, ac as SDKUserMessage, ae as SendOptions, b as Run, G as GenerateOptions, n as GenerateRunResult, _ as RunToCompletionOptions, $ as RunToCompletionResult, S as SDKMessage, al as StreamToCompletionResult, C as CustomTool, c as PermissionMode, a as McpServerConfig, P as Processor } from './run-CwEJtLPE.js';
|
|
2
2
|
import * as zod from 'zod';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -16,6 +16,49 @@ import * as zod from 'zod';
|
|
|
16
16
|
* @public
|
|
17
17
|
*/
|
|
18
18
|
/** One transcript record (one JSONL line). `message` absent on `system` (compact_boundary) records. */
|
|
19
|
+
/** Um bloco de conteúdo dentro de {@link TranscriptMessage}. */
|
|
20
|
+
type TranscriptBlock = {
|
|
21
|
+
type: "text";
|
|
22
|
+
text: string;
|
|
23
|
+
} | {
|
|
24
|
+
type: "thinking";
|
|
25
|
+
thinking?: string;
|
|
26
|
+
signature?: string;
|
|
27
|
+
} | {
|
|
28
|
+
type: "tool_use";
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
input: unknown;
|
|
32
|
+
} | {
|
|
33
|
+
type: "tool_result";
|
|
34
|
+
tool_use_id: string;
|
|
35
|
+
content: unknown;
|
|
36
|
+
is_error?: boolean;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* O corpo de mensagem de um {@link SessionRecord}.
|
|
40
|
+
*
|
|
41
|
+
* **NÃO se chama `SessionMessage`** — esse nome já existe em `internal/session/session-types.ts` com
|
|
42
|
+
* a forma `{role, text}`, incompatível com esta. Repropor um nome exportado com forma nova é
|
|
43
|
+
* precisamente a quebra silenciosa que o M91 custou dois patches para desfazer.
|
|
44
|
+
*
|
|
45
|
+
* O parse do disco continua **tolerante** (`readTranscript` pula linha malformada): o que muda aqui
|
|
46
|
+
* é o **tipo**, não a leniência — registros gravados por versões anteriores continuam legíveis.
|
|
47
|
+
*
|
|
48
|
+
* @public
|
|
49
|
+
*/
|
|
50
|
+
interface TranscriptMessage {
|
|
51
|
+
role: "user" | "assistant";
|
|
52
|
+
content: TranscriptBlock[];
|
|
53
|
+
/**
|
|
54
|
+
* Os três campos abaixo aparecem **só** no registro de assistant, e vêm do escritor
|
|
55
|
+
* (`SessionTranscript.appendAssistant`). Declarados opcionais porque o registro de user não os
|
|
56
|
+
* tem — medido no próprio escritor, não presumido.
|
|
57
|
+
*/
|
|
58
|
+
id?: string;
|
|
59
|
+
type?: "message";
|
|
60
|
+
model?: string;
|
|
61
|
+
}
|
|
19
62
|
interface SessionRecord {
|
|
20
63
|
type: "user" | "assistant" | "system";
|
|
21
64
|
uuid: string;
|
|
@@ -31,7 +74,14 @@ interface SessionRecord {
|
|
|
31
74
|
preTokens: number;
|
|
32
75
|
trigger: string;
|
|
33
76
|
};
|
|
34
|
-
|
|
77
|
+
/**
|
|
78
|
+
* O corpo da mensagem, na forma que o escritor de transcript de fato grava.
|
|
79
|
+
*
|
|
80
|
+
* M94 — era `Record<string, unknown>`, e o consumidor recuperava o tipo com cast a cada leitura.
|
|
81
|
+
* A forma **sempre foi fixa** (`SessionTranscript.appendToolResults` / `#push` a produzem); só não
|
|
82
|
+
* estava declarada. Segue opcional porque registros de sistema não carregam mensagem.
|
|
83
|
+
*/
|
|
84
|
+
message?: TranscriptMessage;
|
|
35
85
|
}
|
|
36
86
|
|
|
37
87
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { sessions, transcriptKey, hydratedKeys } from './chunk-EEZ7CFMM.js';
|
|
2
|
-
import { reconstructMessages, SessionTranscript } from './chunk-
|
|
2
|
+
import { reconstructMessages, SessionTranscript } from './chunk-WPBTPSKQ.js';
|
|
3
3
|
|
|
4
4
|
// src/internal/session/agent-session-store.ts
|
|
5
5
|
function seedTranscript(prior, opts) {
|
|
@@ -87,7 +87,7 @@ function persistTurnToTranscript(store, loc, sessionId, turn, onCompact) {
|
|
|
87
87
|
const count = (recordCounts.get(key) ?? 0) + 1;
|
|
88
88
|
recordCounts.set(key, count);
|
|
89
89
|
if (turn.autoCompact !== void 0) {
|
|
90
|
-
const { autoCompactIfNeeded } = await import('./compact-session-
|
|
90
|
+
const { autoCompactIfNeeded } = await import('./compact-session-UHGMWPMW.js');
|
|
91
91
|
const fired = await autoCompactIfNeeded({
|
|
92
92
|
store,
|
|
93
93
|
loc,
|
|
@@ -148,5 +148,5 @@ function enqueueSessionWrite(cwd, agentId, fn) {
|
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
export { appendSessionMessage, clearSession, enqueueSessionWrite, flushSessionWrites, getSessionMessages, hydrateSession, persistTurnToTranscript };
|
|
151
|
-
//# sourceMappingURL=chunk-
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
151
|
+
//# sourceMappingURL=chunk-334WDVFZ.js.map
|
|
152
|
+
//# sourceMappingURL=chunk-334WDVFZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session-store.ts","../src/internal/session/agent-session.ts"],"names":[],"mappings":";;;;AA8BA,SAAS,cAAA,CACP,OACA,IAAA,EACmB;AACnB,EAAA,OAAO,iBAAA,CAAkB,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA;AAClD;AAyBA,SAAS,aAAa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;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-VUXLNVX7.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") assistant.thinking = step.message.text;\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = { type: string; text?: string; content?: unknown; name?: string };\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n return { role, text };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n","import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — o cache mora numa folha; ver session-cache.ts para a razao (quebra de ciclo por extracao).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n sessions.set(agentId, existing);\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n // de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n // pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n // arriscado. Rastreado em usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`,\n );\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/agent-session-store.ts","../src/internal/session/agent-session.ts"],"names":[],"mappings":";;;;AA8BA,SAAS,cAAA,CACP,OACA,IAAA,EACmB;AACnB,EAAA,OAAO,iBAAA,CAAkB,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA;AAClD;AAyBA,SAAS,aAAa,KAAA,EAAgD;AACpE,EAAA,MAAM,YAA2B,EAAC;AAClC,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,YAAqD,EAAC;AAC5D,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,KAAK,IAAA,KAAS,iBAAA,EAAmB,SAAA,CAAU,QAAA,GAAW,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAC9D,KAAK,IAAA,KAAS,kBAAA,EAAoB,SAAA,CAAU,IAAA,GAAO,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAChE,KAAK,IAAA,KAAS,UAAA;AACrB,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,EAAA,EAAI,KAAK,OAAA,CAAQ,MAAA;AAAA,QACjB,IAAA,EAAM,KAAK,OAAA,CAAQ,IAAA;AAAA,QACnB,KAAA,EAAQ,IAAA,CAAK,OAAA,CAAQ,IAA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,aAAA,CAAc,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAC7C,IAAA,aAAA,CAAc,KAAA,EAAM;AACpB,IAAA,MAAM,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACvB;AACF;AAEO,SAAS,aAAa,OAAA,EAAuB;AAClD,EAAA,QAAA,CAAS,OAAO,OAAO,CAAA;AACzB;AAYO,SAAS,mBAAA,CACd,GAAA,EACA,OAAA,EACA,EAAA,EACY;AACZ,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AACtC,EAAA,MAAM,QAAQ,aAAA,CAAc,GAAA,CAAI,GAAG,CAAA,IAAK,QAAQ,OAAA,EAAQ;AACxD,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,EAAE,CAAA;AAC5B,EAAA,aAAA,CAAc,GAAA;AAAA,IACZ,GAAA;AAAA,IACA,MAAA,CAAO,IAAA;AAAA,MACL,MAAM,MAAA;AAAA,MACN,MAAM;AAAA;AACR,GACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-334WDVFZ.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") assistant.thinking = step.message.text;\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = { type: string; text?: string; content?: unknown; name?: string };\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n return { role, text };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n","import type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type PersistTurnInput,\n persistTurn,\n readSessionMessages,\n type TranscriptLocation,\n} from \"./agent-session-store.js\";\n\n/**\n * Per-agent conversation history kept across runs (and across `Agent.resume()`\n * within the same process). Lets the fixture responder recall prior facts when\n * the user asks a follow-up question.\n *\n * SE40 — disk persistence IS the native Claude-shaped `.jsonl` transcript. The\n * in-memory cache holds the narrowed `SessionMessage[]` (user/assistant text) so\n * a send can read `priorMessages` synchronously; the whole rich turn (user +\n * assistant + tool blocks) lands on disk once per send via {@link persistTurnToTranscript}\n * (fed by `run.conversation()`). Hydration on resume reconstructs the session by\n * walking the transcript DAG (`readSessionMessages`).\n *\n * @internal\n */\n\n// `SessionMessage` lives in `./session-types.ts` (leaf types file). Re-exported\n// for back-compat with downstream importers that pulled it from here.\nexport type { SessionMessage } from \"./session-types.js\";\n\nimport type { SessionMessage } from \"./session-types.js\";\n\n// M75 — o cache mora numa folha; ver session-cache.ts para a razao (quebra de ciclo por extracao).\nexport {\n hydratedKeys,\n invalidateSessionCache,\n sessions,\n transcriptKey,\n} from \"./session-cache.js\";\n\nimport { hydratedKeys, sessions, transcriptKey } from \"./session-cache.js\";\n\nconst pendingWrites = new Map<string, Promise<void>>();\nconst recordCounts = new Map<string, number>();\n\n/**\n * Append a session message to the in-memory cache only. Disk persistence for the\n * whole turn happens once per send via {@link persistTurnToTranscript}; the cache\n * feeds `priorMessages` / `onBeforeSend.previousMessageCount` synchronously.\n *\n * @internal\n */\nexport function appendSessionMessage(agentId: string, message: SessionMessage): void {\n const existing = sessions.get(agentId) ?? [];\n existing.push(message);\n sessions.set(agentId, existing);\n}\n\nexport function getSessionMessages(agentId: string): SessionMessage[] {\n return sessions.get(agentId) ?? [];\n}\n\n/**\n * Persist a full conversation turn (user + assistant + tool blocks) to the native\n * transcript. Chained per-(agent, transcript) so on-disk order matches send order,\n * and fire-and-forget so `send()` is not blocked by disk I/O. Every\n * M50 — when the caller supplies `turn.autoCompact`, size-driven auto-compaction (usage real vs\n * the model's context window) runs in this same chain, surfaced via the optional `onCompact` observer.\n *\n * @internal\n */\nexport function persistTurnToTranscript(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n onCompact?: () => void,\n): void {\n const key = transcriptKey(loc.cwd, loc.agentId);\n // Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n // de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n // pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n // arriscado. Rastreado em usetheodev/theokit-sdk#151.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\n const chained = (pendingWrites.get(key) ?? Promise.resolve()).then(async () => {\n try {\n await persistTurn(store, loc, sessionId, turn);\n const count = (recordCounts.get(key) ?? 0) + 1;\n recordCounts.set(key, count);\n // M50 — the 50-turn no-summary boundary stub is GONE (it silently amnesia'd the session).\n // Auto-compaction is now size-driven with a real summary: see `maybeAutoCompact` below,\n // invoked in this same write chain by the post-run lifecycle when usage is known.\n if (turn.autoCompact !== undefined) {\n const { autoCompactIfNeeded } = await import(\"./compact-session.js\");\n const fired = await autoCompactIfNeeded({\n store,\n loc,\n sessionId,\n usageTotal: turn.autoCompact.usageTotal,\n contextWindow: turn.autoCompact.contextWindow,\n turnCount: count,\n summarize: turn.autoCompact.summarize,\n });\n if (fired) onCompact?.();\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-sdk] session transcript write failed (${loc.agentId}): ${msg}\\n`,\n );\n }\n });\n pendingWrites.set(\n key,\n chained.then(\n () => undefined,\n () => undefined,\n ),\n );\n}\n\n/**\n * Load the persisted transcript into the in-memory cache. Idempotent per\n * (baseDir, cwd, agentId). Call once per agent lifecycle before the first read.\n *\n * @internal\n */\nexport async function hydrateSession(\n agentId: string,\n loc: { store: SessionStore; cwd: string },\n): Promise<void> {\n const key = transcriptKey(loc.cwd, agentId);\n if (hydratedKeys.has(key)) return;\n hydratedKeys.add(key);\n\n const persisted = await readSessionMessages(loc.store, agentId);\n if (persisted.length === 0) return;\n // M51 review F4 — the DISK is the source of truth at hydration time: after an invalidation\n // (compact/inject), an in-flight turn may have repopulated the cache with a SINGLE message before\n // this hydrate ran; the old \"skip when non-empty\" guard then pinned the parent to a 1-message\n // context (history + injected pair lost until restart). The persist chain serializes writes, so\n // the disk already contains that in-flight turn — replacing is always correct.\n sessions.set(agentId, persisted);\n}\n\n/**\n * Wait for all pending transcript writes to settle. Used by tests and by the\n * agent dispose path so on-disk state matches in-memory before the caller proceeds.\n *\n * @internal\n */\nexport async function flushSessionWrites(): Promise<void> {\n while (pendingWrites.size > 0) {\n const all = Array.from(pendingWrites.values());\n pendingWrites.clear();\n await Promise.all(all);\n }\n}\n\nexport function clearSession(agentId: string): void {\n sessions.delete(agentId);\n}\n\n/**\n * M50 review F1 — drop BOTH the message cache and the hydration marker so the NEXT send re-hydrates\n * from disk. Without this, a compaction only helps after a process restart: the live process keeps\n * sending the full pre-compact history (the cache is read synchronously by every send).\n */\n/**\n * M50 review F5 — run `fn` serialized on the SAME per-(cwd,agentId) write chain the per-turn\n * persistence uses, so a manual `Agent.compact` can never interleave with an in-flight turn's\n * writes (boundary landing mid-turn would orphan the turn from the replay).\n */\nexport function enqueueSessionWrite<T>(\n cwd: string,\n agentId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const key = transcriptKey(cwd, agentId);\n const prior = pendingWrites.get(key) ?? Promise.resolve();\n const result = prior.then(fn);\n pendingWrites.set(\n key,\n result.then(\n () => undefined,\n () => undefined,\n ),\n );\n return result;\n}\n\n/** Test-only: drop every cached session and hydration marker. @internal */\nexport function clearAllSessions(): void {\n sessions.clear();\n hydratedKeys.clear();\n recordCounts.clear();\n // M50 review F11 — the auto-compact attempt marks live on globalThis; tests reset them here.\n const g = globalThis as unknown as Record<symbol, Map<string, number>>;\n const sym = Symbol.for(\"theokit-sdk.session.auto-compact-attempts\");\n g[sym]?.clear();\n}\n"]}
|
|
@@ -117,8 +117,31 @@ function parsearLinha(line, lineNumber, tolerar) {
|
|
|
117
117
|
}
|
|
118
118
|
function appendJsonl(path$1, record) {
|
|
119
119
|
fs.mkdirSync(path.dirname(path$1), { recursive: true });
|
|
120
|
-
|
|
120
|
+
const prefixo = precisaDeQuebraAntes(path$1) ? "\n" : "";
|
|
121
|
+
const fd = fs.openSync(path$1, "a", 384);
|
|
122
|
+
try {
|
|
123
|
+
fs.writeSync(fd, `${prefixo}${JSON.stringify(record)}
|
|
121
124
|
`);
|
|
125
|
+
} finally {
|
|
126
|
+
fs.closeSync(fd);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function precisaDeQuebraAntes(path) {
|
|
130
|
+
let fd;
|
|
131
|
+
try {
|
|
132
|
+
fd = fs.openSync(path, "r");
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
const tamanho = fs.fstatSync(fd).size;
|
|
138
|
+
if (tamanho === 0) return false;
|
|
139
|
+
const buf = Buffer.alloc(1);
|
|
140
|
+
fs.readSync(fd, buf, 0, 1, tamanho - 1);
|
|
141
|
+
return buf[0] !== 10;
|
|
142
|
+
} finally {
|
|
143
|
+
fs.closeSync(fd);
|
|
144
|
+
}
|
|
122
145
|
}
|
|
123
146
|
function readJsonlIds(path, keyFn) {
|
|
124
147
|
const done = /* @__PURE__ */ new Set();
|
|
@@ -142,5 +165,5 @@ exports.appendJsonl = appendJsonl;
|
|
|
142
165
|
exports.loadJsonl = loadJsonl;
|
|
143
166
|
exports.readJsonlIds = readJsonlIds;
|
|
144
167
|
exports.withFileLock = withFileLock;
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
168
|
+
//# sourceMappingURL=chunk-CJVMDRQB.cjs.map
|
|
169
|
+
//# sourceMappingURL=chunk-CJVMDRQB.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/file-lock.ts","../src/internal/persistence/jsonl.ts"],"names":["withCwdMutex","readFileSync","path","mkdirSync","dirname","openSync","writeSync","closeSync","fstatSync","readSync"],"mappings":";;;;;;;AAgCA,IAAI,MAAA;AACJ,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AAA,SAAE;AACA,IAAAF,YAAA,CAAU,EAAE,CAAA;AAAA,EACd;AACF;AAYO,SAAS,YAAA,CACd,MACA,KAAA,EACa;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAON,eAAA,CAAa,MAAM,MAAM,CAAA;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,KAAA,MAAW,OAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA,EAAG;AAEtC,IAAA,MAAM,MAAA,GAAS,kBAAA,CAAmB,OAAA,CAAQ,IAAA,EAAM,CAAA;AAChD,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,IAAA,IAAI,OAAO,QAAQ,QAAA,IAAY,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,IAAI,GAAG,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-CJVMDRQB.cjs","sourcesContent":["/**\n * Cross-process file lock helper (ADR D61).\n *\n * Uses `proper-lockfile` (optional peer dep) for cross-process locks. When\n * the peer dep is absent, falls back to `withCwdMutex` (in-process only)\n * with a one-shot stderr warning.\n *\n * EC-1 fix: uses a companion `<path>.lock` file with `realpath: false` so\n * `withFileLock` works even when the target `path` does not exist yet.\n * Without this, fresh installs that lock-then-create would crash with ENOENT.\n *\n * @internal\n */\n\nimport { withCwdMutex } from \"./cwd-mutex.js\";\n\ninterface ProperLockfileModule {\n lock: (file: string, options: ProperLockfileOptions) => Promise<() => Promise<void>>;\n}\n\ninterface ProperLockfileOptions {\n lockfilePath?: string;\n realpath?: boolean;\n stale?: number;\n retries?: {\n retries: number;\n factor?: number;\n minTimeout?: number;\n maxTimeout?: number;\n };\n}\n\nlet cached: ProperLockfileModule | null | undefined;\nlet warnedMissing = false;\nlet warnedStructural = false;\n\nasync function getProperLockfile(): Promise<ProperLockfileModule | null> {\n if (cached !== undefined) return cached;\n try {\n const mod = await import(\"proper-lockfile\");\n // T5.9 — supply-chain hardening: validate the imported module\n // exposes the API surface we depend on BEFORE caching it. A\n // tampered or incompatible version that lacks `lock`/`unlock`\n // functions gets treated as \"not installed\" with an advisory\n // warning — never silently used.\n if (!validateLockModule(mod)) {\n if (!warnedStructural) {\n warnedStructural = true;\n process.stderr.write(\n \"[theokit-sdk] proper-lockfile: imported module does NOT expose \" +\n \"the expected `lock`/`unlock` API surface. This may indicate a \" +\n \"supply-chain compromise or an incompatible major version. \" +\n \"Falling back to in-process mutex (no cross-process safety). \" +\n \"Reinstall with: pnpm add proper-lockfile@^11\\n\",\n );\n }\n cached = null;\n return cached;\n }\n cached = mod as ProperLockfileModule;\n } catch {\n cached = null;\n }\n return cached;\n}\n\n/**\n * T5.9 — Structural validation of the dynamically-imported\n * `proper-lockfile` module. Verifies the API surface we depend on\n * (`lock` and `unlock` as functions) is present. Pure function —\n * never throws, never mutates, never performs I/O.\n *\n * Exported via `__TESTING__validateLockModule` seam so unit tests\n * can drive the check without spinning up the dynamic import.\n *\n * @internal\n */\nfunction validateLockModule(mod: unknown): boolean {\n if (mod === null || mod === undefined || typeof mod !== \"object\") return false;\n const m = mod as Record<string, unknown>;\n return typeof m.lock === \"function\" && typeof m.unlock === \"function\";\n}\n\n/**\n * T5.9 — Test seam: expose the structural validator for unit tests.\n * NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__validateLockModule(mod: unknown): boolean {\n return validateLockModule(mod);\n}\n\n/**\n * T5.9 — Test seam: reset the module cache + warning flags between\n * tests so each test starts fresh. NOT included in the public barrel.\n *\n * @internal\n */\nexport function __TESTING__resetFileLockCache(): void {\n cached = undefined;\n warnedMissing = false;\n warnedStructural = false;\n}\n\n/**\n * Options for `withFileLock`.\n *\n * @internal\n */\nexport interface FileLockOptions {\n /** Stale lock timeout in ms. Default 30_000 (30s). */\n stale?: number;\n /** Max retries on busy lock. Default 5. */\n retries?: number;\n /** Backoff factor between retries. Default 1.5. */\n retryFactor?: number;\n}\n\n/**\n * Run `fn` while holding an OS-level cross-process lock on `path`.\n *\n * If `proper-lockfile` is installed, uses it with a companion `<path>.lock`\n * file (`realpath: false`, so target file does NOT need to exist yet).\n * Otherwise falls back to in-process `withCwdMutex` and prints a one-shot\n * stderr warning telling the user to install `proper-lockfile` for\n * cross-process safety.\n *\n * The lock is released even when `fn` throws.\n *\n * @internal\n */\nexport async function withFileLock<T>(\n path: string,\n fn: () => Promise<T>,\n options?: FileLockOptions,\n): Promise<T> {\n const lib = await getProperLockfile();\n\n if (lib === null) {\n if (!warnedMissing) {\n warnedMissing = true;\n process.stderr.write(\n \"[theokit-sdk] proper-lockfile not installed; \" +\n \"cross-process file lock unavailable. \" +\n \"Install with: pnpm add proper-lockfile\\n\",\n );\n }\n return withCwdMutex(`file-lock:${path}`, fn);\n }\n\n // proper-lockfile errors immediately on same-process concurrent acquire\n // (\"Lock file is already being held\"). Wrap with cwd-mutex first so\n // in-process callers queue and only ONE thread at a time enters the\n // cross-process acquire path. Combined: full in-process + cross-process\n // serialization.\n return withCwdMutex(`file-lock:${path}`, async () => {\n const release = await lib.lock(path, {\n // EC-1: companion lockfile, target path may not exist yet.\n lockfilePath: `${path}.lock`,\n realpath: false,\n stale: options?.stale ?? 30_000,\n retries: {\n retries: options?.retries ?? 5,\n factor: options?.retryFactor ?? 1.5,\n minTimeout: 100,\n maxTimeout: 5_000,\n },\n });\n\n try {\n return await fn();\n } finally {\n await release();\n }\n });\n}\n\n/**\n * Test helper — resets the cached proper-lockfile module + warning flag.\n * Allows tests to simulate \"module absent\" by clearing cache then\n * monkey-patching the dynamic import resolution.\n *\n * @internal\n */\nexport function _resetFileLockCacheForTesting(): void {\n cached = undefined;\n warnedMissing = false;\n}\n","/**\n * Durable JSONL primitives shared by the eval harness (M6).\n *\n * - `loadJsonl` — generic dataset reader (split/trim/skip-blank/parse) with a\n * line-numbered {@link JsonlParseError}. The dataset SCHEMA is the caller's\n * concern via `map` (M6 ADR D3) — this module owns only the parse.\n * - `appendJsonl` / `readJsonlIds` — crash-durable, resumable batch persistence\n * (M6 ADR D1): each record is appended as one whole `\\n`-terminated line the\n * instant it is produced, and a re-run resumes by skipping already-keyed rows.\n *\n * referencia: knowledge-base/references/theocode-eval/lib/swebench-dataset.ts:82\n * (parseJsonl + line-N error) and swebench-batch.ts:113,205 (resume + per-line\n * flush).\n *\n * @internal\n */\nimport {\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n writeSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/** Raised when a JSONL line is not valid JSON or is not a JSON object. Carries the 1-based line number. */\nexport class JsonlParseError extends Error {\n constructor(\n message: string,\n readonly line: number,\n ) {\n super(message);\n this.name = \"JsonlParseError\";\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Parse a single trimmed line to a plain object, or `undefined` if blank / invalid / non-object. */\nfunction tryParseObjectLine(line: string): Record<string, unknown> | undefined {\n if (line.length === 0) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n return isPlainObject(parsed) ? parsed : undefined;\n}\n\n/**\n * Parse a JSONL file into rows. Blank lines are skipped. A malformed or\n * non-object line throws {@link JsonlParseError} naming the 1-based line. When\n * `map` is provided, each raw object is mapped to the typed row (the SWE-bench\n * schema lives in the caller's `map`, per M6 ADR D3).\n */\nexport function loadJsonl<T = Record<string, unknown>>(\n path: string,\n opts: {\n map?: (raw: Record<string, unknown>, lineNumber: number) => T;\n /**\n * M81 — tolerate a truncated LAST line (a crash artifact: the process died mid-write).\n *\n * Opt-in on purpose. As a default it would also swallow corruption in the MIDDLE of the file,\n * turning loud data loss into silent data loss — the wrong trade for a session store.\n */\n tolerateTrailingPartialLine?: boolean;\n } = {},\n): T[] {\n const linhas = readFileSync(path, \"utf8\").split(\"\\n\");\n const out: T[] = [];\n for (let i = 0; i < linhas.length; i += 1) {\n const lineNumber = i + 1;\n const line = (linhas[i] ?? \"\").trim();\n if (line.length === 0) continue;\n // M81 — `undefined` = linha inválida tolerada (última, truncada por crash). Qualquer outra\n // linha inválida já lançou dentro de `parsearLinha`.\n const parsed = parsearLinha(\n line,\n lineNumber,\n opts.tolerateTrailingPartialLine === true && lineNumber === linhas.length,\n );\n if (parsed === undefined) break;\n out.push(opts.map ? opts.map(parsed, lineNumber) : (parsed as unknown as T));\n }\n return out;\n}\n\n/**\n * Parse de UMA linha, devolvendo `undefined` quando ela é uma última-linha-truncada tolerada.\n *\n * Extraído porque `loadJsonl` passou do teto de complexidade cognitiva quando ganhou a tolerância —\n * e porque parse-de-linha e iteração-do-arquivo são duas responsabilidades que só estavam juntas\n * por hábito.\n */\nfunction parsearLinha(\n line: string,\n lineNumber: number,\n tolerar: boolean,\n): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n if (tolerar) return undefined;\n throw new JsonlParseError(`line ${lineNumber}: invalid JSON`, lineNumber);\n }\n if (!isPlainObject(parsed)) {\n throw new JsonlParseError(`line ${lineNumber}: not a JSON object`, lineNumber);\n }\n return parsed;\n}\n\n/**\n * Append one record as a whole `\\n`-terminated JSON line. Creates the parent dir\n * if missing. `appendFileSync` is synchronous, so within a single Node process\n * the event loop serializes writes and each call writes its line atomically —\n * interleave-safe for the bounded-concurrency batch runner.\n *\n * referencia: swebench-batch.ts:192 (mkdir-before-append), :205 (per-line flush).\n */\nexport function appendJsonl(path: string, record: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n const prefixo = precisaDeQuebraAntes(path) ? \"\\n\" : \"\";\n // M93 (revisão adversarial, H1) — `0o600`. `appendFileSync` não aceita `mode`, então a permissão\n // vinha do umask: sob `umask 022` o transcript nascia `0664`, world-readable. O caminho anterior\n // (`replaceFileAtomic`) fixava `0o600` de propósito — \"holds the FULL in-flight content\n // (credential snapshots, OAuth tokens)\" (`atomic-write.ts:107`) — e trocar para append perdeu isso\n // em silêncio. A mesma classe já havia sido pega no consumidor (`atomic-sync.ts`, M88 HIGH-1).\n //\n // `mode` só vale na CRIAÇÃO; um arquivo pré-existente mantém a permissão que já tem.\n const fd = openSync(path, \"a\", 0o600);\n try {\n writeSync(fd, `${prefixo}${JSON.stringify(record)}\\n`);\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * O arquivo termina sem `\\n`? Então a última linha está truncada — um crash no meio de um append.\n *\n * Sem esta checagem o append seguinte **cola** no meio da linha partida, produzindo uma linha\n * inválida que o leitor descarta: o registro NOVO some junto com o parcial. O caminho anterior\n * (read-modify-write) se auto-curava disso porque reescrevia o arquivo inteiro. Medido na revisão\n * adversarial do M93 (H2): após um append sobre arquivo truncado, o registro recém-escrito não era\n * mais legível.\n *\n * Lê **um byte**, não o arquivo.\n */\nfunction precisaDeQuebraAntes(path: string): boolean {\n let fd: number;\n try {\n fd = openSync(path, \"r\");\n } catch {\n return false; // arquivo ainda não existe: nada a emendar\n }\n try {\n const tamanho = fstatSync(fd).size;\n if (tamanho === 0) return false;\n const buf = Buffer.alloc(1);\n readSync(fd, buf, 0, 1, tamanho - 1);\n return buf[0] !== 0x0a;\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Read the set of keys from an existing JSONL file for which `keyFn(parsed)`\n * returns a non-empty string. Used to resume a crashed batch by skipping rows\n * already persisted with a successful result. A trailing partial line from an\n * interrupted append is tolerated (skipped, not thrown), and a missing file\n * yields an empty set.\n *\n * referencia: swebench-batch.ts:113 (readDoneIds), :129 (success-only),\n * :131 (tolerate partial line).\n */\nexport function readJsonlIds(\n path: string,\n keyFn: (parsed: Record<string, unknown>) => string | undefined,\n): Set<string> {\n const done = new Set<string>();\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return done; // no file yet → nothing done\n }\n for (const rawLine of text.split(\"\\n\")) {\n // A trailing partial line from an interrupted run parses to undefined → skipped.\n const parsed = tryParseObjectLine(rawLine.trim());\n if (parsed === undefined) continue;\n const key = keyFn(parsed);\n if (typeof key === \"string\" && key.length > 0) done.add(key);\n }\n return done;\n}\n"]}
|