kiki-agent 0.5.0 → 0.5.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/README.md +3 -3
- package/dist/cpu-worker.mjs +52744 -0
- package/dist/docs/en/configuration/config-files.md +92 -30
- package/dist/docs/en/configuration/data-locations.md +14 -9
- package/dist/docs/en/configuration/env-vars.md +32 -2
- package/dist/docs/en/configuration/overrides.md +1 -1
- package/dist/docs/en/configuration/providers.md +44 -10
- package/dist/docs/en/customization/agent-profiles.md +1 -1
- package/dist/docs/en/customization/agents-and-subagents.md +49 -10
- package/dist/docs/en/customization/hooks.md +3 -3
- package/dist/docs/en/customization/personas.md +1 -1
- package/dist/docs/en/customization/plugins.md +16 -3
- package/dist/docs/en/customization/prompt-fields.md +62 -6
- package/dist/docs/en/customization/recipes.md +77 -0
- package/dist/docs/en/customization/skins.md +2 -2
- package/dist/docs/en/customization/themes.md +1 -1
- package/dist/docs/en/features/browser-and-computer.md +5 -5
- package/dist/docs/en/features/daily.md +3 -3
- package/dist/docs/en/features/ecosystem.md +1 -1
- package/dist/docs/en/features/extend.md +2 -2
- package/dist/docs/en/features/freedom.md +1 -1
- package/dist/docs/en/features/index.md +15 -1
- package/dist/docs/en/features/long-work.md +9 -5
- package/dist/docs/en/features/look.md +1 -1
- package/dist/docs/en/features/phone.md +11 -3
- package/dist/docs/en/features/spaces.md +5 -5
- package/dist/docs/en/getting-started/desktop-app.md +4 -8
- package/dist/docs/en/getting-started/first-launch.md +1 -1
- package/dist/docs/en/guides/goals.md +4 -2
- package/dist/docs/en/guides/interface.md +18 -8
- package/dist/docs/en/guides/memory.md +64 -10
- package/dist/docs/en/guides/sessions.md +15 -7
- package/dist/docs/en/guides/settings.md +49 -38
- package/dist/docs/en/index.md +3 -1
- package/dist/docs/en/reference/command.md +35 -33
- package/dist/docs/en/reference/model-vocabulary.md +2 -2
- package/dist/docs/en/reference/slash-commands.md +1 -1
- package/dist/docs/en/reference/tools.md +40 -15
- package/dist/docs/en/server/acp.md +6 -2
- package/dist/docs/en/server/local-server.md +19 -27
- package/dist/docs/en/server/mcp.md +4 -4
- package/dist/docs/en/server/rest-api.md +240 -23
- package/dist/docs/en/server/script-tools.md +268 -0
- package/dist/docs/zh/configuration/config-files.md +92 -30
- package/dist/docs/zh/configuration/data-locations.md +14 -9
- package/dist/docs/zh/configuration/env-vars.md +32 -2
- package/dist/docs/zh/configuration/overrides.md +1 -1
- package/dist/docs/zh/configuration/providers.md +44 -10
- package/dist/docs/zh/customization/agent-profiles.md +1 -1
- package/dist/docs/zh/customization/agents-and-subagents.md +49 -10
- package/dist/docs/zh/customization/hooks.md +3 -3
- package/dist/docs/zh/customization/personas.md +1 -1
- package/dist/docs/zh/customization/plugins.md +16 -3
- package/dist/docs/zh/customization/prompt-fields.md +62 -6
- package/dist/docs/zh/customization/recipes.md +77 -0
- package/dist/docs/zh/customization/skins.md +2 -2
- package/dist/docs/zh/customization/themes.md +1 -1
- package/dist/docs/zh/features/browser-and-computer.md +5 -5
- package/dist/docs/zh/features/daily.md +3 -3
- package/dist/docs/zh/features/ecosystem.md +1 -1
- package/dist/docs/zh/features/extend.md +2 -2
- package/dist/docs/zh/features/freedom.md +1 -1
- package/dist/docs/zh/features/index.md +16 -2
- package/dist/docs/zh/features/long-work.md +9 -5
- package/dist/docs/zh/features/look.md +1 -1
- package/dist/docs/zh/features/phone.md +11 -3
- package/dist/docs/zh/features/spaces.md +5 -5
- package/dist/docs/zh/getting-started/desktop-app.md +4 -8
- package/dist/docs/zh/getting-started/first-launch.md +1 -1
- package/dist/docs/zh/guides/goals.md +4 -2
- package/dist/docs/zh/guides/interface.md +18 -8
- package/dist/docs/zh/guides/memory.md +64 -10
- package/dist/docs/zh/guides/sessions.md +15 -7
- package/dist/docs/zh/guides/settings.md +49 -38
- package/dist/docs/zh/index.md +4 -2
- package/dist/docs/zh/reference/command.md +35 -33
- package/dist/docs/zh/reference/model-vocabulary.md +2 -2
- package/dist/docs/zh/reference/slash-commands.md +1 -1
- package/dist/docs/zh/reference/tools.md +40 -15
- package/dist/docs/zh/server/acp.md +6 -2
- package/dist/docs/zh/server/local-server.md +19 -27
- package/dist/docs/zh/server/mcp.md +4 -4
- package/dist/docs/zh/server/rest-api.md +229 -23
- package/dist/docs/zh/server/script-tools.md +268 -0
- package/dist/external-harness/agy-cli-acp.mjs +168 -162
- package/dist/external-harness/agy-hook-registration.mjs +69 -30
- package/dist/external-harness/agy-mcp-plugin.mjs +19 -0
- package/dist/external-harness/agy-permission-hook.mjs +29 -2
- package/dist/hostRunner.mjs +24 -6
- package/dist/mailbox-worker.mjs +111 -5
- package/dist/main.mjs +2 -2
- package/dist/memory-worker.mjs +1008 -0
- package/dist/native/windows-process-helper.exe +0 -0
- package/dist/query-store-worker.mjs +52 -11
- package/dist/sqlite-indexer.mjs +32 -2
- package/dist/sqlite-query-worker.mjs +35 -0
- package/dist/usage-parser-worker.mjs +3953 -4
- package/dist/usage-read-model-worker.mjs +761 -0
- package/dist/web/assets/{AppErrorBoundary-BN6IDdP1.js → AppErrorBoundary-B5Fc4f6-.js} +1 -1
- package/dist/web/assets/NavScopeBoundary-C7MnGQio.js +1 -0
- package/dist/web/assets/{arc-C7IAvCCJ.js → arc-DGB9OVgQ.js} +1 -1
- package/dist/web/assets/{architectureDiagram-3BPJPVTR-CbwFBxn7.js → architectureDiagram-3BPJPVTR-glnQCMub.js} +1 -1
- package/dist/web/assets/{blockDiagram-GPEHLZMM-B20N4t8r.js → blockDiagram-GPEHLZMM-bM0tnGby.js} +1 -1
- package/dist/web/assets/{c4Diagram-AAUBKEIU-3BYtlcP-.js → c4Diagram-AAUBKEIU-DMf_rTtt.js} +1 -1
- package/dist/web/assets/channel-Cj8SKJ38.js +1 -0
- package/dist/web/assets/{chunk-2J33WTMH-CpjgczxM.js → chunk-2J33WTMH-mTccJ3tW.js} +1 -1
- package/dist/web/assets/{chunk-4BX2VUAB-BScxUF5G.js → chunk-4BX2VUAB-DhqPYMjY.js} +1 -1
- package/dist/web/assets/{chunk-55IACEB6-CrcLYJXd.js → chunk-55IACEB6-BujrYRoO.js} +1 -1
- package/dist/web/assets/{chunk-727SXJPM-BwlyIOjw.js → chunk-727SXJPM-ciMmSI4G.js} +1 -1
- package/dist/web/assets/{chunk-AQP2D5EJ-DKKIRkRv.js → chunk-AQP2D5EJ-CZW9pKTc.js} +1 -1
- package/dist/web/assets/{chunk-FMBD7UC4-CVDMj2kX.js → chunk-FMBD7UC4-hdALNnnU.js} +1 -1
- package/dist/web/assets/{chunk-ND2GUHAM-CL-PM6r8.js → chunk-ND2GUHAM-CgKyqUdb.js} +1 -1
- package/dist/web/assets/{chunk-QZHKN3VN-DPV2KbKZ.js → chunk-QZHKN3VN-B2mmUz_E.js} +1 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-f8V9p-dD.js +1 -0
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-f8V9p-dD.js +1 -0
- package/dist/web/assets/client-ClWQBErG.js +3 -0
- package/dist/web/assets/connection-C0J3BPgk.js +1 -0
- package/dist/web/assets/{cose-bilkent-S5V4N54A-D1CEiQM6.js → cose-bilkent-S5V4N54A-UV3uPjkK.js} +1 -1
- package/dist/web/assets/{dagre-BM42HDAG-BlFV941E.js → dagre-BM42HDAG-Zjy-gQ6C.js} +1 -1
- package/dist/web/assets/{diagram-2AECGRRQ-BC0ldkFY.js → diagram-2AECGRRQ-DL-kilIf.js} +1 -1
- package/dist/web/assets/{diagram-5GNKFQAL-B22Iej6G.js → diagram-5GNKFQAL-CjB_xR5B.js} +1 -1
- package/dist/web/assets/{diagram-KO2AKTUF-B75UNw6D.js → diagram-KO2AKTUF-CjN4i3b9.js} +1 -1
- package/dist/web/assets/{diagram-LMA3HP47-CypI7IJM.js → diagram-LMA3HP47-CPCAMndo.js} +1 -1
- package/dist/web/assets/{diagram-OG6HWLK6-OsXumvcD.js → diagram-OG6HWLK6-DVeBWBKd.js} +1 -1
- package/dist/web/assets/{erDiagram-TEJ5UH35-3756GOvS.js → erDiagram-TEJ5UH35-CHKzBHrr.js} +1 -1
- package/dist/web/assets/export-CXoWon32.js +2 -0
- package/dist/web/assets/{flowDiagram-I6XJVG4X-DB6Y_UDg.js → flowDiagram-I6XJVG4X-C5rQa2pq.js} +1 -1
- package/dist/web/assets/{ganttDiagram-6RSMTGT7-CHJeuoAY.js → ganttDiagram-6RSMTGT7-BrLjEsNJ.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-PVQCEYII-Dj85554Y.js → gitGraphDiagram-PVQCEYII-3DRR5VZj.js} +1 -1
- package/dist/web/assets/highlighted-body-OFNGDK62-Bdj5SJfv.js +1 -0
- package/dist/web/assets/index-2Vx5mHRn.js +1 -0
- package/dist/web/assets/index-B1UXw2C9.js +1 -0
- package/dist/web/assets/{index-C6qeLCPw.js → index-BJxtlf4P.js} +4 -4
- package/dist/web/assets/{index-DxUmR9aV.js → index-BY7jPurv.js} +1 -1
- package/dist/web/assets/index-Bq79v-Sa.js +1 -0
- package/dist/web/assets/index-BqD3iTIl.js +1 -0
- package/dist/web/assets/index-Br3AlBrQ.js +1 -0
- package/dist/web/assets/{index-DZMkZKhW.js → index-BvRBCpc6.js} +2 -2
- package/dist/web/assets/index-BxYCSNg_.js +3 -0
- package/dist/web/assets/{index-CJqIcuAl.js → index-C62wjCF_.js} +1 -1
- package/dist/web/assets/index-CBvwNH_H.js +1 -0
- package/dist/web/assets/{index-DRMjjql1.js → index-CG9e6lgq.js} +1 -1
- package/dist/web/assets/{index-C7mOS2T4.js → index-CPSWYh_R.js} +2 -2
- package/dist/web/assets/index-CS4xJLZV.js +1 -0
- package/dist/web/assets/index-CjvqtF2I.js +1 -0
- package/dist/web/assets/index-CprdjRRk.js +13 -0
- package/dist/web/assets/{index-bYtKyBMB.js → index-CypTtrCB.js} +1 -1
- package/dist/web/assets/{index-DqK8MfQN.js → index-DDJQGcUL.js} +1 -1
- package/dist/web/assets/index-DLWzxUOO.js +1 -0
- package/dist/web/assets/index-DQxkxZmn.js +7 -0
- package/dist/web/assets/index-DRo5Y_9p.js +1 -0
- package/dist/web/assets/index-De_LkTZx.js +1 -0
- package/dist/web/assets/{index-0tHq8zh2.js → index-DfUpwUTM.js} +2 -2
- package/dist/web/assets/{index-D--cw39y.js → index-Dkbz748K.js} +2 -2
- package/dist/web/assets/index-DmwFFSkV.js +1 -0
- package/dist/web/assets/index-DpcWEDhW.js +1 -0
- package/dist/web/assets/index-Dqq1RDP4.js +1 -0
- package/dist/web/assets/index-H1uMvIoa.css +1 -0
- package/dist/web/assets/index-ICHWJ2SM.js +1 -0
- package/dist/web/assets/index-O5fSd569.js +229 -0
- package/dist/web/assets/index-odjtqLLS.js +1 -0
- package/dist/web/assets/index-v_yAQ0Am.js +1 -0
- package/dist/web/assets/{infoDiagram-5YYISTIA-DeDPIdEH.js → infoDiagram-5YYISTIA-CCwV4Z0v.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-ButuBiBW.js → ishikawaDiagram-YF4QCWOH-BwwZcGyZ.js} +1 -1
- package/dist/web/assets/{journeyDiagram-JHISSGLW-Dlbmqm-j.js → journeyDiagram-JHISSGLW-Dc6WqniQ.js} +1 -1
- package/dist/web/assets/{kanban-definition-UN3LZRKU-tlQK1cOz.js → kanban-definition-UN3LZRKU-DVUqULOS.js} +1 -1
- package/dist/web/assets/{linear-iXuNfUWp.js → linear-d6rWsNOU.js} +1 -1
- package/dist/web/assets/memoryAdvisor-DBQXJB1o.js +1 -0
- package/dist/web/assets/mermaid-GHXKKRXX-Ik6SkVDT.js +642 -0
- package/dist/web/assets/{mindmap-definition-RKZ34NQL-2qPv-mwT.js → mindmap-definition-RKZ34NQL-_JHAkhHL.js} +1 -1
- package/dist/web/assets/navViewState-DaCMIYWA.js +1 -0
- package/dist/web/assets/{pieDiagram-4H26LBE5-CrLe1C-O.js → pieDiagram-4H26LBE5-BlhlygGy.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-W4KKPZXB-DfeIFxc0.js → quadrantDiagram-W4KKPZXB-jn6R_C0S.js} +1 -1
- package/dist/web/assets/{requirementDiagram-4Y6WPE33-BWtjdxie.js → requirementDiagram-4Y6WPE33-B9fXCHBr.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-5OEKKPKP-B5TxJ6mb.js → sankeyDiagram-5OEKKPKP-fPJwIxkl.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-3UESZ5HK-Cf92ZCl1.js → sequenceDiagram-3UESZ5HK-1v1DTNGt.js} +1 -1
- package/dist/web/assets/{spaces-DqMTtCXX.js → spaces-CvL2DRZM.js} +1 -1
- package/dist/web/assets/{stateDiagram-AJRCARHV-NR9I-Q4d.js → stateDiagram-AJRCARHV-CEc_PLov.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-iAMctzaT.js +1 -0
- package/dist/web/assets/theme-LRSmy8mD.js +1 -0
- package/dist/web/assets/{timeline-definition-PNZ67QCA-CBAOVMfm.js → timeline-definition-PNZ67QCA-CEjhuitj.js} +1 -1
- package/dist/web/assets/{vennDiagram-CIIHVFJN-C68x6TdS.js → vennDiagram-CIIHVFJN-CActt9h9.js} +1 -1
- package/dist/web/assets/{wardley-L42UT6IY-DuZZr5jm.js → wardley-L42UT6IY-Bp3q2izt.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-YWT4CUSO-D6dVGtHd.js → wardleyDiagram-YWT4CUSO-C_zutiQ2.js} +1 -1
- package/dist/web/assets/{xychartDiagram-2RQKCTM6-DYLUhZX4.js → xychartDiagram-2RQKCTM6-CRafvv33.js} +1 -1
- package/dist/web/icons/apple-touch-icon.png +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/maskable-512.png +0 -0
- package/dist/web/index.html +12 -2
- package/dist/web/manifest.webmanifest +16 -0
- package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
- package/package.json +22 -3
- package/dist/web/assets/LifeMark-UBMVaTWr.js +0 -1
- package/dist/web/assets/NavScopeBoundary-BCryw-UG.js +0 -1
- package/dist/web/assets/channel-BJs5vJuh.js +0 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-BookeACB.js +0 -1
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-BookeACB.js +0 -1
- package/dist/web/assets/client-CXcrCawx.js +0 -3
- package/dist/web/assets/connection-C8nwzwXB.js +0 -1
- package/dist/web/assets/export-Bn8PqPg4.js +0 -2
- package/dist/web/assets/highlighted-body-OFNGDK62-DMgPHetp.js +0 -1
- package/dist/web/assets/index-7ySDqvaN.css +0 -1
- package/dist/web/assets/index-B0KPRi1U.js +0 -166
- package/dist/web/assets/index-B599VnpP.js +0 -1
- package/dist/web/assets/index-BFK-GypQ.js +0 -1
- package/dist/web/assets/index-BPX8gmpB.js +0 -1
- package/dist/web/assets/index-BSGYc1tb.js +0 -1
- package/dist/web/assets/index-BTt9Q5iv.js +0 -1
- package/dist/web/assets/index-BWzUsoY_.js +0 -1
- package/dist/web/assets/index-BYlSV3FO.js +0 -3
- package/dist/web/assets/index-BpXQ1q-u.js +0 -1
- package/dist/web/assets/index-BqPxpGUh.js +0 -1
- package/dist/web/assets/index-C8OFfbEs.js +0 -1
- package/dist/web/assets/index-CI7yuMGZ.js +0 -1
- package/dist/web/assets/index-CTRJmDep.js +0 -1
- package/dist/web/assets/index-CXGCKoId.js +0 -1
- package/dist/web/assets/index-CsY571EL.js +0 -13
- package/dist/web/assets/index-CwQG_9rB.js +0 -1
- package/dist/web/assets/index-D260jsUJ.js +0 -1
- package/dist/web/assets/index-DJjmEXx4.js +0 -1
- package/dist/web/assets/index-DUxOVxHS.js +0 -1
- package/dist/web/assets/index-GK8aa9pT.js +0 -7
- package/dist/web/assets/index-wxHFHTgD.js +0 -1
- package/dist/web/assets/mermaid-GHXKKRXX-sDJax95P.js +0 -624
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-BiegFWxE.js +0 -1
- package/dist/web/assets/theme-6OL1RXgY.js +0 -1
|
@@ -3,18 +3,28 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { createHash, randomUUID } from 'node:crypto';
|
|
4
4
|
|
|
5
5
|
const KEY = 'kiki-agy-permission-bridge';
|
|
6
|
+
const STEERING_KEY = 'kiki-agy-steering-bridge';
|
|
7
|
+
const OWNED = Object.freeze({
|
|
8
|
+
[KEY]: { state: '.kiki-agy-hook-ownership.json', definition: command => ({ PreToolUse: [{ matcher: '.*', hooks: [{ type: 'command', command, timeout: 86400 }] }] }) },
|
|
9
|
+
[STEERING_KEY]: { state: '.kiki-agy-steering-ownership.json', definition: command => ({ PostInvocation: [{ type: 'command', command, timeout: 30 }] }) },
|
|
10
|
+
});
|
|
11
|
+
const LOCK = '.kiki-agy-hook-ownership.json.lock';
|
|
12
|
+
const ownedKeys = hooks => Object.keys(hooks).filter(key => Object.hasOwn(OWNED, key));
|
|
13
|
+
export const AGY_PERMISSION_HOOK_KEY = KEY;
|
|
14
|
+
export const AGY_STEERING_HOOK_KEY = STEERING_KEY;
|
|
6
15
|
|
|
7
|
-
export function hookCommand(nodePath, handlerPath) {
|
|
8
|
-
if (
|
|
16
|
+
export function hookCommand(nodePath, handlerPath, args = []) {
|
|
17
|
+
if (args.some(arg => !/^--[a-z-]+$/.test(arg))) throw Error('AGY hook arguments must be fixed flags');
|
|
18
|
+
if (process.platform !== 'win32') return [`"${nodePath}"`, `"${handlerPath}"`, ...args].join(' ');
|
|
9
19
|
const literal = value => `'${value.replaceAll("'", "''")}'`;
|
|
10
|
-
const script = `$ErrorActionPreference='Stop'; $encoding=New-Object System.Text.UTF8Encoding($false); [Console]::InputEncoding=$encoding; [Console]::OutputEncoding=$encoding; $OutputEncoding=$encoding; $json=[Console]::In.ReadToEnd(); $json | & ${
|
|
20
|
+
const script = `$ErrorActionPreference='Stop'; $encoding=New-Object System.Text.UTF8Encoding($false); [Console]::InputEncoding=$encoding; [Console]::OutputEncoding=$encoding; $OutputEncoding=$encoding; $json=[Console]::In.ReadToEnd(); $json | & ${[nodePath, handlerPath, ...args].map(literal).join(' ')}; exit $LASTEXITCODE`;
|
|
11
21
|
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
|
12
22
|
return `${join(process.env.SystemRoot ?? 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')} -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
|
|
13
23
|
}
|
|
14
24
|
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
15
25
|
async function optional(path) { try { return await readFile(path); } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; } }
|
|
16
26
|
|
|
17
|
-
function ownedRange(text) {
|
|
27
|
+
function ownedRange(text, ownedKey) {
|
|
18
28
|
JSON.parse(text);
|
|
19
29
|
let i = text.indexOf('{') + 1;
|
|
20
30
|
let previousComma;
|
|
@@ -46,7 +56,7 @@ function ownedRange(text) {
|
|
|
46
56
|
else if (char === '}' || char === ']') { if (depth === 0) break; depth--; }
|
|
47
57
|
else if (char === ',' && depth === 0) break;
|
|
48
58
|
}
|
|
49
|
-
if (key ===
|
|
59
|
+
if (key === ownedKey) return previousComma === undefined
|
|
50
60
|
? { start, end: text[i] === ',' ? i + 1 : i }
|
|
51
61
|
: { start: previousComma, end: i };
|
|
52
62
|
previousComma = i;
|
|
@@ -88,13 +98,21 @@ async function locked(lockPath, operation) {
|
|
|
88
98
|
finally { await file.close(); await unlink(lockPath); }
|
|
89
99
|
}
|
|
90
100
|
|
|
91
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Adds one owned key to `.agents/hooks.json` and leases it to this adapter session.
|
|
103
|
+
* `key` selects the permission gate (PreToolUse) or the steering bridge (PostInvocation);
|
|
104
|
+
* each owned key keeps its own receipt, while the original file bytes come back only
|
|
105
|
+
* after the last owned key and lease are gone.
|
|
106
|
+
*/
|
|
107
|
+
export async function registerProjectHook({ cwd, nodePath, handlerPath, sessionId, key = KEY, args = [] }) {
|
|
108
|
+
const owned = OWNED[key];
|
|
109
|
+
if (!owned) throw Error('Unknown AGY owned hook key');
|
|
92
110
|
const dir = join(cwd, '.agents');
|
|
93
111
|
await mkdir(dir, { recursive: true });
|
|
94
112
|
const path = join(dir, 'hooks.json');
|
|
95
|
-
const statePath = join(dir,
|
|
96
|
-
const lockPath =
|
|
97
|
-
const definition =
|
|
113
|
+
const statePath = join(dir, owned.state);
|
|
114
|
+
const lockPath = join(dir, LOCK);
|
|
115
|
+
const definition = owned.definition(hookCommand(nodePath, handlerPath, args));
|
|
98
116
|
const definitionHash = sha(JSON.stringify(definition));
|
|
99
117
|
await locked(lockPath, async () => {
|
|
100
118
|
const before = await optional(path);
|
|
@@ -105,15 +123,16 @@ export async function registerProjectHook({ cwd, nodePath, handlerPath, sessionI
|
|
|
105
123
|
let state = saved ? JSON.parse(saved.toString('utf8')) : undefined;
|
|
106
124
|
if (state && (state.version !== 1 || state.definitionHash !== definitionHash)) throw Error('AGY hook registration version differs; recover its owned registration first');
|
|
107
125
|
if (!state) {
|
|
108
|
-
if (Object.hasOwn(hooks,
|
|
109
|
-
|
|
126
|
+
if (Object.hasOwn(hooks, key)) throw Error('Project AGY hook key is already owned; do not overwrite it');
|
|
127
|
+
const original = await originalBytes(dir, before);
|
|
128
|
+
state = { version: 1, definitionHash, original, leases: [] };
|
|
110
129
|
const end = text.lastIndexOf('}');
|
|
111
|
-
const updated = text.slice(0, end) + `${Object.keys(hooks).length ? ',' : ''}\n ${JSON.stringify(
|
|
130
|
+
const updated = text.slice(0, end) + `${Object.keys(hooks).length ? ',' : ''}\n ${JSON.stringify(key)}: ${JSON.stringify(definition)}\n` + text.slice(end);
|
|
112
131
|
const current = await optional(path);
|
|
113
132
|
if (Boolean(current) !== Boolean(before) || current && sha(current) !== sha(before)) throw Error('Project hooks changed during registration');
|
|
114
133
|
await atomic(statePath, JSON.stringify(state));
|
|
115
134
|
await atomic(path, updated);
|
|
116
|
-
} else if (sha(JSON.stringify(hooks[
|
|
135
|
+
} else if (sha(JSON.stringify(hooks[key])) !== definitionHash) throw Error('Owned AGY hook definition changed; preserve the concurrent edit');
|
|
117
136
|
state.leases = state.leases.filter(lease => processAlive(lease.pid));
|
|
118
137
|
state.leases.push({ sessionId, pid: process.pid });
|
|
119
138
|
await atomic(statePath, JSON.stringify(state));
|
|
@@ -122,7 +141,7 @@ export async function registerProjectHook({ cwd, nodePath, handlerPath, sessionI
|
|
|
122
141
|
let closePromise;
|
|
123
142
|
return { path, close() {
|
|
124
143
|
if (closed) return Promise.resolve();
|
|
125
|
-
|
|
144
|
+
closePromise ??= locked(lockPath, async () => {
|
|
126
145
|
const saved = await optional(statePath);
|
|
127
146
|
if (!saved) throw Error('AGY hook ownership receipt is missing');
|
|
128
147
|
const state = JSON.parse(saved.toString('utf8'));
|
|
@@ -132,49 +151,69 @@ export async function registerProjectHook({ cwd, nodePath, handlerPath, sessionI
|
|
|
132
151
|
if (bytes) {
|
|
133
152
|
const text = bytes.toString('utf8');
|
|
134
153
|
const hooks = JSON.parse(text);
|
|
135
|
-
if (sha(JSON.stringify(hooks[
|
|
136
|
-
const range = ownedRange(text);
|
|
154
|
+
if (sha(JSON.stringify(hooks[key])) !== definitionHash) throw Error('Owned AGY hook changed; manual scoped recovery required');
|
|
155
|
+
const range = ownedRange(text, key);
|
|
137
156
|
if (!range) throw Error('Owned AGY hook cannot be located safely');
|
|
138
157
|
const remaining = text.slice(0, range.start) + text.slice(range.end);
|
|
139
158
|
const original = state.original === null ? undefined : Buffer.from(state.original, 'base64');
|
|
140
159
|
const originalHooks = original ? JSON.parse(original.toString('utf8')) : {};
|
|
141
|
-
delete hooks[
|
|
160
|
+
delete hooks[key];
|
|
142
161
|
const current = await optional(path);
|
|
143
162
|
if (!current || sha(current) !== sha(bytes)) throw Error('Project hooks changed during cleanup');
|
|
144
|
-
if (JSON.stringify(hooks) === JSON.stringify(originalHooks)) {
|
|
163
|
+
if (ownedKeys(hooks).length === 0 && JSON.stringify(hooks) === JSON.stringify(originalHooks)) {
|
|
145
164
|
if (original) await atomic(path, original); else await unlink(path);
|
|
146
165
|
} else await atomic(path, remaining);
|
|
147
166
|
}
|
|
148
167
|
await unlink(statePath);
|
|
149
168
|
closed = true;
|
|
150
|
-
});
|
|
169
|
+
}).finally(() => { closePromise = undefined; });
|
|
170
|
+
return closePromise;
|
|
151
171
|
} };
|
|
152
172
|
}
|
|
153
173
|
|
|
174
|
+
async function originalBytes(dir, before) {
|
|
175
|
+
for (const { state } of Object.values(OWNED)) {
|
|
176
|
+
const saved = await optional(join(dir, state));
|
|
177
|
+
if (saved) return JSON.parse(saved.toString('utf8')).original ?? null;
|
|
178
|
+
}
|
|
179
|
+
return before?.toString('base64') ?? null;
|
|
180
|
+
}
|
|
181
|
+
|
|
154
182
|
|
|
155
183
|
/**
|
|
156
|
-
* Recover only this adapter's dead
|
|
184
|
+
* Recover only this adapter's dead registrations in an explicitly selected workspace.
|
|
157
185
|
* `node agy-cli-acp.mjs --recover-project-hook <absolute-workspace>` starts no vendor
|
|
158
186
|
* process. A live lease or changed definition is preserved; successful recovery
|
|
159
|
-
* restores original bytes or removes only the owned
|
|
187
|
+
* restores original bytes or removes only the owned keys alongside foreign edits.
|
|
160
188
|
*/
|
|
161
189
|
export async function recoverProjectHook({ cwd, nodePath, handlerPath }) {
|
|
162
|
-
const
|
|
190
|
+
const results = [];
|
|
191
|
+
for (const [key, owned] of Object.entries(OWNED)) {
|
|
192
|
+
results.push(await recoverOwnedKey({ cwd, nodePath, handlerPath, key, statePath: join(cwd, '.agents', owned.state) }));
|
|
193
|
+
}
|
|
194
|
+
for (const status of ['owned-session-still-live', 'registration-changed-retry-recovery', 'owned-registration-recovered']) {
|
|
195
|
+
if (results.includes(status)) return { status };
|
|
196
|
+
}
|
|
197
|
+
return { status: 'no-owned-registration' };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function recoverOwnedKey({ cwd, nodePath, handlerPath, key, statePath }) {
|
|
163
201
|
const bytes = await optional(statePath);
|
|
164
|
-
if (!bytes) return
|
|
202
|
+
if (!bytes) return 'no-owned-registration';
|
|
165
203
|
const state = JSON.parse(bytes.toString('utf8'));
|
|
166
204
|
if (state.version !== 1 || !Array.isArray(state.leases)) throw Error('Invalid AGY hook ownership receipt; preserve it for scoped recovery');
|
|
167
|
-
if (state.leases.some(lease => processAlive(lease.pid))) return
|
|
205
|
+
if (state.leases.some(lease => processAlive(lease.pid))) return 'owned-session-still-live';
|
|
168
206
|
const hookBytes = await optional(join(cwd, '.agents', 'hooks.json'));
|
|
169
|
-
if (!hookBytes || !Object.hasOwn(JSON.parse(hookBytes.toString('utf8')),
|
|
170
|
-
return locked(
|
|
207
|
+
if (!hookBytes || !Object.hasOwn(JSON.parse(hookBytes.toString('utf8')), key)) {
|
|
208
|
+
return locked(join(cwd, '.agents', LOCK), async () => {
|
|
171
209
|
const current = await optional(statePath);
|
|
172
|
-
if (!current || sha(current) !== sha(bytes)) return
|
|
210
|
+
if (!current || sha(current) !== sha(bytes)) return 'registration-changed-retry-recovery';
|
|
173
211
|
await unlink(statePath);
|
|
174
|
-
return
|
|
212
|
+
return 'owned-registration-recovered';
|
|
175
213
|
});
|
|
176
214
|
}
|
|
177
|
-
const
|
|
215
|
+
const args = key === STEERING_KEY ? ['--steering'] : [];
|
|
216
|
+
const registration = await registerProjectHook({ cwd, nodePath, handlerPath, sessionId: `recovery-${randomUUID()}`, key, args });
|
|
178
217
|
await registration.close();
|
|
179
|
-
return
|
|
218
|
+
return await optional(statePath) ? 'owned-session-still-live' : 'owned-registration-recovered';
|
|
180
219
|
}
|
|
@@ -78,6 +78,25 @@ export async function registerProjectMcpPlugin({ cwd, sessionId, namespace, node
|
|
|
78
78
|
};
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Recovers every dead owned plugin under one workspace's `.agents/plugins`. Each receipt is
|
|
83
|
+
* handled by the per-session recovery rules, so live owners, unconfirmed launches, edited
|
|
84
|
+
* files and foreign entries stay in place; a directory without a valid receipt is ignored.
|
|
85
|
+
*/
|
|
86
|
+
export async function recoverDeadProjectMcpPlugins({ cwd }) {
|
|
87
|
+
let names;
|
|
88
|
+
try { names = await readdir(resolve(cwd, '.agents', 'plugins')); } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
89
|
+
const results = [];
|
|
90
|
+
for (const name of names) {
|
|
91
|
+
let state;
|
|
92
|
+
try { state = JSON.parse(await optional(resolve(cwd, '.agents', 'plugins', name, RECEIPT)) ?? 'null'); } catch { continue; }
|
|
93
|
+
if (!state || typeof state.sessionId !== 'string') continue;
|
|
94
|
+
try { results.push({ name, ...await recoverProjectMcpPlugin({ cwd, sessionId: state.sessionId }) }); }
|
|
95
|
+
catch (error) { results.push({ name, status: 'preserved', reason: error instanceof Error ? error.message : String(error) }); }
|
|
96
|
+
}
|
|
97
|
+
return results;
|
|
98
|
+
}
|
|
99
|
+
|
|
81
100
|
export async function recoverProjectMcpPlugin({ cwd, sessionId }) {
|
|
82
101
|
const paths = [pluginName(sessionId), `kiki-acp-${sessionId}`].map(name => resolve(cwd, '.agents', 'plugins', name));
|
|
83
102
|
const registrations = (await Promise.all(paths.map(async path => ({ path, receipt: await optional(resolve(path, RECEIPT)) })))).filter(entry => entry.receipt !== undefined);
|
|
@@ -62,7 +62,10 @@ export async function openPermissionChannel(handle, identity = permissionChannel
|
|
|
62
62
|
} catch (error) {
|
|
63
63
|
response = denied(error instanceof Error ? error.message : 'AGY permission request failed');
|
|
64
64
|
}
|
|
65
|
-
if (
|
|
65
|
+
if (socket.destroyed || closed) { response?.afterFailure?.(); return; }
|
|
66
|
+
let failed = false;
|
|
67
|
+
socket.once('error', () => { failed = true; response?.afterFailure?.(); });
|
|
68
|
+
socket.end(JSON.stringify(response) + '\n', () => { if (!failed) response?.afterWrite?.(); });
|
|
66
69
|
})();
|
|
67
70
|
});
|
|
68
71
|
});
|
|
@@ -112,7 +115,31 @@ export async function requestHookPermission(input, env = process.env, timeoutMs)
|
|
|
112
115
|
});
|
|
113
116
|
}
|
|
114
117
|
|
|
115
|
-
|
|
118
|
+
/**
|
|
119
|
+
* PostInvocation hook body: asks the owning adapter for steering messages queued for this
|
|
120
|
+
* exact conversation and returns them as AGY `injectSteps`, forcing one more invocation so
|
|
121
|
+
* the model reads them inside the running turn. Without an owned channel it injects nothing.
|
|
122
|
+
*/
|
|
123
|
+
export async function steeringHookOutput(input, env = process.env) {
|
|
124
|
+
if (!env.KIKI_AGY_PERMISSION_ENDPOINT && !env.KIKI_AGY_PERMISSION_TOKEN) return {};
|
|
125
|
+
if (!input || typeof input.conversationId !== 'string') return {};
|
|
126
|
+
const response = await requestHookPermission({ type: 'steer_poll', conversationId: input.conversationId,
|
|
127
|
+
invocationNum: input.invocationNum }, env, 10_000);
|
|
128
|
+
const steps = response?.steering?.injectSteps;
|
|
129
|
+
if (response.decision !== 'allow' || !Array.isArray(steps) || steps.length === 0) return {};
|
|
130
|
+
return { injectSteps: steps, terminationBehavior: 'force_continue' };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url && process.argv[2] === '--steering') {
|
|
134
|
+
let input = '';
|
|
135
|
+
process.stdin.setEncoding('utf8');
|
|
136
|
+
let output = {};
|
|
137
|
+
try {
|
|
138
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
139
|
+
output = await steeringHookOutput(JSON.parse(input));
|
|
140
|
+
} catch { output = {}; }
|
|
141
|
+
process.stdout.write(JSON.stringify(output) + '\n');
|
|
142
|
+
} else if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
|
|
116
143
|
const owned = process.env.KIKI_AGY_PERMISSION_ENDPOINT || process.env.KIKI_AGY_PERMISSION_TOKEN;
|
|
117
144
|
let input = '';
|
|
118
145
|
process.stdin.setEncoding('utf8');
|
package/dist/hostRunner.mjs
CHANGED
|
@@ -28,6 +28,17 @@ function emitImEvent(id, event, owner) {
|
|
|
28
28
|
}
|
|
29
29
|
return transmitImEvent(id, event, owner);
|
|
30
30
|
}
|
|
31
|
+
function reportImDiagnostic(id, diagnostic, owner) {
|
|
32
|
+
const connection = imConnections.get(id);
|
|
33
|
+
if (connection !== owner || connection?.started !== true || !connection.definition.inbound || connection.controller.signal.aborted) return Promise.reject(new Error('IM connection is not receiving'));
|
|
34
|
+
if (Buffer.byteLength(JSON.stringify(diagnostic), 'utf8') > 1024) return Promise.reject(new Error('IM diagnostic exceeds the byte limit'));
|
|
35
|
+
const callId = ++nextImEvent;
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const timer = setTimeout(() => { imEventCalls.delete(callId); reject(new Error('IM diagnostic acknowledgement timed out')); }, 30_000);
|
|
38
|
+
imEventCalls.set(callId, { adapterId: id, resolve: () => { clearTimeout(timer); resolve(); }, reject: (error) => { clearTimeout(timer); reject(error); } });
|
|
39
|
+
send({ method: 'im-adapter-report', params: { adapterId: id, connectionId: connection.id, callId, diagnostic } });
|
|
40
|
+
});
|
|
41
|
+
}
|
|
31
42
|
function transmitImEvent(id, event, connection) {
|
|
32
43
|
if (imConnections.get(id) !== connection || connection.controller.signal.aborted) throw new Error('IM connection is not receiving');
|
|
33
44
|
const imCompleteLimits = connection.context.messageLimits;
|
|
@@ -199,8 +210,15 @@ function shutdown() {
|
|
|
199
210
|
});
|
|
200
211
|
return shuttingDown;
|
|
201
212
|
}
|
|
202
|
-
|
|
203
|
-
|
|
213
|
+
function stopWithOwner() {
|
|
214
|
+
const timer = setTimeout(() => process.exit(), 1000);
|
|
215
|
+
timer.unref();
|
|
216
|
+
void shutdown().finally(() => process.exit());
|
|
217
|
+
}
|
|
218
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, stopWithOwner);
|
|
219
|
+
const input = createInterface({ input: process.stdin });
|
|
220
|
+
input.once('close', stopWithOwner);
|
|
221
|
+
for await (const line of input) {
|
|
204
222
|
let message;
|
|
205
223
|
try { message = JSON.parse(line); } catch { continue; }
|
|
206
224
|
if (message.method === 'handshake') {
|
|
@@ -311,7 +329,7 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
311
329
|
else call?.resolve(message.params?.result);
|
|
312
330
|
continue;
|
|
313
331
|
}
|
|
314
|
-
if (message.method === 'im-adapter-event-result') {
|
|
332
|
+
if (message.method === 'im-adapter-event-result' || message.method === 'im-adapter-report-result') {
|
|
315
333
|
const call = imEventCalls.get(message.params?.callId);
|
|
316
334
|
imEventCalls.delete(message.params?.callId);
|
|
317
335
|
if (message.params?.error !== undefined) call?.reject(new Error(message.params.error));
|
|
@@ -319,7 +337,7 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
319
337
|
continue;
|
|
320
338
|
}
|
|
321
339
|
if (message.method === 'im-adapter-request') {
|
|
322
|
-
const { adapterId, action, input, settings, instanceId, offset, messageLimits } = message.params ?? {};
|
|
340
|
+
const { adapterId, action, input, settings, instanceId, offset, messageLimits, connectionId } = message.params ?? {};
|
|
323
341
|
Promise.resolve().then(async () => {
|
|
324
342
|
const registered = imAdapters.get(adapterId);
|
|
325
343
|
if (registered === undefined) throw new Error('Unknown IM adapter');
|
|
@@ -327,10 +345,10 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
327
345
|
if (action === 'start') {
|
|
328
346
|
if (imConnections.has(adapterId)) throw new Error('IM adapter already connected');
|
|
329
347
|
const controller = new AbortController();
|
|
330
|
-
const connection = { ...registered, controller, started: false, context: { signal: controller.signal, settings: settings ?? {}, instanceId, messageLimits: Object.freeze({ ...messageLimits }) } };
|
|
348
|
+
const connection = { ...registered, id: connectionId, controller, started: false, context: { signal: controller.signal, settings: settings ?? {}, instanceId, messageLimits: Object.freeze({ ...messageLimits }) } };
|
|
331
349
|
imConnections.set(adapterId, connection);
|
|
332
350
|
try {
|
|
333
|
-
const result = await registered.adapter.start({ ...connection.context, offset, emit: (event) => emitImEvent(adapterId, event, connection) });
|
|
351
|
+
const result = await registered.adapter.start({ ...connection.context, offset, emit: (event) => emitImEvent(adapterId, event, connection), report: (diagnostic) => reportImDiagnostic(adapterId, diagnostic, connection) });
|
|
334
352
|
connection.started = true;
|
|
335
353
|
return result;
|
|
336
354
|
} catch (error) { await stopImAdapter(adapterId); throw error; }
|
package/dist/mailbox-worker.mjs
CHANGED
|
@@ -1,10 +1,46 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { existsSync, mkdirSync } from "node:fs";
|
|
2
3
|
import { dirname } from "node:path";
|
|
3
4
|
import { DatabaseSync, backup } from "node:sqlite";
|
|
4
5
|
import { parentPort, workerData } from "node:worker_threads";
|
|
5
6
|
import { isDeepStrictEqual } from "node:util";
|
|
7
|
+
import { availableParallelism, totalmem } from "node:os";
|
|
8
|
+
import { getHeapStatistics } from "node:v8";
|
|
6
9
|
|
|
10
|
+
//#region ../../packages/agent-core-v2/src/_base/node/resourceDefaults.ts
|
|
11
|
+
function resourceDefaults(hardware = {
|
|
12
|
+
parallelism: availableParallelism(),
|
|
13
|
+
memoryBytes: totalmem()
|
|
14
|
+
}) {
|
|
15
|
+
const memoryMiB = Math.floor(hardware.memoryBytes / 1024 / 1024);
|
|
16
|
+
const spareCpus = Math.max(1, hardware.parallelism - 1);
|
|
17
|
+
const workerHeapMb = Math.max(512, Math.floor(memoryMiB / 64));
|
|
18
|
+
const cpuWorkers = Math.max(1, Math.min(spareCpus, Math.floor(memoryMiB / 4 / workerHeapMb)));
|
|
19
|
+
return {
|
|
20
|
+
workerHeapMb,
|
|
21
|
+
searchIndexerSoftMb: workerHeapMb * 2 + 256,
|
|
22
|
+
searchIndexerHardMb: workerHeapMb * 3 + 256,
|
|
23
|
+
cpuWorkers,
|
|
24
|
+
workerQueue: Math.max(128, hardware.parallelism * 16),
|
|
25
|
+
cpuQueue: Math.max(128, cpuWorkers * 16),
|
|
26
|
+
cpuQueuedBytes: Math.max(64, Math.floor(memoryMiB / 128)) * 1024 * 1024,
|
|
27
|
+
liveSessions: Math.max(16, Math.floor(memoryMiB / 128)),
|
|
28
|
+
queuedRestores: Math.max(128, hardware.parallelism * 16),
|
|
29
|
+
residentHeapBytes: Math.max(256, Math.floor(memoryMiB / 8)) * 1024 * 1024
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const RESOURCE_DEFAULTS = resourceDefaults();
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region ../../packages/agent-core-v2/src/_base/node/workerHeapPolicy.ts
|
|
36
|
+
function warnIfWorkerHeapLimit(expectedMb) {
|
|
37
|
+
const observedMb = getHeapStatistics().heap_size_limit / 1024 / 1024;
|
|
38
|
+
if (observedMb < expectedMb * .9 || observedMb > expectedMb + 256) process.emitWarning(`Worker heap limit is ${Math.round(observedMb)} MiB; expected ${expectedMb} MiB old-space plus at most 256 MiB young/code space. Check inherited Node heap flags.`, { code: "KIKI_WORKER_HEAP_LIMIT" });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
7
42
|
//#region ../../packages/agent-core-v2/src/persistence/backends/sqliteMailbox/entry.ts
|
|
43
|
+
warnIfWorkerHeapLimit(RESOURCE_DEFAULTS.workerHeapMb);
|
|
8
44
|
const port = parentPort;
|
|
9
45
|
if (port === null) throw new Error("Canonical mailbox requires a worker");
|
|
10
46
|
const configuration = workerData;
|
|
@@ -33,6 +69,7 @@ function open() {
|
|
|
33
69
|
connection = db;
|
|
34
70
|
return db;
|
|
35
71
|
}
|
|
72
|
+
if (application === 0) db.exec("PRAGMA auto_vacuum=INCREMENTAL");
|
|
36
73
|
db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA cache_size=-8192;
|
|
37
74
|
CREATE TABLE IF NOT EXISTS records(key TEXT PRIMARY KEY COLLATE BINARY, json TEXT NOT NULL CHECK(json_valid(json)), expire_at INTEGER NOT NULL DEFAULT 0 CHECK(expire_at>=0),
|
|
38
75
|
kind TEXT GENERATED ALWAYS AS (json_extract(json,'$.kind')) VIRTUAL,
|
|
@@ -81,12 +118,26 @@ function assertOwner(db, owner) {
|
|
|
81
118
|
if (metadata(db, "authority") !== "sqlite" || current?.epoch !== owner.epoch || current.hostId !== owner.hostId) throw Object.assign(/* @__PURE__ */ new Error("Canonical mailbox owner epoch is no longer active"), { code: "runtime.owner_gone" });
|
|
82
119
|
}
|
|
83
120
|
function row(value) {
|
|
121
|
+
const key = value["key"];
|
|
122
|
+
const json = value["json"];
|
|
123
|
+
if (typeof key !== "string" || typeof json !== "string") throw new Error("Canonical mailbox row is not text");
|
|
84
124
|
return {
|
|
85
|
-
key
|
|
86
|
-
value: JSON.parse(
|
|
125
|
+
key,
|
|
126
|
+
value: JSON.parse(json),
|
|
87
127
|
expireAt: Number(value["expire_at"])
|
|
88
128
|
};
|
|
89
129
|
}
|
|
130
|
+
function archiveDigest(json) {
|
|
131
|
+
return createHash("sha256").update(json).digest("base64url");
|
|
132
|
+
}
|
|
133
|
+
function ensureLegacyOrder(db) {
|
|
134
|
+
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_delivery_order'").get() !== void 0) return;
|
|
135
|
+
db.exec("CREATE TABLE legacy_delivery_order(source TEXT NOT NULL,target TEXT NOT NULL,seq INTEGER NOT NULL,key TEXT NOT NULL,PRIMARY KEY(source,target,seq,key)) WITHOUT ROWID");
|
|
136
|
+
db.prepare(`INSERT OR IGNORE INTO legacy_delivery_order
|
|
137
|
+
SELECT source,json_array(json_extract(json,'$.message.target.hostId'),json_extract(json,'$.message.target.workspaceId'),json_extract(json,'$.message.target.sessionId')),
|
|
138
|
+
coalesce(json_extract(json,'$.message.targetSeq'),-1),key FROM legacy_archive
|
|
139
|
+
WHERE json_extract(json,'$.kind')='delivery'`).run();
|
|
140
|
+
}
|
|
90
141
|
function verify(db) {
|
|
91
142
|
const integrity = db.prepare("PRAGMA integrity_check").all();
|
|
92
143
|
if (integrity.length !== 1 || integrity[0]["integrity_check"] !== "ok") throw new Error(`Canonical mailbox integrity check failed: ${JSON.stringify(integrity)}`);
|
|
@@ -141,8 +192,15 @@ function verify(db) {
|
|
|
141
192
|
}
|
|
142
193
|
}
|
|
143
194
|
if (metadata(db, "authority") === void 0) {
|
|
144
|
-
const
|
|
145
|
-
|
|
195
|
+
const current = db.prepare("SELECT json,expire_at FROM records WHERE key=?");
|
|
196
|
+
for (const archived of db.prepare("SELECT key,json,expire_at FROM legacy_archive WHERE source LIKE 'thread-mailbox-v3/%'").iterate()) {
|
|
197
|
+
check();
|
|
198
|
+
const key = String(archived["key"]);
|
|
199
|
+
const source = JSON.parse(String(archived["json"]));
|
|
200
|
+
if (source["kind"] === "target_meta" || source["kind"] === "workspace_override") continue;
|
|
201
|
+
const found = current.get(key);
|
|
202
|
+
if (found === void 0 || Number(found["expire_at"]) !== Number(archived["expire_at"]) || (typeof source["digest"] === "string" ? archiveDigest(String(found["json"])) !== source["digest"] : String(found["json"]) !== String(archived["json"]))) throw new Error(`Imported canonical record differs from its frozen source at ${key}`);
|
|
203
|
+
}
|
|
146
204
|
}
|
|
147
205
|
return {
|
|
148
206
|
counts,
|
|
@@ -197,7 +255,19 @@ async function execute(operation) {
|
|
|
197
255
|
}
|
|
198
256
|
if (operation.archive !== void 0) {
|
|
199
257
|
const archive = db.prepare("INSERT INTO legacy_archive VALUES(?,?,?,?) ON CONFLICT(source,key) DO UPDATE SET json=excluded.json,expire_at=excluded.expire_at");
|
|
200
|
-
|
|
258
|
+
const order = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_delivery_order'").get() === void 0 ? void 0 : db.prepare(`INSERT OR IGNORE INTO legacy_delivery_order
|
|
259
|
+
SELECT source,json_array(json_extract(json,'$.message.target.hostId'),json_extract(json,'$.message.target.workspaceId'),json_extract(json,'$.message.target.sessionId')),
|
|
260
|
+
coalesce(json_extract(json,'$.message.targetSeq'),-1),key FROM legacy_archive WHERE source=? AND key=?`);
|
|
261
|
+
for (const item of operation.archive.rows) {
|
|
262
|
+
check();
|
|
263
|
+
const json = JSON.stringify(item.value);
|
|
264
|
+
const retained = operation.archive.source.startsWith("thread-mailbox-v3/") ? JSON.stringify({
|
|
265
|
+
kind: item.value["kind"],
|
|
266
|
+
digest: archiveDigest(json)
|
|
267
|
+
}) : json;
|
|
268
|
+
archive.run(operation.archive.source, item.key, retained, item.expireAt);
|
|
269
|
+
if (order !== void 0 && item.value["kind"] === "delivery") order.run(operation.archive.source, item.key);
|
|
270
|
+
}
|
|
201
271
|
}
|
|
202
272
|
if (operation.importCheckpoint !== void 0) {
|
|
203
273
|
const point = operation.importCheckpoint;
|
|
@@ -233,6 +303,42 @@ async function execute(operation) {
|
|
|
233
303
|
}));
|
|
234
304
|
}
|
|
235
305
|
case "checkpoint": return db.prepare("SELECT after_key AS after,items,bytes FROM imports WHERE source=?").get(operation.source);
|
|
306
|
+
case "legacy_deliveries": {
|
|
307
|
+
if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_delivery_order'").get() === void 0) transaction((connection) => {
|
|
308
|
+
assertOwner(connection, void 0);
|
|
309
|
+
ensureLegacyOrder(connection);
|
|
310
|
+
});
|
|
311
|
+
const after = operation.after;
|
|
312
|
+
return { rows: db.prepare(`SELECT target,seq,key FROM legacy_delivery_order WHERE source=?
|
|
313
|
+
AND (? IS NULL OR (target,seq,key)>(?,?,?)) ORDER BY target,seq,key LIMIT ?`).all(operation.source, after?.target ?? null, after?.target ?? "", after?.seq ?? 0, after?.key ?? "", operation.limit).map((entry) => ({
|
|
314
|
+
target: String(entry["target"]),
|
|
315
|
+
seq: Number(entry["seq"]),
|
|
316
|
+
key: String(entry["key"])
|
|
317
|
+
})) };
|
|
318
|
+
}
|
|
319
|
+
case "discard_archive": {
|
|
320
|
+
transaction((connection) => {
|
|
321
|
+
if (operation.completedMigrationId === void 0) assertOwner(connection, void 0);
|
|
322
|
+
else if (metadata(connection, "authority") !== "sqlite" || metadata(connection, "migrationReady") !== operation.completedMigrationId || metadata(connection, "hasNewWrites") !== true) throw new Error("Only a completed mailbox migration with new SQLite writes can discard its old import archive");
|
|
323
|
+
connection.exec(`DROP TABLE IF EXISTS legacy_archive;
|
|
324
|
+
CREATE TABLE legacy_archive(source TEXT NOT NULL,key TEXT NOT NULL,json TEXT NOT NULL CHECK(json_valid(json)),expire_at INTEGER NOT NULL,PRIMARY KEY(source,key)) WITHOUT ROWID;
|
|
325
|
+
DROP TABLE IF EXISTS legacy_delivery_order`);
|
|
326
|
+
});
|
|
327
|
+
const free = () => Number(db.prepare("PRAGMA freelist_count").get()["freelist_count"]);
|
|
328
|
+
if (Number(db.prepare("PRAGMA auto_vacuum").get()["auto_vacuum"]) === 2) while (free() > 0) {
|
|
329
|
+
check();
|
|
330
|
+
db.exec("PRAGMA incremental_vacuum(256)");
|
|
331
|
+
}
|
|
332
|
+
else if (operation.completedMigrationId !== void 0 && free() > 0) {
|
|
333
|
+
check();
|
|
334
|
+
db.exec("VACUUM");
|
|
335
|
+
}
|
|
336
|
+
if (operation.completedMigrationId !== void 0) {
|
|
337
|
+
const checkpoint = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
338
|
+
if (Number(checkpoint["busy"]) !== 0) throw new Error("SQLite archive cleanup cannot checkpoint while another reader holds the database");
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
236
342
|
case "metadata":
|
|
237
343
|
if (operation.value === void 0) return metadata(db, operation.key);
|
|
238
344
|
return transaction((db) => {
|
package/dist/main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/dist/main.mjs
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 45109777 bytes
|
|
4
|
+
sha256: 03f6b7448a1d3f2c9fbc6a2490dcd37595992a3044a519367cdabd9b365a2d15
|