kiki-agent 0.4.2 → 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 +121 -46
- package/dist/docs/en/configuration/data-locations.md +34 -7
- package/dist/docs/en/configuration/env-vars.md +37 -9
- package/dist/docs/en/configuration/overrides.md +20 -9
- package/dist/docs/en/configuration/providers.md +114 -9
- package/dist/docs/en/customization/agent-profiles.md +1 -1
- package/dist/docs/en/customization/agents-and-subagents.md +55 -12
- package/dist/docs/en/customization/hooks.md +3 -3
- package/dist/docs/en/customization/personas.md +36 -2
- package/dist/docs/en/customization/plugins.md +56 -3
- package/dist/docs/en/customization/prompt-fields.md +65 -5
- 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/agent-workflows.md +8 -8
- package/dist/docs/en/features/browser-and-computer.md +40 -0
- package/dist/docs/en/features/daily.md +13 -13
- package/dist/docs/en/features/ecosystem.md +6 -6
- package/dist/docs/en/features/extend.md +11 -10
- package/dist/docs/en/features/freedom.md +9 -9
- package/dist/docs/en/features/index.md +58 -28
- package/dist/docs/en/features/long-work.md +18 -14
- package/dist/docs/en/features/look.md +6 -6
- package/dist/docs/en/features/people.md +6 -6
- package/dist/docs/en/features/phone.md +13 -3
- package/dist/docs/en/features/spaces.md +12 -12
- package/dist/docs/en/features/workbench.md +8 -8
- 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 +32 -10
- package/dist/docs/en/guides/memory.md +64 -10
- package/dist/docs/en/guides/sessions.md +21 -9
- package/dist/docs/en/guides/settings.md +64 -40
- package/dist/docs/en/index.md +3 -1
- package/dist/docs/en/reference/command.md +90 -31
- 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 +65 -20
- package/dist/docs/en/server/acp.md +9 -3
- package/dist/docs/en/server/local-server.md +19 -27
- package/dist/docs/en/server/mcp.md +9 -5
- package/dist/docs/en/server/rest-api.md +350 -22
- package/dist/docs/en/server/script-tools.md +268 -0
- package/dist/docs/zh/configuration/config-files.md +121 -46
- package/dist/docs/zh/configuration/data-locations.md +34 -7
- package/dist/docs/zh/configuration/env-vars.md +37 -9
- package/dist/docs/zh/configuration/overrides.md +20 -9
- package/dist/docs/zh/configuration/providers.md +114 -9
- package/dist/docs/zh/customization/agent-profiles.md +1 -1
- package/dist/docs/zh/customization/agents-and-subagents.md +55 -12
- package/dist/docs/zh/customization/hooks.md +3 -3
- package/dist/docs/zh/customization/personas.md +36 -2
- package/dist/docs/zh/customization/plugins.md +56 -3
- package/dist/docs/zh/customization/prompt-fields.md +65 -5
- 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/agent-workflows.md +10 -10
- package/dist/docs/zh/features/browser-and-computer.md +40 -0
- package/dist/docs/zh/features/daily.md +13 -13
- package/dist/docs/zh/features/ecosystem.md +6 -6
- package/dist/docs/zh/features/extend.md +10 -9
- package/dist/docs/zh/features/freedom.md +9 -9
- package/dist/docs/zh/features/index.md +58 -28
- package/dist/docs/zh/features/long-work.md +17 -13
- package/dist/docs/zh/features/look.md +6 -6
- package/dist/docs/zh/features/people.md +5 -5
- package/dist/docs/zh/features/phone.md +13 -3
- package/dist/docs/zh/features/spaces.md +12 -12
- package/dist/docs/zh/features/workbench.md +8 -8
- 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 +32 -10
- package/dist/docs/zh/guides/memory.md +64 -10
- package/dist/docs/zh/guides/sessions.md +21 -9
- package/dist/docs/zh/guides/settings.md +64 -40
- package/dist/docs/zh/index.md +4 -2
- package/dist/docs/zh/reference/command.md +90 -31
- 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 +65 -20
- package/dist/docs/zh/server/acp.md +9 -3
- package/dist/docs/zh/server/local-server.md +19 -27
- package/dist/docs/zh/server/mcp.md +9 -5
- package/dist/docs/zh/server/rest-api.md +338 -21
- 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 +112 -3
- package/dist/mailbox-worker.mjs +403 -0
- 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 +487 -0
- package/dist/sqlite-indexer.mjs +255 -403
- package/dist/sqlite-query-worker.mjs +261 -249
- package/dist/usage-parser-worker.mjs +3977 -9
- package/dist/usage-read-model-worker.mjs +761 -0
- package/dist/web/assets/AppErrorBoundary-B5Fc4f6-.js +1 -0
- package/dist/web/assets/NavScopeBoundary-C7MnGQio.js +1 -0
- package/dist/web/assets/{arc-DYDCMlOS.js → arc-DGB9OVgQ.js} +1 -1
- package/dist/web/assets/{architectureDiagram-3BPJPVTR-C9Y7T0O2.js → architectureDiagram-3BPJPVTR-glnQCMub.js} +1 -1
- package/dist/web/assets/{blockDiagram-GPEHLZMM-CdUrp-tD.js → blockDiagram-GPEHLZMM-bM0tnGby.js} +1 -1
- package/dist/web/assets/{c4Diagram-AAUBKEIU-PrwvB9IJ.js → c4Diagram-AAUBKEIU-DMf_rTtt.js} +1 -1
- package/dist/web/assets/channel-Cj8SKJ38.js +1 -0
- package/dist/web/assets/{chunk-2J33WTMH-BL56g_Es.js → chunk-2J33WTMH-mTccJ3tW.js} +1 -1
- package/dist/web/assets/{chunk-4BX2VUAB-DvJD5M9M.js → chunk-4BX2VUAB-DhqPYMjY.js} +1 -1
- package/dist/web/assets/{chunk-55IACEB6-C8f-nzvx.js → chunk-55IACEB6-BujrYRoO.js} +1 -1
- package/dist/web/assets/{chunk-727SXJPM-DOGkWKkV.js → chunk-727SXJPM-ciMmSI4G.js} +1 -1
- package/dist/web/assets/{chunk-AQP2D5EJ-fFOuz7g6.js → chunk-AQP2D5EJ-CZW9pKTc.js} +1 -1
- package/dist/web/assets/{chunk-FMBD7UC4-BpeXZ9LM.js → chunk-FMBD7UC4-hdALNnnU.js} +1 -1
- package/dist/web/assets/{chunk-ND2GUHAM-CRUh76fb.js → chunk-ND2GUHAM-CgKyqUdb.js} +1 -1
- package/dist/web/assets/{chunk-QZHKN3VN-uNfxaPk0.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-BNkxG-qX.js → cose-bilkent-S5V4N54A-UV3uPjkK.js} +1 -1
- package/dist/web/assets/{dagre-BM42HDAG-BerioUei.js → dagre-BM42HDAG-Zjy-gQ6C.js} +1 -1
- package/dist/web/assets/{diagram-2AECGRRQ-Czv2SR07.js → diagram-2AECGRRQ-DL-kilIf.js} +1 -1
- package/dist/web/assets/{diagram-5GNKFQAL-Uzi1weGK.js → diagram-5GNKFQAL-CjB_xR5B.js} +1 -1
- package/dist/web/assets/{diagram-KO2AKTUF-W36h_ff3.js → diagram-KO2AKTUF-CjN4i3b9.js} +1 -1
- package/dist/web/assets/{diagram-LMA3HP47-FG4dDk52.js → diagram-LMA3HP47-CPCAMndo.js} +1 -1
- package/dist/web/assets/{diagram-OG6HWLK6-CQoEjIAY.js → diagram-OG6HWLK6-DVeBWBKd.js} +1 -1
- package/dist/web/assets/{erDiagram-TEJ5UH35-Ck06KVyZ.js → erDiagram-TEJ5UH35-CHKzBHrr.js} +1 -1
- package/dist/web/assets/export-CXoWon32.js +2 -0
- package/dist/web/assets/{flowDiagram-I6XJVG4X-C5hgxdFZ.js → flowDiagram-I6XJVG4X-C5rQa2pq.js} +1 -1
- package/dist/web/assets/{ganttDiagram-6RSMTGT7-BS52Pw5_.js → ganttDiagram-6RSMTGT7-BrLjEsNJ.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-PVQCEYII-DLlQKZHs.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-CM-nNfuV.js → index-BJxtlf4P.js} +4 -4
- package/dist/web/assets/{index-DKIysLbI.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-Ca607_hK.js → index-BvRBCpc6.js} +2 -2
- package/dist/web/assets/index-BxYCSNg_.js +3 -0
- package/dist/web/assets/{index-B2Pu0Iuu.js → index-C62wjCF_.js} +1 -1
- package/dist/web/assets/index-CBvwNH_H.js +1 -0
- package/dist/web/assets/{index-BNch_a4L.js → index-CG9e6lgq.js} +1 -1
- package/dist/web/assets/{index-ByiwExpV.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-Bg99yVX_.js → index-CypTtrCB.js} +1 -1
- package/dist/web/assets/{index-BwcG86o3.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-CZX3qUe2.js → index-DfUpwUTM.js} +2 -2
- package/dist/web/assets/{index-BLU8_Um7.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-CD4XJGFm.js → infoDiagram-5YYISTIA-CCwV4Z0v.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-fu5E3_CT.js → ishikawaDiagram-YF4QCWOH-BwwZcGyZ.js} +1 -1
- package/dist/web/assets/{journeyDiagram-JHISSGLW-CXcnKBfJ.js → journeyDiagram-JHISSGLW-Dc6WqniQ.js} +1 -1
- package/dist/web/assets/{kanban-definition-UN3LZRKU-BawKH6Pl.js → kanban-definition-UN3LZRKU-DVUqULOS.js} +1 -1
- package/dist/web/assets/{linear-BplJuXph.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-DA1SE2uy.js → mindmap-definition-RKZ34NQL-_JHAkhHL.js} +1 -1
- package/dist/web/assets/navViewState-DaCMIYWA.js +1 -0
- package/dist/web/assets/{pieDiagram-4H26LBE5-6i021QeX.js → pieDiagram-4H26LBE5-BlhlygGy.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-W4KKPZXB-CcKSZDMT.js → quadrantDiagram-W4KKPZXB-jn6R_C0S.js} +1 -1
- package/dist/web/assets/{requirementDiagram-4Y6WPE33-lYVuWRuD.js → requirementDiagram-4Y6WPE33-B9fXCHBr.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-5OEKKPKP-4Zfb4_h4.js → sankeyDiagram-5OEKKPKP-fPJwIxkl.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DqltKmlY.js → sequenceDiagram-3UESZ5HK-1v1DTNGt.js} +1 -1
- package/dist/web/assets/{spaces-CjuXbmxF.js → spaces-CvL2DRZM.js} +1 -1
- package/dist/web/assets/{stateDiagram-AJRCARHV-HFdhqxzx.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-HNRxaB3t.js → timeline-definition-PNZ67QCA-CEjhuitj.js} +1 -1
- package/dist/web/assets/{vennDiagram-CIIHVFJN-DwsCTyaD.js → vennDiagram-CIIHVFJN-CActt9h9.js} +1 -1
- package/dist/web/assets/{wardley-L42UT6IY-BWW2wtVO.js → wardley-L42UT6IY-Bp3q2izt.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-YWT4CUSO-C-ktKm7v.js → wardleyDiagram-YWT4CUSO-C_zutiQ2.js} +1 -1
- package/dist/web/assets/{xychartDiagram-2RQKCTM6-48AxNW9k.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 +23 -4
- package/dist/search-worker.mjs +0 -14177
- package/dist/web/assets/AppErrorBoundary-DiGMUg4r.js +0 -1
- package/dist/web/assets/LifeMark-CL6-HWDu.js +0 -1
- package/dist/web/assets/NavScopeBoundary-CFCnvZR0.js +0 -1
- package/dist/web/assets/channel-Bj_gZ_Lv.js +0 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-ssCwe2R4.js +0 -1
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-ssCwe2R4.js +0 -1
- package/dist/web/assets/client-DGj93bGT.js +0 -3
- package/dist/web/assets/connection-Bpf-EjrL.js +0 -1
- package/dist/web/assets/export-T_izwEkQ.js +0 -2
- package/dist/web/assets/highlighted-body-OFNGDK62-Btm6MuZ4.js +0 -1
- package/dist/web/assets/index-5_yzg61S.js +0 -1
- package/dist/web/assets/index-B-6LiYTY.js +0 -1
- package/dist/web/assets/index-B4iu4SJW.js +0 -1
- package/dist/web/assets/index-B9MlqF7J.js +0 -1
- package/dist/web/assets/index-BECSk4If.js +0 -1
- package/dist/web/assets/index-BFcyN2Zw.js +0 -1
- package/dist/web/assets/index-BIebkSEI.css +0 -1
- package/dist/web/assets/index-BMWid2q9.js +0 -1
- package/dist/web/assets/index-BeMvPEXs.js +0 -1
- package/dist/web/assets/index-Bezli3SF.js +0 -1
- package/dist/web/assets/index-BkPV0psm.js +0 -1
- package/dist/web/assets/index-CG8uIlD7.js +0 -1
- package/dist/web/assets/index-CJ92kLtO.js +0 -1
- package/dist/web/assets/index-CRDDqofN.js +0 -1
- package/dist/web/assets/index-Cd62y0wD.js +0 -1
- package/dist/web/assets/index-CgcJPsK6.js +0 -3
- package/dist/web/assets/index-Cy8C_eFR.js +0 -7
- package/dist/web/assets/index-D8z7lcQn.js +0 -166
- package/dist/web/assets/index-D_oPSlBL.js +0 -1
- package/dist/web/assets/index-Dceu0bqY.js +0 -1
- package/dist/web/assets/index-eUyF-8Sq.js +0 -1
- package/dist/web/assets/index-hG2s2Spn.js +0 -13
- package/dist/web/assets/mermaid-GHXKKRXX-BO9hkP3Z.js +0 -621
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Dx28QuZF.js +0 -1
- package/dist/web/assets/theme-beWE_6f8.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
|
@@ -6,6 +6,61 @@ const [entry] = process.argv.slice(2);
|
|
|
6
6
|
const tools = new Map();
|
|
7
7
|
const sources = new Map();
|
|
8
8
|
const providers = new Map();
|
|
9
|
+
const imAdapters = new Map();
|
|
10
|
+
const imConnections = new Map();
|
|
11
|
+
const imEventCalls = new Map();
|
|
12
|
+
let nextImEvent = 0;
|
|
13
|
+
async function stopImAdapter(id) {
|
|
14
|
+
const connection = imConnections.get(id);
|
|
15
|
+
if (connection === undefined) return;
|
|
16
|
+
imConnections.delete(id);
|
|
17
|
+
connection.controller.abort();
|
|
18
|
+
for (const [callId, call] of imEventCalls) if (call.adapterId === id) { imEventCalls.delete(callId); call.reject(new Error('IM adapter stopped')); }
|
|
19
|
+
await connection.adapter.stop();
|
|
20
|
+
}
|
|
21
|
+
function emitImEvent(id, event, owner) {
|
|
22
|
+
const connection = imConnections.get(id);
|
|
23
|
+
if (connection !== owner || connection?.started !== true || !connection.definition.inbound || connection.controller.signal.aborted) return Promise.reject(new Error('IM connection is not receiving'));
|
|
24
|
+
if (event.kind === 'message') {
|
|
25
|
+
const work = (connection.inputQueue ?? Promise.resolve()).catch(() => undefined).then(() => transmitImEvent(id, event, owner));
|
|
26
|
+
connection.inputQueue = work;
|
|
27
|
+
return work;
|
|
28
|
+
}
|
|
29
|
+
return transmitImEvent(id, event, owner);
|
|
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
|
+
}
|
|
42
|
+
function transmitImEvent(id, event, connection) {
|
|
43
|
+
if (imConnections.get(id) !== connection || connection.controller.signal.aborted) throw new Error('IM connection is not receiving');
|
|
44
|
+
const imCompleteLimits = connection.context.messageLimits;
|
|
45
|
+
const wireMedia = (media) => media === undefined ? undefined : { name: media.name, mediaType: media.mediaType, base64: Buffer.from(media.bytes).toString('base64') };
|
|
46
|
+
if (event.kind === 'message') {
|
|
47
|
+
if (!Array.isArray(event.parts) || event.parts.length < 1 || event.parts.length > imCompleteLimits.parts) throw new Error('IM complete input has an invalid part count');
|
|
48
|
+
if (event.parts.some((part) => part.tooLarge === true)) throw new Error('IM complete input contains a tooLarge part');
|
|
49
|
+
const bytes = event.parts.map((part) => part.media?.bytes?.byteLength ?? 0);
|
|
50
|
+
if (bytes.some((size) => size > connection.definition.maxInboundBytes) || bytes.reduce((sum, size) => sum + size, 0) > imCompleteLimits.mediaBytes) throw new Error('IM complete input exceeds the media byte limit');
|
|
51
|
+
if (event.parts.reduce((sum, part) => sum + (part.text?.length ?? 0), 0) > imCompleteLimits.textChars) throw new Error('IM complete input exceeds the text limit');
|
|
52
|
+
}
|
|
53
|
+
const wireEvent = event.kind === 'message' ? { ...event, parts: event.parts.map((part) => ({ ...part, media: wireMedia(part.media) })) } : { ...event, media: wireMedia(event.media) };
|
|
54
|
+
const serialized = event.kind === 'message' ? JSON.stringify(wireEvent) : undefined;
|
|
55
|
+
if (serialized !== undefined && serialized.length > imCompleteLimits.serializedChars) throw new Error('IM complete input exceeds the serialized message limit');
|
|
56
|
+
const callId = ++nextImEvent;
|
|
57
|
+
return new Promise((resolve, reject) => {
|
|
58
|
+
const timer = setTimeout(() => { imEventCalls.delete(callId); reject(new Error('IM input acknowledgement timed out')); }, 30_000);
|
|
59
|
+
imEventCalls.set(callId, { adapterId: id, resolve: () => { clearTimeout(timer); resolve(); }, reject: (error) => { clearTimeout(timer); reject(error); } });
|
|
60
|
+
if (serialized === undefined) send({ method: 'im-adapter-event', params: { adapterId: id, callId, event: wireEvent } });
|
|
61
|
+
else for (let offset = 0, index = 0; offset < serialized.length; offset += imCompleteLimits.chunkChars, index++) send({ method: 'im-adapter-message-chunk', params: { adapterId: id, callId, index, characters: serialized.length, data: serialized.slice(offset, offset + imCompleteLimits.chunkChars) } });
|
|
62
|
+
});
|
|
63
|
+
}
|
|
9
64
|
const mediaCalls = new Map();
|
|
10
65
|
let nextMediaCall = 0;
|
|
11
66
|
const outputCalls = new Map();
|
|
@@ -147,11 +202,23 @@ function shutdown() {
|
|
|
147
202
|
if (shuttingDown !== undefined) return shuttingDown;
|
|
148
203
|
lifetime.abort();
|
|
149
204
|
for (const controller of pending.values()) controller.abort();
|
|
150
|
-
shuttingDown = Promise.resolve().then(() =>
|
|
205
|
+
shuttingDown = Promise.resolve().then(async () => {
|
|
206
|
+
await Promise.allSettled([...imConnections.keys()].map(stopImAdapter));
|
|
207
|
+
for (const call of imEventCalls.values()) call.reject(new Error('IM adapter stopped'));
|
|
208
|
+
imEventCalls.clear();
|
|
209
|
+
await deactivate?.();
|
|
210
|
+
});
|
|
151
211
|
return shuttingDown;
|
|
152
212
|
}
|
|
153
|
-
|
|
154
|
-
|
|
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) {
|
|
155
222
|
let message;
|
|
156
223
|
try { message = JSON.parse(line); } catch { continue; }
|
|
157
224
|
if (message.method === 'handshake') {
|
|
@@ -190,6 +257,11 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
190
257
|
providers.set(definition.id, adapter);
|
|
191
258
|
send({ method: 'register-media-provider', params: { version: 1, definition } });
|
|
192
259
|
},
|
|
260
|
+
registerImAdapter(definition, adapter) {
|
|
261
|
+
if (typeof definition?.id !== 'string' || imAdapters.has(definition.id) || typeof adapter?.start !== 'function' || typeof adapter?.stop !== 'function' || (definition.outbound && typeof adapter?.sendText !== 'function') || (definition.supportsEdit && typeof adapter?.editText !== 'function') || (definition.mediaCapabilities?.length && typeof adapter?.sendMedia !== 'function')) throw new Error('Invalid or duplicate IM adapter');
|
|
262
|
+
imAdapters.set(definition.id, { adapter, definition });
|
|
263
|
+
send({ method: 'register-im-adapter', params: { version: 1, definition } });
|
|
264
|
+
},
|
|
193
265
|
});
|
|
194
266
|
} catch (error) {
|
|
195
267
|
send({ method: 'register-error', params: { message: String(error) } });
|
|
@@ -257,6 +329,42 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
257
329
|
else call?.resolve(message.params?.result);
|
|
258
330
|
continue;
|
|
259
331
|
}
|
|
332
|
+
if (message.method === 'im-adapter-event-result' || message.method === 'im-adapter-report-result') {
|
|
333
|
+
const call = imEventCalls.get(message.params?.callId);
|
|
334
|
+
imEventCalls.delete(message.params?.callId);
|
|
335
|
+
if (message.params?.error !== undefined) call?.reject(new Error(message.params.error));
|
|
336
|
+
else call?.resolve();
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (message.method === 'im-adapter-request') {
|
|
340
|
+
const { adapterId, action, input, settings, instanceId, offset, messageLimits, connectionId } = message.params ?? {};
|
|
341
|
+
Promise.resolve().then(async () => {
|
|
342
|
+
const registered = imAdapters.get(adapterId);
|
|
343
|
+
if (registered === undefined) throw new Error('Unknown IM adapter');
|
|
344
|
+
if (action === 'stop') return stopImAdapter(adapterId);
|
|
345
|
+
if (action === 'start') {
|
|
346
|
+
if (imConnections.has(adapterId)) throw new Error('IM adapter already connected');
|
|
347
|
+
const controller = new AbortController();
|
|
348
|
+
const connection = { ...registered, id: connectionId, controller, started: false, context: { signal: controller.signal, settings: settings ?? {}, instanceId, messageLimits: Object.freeze({ ...messageLimits }) } };
|
|
349
|
+
imConnections.set(adapterId, connection);
|
|
350
|
+
try {
|
|
351
|
+
const result = await registered.adapter.start({ ...connection.context, offset, emit: (event) => emitImEvent(adapterId, event, connection), report: (diagnostic) => reportImDiagnostic(adapterId, diagnostic, connection) });
|
|
352
|
+
connection.started = true;
|
|
353
|
+
return result;
|
|
354
|
+
} catch (error) { await stopImAdapter(adapterId); throw error; }
|
|
355
|
+
}
|
|
356
|
+
const connection = imConnections.get(adapterId);
|
|
357
|
+
if (connection?.started !== true || connection.controller.signal.aborted) throw new Error('IM adapter is not connected');
|
|
358
|
+
if (action === 'readHistory') {
|
|
359
|
+
if (!connection.definition.inbound || connection.definition.supportsHistory !== true || typeof connection.adapter.readHistory !== 'function') return { status: 'unsupported' };
|
|
360
|
+
return connection.adapter.readHistory(input, connection.context);
|
|
361
|
+
}
|
|
362
|
+
if (!connection.definition.outbound || !['sendText', 'sendMedia', 'editText', 'answerCallback'].includes(action) || typeof connection.adapter[action] !== 'function') throw new Error('IM action unsupported');
|
|
363
|
+
const value = action === 'sendMedia' ? { ...input, bytes: new Uint8Array(Buffer.from(input.base64, 'base64')), base64: undefined } : input;
|
|
364
|
+
return connection.adapter[action](value, connection.context);
|
|
365
|
+
}).then((result) => send({ id: message.id, result }), (error) => send({ id: message.id, error: { code: -32000, message: String(error) } }));
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
260
368
|
if (message.method === 'media-provider-request') {
|
|
261
369
|
const controller = new AbortController();
|
|
262
370
|
pending.set(message.id, controller);
|
|
@@ -332,6 +440,7 @@ for await (const line of createInterface({ input: process.stdin })) {
|
|
|
332
440
|
generate(input) { return callMedia(message.id, 'generate', input); },
|
|
333
441
|
media(input) { return callMedia(message.id, 'media', input); },
|
|
334
442
|
},
|
|
443
|
+
messages: { send(input) { return callMedia(message.id, 'message-send', input); } },
|
|
335
444
|
});
|
|
336
445
|
}).then((result) => prepareToolResult(message.id, result, controller.signal)).then(
|
|
337
446
|
(result) => send({ id: message.id, result }),
|