@theokit/sdk 4.34.0 → 4.34.2
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 +19 -0
- package/dist/{agent-EQQA5VGX.js → agent-F77TRYGM.js} +5 -5
- package/dist/{agent-EQQA5VGX.js.map → agent-F77TRYGM.js.map} +1 -1
- package/dist/{agent-W6NI3HY4.cjs → agent-IJUQN6RK.cjs} +6 -6
- package/dist/{agent-W6NI3HY4.cjs.map → agent-IJUQN6RK.cjs.map} +1 -1
- package/dist/{chunk-VQ6NY4F5.js → chunk-4NU7GXH2.js} +16 -3
- package/dist/chunk-4NU7GXH2.js.map +1 -0
- package/dist/{chunk-JYMBHNNU.cjs → chunk-AFOLLMVQ.cjs} +8 -4
- package/dist/chunk-AFOLLMVQ.cjs.map +1 -0
- package/dist/{chunk-IZFZ6RHA.cjs → chunk-BOTI6ZOX.cjs} +5 -5
- package/dist/{chunk-IZFZ6RHA.cjs.map → chunk-BOTI6ZOX.cjs.map} +1 -1
- package/dist/{chunk-TPTHVSIG.js → chunk-JZSBSUFT.js} +15 -6
- package/dist/chunk-JZSBSUFT.js.map +1 -0
- package/dist/{chunk-5QMXYX3X.js → chunk-MNLBNL7T.js} +3 -3
- package/dist/{chunk-5QMXYX3X.js.map → chunk-MNLBNL7T.js.map} +1 -1
- package/dist/{chunk-TS6IPRME.cjs → chunk-P7SIIQIS.cjs} +18 -9
- package/dist/chunk-P7SIIQIS.cjs.map +1 -0
- package/dist/{chunk-IPHW3VKP.js → chunk-QWP3ZQ75.js} +9 -5
- package/dist/chunk-QWP3ZQ75.js.map +1 -0
- package/dist/{chunk-IAZX7RZM.cjs → chunk-RMRBHTA3.cjs} +17 -4
- package/dist/chunk-RMRBHTA3.cjs.map +1 -0
- package/dist/cron.cjs +5 -5
- package/dist/cron.js +4 -4
- package/dist/eval.cjs +4 -4
- package/dist/eval.js +3 -3
- package/dist/{fs-session-store-QS763E3Y.cjs → fs-session-store-2G4O63PO.cjs} +5 -5
- package/dist/{fs-session-store-QS763E3Y.cjs.map → fs-session-store-2G4O63PO.cjs.map} +1 -1
- package/dist/fs-session-store-Q3E5S7MC.js +10 -0
- package/dist/{fs-session-store-SJ3RA5I2.js.map → fs-session-store-Q3E5S7MC.js.map} +1 -1
- package/dist/index.cjs +23 -23
- package/dist/index.js +6 -6
- package/dist/internal/persistence/fs-session-store.d.cts +8 -0
- package/dist/internal/persistence/fs-session-store.d.ts +8 -0
- package/dist/persistence.cjs +3 -3
- package/dist/persistence.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-IAZX7RZM.cjs.map +0 -1
- package/dist/chunk-IPHW3VKP.js.map +0 -1
- package/dist/chunk-JYMBHNNU.cjs.map +0 -1
- package/dist/chunk-TPTHVSIG.js.map +0 -1
- package/dist/chunk-TS6IPRME.cjs.map +0 -1
- package/dist/chunk-VQ6NY4F5.js.map +0 -1
- package/dist/fs-session-store-SJ3RA5I2.js +0 -10
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TheokitAgentError } from './chunk-WLKFWQSJ.js';
|
|
2
|
-
import { openSync, closeSync, rmSync, readFileSync, writeSync } from 'fs';
|
|
2
|
+
import { openSync, closeSync, rmSync, readFileSync, writeSync, fchmodSync } from 'fs';
|
|
3
3
|
import { hostname } from 'os';
|
|
4
4
|
|
|
5
5
|
var SessionBusyError = class extends TheokitAgentError {
|
|
@@ -18,6 +18,7 @@ function gravarDono(lockPath, dono) {
|
|
|
18
18
|
const fd = openSync(lockPath, "w", 384);
|
|
19
19
|
try {
|
|
20
20
|
writeSync(fd, JSON.stringify(dono));
|
|
21
|
+
fchmodSync(fd, 384);
|
|
21
22
|
} finally {
|
|
22
23
|
closeSync(fd);
|
|
23
24
|
}
|
|
@@ -26,8 +27,11 @@ function lerDono(lockPath) {
|
|
|
26
27
|
let bruto;
|
|
27
28
|
try {
|
|
28
29
|
bruto = readFileSync(lockPath, "utf8");
|
|
29
|
-
} catch {
|
|
30
|
-
|
|
30
|
+
} catch (err) {
|
|
31
|
+
const code = err.code;
|
|
32
|
+
if (code === "ENOENT") return void 0;
|
|
33
|
+
if (code === "EISDIR") return void 0;
|
|
34
|
+
throw new SessionBusyError(lockPath.replace(/\.writer\.lock$/, ""));
|
|
31
35
|
}
|
|
32
36
|
try {
|
|
33
37
|
const d = JSON.parse(bruto);
|
|
@@ -83,5 +87,5 @@ function criarLease(sessionPath, lockPath) {
|
|
|
83
87
|
}
|
|
84
88
|
|
|
85
89
|
export { SessionBusyError, acquireSessionWriter };
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
90
|
+
//# sourceMappingURL=chunk-QWP3ZQ75.js.map
|
|
91
|
+
//# sourceMappingURL=chunk-QWP3ZQ75.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":[],"mappings":";;;;AA2CO,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;AAgCO,IAAM,sBAAA,GAAyB,GAAA;AAiBtC,SAAS,UAAA,CAAW,UAAkB,IAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,EAAA,EAAI,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAIlC,IAAA,UAAA,CAAW,IAAI,GAAK,CAAA;AAAA,EACtB,CA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AAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC;AAAA,GACF;AACF","file":"chunk-QWP3ZQ75.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, fchmodSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\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 */\n/**\n * Janela de obsolescência **entre máquinas** — e só entre elas.\n *\n * 30 s a partir da AQUISIÇÃO. O nome \"heartbeat\" seria mentira: o registro é gravado uma vez, na\n * tomada do lease, e **não** é renovado a cada escrita. A versão anterior deste comentário dizia\n * \"o dono toca o arquivo a cada aquisição, então um processo ativo nunca cruza a janela\" — falso\n * duas vezes, e a revisão adversarial mediu as duas.\n *\n * No **mesmo host** isso não importa: `reclamavel` decide pelo `pid`, que é exato, e a idade não\n * entra na conta. Entre hosts, importa e é um limite real: um dono remoto **vivo** perde o lease\n * depois de 30 s, porque não há como perguntar a outra máquina se o processo dela existe.\n *\n * **Resíduo declarado, não mecanizado** (a disciplina de `error-handling.md § 4`): renovar o\n * registro a cada append fecharia essa janela, ao custo de um `write` por turno num arquivo que\n * hoje é escrito uma vez por sessão. Não foi feito, e o caso multi-host não é o que motiva este\n * milestone — o enunciado é `exec` e TUI na mesma máquina.\n */\nexport const JANELA_DE_HEARTBEAT_MS = 30_000;\n\n/** Quem detém o lock. Gravado como JSON no `.writer.lock`. */\ninterface DonoDoLock {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/**\n * Grava o dono com permissão restrita ao usuário.\n *\n * `0600` porque o lock é uma afirmação de POSSE: com o `0664` que o umask usual produz, outro\n * usuário do mesmo grupo pode sobrescrever o arquivo e forjar a posse da sessão — e a partir daí o\n * dono legítimo é quem passa a receber `SessionBusyError`. O conteúdo (`pid`, `hostname`) é de\n * baixa sensibilidade; o que a permissão protege é a **integridade** do sinal, não o sigilo dele.\n */\nfunction gravarDono(lockPath: string, dono: DonoDoLock): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(dono));\n // O `mode` do `open` só vale na CRIAÇÃO. Um `.writer.lock` herdado de uma versão anterior — ou\n // deixado por um processo com umask diferente — continuaria `0664` depois de reclamado, e a\n // janela de forja que o modo fecha para locks novos seguiria aberta para os antigos.\n fchmodSync(fd, 0o600);\n } finally {\n closeSync(fd);\n }\n}\n\n/** Lê o dono do lock. `undefined` quando o arquivo sumiu ou o conteúdo é ilegível. */\nfunction lerDono(lockPath: string): DonoDoLock | undefined {\n let bruto: string;\n try {\n bruto = readFileSync(lockPath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // `ENOENT` — sumiu entre o `EEXIST` e a leitura. Corrida benigna: o lock não existe mais.\n if (code === \"ENOENT\") return undefined;\n // `EISDIR` — o caminho do lock é um DIRETÓRIO. Nenhum processo desta biblioteca cria um; é\n // lixo de outra coisa, e nunca vai virar um lock legível. Fail-closed aqui trancaria a sessão\n // para sempre, sem recuperação — o oposto do que este milestone existe para garantir.\n if (code === \"EISDIR\") return undefined;\n // Qualquer outra falha de leitura (`EACCES` num diretório compartilhado, `EIO`) é diferente em\n // espécie: o lock **existe** e nós é que não conseguimos ler o dono. Tratar como livre faria\n // dois escritores conviverem — precisamente o que o lease existe para impedir —, e o `0600`\n // que protege o lock contra forja AMPLIA essa superfície: num diretório compartilhado, o lock\n // do outro usuário é ilegível por desenho.\n //\n // Não saber quem é o dono não é o mesmo que não haver dono. Fail-closed.\n throw new SessionBusyError(lockPath.replace(/\\.writer\\.lock$/, \"\"));\n }\n try {\n const d = JSON.parse(bruto) as Partial<DonoDoLock>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // JSON ilegível: um lock que ninguém consegue interpretar não pode trancar a sessão para\n // sempre. Tratar como obsoleto é a escolha recuperável; o custo é o mesmo de um lock velho.\n return undefined;\n }\n}\n\n/** O processo existe? `signal 0` não envia nada — só consulta permissão/existência. */\nfunction processoVivo(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM significa que ele EXISTE e é de outro usuário.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * O lock pode ser tomado de quem o detém?\n *\n * ADR-2 do plano: reclamar por `pid` sozinho tem falso positivo entre máquinas — o mesmo número\n * existe noutro host, apontando para um processo sem relação. Então:\n *\n * - **mesmo host:** o `pid` é autoritativo, e **só** ele. Processo morto ⇒ reclamável na hora;\n * processo vivo ⇒ nunca, por mais velho que o lock esteja.\n * - **outro host:** o `pid` não diz nada aqui. Só a janela de heartbeat vale, porque é o único\n * sinal que não mente entre máquinas.\n *\n * ## Por que a idade NÃO conta no mesmo host\n *\n * A primeira versão fazia `velho || !processoVivo(pid)`, e isso era um defeito grave: o `mtime` é\n * gravado na **aquisição** e não é tocado a cada append, então qualquer sessão que durasse mais que\n * a janela — isto é, **toda sessão real** — passava a ser roubável por outro processo. Dois\n * escritores no mesmo transcript é exatamente o que o lease existe para impedir.\n *\n * No mesmo host a pergunta \"o dono ainda existe?\" tem resposta exata, e a idade não acrescenta\n * informação nenhuma a ela — só um modo de errar. Manter a janela ali seria heurística por cima de\n * um fato.\n */\nfunction reclamavel(dono: DonoDoLock | undefined): boolean {\n if (dono === undefined) return true; // ilegível ou sumido\n if (dono.hostname !== hostname()) {\n return Date.now() - dono.mtime > JANELA_DE_HEARTBEAT_MS;\n }\n return !processoVivo(dono.pid);\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NÃO `.lock`.\n //\n // `withFileLock(path, fn)` já usa `<path>.lock` como companheiro. Enquanto o lease não era\n // chamado de lugar nenhum (o defeito que este milestone corrige) a colisão era teórica; ligá-lo\n // ao mesmo arquivo faria o lease de vida longa bloquear toda seção crítica curta do mesmo path.\n //\n // Dois arquivos porque são duas coisas: `withFileLock` protege uma seção com início e fim; o\n // lease é POSSE, mantida através de turnos, com `release()` explícito — a distinção que o\n // docstring do M81 acima já explica.\n const lockPath = `${sessionPath}.writer.lock`;\n const meu: DonoDoLock = { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n let fd: number;\n try {\n // O modo vale na CRIAÇÃO — o `w` de `gravarDono` não altera arquivo existente.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — o lock existe. Até aqui isso bastava para recusar, e era o defeito: uma TUI morta por\n // SIGKILL trancava o usuário para fora da própria sessão PERMANENTEMENTE, sem caminho de\n // recuperação documentado. Agora o lock diz quem é o dono, e um dono morto cede o lugar.\n if (!reclamavel(lerDono(lockPath))) throw new SessionBusyError(sessionPath);\n gravarDono(lockPath, meu);\n return criarLease(sessionPath, lockPath);\n }\n closeSync(fd);\n gravarDono(lockPath, meu);\n\n return criarLease(sessionPath, lockPath);\n}\n\n/** O lease em si — `release()` idempotente. Extraído porque a aquisição tem dois caminhos de saída. */\nfunction criarLease(sessionPath: string, lockPath: string): SessionWriterLease {\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"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkAFOLLMVQ_cjs = require('./chunk-AFOLLMVQ.cjs');
|
|
4
4
|
var chunkCJVMDRQB_cjs = require('./chunk-CJVMDRQB.cjs');
|
|
5
5
|
var chunk2DYI7MIF_cjs = require('./chunk-2DYI7MIF.cjs');
|
|
6
6
|
var promises = require('fs/promises');
|
|
@@ -13,7 +13,7 @@ async function adquirirCompartilhado(path) {
|
|
|
13
13
|
existente.refs++;
|
|
14
14
|
return criarProxy(path);
|
|
15
15
|
}
|
|
16
|
-
const lease = await
|
|
16
|
+
const lease = await chunkAFOLLMVQ_cjs.acquireSessionWriter(path);
|
|
17
17
|
compartilhados.set(path, { lease, refs: 1 });
|
|
18
18
|
return criarProxy(path);
|
|
19
19
|
}
|
|
@@ -73,6 +73,19 @@ var FsSessionStore = class {
|
|
|
73
73
|
await promises.mkdir(path.dirname(path$1), { recursive: true });
|
|
74
74
|
this.#leases.set(agentId, await adquirirCompartilhado(path$1));
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Solta o lease de UM agente.
|
|
78
|
+
*
|
|
79
|
+
* Existe porque `dispose()` solta **todos** os leases do store, e um store injetado pelo
|
|
80
|
+
* consumidor pode servir vários agentes: um init que falha para o agente B não pode liberar o
|
|
81
|
+
* lease do agente A, que segue vivo e escrevendo.
|
|
82
|
+
*/
|
|
83
|
+
async release(agentId) {
|
|
84
|
+
const lease = this.#leases.get(agentId);
|
|
85
|
+
if (lease === void 0) return;
|
|
86
|
+
this.#leases.delete(agentId);
|
|
87
|
+
await lease.release();
|
|
88
|
+
}
|
|
76
89
|
/**
|
|
77
90
|
* Solta todo lease que este store detém.
|
|
78
91
|
*
|
|
@@ -88,5 +101,5 @@ var FsSessionStore = class {
|
|
|
88
101
|
};
|
|
89
102
|
|
|
90
103
|
exports.FsSessionStore = FsSessionStore;
|
|
91
|
-
//# sourceMappingURL=chunk-
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
104
|
+
//# sourceMappingURL=chunk-RMRBHTA3.cjs.map
|
|
105
|
+
//# sourceMappingURL=chunk-RMRBHTA3.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":["acquireSessionWriter","readTranscript","transcriptPath","path","mkdir","dirname","withFileLock","appendJsonl"],"mappings":";;;;;;;;AAyDA,IAAM,cAAA,uBAAqB,GAAA,EAAyD;AAEpF,e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AA,IAAA,CAAK,OAAA,CAAQ,OAAO,OAAO,CAAA;AAC3B,IAAA,MAAM,MAAM,OAAA,EAAQ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,SAAS,CAAC,GAAG,IAAA,CAAK,OAAA,CAAQ,QAAQ,CAAA;AACxC,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AACnB,IAAA,KAAA,MAAW,KAAA,IAAS,MAAA,EAAQ,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,EAClD;AACF","file":"chunk-RMRBHTA3.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\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport { appendJsonl } from \"./jsonl.js\";\nimport { readTranscript, type SessionRecord, transcriptPath } from \"./session-transcript.js\";\nimport { acquireSessionWriter, type SessionWriterLease } from \"./session-writer.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 */\n/**\n * Leases compartilhados por caminho, com contagem de referências.\n *\n * `acquireSessionWriter` é ESTRITO de propósito: duas aquisições concorrentes do mesmo caminho, e\n * exatamente uma vence — \"um lease que deixasse as duas passarem seria decorativo\" (o teste do M81\n * diz isso com todas as letras, e está certo). Esse é o contrato do primitivo, e ele não muda.\n *\n * Mas dentro de UM processo é normal existir mais de um store sobre a mesma sessão: os testes\n * golden de compactação e de sends concorrentes fazem exatamente isso, e são registro de\n * comportamento real do runtime. Aplicar o primitivo cru ali transformaria um padrão legítimo em\n * `SessionBusyError`.\n *\n * A conciliação é aqui, no consumidor do primitivo: o processo tira UM lease por caminho e conta\n * quantos stores o usam. O último a soltar libera de fato. Cross-process continua estrito — que é o\n * problema que o M81 enuncia (\"`exec resume --last` pode escrever na sessão viva da TUI\").\n */\nconst compartilhados = new Map<string, { lease: SessionWriterLease; refs: number }>();\n\nasync function adquirirCompartilhado(path: string): Promise<SessionWriterLease> {\n const existente = compartilhados.get(path);\n if (existente !== undefined) {\n existente.refs++;\n return criarProxy(path);\n }\n const lease = await acquireSessionWriter(path);\n compartilhados.set(path, { lease, refs: 1 });\n return criarProxy(path);\n}\n\n/** Um handle que decrementa a contagem; o último a soltar libera o lease de verdade. */\nfunction criarProxy(path: string): SessionWriterLease {\n let solto = false;\n return {\n sessionPath: path,\n release: async (): Promise<void> => {\n if (solto) return;\n solto = true;\n const entrada = compartilhados.get(path);\n if (entrada === undefined) return;\n entrada.refs--;\n if (entrada.refs > 0) return;\n compartilhados.delete(path);\n await entrada.lease.release();\n },\n };\n}\n\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n /** Um lease por `agentId` — um store serve mais de uma sessão ao longo da vida do processo. */\n readonly #leases = new Map<string, SessionWriterLease>();\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\n await withFileLock(path, async () => {\n // M93 — acrescenta o DELTA em vez de reescrever o arquivo inteiro.\n //\n // Antes: `readTranscript` + `writeTranscript` de tudo, por turno. O(n) de I/O **e** de parse a\n // cada turno, O(n²) por sessão — a nota do consumidor em `agents/lib/session/backtrack.ts`\n // registra 1,4 MB / 3000 linhas em 200 turnos.\n //\n // Correto porque o formato **já é append-only**: o DAG de `parentUuid` não depende da ordem de\n // linha, e cada registro carrega o próprio pai. `appendJsonl` **já existia no pacote** e tinha um\n // único chamador (`eval/runner.ts`) — a primitiva estava lá, o store é que a ignorava (rung 4).\n //\n // O `withFileLock` permanece — mas a afirmação anterior de que \"ele é o que serializa dois\n // `appendRecords` concorrentes\" era forte demais, e a revisão adversarial do M93 mediu isso:\n // removê-lo não reprova nenhum teste. A razão é o próprio parágrafo acima — o DAG de\n // `parentUuid` não depende da ordem de linha, então dois lotes intercalados reconstroem igual.\n // O trabalho que o lock fazia (proteger um read-modify-write) sumiu junto com o rewrite.\n //\n // O que ele ainda cobre é a janela TOCTOU de `precisaDeQuebraAntes` (ler o último byte, depois\n // escrever): sem ele, dois processos podem ambos concluir \"falta \\n\" e produzir uma linha em\n // branco — que o leitor descarta, isto é, benigno. Fica como **defesa declarada, não\n // mecanizada** (a disciplina de `error-handling.md § 4`: enumerar o resíduo em vez de deixar a\n // ausência de teste passar por cobertura).\n //\n // `writeTranscript` continua existindo para **compactação**, a única operação que legitimamente\n // reescreve o arquivo.\n for (const record of records) appendJsonl(path, record);\n });\n }\n\n /**\n * Toma o lease de escritor da sessão. Lança `SessionBusyError` quando outro processo a detém.\n *\n * **Explícito, e NÃO no `appendRecords`** — a revisão adversarial do M95 mediu por que isso\n * importa: o contrato de `SessionStore` diz que \"an `appendRecords` rejection is logged to\n * stderr, NOT thrown to the caller (best-effort write)\". Adquirir ali fazia o `SessionBusyError`\n * ser **engolido**, e o resultado era pior que o problema original: em vez de dois escritores\n * intercalarem linhas, o perdedor **perdia o turno em silêncio** — nada em disco, um aviso em\n * stderr invisível sob a TUI, e o chamador sem como reagir.\n *\n * No init o erro chega a quem pode agir: o `exec` forka para um id novo, que é o que a própria\n * mensagem do erro prescreve. É a diferença entre falhar onde dá para decidir e falhar onde só\n * dá para perder.\n */\n async acquire(agentId: string): Promise<void> {\n if (this.#leases.has(agentId)) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n await mkdir(dirname(path), { recursive: true });\n this.#leases.set(agentId, await adquirirCompartilhado(path));\n }\n\n /**\n * Solta o lease de UM agente.\n *\n * Existe porque `dispose()` solta **todos** os leases do store, e um store injetado pelo\n * consumidor pode servir vários agentes: um init que falha para o agente B não pode liberar o\n * lease do agente A, que segue vivo e escrevendo.\n */\n async release(agentId: string): Promise<void> {\n const lease = this.#leases.get(agentId);\n if (lease === undefined) return;\n this.#leases.delete(agentId);\n await lease.release();\n }\n\n /**\n * Solta todo lease que este store detém.\n *\n * Sem isto o `.writer.lock` sobrevive ao processo e a próxima abertura teria de esperar a janela\n * de heartbeat — recuperável, mas 30 s de espera para um encerramento LIMPO seria um defeito\n * evitável. Idempotente: chamar duas vezes não é erro.\n */\n async dispose(): Promise<void> {\n const leases = [...this.#leases.values()];\n this.#leases.clear();\n for (const lease of leases) await lease.release();\n }\n}\n"]}
|
package/dist/cron.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('./chunk-
|
|
3
|
+
var chunkBOTI6ZOX_cjs = require('./chunk-BOTI6ZOX.cjs');
|
|
4
|
+
require('./chunk-P7SIIQIS.cjs');
|
|
5
5
|
require('./chunk-BV2MWEMV.cjs');
|
|
6
6
|
require('./chunk-MZ5ZRORA.cjs');
|
|
7
7
|
require('./chunk-G4WI3VW2.cjs');
|
|
8
8
|
require('./chunk-BUUUWQMB.cjs');
|
|
9
|
-
require('./chunk-
|
|
9
|
+
require('./chunk-RMRBHTA3.cjs');
|
|
10
10
|
require('./chunk-WEHUJ7ZS.cjs');
|
|
11
11
|
require('./chunk-LUSXDZPV.cjs');
|
|
12
12
|
require('./chunk-IT3PWBW4.cjs');
|
|
@@ -22,7 +22,7 @@ require('./chunk-YPEPCZHF.cjs');
|
|
|
22
22
|
require('./chunk-VJ26EKGJ.cjs');
|
|
23
23
|
require('./chunk-GIW4L6HY.cjs');
|
|
24
24
|
require('./chunk-7S7KKUO6.cjs');
|
|
25
|
-
require('./chunk-
|
|
25
|
+
require('./chunk-AFOLLMVQ.cjs');
|
|
26
26
|
require('./chunk-CJVMDRQB.cjs');
|
|
27
27
|
require('./chunk-JD74LN7R.cjs');
|
|
28
28
|
require('./chunk-YLQQX5W2.cjs');
|
|
@@ -46,7 +46,7 @@ require('./chunk-BEURCLDV.cjs');
|
|
|
46
46
|
|
|
47
47
|
Object.defineProperty(exports, "Cron", {
|
|
48
48
|
enumerable: true,
|
|
49
|
-
get: function () { return
|
|
49
|
+
get: function () { return chunkBOTI6ZOX_cjs.Cron; }
|
|
50
50
|
});
|
|
51
51
|
//# sourceMappingURL=cron.cjs.map
|
|
52
52
|
//# sourceMappingURL=cron.cjs.map
|
package/dist/cron.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export { Cron } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
export { Cron } from './chunk-MNLBNL7T.js';
|
|
2
|
+
import './chunk-JZSBSUFT.js';
|
|
3
3
|
import './chunk-2SFBB54R.js';
|
|
4
4
|
import './chunk-HRA3CPGG.js';
|
|
5
5
|
import './chunk-7BTE3RXJ.js';
|
|
6
6
|
import './chunk-K2BQQ445.js';
|
|
7
|
-
import './chunk-
|
|
7
|
+
import './chunk-4NU7GXH2.js';
|
|
8
8
|
import './chunk-IX2LKBCD.js';
|
|
9
9
|
import './chunk-6CLRANZA.js';
|
|
10
10
|
import './chunk-EEZ7CFMM.js';
|
|
@@ -20,7 +20,7 @@ import './chunk-UJ7IQJAG.js';
|
|
|
20
20
|
import './chunk-7AD3ZTZL.js';
|
|
21
21
|
import './chunk-V4XRLPEF.js';
|
|
22
22
|
import './chunk-5PZMMF4H.js';
|
|
23
|
-
import './chunk-
|
|
23
|
+
import './chunk-QWP3ZQ75.js';
|
|
24
24
|
import './chunk-UAYYNWYJ.js';
|
|
25
25
|
import './chunk-77FOZCOT.js';
|
|
26
26
|
import './chunk-2XLKLVVR.js';
|
package/dist/eval.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkS7OEXQMI_cjs = require('./chunk-S7OEXQMI.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkP7SIIQIS_cjs = require('./chunk-P7SIIQIS.cjs');
|
|
5
5
|
require('./chunk-BV2MWEMV.cjs');
|
|
6
6
|
require('./chunk-MZ5ZRORA.cjs');
|
|
7
7
|
require('./chunk-G4WI3VW2.cjs');
|
|
8
8
|
var chunkBUUUWQMB_cjs = require('./chunk-BUUUWQMB.cjs');
|
|
9
|
-
require('./chunk-
|
|
9
|
+
require('./chunk-RMRBHTA3.cjs');
|
|
10
10
|
require('./chunk-WEHUJ7ZS.cjs');
|
|
11
11
|
require('./chunk-LUSXDZPV.cjs');
|
|
12
12
|
require('./chunk-IT3PWBW4.cjs');
|
|
@@ -22,7 +22,7 @@ require('./chunk-YPEPCZHF.cjs');
|
|
|
22
22
|
require('./chunk-VJ26EKGJ.cjs');
|
|
23
23
|
require('./chunk-GIW4L6HY.cjs');
|
|
24
24
|
require('./chunk-7S7KKUO6.cjs');
|
|
25
|
-
require('./chunk-
|
|
25
|
+
require('./chunk-AFOLLMVQ.cjs');
|
|
26
26
|
var chunkCJVMDRQB_cjs = require('./chunk-CJVMDRQB.cjs');
|
|
27
27
|
require('./chunk-JD74LN7R.cjs');
|
|
28
28
|
require('./chunk-YLQQX5W2.cjs');
|
|
@@ -768,7 +768,7 @@ function makeDefaultEmbedder(opts) {
|
|
|
768
768
|
let runtime;
|
|
769
769
|
return (texts) => {
|
|
770
770
|
if (runtime === void 0) {
|
|
771
|
-
runtime =
|
|
771
|
+
runtime = chunkP7SIIQIS_cjs.openRouterMemoryEmbeddingProviderAdapter.create(embedderCreateOptions(opts));
|
|
772
772
|
}
|
|
773
773
|
return runtime.then((rt) => rt.embed(texts));
|
|
774
774
|
};
|
package/dist/eval.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { shellEscapePosix, LocalSandbox } from './chunk-SKWVAQAY.js';
|
|
2
|
-
import { openRouterMemoryEmbeddingProviderAdapter } from './chunk-
|
|
2
|
+
import { openRouterMemoryEmbeddingProviderAdapter } from './chunk-JZSBSUFT.js';
|
|
3
3
|
import './chunk-2SFBB54R.js';
|
|
4
4
|
import './chunk-HRA3CPGG.js';
|
|
5
5
|
import './chunk-7BTE3RXJ.js';
|
|
6
6
|
import { getTracer } from './chunk-K2BQQ445.js';
|
|
7
|
-
import './chunk-
|
|
7
|
+
import './chunk-4NU7GXH2.js';
|
|
8
8
|
import './chunk-IX2LKBCD.js';
|
|
9
9
|
import './chunk-6CLRANZA.js';
|
|
10
10
|
import './chunk-EEZ7CFMM.js';
|
|
@@ -20,7 +20,7 @@ import './chunk-UJ7IQJAG.js';
|
|
|
20
20
|
import './chunk-7AD3ZTZL.js';
|
|
21
21
|
import './chunk-V4XRLPEF.js';
|
|
22
22
|
import './chunk-5PZMMF4H.js';
|
|
23
|
-
import './chunk-
|
|
23
|
+
import './chunk-QWP3ZQ75.js';
|
|
24
24
|
import { readJsonlIds, appendJsonl } from './chunk-UAYYNWYJ.js';
|
|
25
25
|
export { JsonlParseError, loadJsonl } from './chunk-UAYYNWYJ.js';
|
|
26
26
|
import './chunk-77FOZCOT.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('./chunk-
|
|
3
|
+
var chunkRMRBHTA3_cjs = require('./chunk-RMRBHTA3.cjs');
|
|
4
|
+
require('./chunk-AFOLLMVQ.cjs');
|
|
5
5
|
require('./chunk-CJVMDRQB.cjs');
|
|
6
6
|
require('./chunk-YLQQX5W2.cjs');
|
|
7
7
|
require('./chunk-2DYI7MIF.cjs');
|
|
@@ -13,7 +13,7 @@ require('./chunk-BEURCLDV.cjs');
|
|
|
13
13
|
|
|
14
14
|
Object.defineProperty(exports, "FsSessionStore", {
|
|
15
15
|
enumerable: true,
|
|
16
|
-
get: function () { return
|
|
16
|
+
get: function () { return chunkRMRBHTA3_cjs.FsSessionStore; }
|
|
17
17
|
});
|
|
18
|
-
//# sourceMappingURL=fs-session-store-
|
|
19
|
-
//# sourceMappingURL=fs-session-store-
|
|
18
|
+
//# sourceMappingURL=fs-session-store-2G4O63PO.cjs.map
|
|
19
|
+
//# sourceMappingURL=fs-session-store-2G4O63PO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"fs-session-store-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"fs-session-store-2G4O63PO.cjs"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { FsSessionStore } from './chunk-4NU7GXH2.js';
|
|
2
|
+
import './chunk-QWP3ZQ75.js';
|
|
3
|
+
import './chunk-UAYYNWYJ.js';
|
|
4
|
+
import './chunk-2XLKLVVR.js';
|
|
5
|
+
import './chunk-Q56IYTBZ.js';
|
|
6
|
+
import './chunk-S2BBRVQX.js';
|
|
7
|
+
import './chunk-WLKFWQSJ.js';
|
|
8
|
+
import './chunk-JTFYYKDT.js';
|
|
9
|
+
//# sourceMappingURL=fs-session-store-Q3E5S7MC.js.map
|
|
10
|
+
//# sourceMappingURL=fs-session-store-Q3E5S7MC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"fs-session-store-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"fs-session-store-Q3E5S7MC.js"}
|
package/dist/index.cjs
CHANGED
|
@@ -8,13 +8,13 @@ require('./chunk-EPYZOCOL.cjs');
|
|
|
8
8
|
var chunkZ2OC3UIW_cjs = require('./chunk-Z2OC3UIW.cjs');
|
|
9
9
|
require('./chunk-BWT67BI4.cjs');
|
|
10
10
|
require('./chunk-PNVDQL5Y.cjs');
|
|
11
|
-
var
|
|
12
|
-
var
|
|
11
|
+
var chunkBOTI6ZOX_cjs = require('./chunk-BOTI6ZOX.cjs');
|
|
12
|
+
var chunkP7SIIQIS_cjs = require('./chunk-P7SIIQIS.cjs');
|
|
13
13
|
require('./chunk-BV2MWEMV.cjs');
|
|
14
14
|
var chunkMZ5ZRORA_cjs = require('./chunk-MZ5ZRORA.cjs');
|
|
15
15
|
require('./chunk-G4WI3VW2.cjs');
|
|
16
16
|
require('./chunk-BUUUWQMB.cjs');
|
|
17
|
-
require('./chunk-
|
|
17
|
+
require('./chunk-RMRBHTA3.cjs');
|
|
18
18
|
var chunkWEHUJ7ZS_cjs = require('./chunk-WEHUJ7ZS.cjs');
|
|
19
19
|
require('./chunk-LUSXDZPV.cjs');
|
|
20
20
|
require('./chunk-IT3PWBW4.cjs');
|
|
@@ -30,7 +30,7 @@ require('./chunk-YPEPCZHF.cjs');
|
|
|
30
30
|
require('./chunk-VJ26EKGJ.cjs');
|
|
31
31
|
require('./chunk-GIW4L6HY.cjs');
|
|
32
32
|
require('./chunk-7S7KKUO6.cjs');
|
|
33
|
-
require('./chunk-
|
|
33
|
+
require('./chunk-AFOLLMVQ.cjs');
|
|
34
34
|
require('./chunk-CJVMDRQB.cjs');
|
|
35
35
|
require('./chunk-JD74LN7R.cjs');
|
|
36
36
|
var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
|
|
@@ -58,8 +58,8 @@ var fs = require('fs');
|
|
|
58
58
|
// src/agent-factory.ts
|
|
59
59
|
function createAgentFactory(common) {
|
|
60
60
|
return {
|
|
61
|
-
forSession: (agentId, overrides) =>
|
|
62
|
-
getOrCreate: (agentId, overrides) =>
|
|
61
|
+
forSession: (agentId, overrides) => chunkP7SIIQIS_cjs.Agent.create(mergeAgentOptions(common, overrides, agentId)),
|
|
62
|
+
getOrCreate: (agentId, overrides) => chunkP7SIIQIS_cjs.Agent.getOrCreate(agentId, mergeAgentOptions(common, overrides, agentId))
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
65
|
function mergeAgentOptions(common, overrides, agentId) {
|
|
@@ -1165,7 +1165,7 @@ var Memory = {
|
|
|
1165
1165
|
return await peer.IndexManager.open(openArgs);
|
|
1166
1166
|
}
|
|
1167
1167
|
const { IndexManager } = await import('./index-manager-H7HUMW52.cjs');
|
|
1168
|
-
openArgs.embedding = await resolveEmbedding(opts.embedding,
|
|
1168
|
+
openArgs.embedding = await resolveEmbedding(opts.embedding, chunkP7SIIQIS_cjs.MEMORY_EMBEDDING_ADAPTERS);
|
|
1169
1169
|
return await IndexManager.open(openArgs);
|
|
1170
1170
|
},
|
|
1171
1171
|
/**
|
|
@@ -1176,7 +1176,7 @@ var Memory = {
|
|
|
1176
1176
|
*/
|
|
1177
1177
|
async runDreamingSweep(opts) {
|
|
1178
1178
|
const peer = await tryLoadSdkMemoryPeer();
|
|
1179
|
-
const catalog = peer !== null ? peer.MEMORY_EMBEDDING_ADAPTERS :
|
|
1179
|
+
const catalog = peer !== null ? peer.MEMORY_EMBEDDING_ADAPTERS : chunkP7SIIQIS_cjs.MEMORY_EMBEDDING_ADAPTERS;
|
|
1180
1180
|
const sweepArgs = await buildDreamingSweepArgs(opts, catalog);
|
|
1181
1181
|
const result = peer !== null ? (
|
|
1182
1182
|
// biome-ignore lint/suspicious/noExplicitAny: peer is dynamically loaded — structural compat ensured by sdk-memory
|
|
@@ -1598,7 +1598,7 @@ function ehAgenteConstruido(m) {
|
|
|
1598
1598
|
return typeof m.send === "function";
|
|
1599
1599
|
}
|
|
1600
1600
|
async function materializar(def, indice) {
|
|
1601
|
-
const { Agent: Agent2 } = await import('./agent-
|
|
1601
|
+
const { Agent: Agent2 } = await import('./agent-IJUQN6RK.cjs');
|
|
1602
1602
|
return Agent2.create({
|
|
1603
1603
|
// `AgentDefinition.model` admite o sentinel `'inherit'`, que não é um id de modelo. Herdar
|
|
1604
1604
|
// aqui significa "não declare nada e deixe o default valer" — passar o literal adiante criaria
|
|
@@ -1740,7 +1740,7 @@ var FIXTURE_USER = {
|
|
|
1740
1740
|
};
|
|
1741
1741
|
var FIXTURE_MODELS = [
|
|
1742
1742
|
{
|
|
1743
|
-
id:
|
|
1743
|
+
id: chunkP7SIIQIS_cjs.DEFAULT_AGENTIC_MODEL_ID,
|
|
1744
1744
|
name: "Gemini 2.0 Flash",
|
|
1745
1745
|
displayName: "Gemini 2.0 Flash",
|
|
1746
1746
|
parameters: [
|
|
@@ -1948,7 +1948,7 @@ var Theokit = class {
|
|
|
1948
1948
|
envVars: p.envVars
|
|
1949
1949
|
}));
|
|
1950
1950
|
},
|
|
1951
|
-
embeddingAdapters: () => Object.entries(
|
|
1951
|
+
embeddingAdapters: () => Object.entries(chunkP7SIIQIS_cjs.MEMORY_EMBEDDING_ADAPTERS).map(([id, adapter]) => ({
|
|
1952
1952
|
id,
|
|
1953
1953
|
transport: adapter.transport,
|
|
1954
1954
|
defaultModel: adapter.defaultModel
|
|
@@ -1980,17 +1980,17 @@ function resolveLocalProviderBaseUrl(providerName, fallback) {
|
|
|
1980
1980
|
return fallback;
|
|
1981
1981
|
}
|
|
1982
1982
|
async function executeCatalogRequest(request) {
|
|
1983
|
-
const apiKey =
|
|
1983
|
+
const apiKey = chunkP7SIIQIS_cjs.resolveApiKey(request.apiKey);
|
|
1984
1984
|
if (apiKey === void 0) {
|
|
1985
1985
|
throw new chunkA44COQJJ_cjs.AuthenticationError("Missing API key", { code: "missing_api_key" });
|
|
1986
1986
|
}
|
|
1987
|
-
if (
|
|
1987
|
+
if (chunkP7SIIQIS_cjs.shouldUseFixtureMode(apiKey)) {
|
|
1988
1988
|
return request.fixture;
|
|
1989
1989
|
}
|
|
1990
|
-
if (!
|
|
1990
|
+
if (!chunkP7SIIQIS_cjs.isFixtureApiKey(apiKey) && process.env.THEOKIT_API_BASE_URL === void 0) {
|
|
1991
1991
|
throw new chunkA44COQJJ_cjs.AuthenticationError("Invalid API key", { code: "authentication_error" });
|
|
1992
1992
|
}
|
|
1993
|
-
return
|
|
1993
|
+
return chunkP7SIIQIS_cjs.httpRequest(request.path, { apiKey });
|
|
1994
1994
|
}
|
|
1995
1995
|
|
|
1996
1996
|
// src/trajectory-helpers.ts
|
|
@@ -2106,35 +2106,35 @@ Object.defineProperty(exports, "GenerateObjectError", {
|
|
|
2106
2106
|
});
|
|
2107
2107
|
Object.defineProperty(exports, "Cron", {
|
|
2108
2108
|
enumerable: true,
|
|
2109
|
-
get: function () { return
|
|
2109
|
+
get: function () { return chunkBOTI6ZOX_cjs.Cron; }
|
|
2110
2110
|
});
|
|
2111
2111
|
Object.defineProperty(exports, "Agent", {
|
|
2112
2112
|
enumerable: true,
|
|
2113
|
-
get: function () { return
|
|
2113
|
+
get: function () { return chunkP7SIIQIS_cjs.Agent; }
|
|
2114
2114
|
});
|
|
2115
2115
|
Object.defineProperty(exports, "AgentBuilder", {
|
|
2116
2116
|
enumerable: true,
|
|
2117
|
-
get: function () { return
|
|
2117
|
+
get: function () { return chunkP7SIIQIS_cjs.AgentBuilder; }
|
|
2118
2118
|
});
|
|
2119
2119
|
Object.defineProperty(exports, "Tool", {
|
|
2120
2120
|
enumerable: true,
|
|
2121
|
-
get: function () { return
|
|
2121
|
+
get: function () { return chunkP7SIIQIS_cjs.Tool; }
|
|
2122
2122
|
});
|
|
2123
2123
|
Object.defineProperty(exports, "ToolError", {
|
|
2124
2124
|
enumerable: true,
|
|
2125
|
-
get: function () { return
|
|
2125
|
+
get: function () { return chunkP7SIIQIS_cjs.ToolError; }
|
|
2126
2126
|
});
|
|
2127
2127
|
Object.defineProperty(exports, "UsageAccumulator", {
|
|
2128
2128
|
enumerable: true,
|
|
2129
|
-
get: function () { return
|
|
2129
|
+
get: function () { return chunkP7SIIQIS_cjs.UsageAccumulator; }
|
|
2130
2130
|
});
|
|
2131
2131
|
Object.defineProperty(exports, "computeCost", {
|
|
2132
2132
|
enumerable: true,
|
|
2133
|
-
get: function () { return
|
|
2133
|
+
get: function () { return chunkP7SIIQIS_cjs.computeCost; }
|
|
2134
2134
|
});
|
|
2135
2135
|
Object.defineProperty(exports, "getPricingEntry", {
|
|
2136
2136
|
enumerable: true,
|
|
2137
|
-
get: function () { return
|
|
2137
|
+
get: function () { return chunkP7SIIQIS_cjs.getPricingEntry; }
|
|
2138
2138
|
});
|
|
2139
2139
|
Object.defineProperty(exports, "emitRunEvent", {
|
|
2140
2140
|
enumerable: true,
|
package/dist/index.js
CHANGED
|
@@ -6,15 +6,15 @@ import './chunk-GJAGKFTR.js';
|
|
|
6
6
|
import { Workflow, agentStep } from './chunk-BFWPZMG7.js';
|
|
7
7
|
import './chunk-UVNG67DG.js';
|
|
8
8
|
import './chunk-CAH3G4IS.js';
|
|
9
|
-
export { Cron } from './chunk-
|
|
10
|
-
import { MEMORY_EMBEDDING_ADAPTERS, resolveApiKey, shouldUseFixtureMode, isFixtureApiKey, httpRequest, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-
|
|
11
|
-
export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry } from './chunk-
|
|
9
|
+
export { Cron } from './chunk-MNLBNL7T.js';
|
|
10
|
+
import { MEMORY_EMBEDDING_ADAPTERS, resolveApiKey, shouldUseFixtureMode, isFixtureApiKey, httpRequest, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-JZSBSUFT.js';
|
|
11
|
+
export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry } from './chunk-JZSBSUFT.js';
|
|
12
12
|
import './chunk-2SFBB54R.js';
|
|
13
13
|
import { configure, submit, list, get, cancel, subscribe } from './chunk-HRA3CPGG.js';
|
|
14
14
|
export { emitRunEvent } from './chunk-HRA3CPGG.js';
|
|
15
15
|
import './chunk-7BTE3RXJ.js';
|
|
16
16
|
import './chunk-K2BQQ445.js';
|
|
17
|
-
import './chunk-
|
|
17
|
+
import './chunk-4NU7GXH2.js';
|
|
18
18
|
import { discoverProviderPlugins, mapOllamaTransportError, mapOllamaHttpError } from './chunk-IX2LKBCD.js';
|
|
19
19
|
import './chunk-6CLRANZA.js';
|
|
20
20
|
import './chunk-EEZ7CFMM.js';
|
|
@@ -30,7 +30,7 @@ import './chunk-UJ7IQJAG.js';
|
|
|
30
30
|
import './chunk-7AD3ZTZL.js';
|
|
31
31
|
import './chunk-V4XRLPEF.js';
|
|
32
32
|
import './chunk-5PZMMF4H.js';
|
|
33
|
-
import './chunk-
|
|
33
|
+
import './chunk-QWP3ZQ75.js';
|
|
34
34
|
import './chunk-UAYYNWYJ.js';
|
|
35
35
|
import './chunk-77FOZCOT.js';
|
|
36
36
|
import { withCwdMutex } from './chunk-2XLKLVVR.js';
|
|
@@ -1600,7 +1600,7 @@ function ehAgenteConstruido(m) {
|
|
|
1600
1600
|
return typeof m.send === "function";
|
|
1601
1601
|
}
|
|
1602
1602
|
async function materializar(def, indice) {
|
|
1603
|
-
const { Agent: Agent2 } = await import('./agent-
|
|
1603
|
+
const { Agent: Agent2 } = await import('./agent-F77TRYGM.js');
|
|
1604
1604
|
return Agent2.create({
|
|
1605
1605
|
// `AgentDefinition.model` admite o sentinel `'inherit'`, que não é um id de modelo. Herdar
|
|
1606
1606
|
// aqui significa "não declare nada e deixe o default valer" — passar o literal adiante criaria
|
|
@@ -46,6 +46,14 @@ export declare class FsSessionStore implements SessionStore {
|
|
|
46
46
|
* dá para perder.
|
|
47
47
|
*/
|
|
48
48
|
acquire(agentId: string): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Solta o lease de UM agente.
|
|
51
|
+
*
|
|
52
|
+
* Existe porque `dispose()` solta **todos** os leases do store, e um store injetado pelo
|
|
53
|
+
* consumidor pode servir vários agentes: um init que falha para o agente B não pode liberar o
|
|
54
|
+
* lease do agente A, que segue vivo e escrevendo.
|
|
55
|
+
*/
|
|
56
|
+
release(agentId: string): Promise<void>;
|
|
49
57
|
/**
|
|
50
58
|
* Solta todo lease que este store detém.
|
|
51
59
|
*
|
|
@@ -46,6 +46,14 @@ export declare class FsSessionStore implements SessionStore {
|
|
|
46
46
|
* dá para perder.
|
|
47
47
|
*/
|
|
48
48
|
acquire(agentId: string): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Solta o lease de UM agente.
|
|
51
|
+
*
|
|
52
|
+
* Existe porque `dispose()` solta **todos** os leases do store, e um store injetado pelo
|
|
53
|
+
* consumidor pode servir vários agentes: um init que falha para o agente B não pode liberar o
|
|
54
|
+
* lease do agente A, que segue vivo e escrevendo.
|
|
55
|
+
*/
|
|
56
|
+
release(agentId: string): Promise<void>;
|
|
49
57
|
/**
|
|
50
58
|
* Solta todo lease que este store detém.
|
|
51
59
|
*
|
package/dist/persistence.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkPNVDQL5Y_cjs = require('./chunk-PNVDQL5Y.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkAFOLLMVQ_cjs = require('./chunk-AFOLLMVQ.cjs');
|
|
5
5
|
var chunkCJVMDRQB_cjs = require('./chunk-CJVMDRQB.cjs');
|
|
6
6
|
var chunkJD74LN7R_cjs = require('./chunk-JD74LN7R.cjs');
|
|
7
7
|
var chunkYLQQX5W2_cjs = require('./chunk-YLQQX5W2.cjs');
|
|
@@ -83,11 +83,11 @@ Object.defineProperty(exports, "PersistenceSchema", {
|
|
|
83
83
|
});
|
|
84
84
|
Object.defineProperty(exports, "SessionBusyError", {
|
|
85
85
|
enumerable: true,
|
|
86
|
-
get: function () { return
|
|
86
|
+
get: function () { return chunkAFOLLMVQ_cjs.SessionBusyError; }
|
|
87
87
|
});
|
|
88
88
|
Object.defineProperty(exports, "acquireSessionWriter", {
|
|
89
89
|
enumerable: true,
|
|
90
|
-
get: function () { return
|
|
90
|
+
get: function () { return chunkAFOLLMVQ_cjs.acquireSessionWriter; }
|
|
91
91
|
});
|
|
92
92
|
Object.defineProperty(exports, "JsonlParseError", {
|
|
93
93
|
enumerable: true,
|
package/dist/persistence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { PersistenceSchema } from './chunk-CAH3G4IS.js';
|
|
2
|
-
export { SessionBusyError, acquireSessionWriter } from './chunk-
|
|
2
|
+
export { SessionBusyError, acquireSessionWriter } from './chunk-QWP3ZQ75.js';
|
|
3
3
|
export { JsonlParseError, appendJsonl, loadJsonl, readJsonlIds, withFileLock } from './chunk-UAYYNWYJ.js';
|
|
4
4
|
export { applyWalWithFallback, isCorruptionError, openSqliteResilient, sanitizeFts5Query } from './chunk-77FOZCOT.js';
|
|
5
5
|
export { withCwdMutex } from './chunk-2XLKLVVR.js';
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":["acquireSessionWriter","readTranscript","transcriptPath","path","mkdir","dirname","withFileLock","appendJsonl"],"mappings":";;;;;;;;AAyDA,IAAM,cAAA,uBAAqB,GAAA,EAAyD;AAEpF,eAAe,sBAAsB,IAAA,EAA2C;AAC9E,EAAA,MAA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AA,CAAM,OAAA,EAAQ;AAAA,EAClD;AACF","file":"chunk-IAZX7RZM.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\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { withFileLock } from \"./file-lock.js\";\nimport { appendJsonl } from \"./jsonl.js\";\nimport { readTranscript, type SessionRecord, transcriptPath } from \"./session-transcript.js\";\nimport { acquireSessionWriter, type SessionWriterLease } from \"./session-writer.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 */\n/**\n * Leases compartilhados por caminho, com contagem de referências.\n *\n * `acquireSessionWriter` é ESTRITO de propósito: duas aquisições concorrentes do mesmo caminho, e\n * exatamente uma vence — \"um lease que deixasse as duas passarem seria decorativo\" (o teste do M81\n * diz isso com todas as letras, e está certo). Esse é o contrato do primitivo, e ele não muda.\n *\n * Mas dentro de UM processo é normal existir mais de um store sobre a mesma sessão: os testes\n * golden de compactação e de sends concorrentes fazem exatamente isso, e são registro de\n * comportamento real do runtime. Aplicar o primitivo cru ali transformaria um padrão legítimo em\n * `SessionBusyError`.\n *\n * A conciliação é aqui, no consumidor do primitivo: o processo tira UM lease por caminho e conta\n * quantos stores o usam. O último a soltar libera de fato. Cross-process continua estrito — que é o\n * problema que o M81 enuncia (\"`exec resume --last` pode escrever na sessão viva da TUI\").\n */\nconst compartilhados = new Map<string, { lease: SessionWriterLease; refs: number }>();\n\nasync function adquirirCompartilhado(path: string): Promise<SessionWriterLease> {\n const existente = compartilhados.get(path);\n if (existente !== undefined) {\n existente.refs++;\n return criarProxy(path);\n }\n const lease = await acquireSessionWriter(path);\n compartilhados.set(path, { lease, refs: 1 });\n return criarProxy(path);\n}\n\n/** Um handle que decrementa a contagem; o último a soltar libera o lease de verdade. */\nfunction criarProxy(path: string): SessionWriterLease {\n let solto = false;\n return {\n sessionPath: path,\n release: async (): Promise<void> => {\n if (solto) return;\n solto = true;\n const entrada = compartilhados.get(path);\n if (entrada === undefined) return;\n entrada.refs--;\n if (entrada.refs > 0) return;\n compartilhados.delete(path);\n await entrada.lease.release();\n },\n };\n}\n\nexport class FsSessionStore implements SessionStore {\n readonly #baseDir: string;\n readonly #cwd: string;\n /** Um lease por `agentId` — um store serve mais de uma sessão ao longo da vida do processo. */\n readonly #leases = new Map<string, SessionWriterLease>();\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\n await withFileLock(path, async () => {\n // M93 — acrescenta o DELTA em vez de reescrever o arquivo inteiro.\n //\n // Antes: `readTranscript` + `writeTranscript` de tudo, por turno. O(n) de I/O **e** de parse a\n // cada turno, O(n²) por sessão — a nota do consumidor em `agents/lib/session/backtrack.ts`\n // registra 1,4 MB / 3000 linhas em 200 turnos.\n //\n // Correto porque o formato **já é append-only**: o DAG de `parentUuid` não depende da ordem de\n // linha, e cada registro carrega o próprio pai. `appendJsonl` **já existia no pacote** e tinha um\n // único chamador (`eval/runner.ts`) — a primitiva estava lá, o store é que a ignorava (rung 4).\n //\n // O `withFileLock` permanece — mas a afirmação anterior de que \"ele é o que serializa dois\n // `appendRecords` concorrentes\" era forte demais, e a revisão adversarial do M93 mediu isso:\n // removê-lo não reprova nenhum teste. A razão é o próprio parágrafo acima — o DAG de\n // `parentUuid` não depende da ordem de linha, então dois lotes intercalados reconstroem igual.\n // O trabalho que o lock fazia (proteger um read-modify-write) sumiu junto com o rewrite.\n //\n // O que ele ainda cobre é a janela TOCTOU de `precisaDeQuebraAntes` (ler o último byte, depois\n // escrever): sem ele, dois processos podem ambos concluir \"falta \\n\" e produzir uma linha em\n // branco — que o leitor descarta, isto é, benigno. Fica como **defesa declarada, não\n // mecanizada** (a disciplina de `error-handling.md § 4`: enumerar o resíduo em vez de deixar a\n // ausência de teste passar por cobertura).\n //\n // `writeTranscript` continua existindo para **compactação**, a única operação que legitimamente\n // reescreve o arquivo.\n for (const record of records) appendJsonl(path, record);\n });\n }\n\n /**\n * Toma o lease de escritor da sessão. Lança `SessionBusyError` quando outro processo a detém.\n *\n * **Explícito, e NÃO no `appendRecords`** — a revisão adversarial do M95 mediu por que isso\n * importa: o contrato de `SessionStore` diz que \"an `appendRecords` rejection is logged to\n * stderr, NOT thrown to the caller (best-effort write)\". Adquirir ali fazia o `SessionBusyError`\n * ser **engolido**, e o resultado era pior que o problema original: em vez de dois escritores\n * intercalarem linhas, o perdedor **perdia o turno em silêncio** — nada em disco, um aviso em\n * stderr invisível sob a TUI, e o chamador sem como reagir.\n *\n * No init o erro chega a quem pode agir: o `exec` forka para um id novo, que é o que a própria\n * mensagem do erro prescreve. É a diferença entre falhar onde dá para decidir e falhar onde só\n * dá para perder.\n */\n async acquire(agentId: string): Promise<void> {\n if (this.#leases.has(agentId)) return;\n const path = transcriptPath(this.#baseDir, this.#cwd, agentId);\n await mkdir(dirname(path), { recursive: true });\n this.#leases.set(agentId, await adquirirCompartilhado(path));\n }\n\n /**\n * Solta todo lease que este store detém.\n *\n * Sem isto o `.writer.lock` sobrevive ao processo e a próxima abertura teria de esperar a janela\n * de heartbeat — recuperável, mas 30 s de espera para um encerramento LIMPO seria um defeito\n * evitável. Idempotente: chamar duas vezes não é erro.\n */\n async dispose(): Promise<void> {\n const leases = [...this.#leases.values()];\n this.#leases.clear();\n for (const lease of leases) await lease.release();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":[],"mappings":";;;;AA2CO,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;AAgCO,IAAM,sBAAA,GAAyB,GAAA;AAiBtC,SAAS,UAAA,CAAW,UAAkB,IAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAA,SAA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ript.\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, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\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 */\n/**\n * Janela de obsolescência **entre máquinas** — e só entre elas.\n *\n * 30 s a partir da AQUISIÇÃO. O nome \"heartbeat\" seria mentira: o registro é gravado uma vez, na\n * tomada do lease, e **não** é renovado a cada escrita. A versão anterior deste comentário dizia\n * \"o dono toca o arquivo a cada aquisição, então um processo ativo nunca cruza a janela\" — falso\n * duas vezes, e a revisão adversarial mediu as duas.\n *\n * No **mesmo host** isso não importa: `reclamavel` decide pelo `pid`, que é exato, e a idade não\n * entra na conta. Entre hosts, importa e é um limite real: um dono remoto **vivo** perde o lease\n * depois de 30 s, porque não há como perguntar a outra máquina se o processo dela existe.\n *\n * **Resíduo declarado, não mecanizado** (a disciplina de `error-handling.md § 4`): renovar o\n * registro a cada append fecharia essa janela, ao custo de um `write` por turno num arquivo que\n * hoje é escrito uma vez por sessão. Não foi feito, e o caso multi-host não é o que motiva este\n * milestone — o enunciado é `exec` e TUI na mesma máquina.\n */\nexport const JANELA_DE_HEARTBEAT_MS = 30_000;\n\n/** Quem detém o lock. Gravado como JSON no `.writer.lock`. */\ninterface DonoDoLock {\n pid: number;\n hostname: string;\n mtime: number;\n}\n\n/**\n * Grava o dono com permissão restrita ao usuário.\n *\n * `0600` porque o lock é uma afirmação de POSSE: com o `0664` que o umask usual produz, outro\n * usuário do mesmo grupo pode sobrescrever o arquivo e forjar a posse da sessão — e a partir daí o\n * dono legítimo é quem passa a receber `SessionBusyError`. O conteúdo (`pid`, `hostname`) é de\n * baixa sensibilidade; o que a permissão protege é a **integridade** do sinal, não o sigilo dele.\n */\nfunction gravarDono(lockPath: string, dono: DonoDoLock): void {\n const fd = openSync(lockPath, \"w\", 0o600);\n try {\n writeSync(fd, JSON.stringify(dono));\n } finally {\n closeSync(fd);\n }\n}\n\n/** Lê o dono do lock. `undefined` quando o arquivo sumiu ou o conteúdo é ilegível. */\nfunction lerDono(lockPath: string): DonoDoLock | undefined {\n let bruto: string;\n try {\n bruto = readFileSync(lockPath, \"utf8\");\n } catch {\n return undefined; // sumiu entre o EEXIST e a leitura — corrida benigna, trate como livre\n }\n try {\n const d = JSON.parse(bruto) as Partial<DonoDoLock>;\n if (\n typeof d.pid !== \"number\" ||\n typeof d.hostname !== \"string\" ||\n typeof d.mtime !== \"number\"\n ) {\n return undefined;\n }\n return { pid: d.pid, hostname: d.hostname, mtime: d.mtime };\n } catch {\n // JSON ilegível: um lock que ninguém consegue interpretar não pode trancar a sessão para\n // sempre. Tratar como obsoleto é a escolha recuperável; o custo é o mesmo de um lock velho.\n return undefined;\n }\n}\n\n/** O processo existe? `signal 0` não envia nada — só consulta permissão/existência. */\nfunction processoVivo(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n // EPERM significa que ele EXISTE e é de outro usuário.\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * O lock pode ser tomado de quem o detém?\n *\n * ADR-2 do plano: reclamar por `pid` sozinho tem falso positivo entre máquinas — o mesmo número\n * existe noutro host, apontando para um processo sem relação. Então:\n *\n * - **mesmo host:** o `pid` é autoritativo, e **só** ele. Processo morto ⇒ reclamável na hora;\n * processo vivo ⇒ nunca, por mais velho que o lock esteja.\n * - **outro host:** o `pid` não diz nada aqui. Só a janela de heartbeat vale, porque é o único\n * sinal que não mente entre máquinas.\n *\n * ## Por que a idade NÃO conta no mesmo host\n *\n * A primeira versão fazia `velho || !processoVivo(pid)`, e isso era um defeito grave: o `mtime` é\n * gravado na **aquisição** e não é tocado a cada append, então qualquer sessão que durasse mais que\n * a janela — isto é, **toda sessão real** — passava a ser roubável por outro processo. Dois\n * escritores no mesmo transcript é exatamente o que o lease existe para impedir.\n *\n * No mesmo host a pergunta \"o dono ainda existe?\" tem resposta exata, e a idade não acrescenta\n * informação nenhuma a ela — só um modo de errar. Manter a janela ali seria heurística por cima de\n * um fato.\n */\nfunction reclamavel(dono: DonoDoLock | undefined): boolean {\n if (dono === undefined) return true; // ilegível ou sumido\n if (dono.hostname !== hostname()) {\n return Date.now() - dono.mtime > JANELA_DE_HEARTBEAT_MS;\n }\n return !processoVivo(dono.pid);\n}\n\nexport async function acquireSessionWriter(sessionPath: string): Promise<SessionWriterLease> {\n // M95 — `.writer.lock`, NÃO `.lock`.\n //\n // `withFileLock(path, fn)` já usa `<path>.lock` como companheiro. Enquanto o lease não era\n // chamado de lugar nenhum (o defeito que este milestone corrige) a colisão era teórica; ligá-lo\n // ao mesmo arquivo faria o lease de vida longa bloquear toda seção crítica curta do mesmo path.\n //\n // Dois arquivos porque são duas coisas: `withFileLock` protege uma seção com início e fim; o\n // lease é POSSE, mantida através de turnos, com `release()` explícito — a distinção que o\n // docstring do M81 acima já explica.\n const lockPath = `${sessionPath}.writer.lock`;\n const meu: DonoDoLock = { pid: process.pid, hostname: hostname(), mtime: Date.now() };\n let fd: number;\n try {\n // O modo vale na CRIAÇÃO — o `w` de `gravarDono` não altera arquivo existente.\n fd = openSync(lockPath, \"wx\", 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n // M95 — o lock existe. Até aqui isso bastava para recusar, e era o defeito: uma TUI morta por\n // SIGKILL trancava o usuário para fora da própria sessão PERMANENTEMENTE, sem caminho de\n // recuperação documentado. Agora o lock diz quem é o dono, e um dono morto cede o lugar.\n if (!reclamavel(lerDono(lockPath))) throw new SessionBusyError(sessionPath);\n gravarDono(lockPath, meu);\n return criarLease(sessionPath, lockPath);\n }\n closeSync(fd);\n gravarDono(lockPath, meu);\n\n return criarLease(sessionPath, lockPath);\n}\n\n/** O lease em si — `release()` idempotente. Extraído porque a aquisição tem dois caminhos de saída. */\nfunction criarLease(sessionPath: string, lockPath: string): SessionWriterLease {\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"]}
|