@theokit/sdk 4.34.0 → 4.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/{agent-EQQA5VGX.js → agent-4QDGRBWZ.js} +5 -5
- package/dist/{agent-EQQA5VGX.js.map → agent-4QDGRBWZ.js.map} +1 -1
- package/dist/{agent-W6NI3HY4.cjs → agent-RMQ5SZWO.cjs} +6 -6
- package/dist/{agent-W6NI3HY4.cjs.map → agent-RMQ5SZWO.cjs.map} +1 -1
- package/dist/{chunk-VQ6NY4F5.js → chunk-5SMWZHX5.js} +3 -3
- package/dist/{chunk-VQ6NY4F5.js.map → chunk-5SMWZHX5.js.map} +1 -1
- package/dist/{chunk-JYMBHNNU.cjs → chunk-K2BXB2TZ.cjs} +7 -4
- package/dist/chunk-K2BXB2TZ.cjs.map +1 -0
- package/dist/{chunk-IZFZ6RHA.cjs → chunk-LJVGAI2G.cjs} +5 -5
- package/dist/{chunk-IZFZ6RHA.cjs.map → chunk-LJVGAI2G.cjs.map} +1 -1
- package/dist/{chunk-IPHW3VKP.js → chunk-ODB6CFVT.js} +8 -5
- package/dist/chunk-ODB6CFVT.js.map +1 -0
- package/dist/{chunk-TPTHVSIG.js → chunk-VC6VXYKA.js} +11 -6
- package/dist/chunk-VC6VXYKA.js.map +1 -0
- package/dist/{chunk-TS6IPRME.cjs → chunk-VREQYYUJ.cjs} +14 -9
- package/dist/chunk-VREQYYUJ.cjs.map +1 -0
- package/dist/{chunk-IAZX7RZM.cjs → chunk-WPOL5UGI.cjs} +4 -4
- package/dist/{chunk-IAZX7RZM.cjs.map → chunk-WPOL5UGI.cjs.map} +1 -1
- package/dist/{chunk-5QMXYX3X.js → chunk-YO67QDHZ.js} +3 -3
- package/dist/{chunk-5QMXYX3X.js.map → chunk-YO67QDHZ.js.map} +1 -1
- 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-A5W573D3.js +10 -0
- package/dist/{fs-session-store-SJ3RA5I2.js.map → fs-session-store-A5W573D3.js.map} +1 -1
- package/dist/{fs-session-store-QS763E3Y.cjs → fs-session-store-F7PNNAIS.cjs} +5 -5
- package/dist/{fs-session-store-QS763E3Y.cjs.map → fs-session-store-F7PNNAIS.cjs.map} +1 -1
- package/dist/index.cjs +23 -23
- package/dist/index.js +6 -6
- package/dist/persistence.cjs +3 -3
- package/dist/persistence.js +1 -1
- package/package.json +1 -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/fs-session-store-SJ3RA5I2.js +0 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.34.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Corrige três formas de a trava de sessão ficar presa ou ser ignorada.
|
|
8
|
+
|
|
9
|
+
- **Uma abertura de sessão que falha depois de tomar a trava agora a solta.** O dono ficava sendo o próprio processo — vivo, mesma máquina — e a trava nunca mais era considerada obsoleta: a sessão ficava bloqueada pelo tempo de vida do processo, sem crash e sem caminho de recuperação. É a mesma situação que a trava existe para eliminar, entrando por outra porta.
|
|
10
|
+
- **Uma trava que existe mas não pode ser lida deixa de ser tratada como inexistente.** Não saber quem é o dono não é o mesmo que não haver dono: a versão anterior seguia em frente sem proteção, com outro escritor ativo na mesma sessão. Em diretório compartilhado isso era o caminho comum, porque a permissão restrita torna a trava alheia ilegível por desenho.
|
|
11
|
+
- **A permissão restrita passa a valer também para uma trava herdada de versão anterior**, que antes mantinha a permissão antiga depois de ser reclamada.
|
|
12
|
+
|
|
3
13
|
## 4.34.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export { Agent } from './chunk-
|
|
1
|
+
export { Agent } from './chunk-VC6VXYKA.js';
|
|
2
2
|
import './chunk-2SFBB54R.js';
|
|
3
3
|
import './chunk-HRA3CPGG.js';
|
|
4
4
|
import './chunk-7BTE3RXJ.js';
|
|
5
5
|
import './chunk-K2BQQ445.js';
|
|
6
|
-
import './chunk-
|
|
6
|
+
import './chunk-5SMWZHX5.js';
|
|
7
7
|
import './chunk-IX2LKBCD.js';
|
|
8
8
|
import './chunk-6CLRANZA.js';
|
|
9
9
|
import './chunk-EEZ7CFMM.js';
|
|
@@ -19,7 +19,7 @@ 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-ODB6CFVT.js';
|
|
23
23
|
import './chunk-UAYYNWYJ.js';
|
|
24
24
|
import './chunk-77FOZCOT.js';
|
|
25
25
|
import './chunk-2XLKLVVR.js';
|
|
@@ -38,5 +38,5 @@ import './chunk-POQT2OIF.js';
|
|
|
38
38
|
import './chunk-FKCC2MED.js';
|
|
39
39
|
import './chunk-WLKFWQSJ.js';
|
|
40
40
|
import './chunk-JTFYYKDT.js';
|
|
41
|
-
//# sourceMappingURL=agent-
|
|
42
|
-
//# sourceMappingURL=agent-
|
|
41
|
+
//# sourceMappingURL=agent-4QDGRBWZ.js.map
|
|
42
|
+
//# sourceMappingURL=agent-4QDGRBWZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-4QDGRBWZ.js"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkVREQYYUJ_cjs = require('./chunk-VREQYYUJ.cjs');
|
|
4
4
|
require('./chunk-BV2MWEMV.cjs');
|
|
5
5
|
require('./chunk-MZ5ZRORA.cjs');
|
|
6
6
|
require('./chunk-G4WI3VW2.cjs');
|
|
7
7
|
require('./chunk-BUUUWQMB.cjs');
|
|
8
|
-
require('./chunk-
|
|
8
|
+
require('./chunk-WPOL5UGI.cjs');
|
|
9
9
|
require('./chunk-WEHUJ7ZS.cjs');
|
|
10
10
|
require('./chunk-LUSXDZPV.cjs');
|
|
11
11
|
require('./chunk-IT3PWBW4.cjs');
|
|
@@ -21,7 +21,7 @@ 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-K2BXB2TZ.cjs');
|
|
25
25
|
require('./chunk-CJVMDRQB.cjs');
|
|
26
26
|
require('./chunk-JD74LN7R.cjs');
|
|
27
27
|
require('./chunk-YLQQX5W2.cjs');
|
|
@@ -45,7 +45,7 @@ require('./chunk-BEURCLDV.cjs');
|
|
|
45
45
|
|
|
46
46
|
Object.defineProperty(exports, "Agent", {
|
|
47
47
|
enumerable: true,
|
|
48
|
-
get: function () { return
|
|
48
|
+
get: function () { return chunkVREQYYUJ_cjs.Agent; }
|
|
49
49
|
});
|
|
50
|
-
//# sourceMappingURL=agent-
|
|
51
|
-
//# sourceMappingURL=agent-
|
|
50
|
+
//# sourceMappingURL=agent-RMQ5SZWO.cjs.map
|
|
51
|
+
//# sourceMappingURL=agent-RMQ5SZWO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"agent-RMQ5SZWO.cjs"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { acquireSessionWriter } from './chunk-
|
|
1
|
+
import { acquireSessionWriter } from './chunk-ODB6CFVT.js';
|
|
2
2
|
import { withFileLock, appendJsonl } from './chunk-UAYYNWYJ.js';
|
|
3
3
|
import { readTranscript, transcriptPath } from './chunk-Q56IYTBZ.js';
|
|
4
4
|
import { mkdir } from 'fs/promises';
|
|
@@ -86,5 +86,5 @@ var FsSessionStore = class {
|
|
|
86
86
|
};
|
|
87
87
|
|
|
88
88
|
export { FsSessionStore };
|
|
89
|
-
//# sourceMappingURL=chunk-
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
89
|
+
//# sourceMappingURL=chunk-5SMWZHX5.js.map
|
|
90
|
+
//# sourceMappingURL=chunk-5SMWZHX5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/persistence/fs-session-store.ts"],"names":[],"mappings":";;;;;;AAyDA,IAAM,cAAA,uBAAqB,GAAA,EAAyD;AAEpF,eAAe,sBAAsB,IAAA,EAA2C;AAC9E,EAAA,MAAM,SAAA,GAAY,cAAA,CAAe,GAAA,CAAI,IAAI,CAAA;AACzC,EAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,IAAA,SAAA,CAAU,IAAA,EAAA;AACV,IAAA,OAAO,WAAW,IAAI,CAAA;AAAA,EACxB;AACA,EAAA,MAAM,KAAA,GAAQ,MAAM,oBAAA,CAAqB,IAAI,CAAA;AAC7C,EAAA,cAAA,CAAe,IAAI,IAAA,EAAM,EAAE,KAAA,EAAO,IAAA,EAAM,GAAG,CAAA;AAC3C,EAAA,OAAO,WAAW,IAAI,CAAA;AACxB;AAGA,SAAS,WAAW,IAAA,EAAkC;AACpD,EAAA,IAAI,KAAA,GAAQ,KAAA;AACZ,EAAA,OAAO;AAAA,IACL,WAAA,EAAa,IAAA;AAAA,IACb,SAAS,YAA2B;AAClC,MAAA,IAAI,KAAA,EAAO;AACX,MAAA,KAAA,GAAQ,IAAA;AACR,MAAA,MAAM,OAAA,GAAU,cAAA,CAAe,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;AAC5C,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA,EAAG;AAC/B,IAAA,MAAM,OAAO,cAAA,CAAe,IAAA,CAAK,QAAA,EAAU,IAAA,CAAK,MAAM,OAAO,CAAA;AAC7D,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,IAAA,CAAK,QAAQ,GAAA,CAAI,OAAA,EAAS,MAAM,qBAAA,CAAsB,IAAI,CAAC,CAAA;AAAA,EAC7D;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-VQ6NY4F5.js","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
|
+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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-5SMWZHX5.js","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"]}
|
|
@@ -20,6 +20,7 @@ function gravarDono(lockPath, dono) {
|
|
|
20
20
|
const fd = fs.openSync(lockPath, "w", 384);
|
|
21
21
|
try {
|
|
22
22
|
fs.writeSync(fd, JSON.stringify(dono));
|
|
23
|
+
fs.fchmodSync(fd, 384);
|
|
23
24
|
} finally {
|
|
24
25
|
fs.closeSync(fd);
|
|
25
26
|
}
|
|
@@ -28,8 +29,10 @@ function lerDono(lockPath) {
|
|
|
28
29
|
let bruto;
|
|
29
30
|
try {
|
|
30
31
|
bruto = fs.readFileSync(lockPath, "utf8");
|
|
31
|
-
} catch {
|
|
32
|
-
|
|
32
|
+
} catch (err) {
|
|
33
|
+
const code = err.code;
|
|
34
|
+
if (code === "ENOENT") return void 0;
|
|
35
|
+
throw new SessionBusyError(lockPath.replace(/\.writer\.lock$/, ""));
|
|
33
36
|
}
|
|
34
37
|
try {
|
|
35
38
|
const d = JSON.parse(bruto);
|
|
@@ -86,5 +89,5 @@ function criarLease(sessionPath, lockPath) {
|
|
|
86
89
|
|
|
87
90
|
exports.SessionBusyError = SessionBusyError;
|
|
88
91
|
exports.acquireSessionWriter = acquireSessionWriter;
|
|
89
|
-
//# sourceMappingURL=chunk-
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-K2BXB2TZ.cjs.map
|
|
93
|
+
//# sourceMappingURL=chunk-K2BXB2TZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-writer.ts"],"names":["TheokitAgentError","openSync","writeSync","fchmodSync","closeSync","readFileSync","hostname","rmSync"],"mappings":";;;;;;AA2CO,IAAM,gBAAA,GAAN,cAA+BA,mCAAA,CAAkB;AAAA,EAGtD,YAAqB,WAAA,EAAqB;AACxC,IAAA,KAAA;AAAA,MACE,oDAAoD,WAAW,CAAA,gJAAA,CAAA;AAAA,MAG/D,EAAE,IAAA,EAAM,cAAA,EAAgB,WAAA,EAAa,KAAA;AAAM,KAC7C;AANmB,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA;AAAA,EAOrB;AAAA,EAPqB,WAAA;AAAA,EAFH,IAAA,GAAO,kBAAA;AAU3B;AAgCO,IAAM,sBAAA,GAAyB,GAAA;AAiBtC,SAAS,UAAA,CAAW,UAAkB,IAAA,EAAwB;AAC5D,EAAA,MAAM,EAAA,GAAKC,WAAA,CAAS,QAAA,EAAU,GAAA,EAAK,GAAK,CAAA;AACxC,EAAA,IAAI;AACF,IAAAC,YAAA,CAAU,EAAA,EAAI,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAIlC,IAAAC,aAAA,CAAW,IAAI,GAAK,CAAA;AAAA,EACtB,CAAA,SAAE;AACA,IAAAC,YAAA,CAAU,EAAE,CAAA;AAAA,EAC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2BXB2TZ.cjs","sourcesContent":["/**\n * M81 — single-writer lease for a session transcript.\n *\n * ## The problem\n *\n * Nothing stops two processes appending to the same JSONL transcript. The concrete case: `exec\n * resume --last` can write into the TUI's live session. Two interleaved appends to an append-only\n * file produce lines that are each individually valid and whose SEQUENCE is fiction — and nothing\n * reports it, because every line parses.\n *\n * ## Why an exclusive lockfile rather than `withFileLock`\n *\n * The plan's ADR D2 said to compose `withFileLock`, and that was the right instinct — do not build a\n * second lock mechanism. It turned out not to fit the SHAPE: `withFileLock(path, fn)` is\n * scope-based — it holds the lock for the duration of a callback. A session lease is **held across\n * turns**, for as long as the process owns the session, with an explicit `release()`. Wrapping the\n * whole session lifetime in a callback would invert control of the entire agent loop.\n *\n * So this uses the same underlying primitive `withFileLock` uses (an exclusive-create lockfile,\n * `wx`) with lease semantics on top. That keeps the mechanism single — the file-existence lock —\n * while giving it the lifetime the caller needs. The deviation from D2 is recorded here because the\n * plan's rationale (no second mechanism) still holds; only its shape assumption did not.\n *\n * ## Fail fast, never wait\n *\n * A second writer that WAITED would block `exec` behind a TUI session that can last hours. The typed\n * error lets the caller choose: fork to a new id, or give up with a real diagnosis.\n *\n * @internal\n */\n\nimport { closeSync, 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 // 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 chunkVREQYYUJ_cjs = require('./chunk-VREQYYUJ.cjs');
|
|
4
4
|
var chunkMZ5ZRORA_cjs = require('./chunk-MZ5ZRORA.cjs');
|
|
5
5
|
var chunkNINIJCHU_cjs = require('./chunk-NINIJCHU.cjs');
|
|
6
6
|
var chunkA44COQJJ_cjs = require('./chunk-A44COQJJ.cjs');
|
|
@@ -375,11 +375,11 @@ async function createCronJob(options) {
|
|
|
375
375
|
validateCronExpression(options.cron);
|
|
376
376
|
const timezone = options.timezone ?? "UTC";
|
|
377
377
|
validateTimezone(timezone);
|
|
378
|
-
|
|
378
|
+
chunkVREQYYUJ_cjs.resolveApiKey(options.apiKey);
|
|
379
379
|
const runtime = detectRuntime(options);
|
|
380
380
|
const now = Date.now();
|
|
381
381
|
const job = {
|
|
382
|
-
id:
|
|
382
|
+
id: chunkVREQYYUJ_cjs.generateCronId(),
|
|
383
383
|
cron: options.cron,
|
|
384
384
|
timezone,
|
|
385
385
|
enabled: options.enabled ?? true,
|
|
@@ -456,5 +456,5 @@ async function updateJobStatus(jobId, enabled) {
|
|
|
456
456
|
}
|
|
457
457
|
|
|
458
458
|
exports.Cron = Cron;
|
|
459
|
-
//# sourceMappingURL=chunk-
|
|
460
|
-
//# sourceMappingURL=chunk-
|
|
459
|
+
//# sourceMappingURL=chunk-LJVGAI2G.cjs.map
|
|
460
|
+
//# sourceMappingURL=chunk-LJVGAI2G.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/cron/run-job.ts","../src/internal/cron/fire-handler.ts","../src/internal/cron/store.ts","../src/internal/cron/scheduler.ts","../src/internal/cron/validate.ts","../src/cron.ts"],"names":["ConfigurationError","getAgentFacade","UnknownAgentError","submit","Croner","resolveApiKey","generateCronId"],"mappings":";;;;;;;;;AAoBA,eAAsB,WAAW,GAAA,EAA0C;AAIzE,EAAA,IAAI,GAAA,CAAI,aAAa,MAAA,EAAW,OAAO,IAAI,QAAA,CAAS,GAAA,CAAI,IAAI,SAAS,CAAA;AACrE,EAAA,IAAI,GAAA,CAAI,UAAU,MAAA,EAAW,OAAO,sBAAsB,GAAA,CAAI,KAAA,EAAO,cAAA,CAAe,GAAG,CAAC,CAAA;AACxF,EAAA,IAAI,GAAA,CAAI,YAAY,MAAA,EAAW,OAAO,qBAAqB,GAAA,CAAI,OAAA,EAAS,cAAA,CAAe,GAAG,CAAC,CAAA;AAC3F,EAAA,MAAM,IAAIA,oCAAA;AAAA,IACR,CAAA,SAAA,EAAY,IAAI,EAAE,CAAA,+DAAA,CAAA;AAAA,IAClB,EAAE,MAAM,gBAAA;AAAiB,GAC3B;AACF;AAOO,SAAS,WAAW,OAAA,EAA4C;AACrE,EAAA,OAAO,OAAQ,QAAgB,IAAA,KAAS,UAAA;AAC1C;AAGA,SAAS,eAAe,GAAA,EAAuC;AAC7D,EA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ZFZ6RHA.cjs","sourcesContent":["import { ConfigurationError, UnknownAgentError } from \"../../errors.js\";\nimport type { AgentOptions } from \"../../types/agent.js\";\nimport type { CronJob } from \"../../types/cron.js\";\nimport type { Run, SDKUserMessage } from \"../../types/run.js\";\nimport type { WorkflowRun } from \"../../types/workflow.js\";\nimport { getAgentFacade } from \"../runtime/registry/agent-factory-registry.js\";\n\n/**\n * Execute a cron job. Dispatches to one of three targets:\n * - `workflow` (SE35) → `workflow.run(inputData)` on the held instance (the\n * instance carries its own `.run`, so this module never imports `workflow.ts`),\n * returning the already-terminal {@link WorkflowRun}.\n * - `agent` → an ephemeral agent per fire; `agent.send(message)` → {@link Run}.\n * - `agentId` → reuse an existing agent; `agent.send(message)` → {@link Run}.\n *\n * Used by both `Cron.run(jobId)` (manual off-schedule fire) and the scheduler's\n * default fire handler. ADR 0014.\n *\n * @internal\n */\nexport async function runCronJob(job: CronJob): Promise<Run | WorkflowRun> {\n // `Workflow.run()` resolves only on a TERMINAL run (completed/failed/suspended/\n // cancelled — the executor never returns `status: \"running\"`), so the fire\n // handler treats the returned WorkflowRun as terminal (no `.wait()`).\n if (job.workflow !== undefined) return job.workflow.run(job.inputData);\n if (job.agent !== undefined) return runWithEphemeralAgent(job.agent, requireMessage(job));\n if (job.agentId !== undefined) return runWithExistingAgent(job.agentId, requireMessage(job));\n throw new ConfigurationError(\n `Cron job ${job.id} has no target (agent, agentId, or workflow) — cannot run.`,\n { code: \"cron_no_target\" },\n );\n}\n\n/**\n * Discriminate the {@link runCronJob} union: an agent `Run` is deferred (carries\n * `.wait()`/`.cancel()`); a {@link WorkflowRun} is already terminal (no `.wait()`).\n * @internal\n */\nexport function isAgentRun(outcome: Run | WorkflowRun): outcome is Run {\n return typeof (outcome as Run).wait === \"function\";\n}\n\n/** Agent targets require a message; fail-loud if one somehow reached a fire without it. */\nfunction requireMessage(job: CronJob): string | SDKUserMessage {\n if (job.message === undefined) {\n throw new ConfigurationError(`Cron job ${job.id} is an agent target but has no message.`, {\n code: \"cron_missing_message\",\n });\n }\n return job.message;\n}\n\nasync function runWithExistingAgent(\n agentId: string,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const info = await getAgentFacade()\n .get(agentId)\n .catch(() => undefined);\n if (info === undefined) {\n throw new UnknownAgentError(\n `Cron job references agentId \"${agentId}\" but no such agent is registered. The agent may have been disposed or the process restarted without persisting the agent registry.`,\n { code: \"agent_not_registered\" },\n );\n }\n const agent = await getAgentFacade().resume(agentId);\n return agent.send(message);\n}\n\nasync function runWithEphemeralAgent(\n baseOptions: AgentOptions,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const agent = await getAgentFacade().create(baseOptions);\n return agent.send(message);\n}\n","/**\n * Default cron fire handler (extracted from `Cron.start` for testability + G8).\n *\n * Every fire registers as a Task (ADRs D363/D374) so callers observe it via\n * `Task.list` / `Task.subscribe`. SE35 (ADR 0014): the fire target may be an\n * agent (a deferred {@link Run} — abort-wire + `wait()`) OR a workflow (an\n * already-terminal {@link WorkflowRun} — no `wait()`); `isAgentRun` discriminates\n * so the handler records the correct terminal status/runId for each shape.\n *\n * @internal\n */\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { submit as taskRegistrySubmit } from \"../task/registry.js\";\nimport { isAgentRun, runCronJob } from \"./run-job.js\";\n\nexport async function fireCronJobAsTask(job: CronJob): Promise<void> {\n // The task id namespace `cron-{jobId}-{fireEpochMs}` honors D368/EC-5.\n const fireTs = Date.now();\n const taskId = `cron-${job.id}-${fireTs}`;\n try {\n await taskRegistrySubmit({\n kind: \"cron\",\n id: taskId,\n allowReservedPrefix: true,\n meta: { jobId: job.id, jobName: job.name, schedule: job.cron, firedAt: fireTs },\n work: async (ctx) => {\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) {\n // Agent target — the Run is deferred: abort-wire + await terminal.\n ctx.signal.addEventListener(\"abort\", () => void outcome.cancel().catch(() => {}), {\n once: true,\n });\n const result = await outcome.wait();\n ctx.emit({ status: result.status, runId: outcome.id });\n return { status: result.status, runId: outcome.id };\n }\n // SE35 workflow target — the WorkflowRun is ALREADY terminal (no wait()).\n ctx.emit({ status: outcome.status, runId: outcome.id });\n return { status: outcome.status, runId: outcome.id };\n },\n });\n } catch {\n // Task registry must not break cron — fall through to a direct run. No\n // double-execution: `taskRegistrySubmit` runs `work` (which calls\n // `runCronJob`) fire-and-forget, so a throw here means the SUBMIT itself\n // failed (id/registry setup) BEFORE `work` started — the job never ran, and\n // this is its first + only execution.\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) await outcome.wait();\n }\n}\n","import type { CronJob } from \"../../types/cron.js\";\n\n/**\n * Process-wide cron job store. In Phase 1 we keep all jobs in memory\n * (across local + cloud runtimes). Local-runtime persistence to\n * `.theokit/cron/jobs.json` lands when the local runtime adapter is wired.\n *\n * @internal\n */\nconst jobs = new Map<string, CronJob>();\n\n/** Snapshot of every known cron job. @internal */\nexport function listJobs(): CronJob[] {\n return Array.from(jobs.values());\n}\n\n/** Total job count across runtimes. @internal */\nexport function jobCount(): number {\n return jobs.size;\n}\n\n/** Fetch a single job by id, or `undefined` if it does not exist. @internal */\nexport function getJob(jobId: string): CronJob | undefined {\n return jobs.get(jobId);\n}\n\n/** Insert or replace a job. @internal */\nexport function upsertJob(job: CronJob): void {\n jobs.set(job.id, job);\n}\n\n/** Delete a job. Returns `true` if a job was removed. @internal */\nexport function deleteJob(jobId: string): boolean {\n return jobs.delete(jobId);\n}\n\n/** Test-only: drop every job. @internal */\nexport function clearJobs(): void {\n jobs.clear();\n}\n","import { Cron as Croner } from \"croner\";\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { listJobs, upsertJob } from \"./store.js\";\n\n/**\n * Real local cron scheduler. When `Cron.start()` is called the scheduler\n * installs a Croner timer per enabled local job; on fire the registered\n * fire handler runs the underlying agent. `Cron.stop()` tears every timer\n * down but keeps the jobs in the store.\n *\n * @internal\n */\n\nexport type CronFireHandler = (job: CronJob) => Promise<void> | void;\n\ninterface SchedulerState {\n running: boolean;\n cwd?: string;\n timers: Map<string, Croner>;\n fireHandler?: CronFireHandler;\n}\n\nconst state: SchedulerState = { running: false, timers: new Map() };\n\n/**\n * Register the callback invoked when a job fires. The runtime adapter\n * supplies a handler that actually executes the agent; fixture-mode tests\n * leave it unset so timers tick without side effects.\n *\n * @internal\n */\nexport function setCronFireHandler(handler: CronFireHandler | undefined): void {\n state.fireHandler = handler;\n}\n\n/** Activate the scheduler and install timers for every enabled local job. @internal */\nexport function startScheduler(cwd?: string): void {\n state.running = true;\n if (cwd !== undefined) state.cwd = cwd;\n for (const job of listJobs()) {\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n }\n}\n\n/** Deactivate the scheduler. Stops every timer; jobs remain in the store. @internal */\nexport function stopScheduler(): void {\n state.running = false;\n for (const timer of state.timers.values()) timer.stop();\n state.timers.clear();\n}\n\n/** Schedule a single job. No-op if the scheduler is not running. @internal */\nexport function scheduleJob(job: CronJob): void {\n if (!state.running) return;\n unscheduleJob(job.id);\n const expression = normalizeExpression(job.cron);\n const timer = new Croner(\n expression,\n { timezone: job.timezone, name: job.id, protect: true },\n () => {\n void fireJob(job.id);\n },\n );\n state.timers.set(job.id, timer);\n refreshNextRunAt(job.id, timer);\n}\n\n/** Tear down the timer for a single job. @internal */\nexport function unscheduleJob(jobId: string): boolean {\n const timer = state.timers.get(jobId);\n if (timer === undefined) return false;\n timer.stop();\n state.timers.delete(jobId);\n return true;\n}\n\n/** Snapshot of the scheduler's running flag and configured workspace. @internal */\nexport function getSchedulerState(): { running: boolean; cwd?: string } {\n const result: { running: boolean; cwd?: string } = { running: state.running };\n if (state.cwd !== undefined) result.cwd = state.cwd;\n return result;\n}\n\nasync function fireJob(jobId: string): Promise<void> {\n const fresh = listJobs().find((entry) => entry.id === jobId);\n if (fresh === undefined || fresh.enabled === false) return;\n const handler = state.fireHandler;\n upsertJob({ ...fresh, lastRunAt: Date.now() });\n if (handler === undefined) return;\n try {\n await handler(fresh);\n } catch {\n // Swallow handler errors — the scheduler must keep ticking. Real\n // surface for run failures lives on the Run.wait() result itself.\n }\n}\n\nfunction refreshNextRunAt(jobId: string, timer: Croner): void {\n const next = timer.nextRun();\n if (next === null) return;\n const existing = listJobs().find((entry) => entry.id === jobId);\n if (existing === undefined) return;\n upsertJob({ ...existing, nextRunAt: next.getTime() });\n}\n\nfunction normalizeExpression(cron: string): string {\n switch (cron) {\n case \"@hourly\":\n return \"0 * * * *\";\n case \"@daily\":\n return \"0 0 * * *\";\n case \"@weekly\":\n return \"0 0 * * 0\";\n case \"@monthly\":\n return \"0 0 1 * *\";\n case \"@yearly\":\n return \"0 0 1 1 *\";\n default:\n return cron;\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\n\n/**\n * POSIX-cron + shorthand validators used by `Cron.create()`. Throws\n * `ConfigurationError` with a stable message and code on invalid input.\n *\n * @internal\n */\n\nconst SHORTHANDS = new Set([\"@hourly\", \"@daily\", \"@weekly\", \"@monthly\", \"@yearly\"]);\n\ninterface FieldRange {\n min: number;\n max: number;\n}\n\nconst FIELD_RANGES: readonly FieldRange[] = [\n { min: 0, max: 59 }, // minute\n { min: 0, max: 23 }, // hour\n { min: 1, max: 31 }, // day-of-month\n { min: 1, max: 12 }, // month\n { min: 0, max: 6 }, // day-of-week\n];\n\n/**\n * Validate a cron expression. Accepts shorthand (`@hourly`, ..., `@yearly`)\n * or 5-field POSIX cron with star, literals, star/N step, N-M range, and\n * N,M,P list.\n *\n * @internal\n */\nexport function validateCronExpression(cron: string): void {\n if (typeof cron !== \"string\" || cron.length === 0) {\n throw new ConfigurationError(\"Invalid cron expression: empty\", {\n code: \"invalid_cron\",\n });\n }\n if (cron.startsWith(\"@\")) {\n if (!SHORTHANDS.has(cron)) {\n throw new ConfigurationError(`Invalid cron expression: unknown shorthand ${cron}`, {\n code: \"invalid_cron\",\n });\n }\n return;\n }\n\n const fields = cron.trim().split(/\\s+/);\n if (fields.length !== 5) {\n throw new ConfigurationError(\n `Invalid cron expression: ${cron} (expected 5 fields, got ${fields.length})`,\n { code: \"invalid_cron\" },\n );\n }\n for (const [index, field] of fields.entries()) {\n validateFieldOrThrow(field, index, cron);\n }\n}\n\nfunction validateFieldOrThrow(field: string, index: number, cron: string): void {\n const range = FIELD_RANGES[index];\n if (range === undefined) {\n throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {\n code: \"invalid_cron\",\n });\n }\n if (!isValidCronField(field, range)) {\n throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {\n code: \"invalid_cron\",\n });\n }\n}\n\nfunction isValidCronField(field: string, range: FieldRange): boolean {\n if (field === \"*\") return true;\n if (field.startsWith(\"*/\")) return isValidStep(field.slice(2), range);\n if (field.includes(\",\")) {\n return field.split(\",\").every((part) => isValidCronField(part, range));\n }\n if (field.includes(\"-\")) return isValidRange(field, range);\n return isValidLiteral(field, range);\n}\n\nfunction isValidStep(stepStr: string, range: FieldRange): boolean {\n const step = Number.parseInt(stepStr, 10);\n return Number.isInteger(step) && String(step) === stepStr && step > 0 && step <= range.max;\n}\n\nfunction isValidRange(field: string, range: FieldRange): boolean {\n const parts = field.split(\"-\");\n if (parts.length !== 2) return false;\n const [startStr, endStr] = parts;\n if (startStr === undefined || endStr === undefined) return false;\n const start = Number.parseInt(startStr, 10);\n const end = Number.parseInt(endStr, 10);\n if (!Number.isInteger(start) || !Number.isInteger(end)) return false;\n return start >= range.min && end <= range.max && start <= end;\n}\n\nfunction isValidLiteral(field: string, range: FieldRange): boolean {\n const n = Number.parseInt(field, 10);\n return Number.isInteger(n) && String(n) === field && n >= range.min && n <= range.max;\n}\n\n/**\n * Validate an IANA timezone. Uses `Intl.DateTimeFormat`'s strict timezone\n * lookup; invalid values raise `RangeError` which we wrap.\n *\n * @internal\n */\nexport function validateTimezone(timezone: string): void {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n } catch {\n throw new ConfigurationError(`Invalid IANA timezone: ${timezone}`, {\n code: \"invalid_timezone\",\n });\n }\n}\n\n/**\n * Heuristic next-fire-at estimator for fixture mode. Returns a timestamp\n * one hour in the future for shorthand/POSIX inputs. Real scheduling uses\n * a proper evaluator wired in by the local scheduler.\n *\n * @internal\n */\nexport function estimateNextRunAt(_cron: string, _timezone: string): number {\n return Date.now() + 60 * 60 * 1000;\n}\n","// Bootstrap import: loading this facade must register the public Agent facade\n// into the agent-factory-registry seam, because `internal/cron/run-job.ts`\n// resolves it via `getAgentFacade()` at runtime instead of importing `agent.ts`\n// directly (which would invert the public-api -> internal dependency\n// direction). The `@theokit/sdk/cron` sub-path entry would otherwise throw\n// \"Agent facade not registered\" at runtime.\nimport \"./agent.js\";\nimport { ConfigurationError, UnknownAgentError } from \"./errors.js\";\nimport { fireCronJobAsTask } from \"./internal/cron/fire-handler.js\";\nimport { runCronJob } from \"./internal/cron/run-job.js\";\nimport {\n getSchedulerState,\n scheduleJob,\n setCronFireHandler,\n startScheduler,\n stopScheduler,\n unscheduleJob,\n} from \"./internal/cron/scheduler.js\";\nimport { deleteJob, getJob, jobCount, listJobs, upsertJob } from \"./internal/cron/store.js\";\nimport {\n estimateNextRunAt,\n validateCronExpression,\n validateTimezone,\n} from \"./internal/cron/validate.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { generateCronId } from \"./internal/ids.js\";\nimport type { AgentOptions, ListResult } from \"./types/agent.js\";\nimport type {\n CronCreateOptions,\n CronGetOptions,\n CronJob,\n CronListOptions,\n CronOperationOptions,\n CronRunOptions,\n CronRuntime,\n CronSchedulerStatus,\n CronStartOptions,\n} from \"./types/cron.js\";\nimport type { Run } from \"./types/run.js\";\n\n/**\n * Static façade for scheduling Theo agent runs on a cron expression.\n *\n * @public\n */\nexport class Cron {\n private constructor() {\n // Static-only façade.\n }\n\n /**\n * Create and persist a cron job.\n *\n * @public\n */\n static async create(options: CronCreateOptions): Promise<CronJob> {\n const job = await createCronJob(options);\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n return job;\n }\n\n /**\n * List cron jobs (local, cloud, or both).\n *\n * @public\n */\n static list(options: CronListOptions = {}): Promise<ListResult<CronJob>> {\n const runtimeFilter = options.runtime;\n const items = listJobs().filter((job) =>\n runtimeFilter === undefined ? true : job.runtime === runtimeFilter,\n );\n return Promise.resolve({ items });\n }\n\n /**\n * Get a single cron job by ID.\n *\n * @public\n */\n static get(jobId: string, _options: CronGetOptions = {}): Promise<CronJob> {\n const job = getJob(jobId);\n if (job === undefined) {\n return Promise.reject(\n new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" }),\n );\n }\n return Promise.resolve(job);\n }\n\n /**\n * Delete a cron job permanently.\n *\n * @public\n */\n static delete(jobId: string, _options: CronOperationOptions = {}): Promise<void> {\n unscheduleJob(jobId);\n deleteJob(jobId);\n return Promise.resolve();\n }\n\n /**\n * Re-enable a paused cron job.\n *\n * @public\n */\n static async enable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, true);\n }\n\n /**\n * Pause a cron job without deleting it.\n *\n * @public\n */\n static async disable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, false);\n }\n\n /**\n * Manually trigger a cron job off-schedule. Returns the resulting `Run`\n * (agent target) or `WorkflowRun` (workflow target — SE35).\n *\n * @public\n */\n static async run(\n jobId: string,\n _options: CronRunOptions = {},\n ): Promise<Run | import(\"./types/workflow.js\").WorkflowRun> {\n const job = getJob(jobId);\n if (job === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n return runCronJob(job);\n }\n\n /**\n * Activate the in-process scheduler for local cron jobs.\n *\n * @public\n */\n static start(options: CronStartOptions = {}): Promise<void> {\n // Install the default fire handler so timer ticks actually drive a real\n // agent/workflow run. Users can override via `setCronFireHandler` from\n // `@theokit/sdk/internal` (test-mode hook). Handler body lives in\n // `internal/cron/fire-handler.ts` (testable + G8).\n setCronFireHandler(fireCronJobAsTask);\n startScheduler(options.cwd);\n return Promise.resolve();\n }\n\n /**\n * Stop the in-process scheduler. Jobs are preserved.\n *\n * @public\n */\n static stop(): Promise<void> {\n stopScheduler();\n return Promise.resolve();\n }\n\n /**\n * Snapshot of the local scheduler.\n *\n * @public\n */\n static status(_options: CronStartOptions = {}): Promise<CronSchedulerStatus> {\n const scheduler = getSchedulerState();\n return Promise.resolve({ running: scheduler.running, jobCount: jobCount() });\n }\n}\n\nasync function createCronJob(options: CronCreateOptions): Promise<CronJob> {\n validateCronTarget(options);\n\n validateCronExpression(options.cron);\n const timezone = options.timezone ?? \"UTC\";\n validateTimezone(timezone);\n\n // apiKey is accepted but not required for cron-create in fixture mode.\n resolveApiKey(options.apiKey);\n\n const runtime = detectRuntime(options);\n const now = Date.now();\n const job: CronJob = {\n id: generateCronId(),\n cron: options.cron,\n timezone,\n enabled: options.enabled ?? true,\n status: options.enabled === false ? \"paused\" : \"scheduled\",\n runtime,\n createdAt: now,\n nextRunAt: estimateNextRunAt(options.cron, timezone),\n ...(options.name !== undefined ? { name: options.name } : {}),\n ...(options.message !== undefined ? { message: options.message } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n ...(options.agentId !== undefined ? { agentId: options.agentId } : {}),\n ...(options.workflow !== undefined ? { workflow: options.workflow } : {}),\n ...(options.inputData !== undefined ? { inputData: options.inputData } : {}),\n };\n upsertJob(job);\n return job;\n}\n\n/**\n * SE35 (ADR 0014) — exactly ONE target (`agent` | `agentId` | `workflow`).\n * Agent targets require `message`; a workflow target takes `inputData` and MUST\n * NOT set `message`.\n */\nfunction validateCronTarget(options: CronCreateOptions): void {\n const targets = [options.agent, options.agentId, options.workflow].filter(\n (t) => t !== undefined,\n ).length;\n if (targets > 1) {\n throw new ConfigurationError(\n \"agent, agentId, and workflow are mutually exclusive — pass exactly one target.\",\n { code: \"cron_ambiguous_target\" },\n );\n }\n if (targets === 0) {\n throw new ConfigurationError(\n \"Cron job requires exactly one target: agent, agentId, or workflow.\",\n { code: \"cron_no_target\" },\n );\n }\n if (options.workflow !== undefined && options.message !== undefined) {\n throw new ConfigurationError(\n \"A workflow cron target takes inputData, not a message — remove `message`.\",\n { code: \"cron_workflow_message\" },\n );\n }\n if (options.workflow === undefined && options.message === undefined) {\n throw new ConfigurationError(\"An agent cron target requires a message.\", {\n code: \"cron_missing_message\",\n });\n }\n}\n\nfunction detectRuntime(options: CronCreateOptions): CronRuntime {\n // SE35 — a workflow target is a held in-memory instance; it can only run in\n // the local (in-process) scheduler. A workflow instance cannot cross the\n // cloud process boundary (ADR 0014).\n if (options.workflow !== undefined) return \"local\";\n if (options.agentId !== undefined) {\n return options.agentId.startsWith(\"bc-\") ? \"cloud\" : \"local\";\n }\n const agent = options.agent as AgentOptions | undefined;\n if (agent?.cloud !== undefined) return \"cloud\";\n return \"local\";\n}\n\nasync function updateJobStatus(jobId: string, enabled: boolean): Promise<CronJob> {\n const existing = getJob(jobId);\n if (existing === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n const updated: CronJob = {\n ...existing,\n enabled,\n status: enabled ? \"scheduled\" : \"paused\",\n };\n upsertJob(updated);\n if (updated.runtime === \"local\") {\n if (enabled) {\n scheduleJob(updated);\n } else {\n unscheduleJob(updated.id);\n }\n }\n return updated;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/cron/run-job.ts","../src/internal/cron/fire-handler.ts","../src/internal/cron/store.ts","../src/internal/cron/scheduler.ts","../src/internal/cron/validate.ts","../src/cron.ts"],"names":["ConfigurationError","getAgentFacade","UnknownAgentError","submit","Croner","resolveApiKey","generateCronId"],"mappings":";;;;;;;;;AAoBA,eAAsB,WAAW,GAAA,EAA0C;AAIzE,EAAA,IAAI,GAAA,CAAI,aAAa,MAAA,EAAW,OAAO,IAAI,QAAA,CAAS,GAAA,CAAI,IAAI,SAAS,CAAA;AACrE,EAAA,IAAI,GAAA,CAAI,UAAU,MAAA,EAAW,OAAO,sBAAsB,GAAA,CAAI,KA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,oBAAoB,CAAA;AAAA,EACzF;AACA,EAAA,MAAM,OAAA,GAAmB;AAAA,IACvB,GAAG,QAAA;AAAA,IACH,OAAA;AAAA,IACA,MAAA,EAAQ,UAAU,WAAA,GAAc;AAAA,GAClC;AACA,EAAA,SAAA,CAAU,OAAO,CAAA;AACjB,EAAA,IAAI,OAAA,CAAQ,YAAY,OAAA,EAAS;AAC/B,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,WAAA,CAAY,OAAO,CAAA;AAAA,IACrB,CAAA,MAAO;AACL,MAAA,aAAA,CAAc,QAAQ,EAAE,CAAA;AAAA,IAC1B;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-LJVGAI2G.cjs","sourcesContent":["import { ConfigurationError, UnknownAgentError } from \"../../errors.js\";\nimport type { AgentOptions } from \"../../types/agent.js\";\nimport type { CronJob } from \"../../types/cron.js\";\nimport type { Run, SDKUserMessage } from \"../../types/run.js\";\nimport type { WorkflowRun } from \"../../types/workflow.js\";\nimport { getAgentFacade } from \"../runtime/registry/agent-factory-registry.js\";\n\n/**\n * Execute a cron job. Dispatches to one of three targets:\n * - `workflow` (SE35) → `workflow.run(inputData)` on the held instance (the\n * instance carries its own `.run`, so this module never imports `workflow.ts`),\n * returning the already-terminal {@link WorkflowRun}.\n * - `agent` → an ephemeral agent per fire; `agent.send(message)` → {@link Run}.\n * - `agentId` → reuse an existing agent; `agent.send(message)` → {@link Run}.\n *\n * Used by both `Cron.run(jobId)` (manual off-schedule fire) and the scheduler's\n * default fire handler. ADR 0014.\n *\n * @internal\n */\nexport async function runCronJob(job: CronJob): Promise<Run | WorkflowRun> {\n // `Workflow.run()` resolves only on a TERMINAL run (completed/failed/suspended/\n // cancelled — the executor never returns `status: \"running\"`), so the fire\n // handler treats the returned WorkflowRun as terminal (no `.wait()`).\n if (job.workflow !== undefined) return job.workflow.run(job.inputData);\n if (job.agent !== undefined) return runWithEphemeralAgent(job.agent, requireMessage(job));\n if (job.agentId !== undefined) return runWithExistingAgent(job.agentId, requireMessage(job));\n throw new ConfigurationError(\n `Cron job ${job.id} has no target (agent, agentId, or workflow) — cannot run.`,\n { code: \"cron_no_target\" },\n );\n}\n\n/**\n * Discriminate the {@link runCronJob} union: an agent `Run` is deferred (carries\n * `.wait()`/`.cancel()`); a {@link WorkflowRun} is already terminal (no `.wait()`).\n * @internal\n */\nexport function isAgentRun(outcome: Run | WorkflowRun): outcome is Run {\n return typeof (outcome as Run).wait === \"function\";\n}\n\n/** Agent targets require a message; fail-loud if one somehow reached a fire without it. */\nfunction requireMessage(job: CronJob): string | SDKUserMessage {\n if (job.message === undefined) {\n throw new ConfigurationError(`Cron job ${job.id} is an agent target but has no message.`, {\n code: \"cron_missing_message\",\n });\n }\n return job.message;\n}\n\nasync function runWithExistingAgent(\n agentId: string,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const info = await getAgentFacade()\n .get(agentId)\n .catch(() => undefined);\n if (info === undefined) {\n throw new UnknownAgentError(\n `Cron job references agentId \"${agentId}\" but no such agent is registered. The agent may have been disposed or the process restarted without persisting the agent registry.`,\n { code: \"agent_not_registered\" },\n );\n }\n const agent = await getAgentFacade().resume(agentId);\n return agent.send(message);\n}\n\nasync function runWithEphemeralAgent(\n baseOptions: AgentOptions,\n message: string | SDKUserMessage,\n): Promise<Run> {\n const agent = await getAgentFacade().create(baseOptions);\n return agent.send(message);\n}\n","/**\n * Default cron fire handler (extracted from `Cron.start` for testability + G8).\n *\n * Every fire registers as a Task (ADRs D363/D374) so callers observe it via\n * `Task.list` / `Task.subscribe`. SE35 (ADR 0014): the fire target may be an\n * agent (a deferred {@link Run} — abort-wire + `wait()`) OR a workflow (an\n * already-terminal {@link WorkflowRun} — no `wait()`); `isAgentRun` discriminates\n * so the handler records the correct terminal status/runId for each shape.\n *\n * @internal\n */\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { submit as taskRegistrySubmit } from \"../task/registry.js\";\nimport { isAgentRun, runCronJob } from \"./run-job.js\";\n\nexport async function fireCronJobAsTask(job: CronJob): Promise<void> {\n // The task id namespace `cron-{jobId}-{fireEpochMs}` honors D368/EC-5.\n const fireTs = Date.now();\n const taskId = `cron-${job.id}-${fireTs}`;\n try {\n await taskRegistrySubmit({\n kind: \"cron\",\n id: taskId,\n allowReservedPrefix: true,\n meta: { jobId: job.id, jobName: job.name, schedule: job.cron, firedAt: fireTs },\n work: async (ctx) => {\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) {\n // Agent target — the Run is deferred: abort-wire + await terminal.\n ctx.signal.addEventListener(\"abort\", () => void outcome.cancel().catch(() => {}), {\n once: true,\n });\n const result = await outcome.wait();\n ctx.emit({ status: result.status, runId: outcome.id });\n return { status: result.status, runId: outcome.id };\n }\n // SE35 workflow target — the WorkflowRun is ALREADY terminal (no wait()).\n ctx.emit({ status: outcome.status, runId: outcome.id });\n return { status: outcome.status, runId: outcome.id };\n },\n });\n } catch {\n // Task registry must not break cron — fall through to a direct run. No\n // double-execution: `taskRegistrySubmit` runs `work` (which calls\n // `runCronJob`) fire-and-forget, so a throw here means the SUBMIT itself\n // failed (id/registry setup) BEFORE `work` started — the job never ran, and\n // this is its first + only execution.\n const outcome = await runCronJob(job);\n if (isAgentRun(outcome)) await outcome.wait();\n }\n}\n","import type { CronJob } from \"../../types/cron.js\";\n\n/**\n * Process-wide cron job store. In Phase 1 we keep all jobs in memory\n * (across local + cloud runtimes). Local-runtime persistence to\n * `.theokit/cron/jobs.json` lands when the local runtime adapter is wired.\n *\n * @internal\n */\nconst jobs = new Map<string, CronJob>();\n\n/** Snapshot of every known cron job. @internal */\nexport function listJobs(): CronJob[] {\n return Array.from(jobs.values());\n}\n\n/** Total job count across runtimes. @internal */\nexport function jobCount(): number {\n return jobs.size;\n}\n\n/** Fetch a single job by id, or `undefined` if it does not exist. @internal */\nexport function getJob(jobId: string): CronJob | undefined {\n return jobs.get(jobId);\n}\n\n/** Insert or replace a job. @internal */\nexport function upsertJob(job: CronJob): void {\n jobs.set(job.id, job);\n}\n\n/** Delete a job. Returns `true` if a job was removed. @internal */\nexport function deleteJob(jobId: string): boolean {\n return jobs.delete(jobId);\n}\n\n/** Test-only: drop every job. @internal */\nexport function clearJobs(): void {\n jobs.clear();\n}\n","import { Cron as Croner } from \"croner\";\n\nimport type { CronJob } from \"../../types/cron.js\";\nimport { listJobs, upsertJob } from \"./store.js\";\n\n/**\n * Real local cron scheduler. When `Cron.start()` is called the scheduler\n * installs a Croner timer per enabled local job; on fire the registered\n * fire handler runs the underlying agent. `Cron.stop()` tears every timer\n * down but keeps the jobs in the store.\n *\n * @internal\n */\n\nexport type CronFireHandler = (job: CronJob) => Promise<void> | void;\n\ninterface SchedulerState {\n running: boolean;\n cwd?: string;\n timers: Map<string, Croner>;\n fireHandler?: CronFireHandler;\n}\n\nconst state: SchedulerState = { running: false, timers: new Map() };\n\n/**\n * Register the callback invoked when a job fires. The runtime adapter\n * supplies a handler that actually executes the agent; fixture-mode tests\n * leave it unset so timers tick without side effects.\n *\n * @internal\n */\nexport function setCronFireHandler(handler: CronFireHandler | undefined): void {\n state.fireHandler = handler;\n}\n\n/** Activate the scheduler and install timers for every enabled local job. @internal */\nexport function startScheduler(cwd?: string): void {\n state.running = true;\n if (cwd !== undefined) state.cwd = cwd;\n for (const job of listJobs()) {\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n }\n}\n\n/** Deactivate the scheduler. Stops every timer; jobs remain in the store. @internal */\nexport function stopScheduler(): void {\n state.running = false;\n for (const timer of state.timers.values()) timer.stop();\n state.timers.clear();\n}\n\n/** Schedule a single job. No-op if the scheduler is not running. @internal */\nexport function scheduleJob(job: CronJob): void {\n if (!state.running) return;\n unscheduleJob(job.id);\n const expression = normalizeExpression(job.cron);\n const timer = new Croner(\n expression,\n { timezone: job.timezone, name: job.id, protect: true },\n () => {\n void fireJob(job.id);\n },\n );\n state.timers.set(job.id, timer);\n refreshNextRunAt(job.id, timer);\n}\n\n/** Tear down the timer for a single job. @internal */\nexport function unscheduleJob(jobId: string): boolean {\n const timer = state.timers.get(jobId);\n if (timer === undefined) return false;\n timer.stop();\n state.timers.delete(jobId);\n return true;\n}\n\n/** Snapshot of the scheduler's running flag and configured workspace. @internal */\nexport function getSchedulerState(): { running: boolean; cwd?: string } {\n const result: { running: boolean; cwd?: string } = { running: state.running };\n if (state.cwd !== undefined) result.cwd = state.cwd;\n return result;\n}\n\nasync function fireJob(jobId: string): Promise<void> {\n const fresh = listJobs().find((entry) => entry.id === jobId);\n if (fresh === undefined || fresh.enabled === false) return;\n const handler = state.fireHandler;\n upsertJob({ ...fresh, lastRunAt: Date.now() });\n if (handler === undefined) return;\n try {\n await handler(fresh);\n } catch {\n // Swallow handler errors — the scheduler must keep ticking. Real\n // surface for run failures lives on the Run.wait() result itself.\n }\n}\n\nfunction refreshNextRunAt(jobId: string, timer: Croner): void {\n const next = timer.nextRun();\n if (next === null) return;\n const existing = listJobs().find((entry) => entry.id === jobId);\n if (existing === undefined) return;\n upsertJob({ ...existing, nextRunAt: next.getTime() });\n}\n\nfunction normalizeExpression(cron: string): string {\n switch (cron) {\n case \"@hourly\":\n return \"0 * * * *\";\n case \"@daily\":\n return \"0 0 * * *\";\n case \"@weekly\":\n return \"0 0 * * 0\";\n case \"@monthly\":\n return \"0 0 1 * *\";\n case \"@yearly\":\n return \"0 0 1 1 *\";\n default:\n return cron;\n }\n}\n","import { ConfigurationError } from \"../../errors.js\";\n\n/**\n * POSIX-cron + shorthand validators used by `Cron.create()`. Throws\n * `ConfigurationError` with a stable message and code on invalid input.\n *\n * @internal\n */\n\nconst SHORTHANDS = new Set([\"@hourly\", \"@daily\", \"@weekly\", \"@monthly\", \"@yearly\"]);\n\ninterface FieldRange {\n min: number;\n max: number;\n}\n\nconst FIELD_RANGES: readonly FieldRange[] = [\n { min: 0, max: 59 }, // minute\n { min: 0, max: 23 }, // hour\n { min: 1, max: 31 }, // day-of-month\n { min: 1, max: 12 }, // month\n { min: 0, max: 6 }, // day-of-week\n];\n\n/**\n * Validate a cron expression. Accepts shorthand (`@hourly`, ..., `@yearly`)\n * or 5-field POSIX cron with star, literals, star/N step, N-M range, and\n * N,M,P list.\n *\n * @internal\n */\nexport function validateCronExpression(cron: string): void {\n if (typeof cron !== \"string\" || cron.length === 0) {\n throw new ConfigurationError(\"Invalid cron expression: empty\", {\n code: \"invalid_cron\",\n });\n }\n if (cron.startsWith(\"@\")) {\n if (!SHORTHANDS.has(cron)) {\n throw new ConfigurationError(`Invalid cron expression: unknown shorthand ${cron}`, {\n code: \"invalid_cron\",\n });\n }\n return;\n }\n\n const fields = cron.trim().split(/\\s+/);\n if (fields.length !== 5) {\n throw new ConfigurationError(\n `Invalid cron expression: ${cron} (expected 5 fields, got ${fields.length})`,\n { code: \"invalid_cron\" },\n );\n }\n for (const [index, field] of fields.entries()) {\n validateFieldOrThrow(field, index, cron);\n }\n}\n\nfunction validateFieldOrThrow(field: string, index: number, cron: string): void {\n const range = FIELD_RANGES[index];\n if (range === undefined) {\n throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {\n code: \"invalid_cron\",\n });\n }\n if (!isValidCronField(field, range)) {\n throw new ConfigurationError(`Invalid cron expression: ${cron} (field ${index + 1})`, {\n code: \"invalid_cron\",\n });\n }\n}\n\nfunction isValidCronField(field: string, range: FieldRange): boolean {\n if (field === \"*\") return true;\n if (field.startsWith(\"*/\")) return isValidStep(field.slice(2), range);\n if (field.includes(\",\")) {\n return field.split(\",\").every((part) => isValidCronField(part, range));\n }\n if (field.includes(\"-\")) return isValidRange(field, range);\n return isValidLiteral(field, range);\n}\n\nfunction isValidStep(stepStr: string, range: FieldRange): boolean {\n const step = Number.parseInt(stepStr, 10);\n return Number.isInteger(step) && String(step) === stepStr && step > 0 && step <= range.max;\n}\n\nfunction isValidRange(field: string, range: FieldRange): boolean {\n const parts = field.split(\"-\");\n if (parts.length !== 2) return false;\n const [startStr, endStr] = parts;\n if (startStr === undefined || endStr === undefined) return false;\n const start = Number.parseInt(startStr, 10);\n const end = Number.parseInt(endStr, 10);\n if (!Number.isInteger(start) || !Number.isInteger(end)) return false;\n return start >= range.min && end <= range.max && start <= end;\n}\n\nfunction isValidLiteral(field: string, range: FieldRange): boolean {\n const n = Number.parseInt(field, 10);\n return Number.isInteger(n) && String(n) === field && n >= range.min && n <= range.max;\n}\n\n/**\n * Validate an IANA timezone. Uses `Intl.DateTimeFormat`'s strict timezone\n * lookup; invalid values raise `RangeError` which we wrap.\n *\n * @internal\n */\nexport function validateTimezone(timezone: string): void {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n } catch {\n throw new ConfigurationError(`Invalid IANA timezone: ${timezone}`, {\n code: \"invalid_timezone\",\n });\n }\n}\n\n/**\n * Heuristic next-fire-at estimator for fixture mode. Returns a timestamp\n * one hour in the future for shorthand/POSIX inputs. Real scheduling uses\n * a proper evaluator wired in by the local scheduler.\n *\n * @internal\n */\nexport function estimateNextRunAt(_cron: string, _timezone: string): number {\n return Date.now() + 60 * 60 * 1000;\n}\n","// Bootstrap import: loading this facade must register the public Agent facade\n// into the agent-factory-registry seam, because `internal/cron/run-job.ts`\n// resolves it via `getAgentFacade()` at runtime instead of importing `agent.ts`\n// directly (which would invert the public-api -> internal dependency\n// direction). The `@theokit/sdk/cron` sub-path entry would otherwise throw\n// \"Agent facade not registered\" at runtime.\nimport \"./agent.js\";\nimport { ConfigurationError, UnknownAgentError } from \"./errors.js\";\nimport { fireCronJobAsTask } from \"./internal/cron/fire-handler.js\";\nimport { runCronJob } from \"./internal/cron/run-job.js\";\nimport {\n getSchedulerState,\n scheduleJob,\n setCronFireHandler,\n startScheduler,\n stopScheduler,\n unscheduleJob,\n} from \"./internal/cron/scheduler.js\";\nimport { deleteJob, getJob, jobCount, listJobs, upsertJob } from \"./internal/cron/store.js\";\nimport {\n estimateNextRunAt,\n validateCronExpression,\n validateTimezone,\n} from \"./internal/cron/validate.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { generateCronId } from \"./internal/ids.js\";\nimport type { AgentOptions, ListResult } from \"./types/agent.js\";\nimport type {\n CronCreateOptions,\n CronGetOptions,\n CronJob,\n CronListOptions,\n CronOperationOptions,\n CronRunOptions,\n CronRuntime,\n CronSchedulerStatus,\n CronStartOptions,\n} from \"./types/cron.js\";\nimport type { Run } from \"./types/run.js\";\n\n/**\n * Static façade for scheduling Theo agent runs on a cron expression.\n *\n * @public\n */\nexport class Cron {\n private constructor() {\n // Static-only façade.\n }\n\n /**\n * Create and persist a cron job.\n *\n * @public\n */\n static async create(options: CronCreateOptions): Promise<CronJob> {\n const job = await createCronJob(options);\n if (job.runtime === \"local\" && job.enabled !== false) scheduleJob(job);\n return job;\n }\n\n /**\n * List cron jobs (local, cloud, or both).\n *\n * @public\n */\n static list(options: CronListOptions = {}): Promise<ListResult<CronJob>> {\n const runtimeFilter = options.runtime;\n const items = listJobs().filter((job) =>\n runtimeFilter === undefined ? true : job.runtime === runtimeFilter,\n );\n return Promise.resolve({ items });\n }\n\n /**\n * Get a single cron job by ID.\n *\n * @public\n */\n static get(jobId: string, _options: CronGetOptions = {}): Promise<CronJob> {\n const job = getJob(jobId);\n if (job === undefined) {\n return Promise.reject(\n new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" }),\n );\n }\n return Promise.resolve(job);\n }\n\n /**\n * Delete a cron job permanently.\n *\n * @public\n */\n static delete(jobId: string, _options: CronOperationOptions = {}): Promise<void> {\n unscheduleJob(jobId);\n deleteJob(jobId);\n return Promise.resolve();\n }\n\n /**\n * Re-enable a paused cron job.\n *\n * @public\n */\n static async enable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, true);\n }\n\n /**\n * Pause a cron job without deleting it.\n *\n * @public\n */\n static async disable(jobId: string, _options: CronOperationOptions = {}): Promise<CronJob> {\n return updateJobStatus(jobId, false);\n }\n\n /**\n * Manually trigger a cron job off-schedule. Returns the resulting `Run`\n * (agent target) or `WorkflowRun` (workflow target — SE35).\n *\n * @public\n */\n static async run(\n jobId: string,\n _options: CronRunOptions = {},\n ): Promise<Run | import(\"./types/workflow.js\").WorkflowRun> {\n const job = getJob(jobId);\n if (job === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n return runCronJob(job);\n }\n\n /**\n * Activate the in-process scheduler for local cron jobs.\n *\n * @public\n */\n static start(options: CronStartOptions = {}): Promise<void> {\n // Install the default fire handler so timer ticks actually drive a real\n // agent/workflow run. Users can override via `setCronFireHandler` from\n // `@theokit/sdk/internal` (test-mode hook). Handler body lives in\n // `internal/cron/fire-handler.ts` (testable + G8).\n setCronFireHandler(fireCronJobAsTask);\n startScheduler(options.cwd);\n return Promise.resolve();\n }\n\n /**\n * Stop the in-process scheduler. Jobs are preserved.\n *\n * @public\n */\n static stop(): Promise<void> {\n stopScheduler();\n return Promise.resolve();\n }\n\n /**\n * Snapshot of the local scheduler.\n *\n * @public\n */\n static status(_options: CronStartOptions = {}): Promise<CronSchedulerStatus> {\n const scheduler = getSchedulerState();\n return Promise.resolve({ running: scheduler.running, jobCount: jobCount() });\n }\n}\n\nasync function createCronJob(options: CronCreateOptions): Promise<CronJob> {\n validateCronTarget(options);\n\n validateCronExpression(options.cron);\n const timezone = options.timezone ?? \"UTC\";\n validateTimezone(timezone);\n\n // apiKey is accepted but not required for cron-create in fixture mode.\n resolveApiKey(options.apiKey);\n\n const runtime = detectRuntime(options);\n const now = Date.now();\n const job: CronJob = {\n id: generateCronId(),\n cron: options.cron,\n timezone,\n enabled: options.enabled ?? true,\n status: options.enabled === false ? \"paused\" : \"scheduled\",\n runtime,\n createdAt: now,\n nextRunAt: estimateNextRunAt(options.cron, timezone),\n ...(options.name !== undefined ? { name: options.name } : {}),\n ...(options.message !== undefined ? { message: options.message } : {}),\n ...(options.agent !== undefined ? { agent: options.agent } : {}),\n ...(options.agentId !== undefined ? { agentId: options.agentId } : {}),\n ...(options.workflow !== undefined ? { workflow: options.workflow } : {}),\n ...(options.inputData !== undefined ? { inputData: options.inputData } : {}),\n };\n upsertJob(job);\n return job;\n}\n\n/**\n * SE35 (ADR 0014) — exactly ONE target (`agent` | `agentId` | `workflow`).\n * Agent targets require `message`; a workflow target takes `inputData` and MUST\n * NOT set `message`.\n */\nfunction validateCronTarget(options: CronCreateOptions): void {\n const targets = [options.agent, options.agentId, options.workflow].filter(\n (t) => t !== undefined,\n ).length;\n if (targets > 1) {\n throw new ConfigurationError(\n \"agent, agentId, and workflow are mutually exclusive — pass exactly one target.\",\n { code: \"cron_ambiguous_target\" },\n );\n }\n if (targets === 0) {\n throw new ConfigurationError(\n \"Cron job requires exactly one target: agent, agentId, or workflow.\",\n { code: \"cron_no_target\" },\n );\n }\n if (options.workflow !== undefined && options.message !== undefined) {\n throw new ConfigurationError(\n \"A workflow cron target takes inputData, not a message — remove `message`.\",\n { code: \"cron_workflow_message\" },\n );\n }\n if (options.workflow === undefined && options.message === undefined) {\n throw new ConfigurationError(\"An agent cron target requires a message.\", {\n code: \"cron_missing_message\",\n });\n }\n}\n\nfunction detectRuntime(options: CronCreateOptions): CronRuntime {\n // SE35 — a workflow target is a held in-memory instance; it can only run in\n // the local (in-process) scheduler. A workflow instance cannot cross the\n // cloud process boundary (ADR 0014).\n if (options.workflow !== undefined) return \"local\";\n if (options.agentId !== undefined) {\n return options.agentId.startsWith(\"bc-\") ? \"cloud\" : \"local\";\n }\n const agent = options.agent as AgentOptions | undefined;\n if (agent?.cloud !== undefined) return \"cloud\";\n return \"local\";\n}\n\nasync function updateJobStatus(jobId: string, enabled: boolean): Promise<CronJob> {\n const existing = getJob(jobId);\n if (existing === undefined) {\n throw new UnknownAgentError(`Cron job ${jobId} not found`, { code: \"unknown_cron_job\" });\n }\n const updated: CronJob = {\n ...existing,\n enabled,\n status: enabled ? \"scheduled\" : \"paused\",\n };\n upsertJob(updated);\n if (updated.runtime === \"local\") {\n if (enabled) {\n scheduleJob(updated);\n } else {\n unscheduleJob(updated.id);\n }\n }\n return updated;\n}\n"]}
|
|
@@ -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,10 @@ 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
|
+
throw new SessionBusyError(lockPath.replace(/\.writer\.lock$/, ""));
|
|
31
34
|
}
|
|
32
35
|
try {
|
|
33
36
|
const d = JSON.parse(bruto);
|
|
@@ -83,5 +86,5 @@ function criarLease(sessionPath, lockPath) {
|
|
|
83
86
|
}
|
|
84
87
|
|
|
85
88
|
export { SessionBusyError, acquireSessionWriter };
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
89
|
+
//# sourceMappingURL=chunk-ODB6CFVT.js.map
|
|
90
|
+
//# sourceMappingURL=chunk-ODB6CFVT.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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,IAAI,CAAC,WAAW,OAAA,CAAQ,QAAQ,CAAC,CAAA,EAAG,MAAM,IAAI,gBAAA,CAAiB,WAAW,CAAA;AAC1E,IAAA,UAAA,CAAW,UAAU,GAAG,CAAA;AACxB,IAAA,OAAO,UAAA,CAAW,aAAa,QAAQ,CAAA;AAAA,EACzC;AACA,EAAA,SAAA,CAAU,EAAE,CAAA;AACZ,EAAA,UAAA,CAAW,UAAU,GAAG,CAAA;AAExB,EAAA,OAAO,UAAA,CAAW,aAAa,QAAQ,CAAA;AACzC;AAGA,SAAS,UAAA,CAAW,aAAqB,QAAA,EAAsC;AAC7E,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,SAAS,YAA2B;AAClC,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,CAAO,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,EAAM,CAAA;AAAA,IAClC;AAAA,GACF;AACF","file":"chunk-ODB6CFVT.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 // 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,7 +1,7 @@
|
|
|
1
1
|
import { extractCodePlugins } from './chunk-2SFBB54R.js';
|
|
2
2
|
import { submit, emitRunEvent } from './chunk-HRA3CPGG.js';
|
|
3
3
|
import { enqueueSessionWrite, hydrateSession, flushSessionWrites, descartarSessao, persistTurnToTranscript, appendSessionMessage, getSessionMessages, clearSession } from './chunk-7BTE3RXJ.js';
|
|
4
|
-
import { FsSessionStore } from './chunk-
|
|
4
|
+
import { FsSessionStore } from './chunk-5SMWZHX5.js';
|
|
5
5
|
import { discoverProviderPlugins, CircuitBreaker, buildDefaultSummarizer, parseSseStream, resolveProviderChain, inferProviderFromApiKey, detectPrimaryProvider, tryFirstEvent, relayStream, mapOpenAICompatibleError, renderToolResultContentText } from './chunk-IX2LKBCD.js';
|
|
6
6
|
import { IndexManager, writeSessionSummary, memoryDir, globalEmbeddingCache, appendFact, readFacts, legacyMemoryJsonPath, memoryMdPath, appendFactToMarkdown } from './chunk-XAUBQMQU.js';
|
|
7
7
|
import { loadHookConfig, warnOnce, currentPersonalityContext, warnPersonalitySwitchInsideFork } from './chunk-XIG2IE3L.js';
|
|
@@ -9638,8 +9638,13 @@ var LocalAgent = class {
|
|
|
9638
9638
|
this.options.agents
|
|
9639
9639
|
);
|
|
9640
9640
|
await adquirirLeaseSePossivel(this.sessionStore, this.agentId);
|
|
9641
|
-
|
|
9642
|
-
|
|
9641
|
+
try {
|
|
9642
|
+
await hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });
|
|
9643
|
+
await this.personalityStore.hydrate(this.agentId);
|
|
9644
|
+
} catch (err) {
|
|
9645
|
+
await disposeSessionStore(this.sessionStore);
|
|
9646
|
+
throw err;
|
|
9647
|
+
}
|
|
9643
9648
|
}
|
|
9644
9649
|
/** T4.2 — expose PluginManager so agent-loop can fire pre_tool_call hooks. @internal */
|
|
9645
9650
|
pluginManager() {
|
|
@@ -10521,12 +10526,12 @@ async function abrirStoreLocal(reg) {
|
|
|
10521
10526
|
const cwd = reg.cwd ?? process.cwd();
|
|
10522
10527
|
const optModel = reg.options.model;
|
|
10523
10528
|
const model = reg.model?.id ?? (typeof optModel === "string" ? optModel : optModel?.id) ?? "unknown";
|
|
10524
|
-
const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-
|
|
10529
|
+
const { FsSessionStore: FsSessionStore2 } = await import('./fs-session-store-A5W573D3.js');
|
|
10525
10530
|
const { defaultBaseDir: defaultBaseDir2, expandTilde: expandTilde2 } = await import('./session-transcript-F2ANTA2M.js');
|
|
10526
10531
|
const baseDir = reg.options.local?.baseDir !== void 0 ? expandTilde2(reg.options.local.baseDir) : defaultBaseDir2();
|
|
10527
10532
|
return { cwd, model, store: new FsSessionStore2({ baseDir, cwd }) };
|
|
10528
10533
|
}
|
|
10529
10534
|
|
|
10530
10535
|
export { Agent, AgentBuilder, DEFAULT_AGENTIC_MODEL_ID, MEMORY_EMBEDDING_ADAPTERS, Tool, ToolError, UsageAccumulator, computeCost, generateCronId, getPricingEntry, httpRequest, isFixtureApiKey, openRouterMemoryEmbeddingProviderAdapter, resolveApiKey, shouldUseFixtureMode };
|
|
10531
|
-
//# sourceMappingURL=chunk-
|
|
10532
|
-
//# sourceMappingURL=chunk-
|
|
10536
|
+
//# sourceMappingURL=chunk-VC6VXYKA.js.map
|
|
10537
|
+
//# sourceMappingURL=chunk-VC6VXYKA.js.map
|