@ai-agent-forge/agent-forge 0.85.7 → 0.85.9
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 +20 -0
- package/dist/bundle/.build-manifest.json +7 -7
- package/dist/bundle/chunks/{chunk-WD7FTOHY.js → chunk-PUOP77IC.js} +3 -3
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/plugin-command.d.ts +3 -1
- package/dist/cli/plugin-command.d.ts.map +1 -1
- package/dist/cli/plugin-command.js +71 -1
- package/dist/cli/plugin-command.js.map +1 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.d.ts.map +1 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.js +2 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +27 -3
- package/dist/utils/tools-manager.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-command.d.ts","sourceRoot":"","sources":["../../src/cli/plugin-command.ts"],"names":[],"mappings":"AAOA,OAAO,EAIN,KAAK,oBAAoB,EAGzB,KAAK,yBAAyB,EAC9B,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAGhF,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,oEAAoE;IACpE,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE;QACf,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAC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AA2B,GAClC,OAAO,CAAC,OAAO,CAAC,CAiBlB","sourcesContent":["import { join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { defaultPluginHostFactsV1, projectPluginScopeRefV1 } from \"../plugins/ecosystem/default-active-bindings.ts\";\nimport {\n\tcreateDefaultPluginMarketWiringV1,\n\ttype DefaultPluginMarketWiringV1,\n} from \"../plugins/ecosystem/default-plugin-market.ts\";\nimport {\n\tcreatePluginEcosystemCliV1,\n\tcreatePluginSelectionStoreV1,\n\tcreatePluginStateStoreV1,\n\ttype PluginDistributionV1,\n\ttype PluginEcosystemCliResponseV1,\n\ttype PluginEcosystemCliV1,\n\ttype PluginEcosystemRegistryV1,\n\ttype PluginInstallerV1,\n\ttype PluginSelectionStoreV1,\n\ttype PluginStateStoreV1,\n} from \"../plugins/ecosystem/index.ts\";\nimport { listBuiltinPluginManifestsV1 } from \"../profile/plugin-profiles.ts\";\nimport type { PluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\nimport { createPluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\n\nexport interface PluginCommandOptionsV1 {\n\treadonly agentDir?: string;\n\t/** Working directory used for the project-local selection store. */\n\treadonly cwd?: string;\n\treadonly host?: {\n\t\treadonly os: string;\n\t\treadonly arch: string;\n\t\treadonly runtime: readonly { readonly name: string; readonly version: string }[];\n\t\treadonly apiVersion: string;\n\t\treadonly hostFeatures: readonly string[];\n\t};\n\t/** Optional host-owned boundaries used by install/update/remove commands. */\n\treadonly registry?: PluginEcosystemRegistryV1;\n\treadonly installer?: PluginInstallerV1;\n\t/** Optional host-owned package download boundary used by install/update. */\n\treadonly distribution?: PluginDistributionV1;\n\t/** Override persistence in tests or an embedding host; defaults remain agentDir files. */\n\treadonly stateStore?: PluginStateStoreV1;\n\t/** Override the project-local persistence boundary in tests or an embedding host. */\n\treadonly projectStateStore?: PluginStateStoreV1;\n\treadonly selectionStore?: PluginSelectionStoreV1;\n\treadonly projectSelectionStore?: PluginSelectionStoreV1;\n\treadonly write?: (line: string) => void;\n}\n\nfunction printResponse(response: PluginEcosystemCliResponseV1, write: (line: string) => void): void {\n\twrite(response.text);\n\tif (response.status !== \"succeeded\") process.exitCode = 1;\n}\n\ninterface MarketCliOptionsV1 {\n\treadonly agentDir: string;\n\treadonly cwd: string;\n\treadonly market?: DefaultPluginMarketWiringV1;\n\treadonly overrides?: PluginCommandOptionsV1;\n}\n\nfunction buildMarketCli(options: MarketCliOptionsV1): PluginEcosystemCliV1 {\n\tconst { market, overrides } = options;\n\treturn createPluginEcosystemCliV1({\n\t\thost: overrides?.host ?? defaultPluginHostFactsV1(),\n\t\tmanifests: listBuiltinPluginManifestsV1(),\n\t\tregistry: overrides?.registry ?? market?.cliRegistry,\n\t\t// Multi-source acquisition (`plugin install <ref>`) rides along with the\n\t\t// default market wiring; a fully host-injected stack replaces it wholesale.\n\t\t...(market?.acquisition === undefined ? {} : { acquisition: market.acquisition }),\n\t\tinstaller: overrides?.installer ?? market?.installer,\n\t\t...(overrides?.distribution !== undefined || market?.distribution !== undefined\n\t\t\t? { distribution: overrides?.distribution ?? market!.distribution }\n\t\t\t: {}),\n\t\tstateStore:\n\t\t\toverrides?.stateStore ??\n\t\t\tmarket?.stateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.agentDir, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectStateStore:\n\t\t\toverrides?.projectStateStore ??\n\t\t\tmarket?.projectStateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.cwd, CONFIG_DIR_NAME, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectScopeRef: projectPluginScopeRefV1(options.cwd),\n\t\tselectionStore:\n\t\t\toverrides?.selectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.agentDir, \".plugin-selection.json\") }),\n\t\tprojectSelectionStore:\n\t\t\toverrides?.projectSelectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.cwd, CONFIG_DIR_NAME, \".plugin-selection.json\") }),\n\t});\n}\n\n/**\n * Default TUI manager controller over the default marketplace wiring. The\n * controller reads the global or project state store per scope; callers must\n * invoke `close` after the config screen closes.\n */\nexport async function createDefaultPluginManagerControllerV1(options: {\n\treadonly agentDir?: string;\n\treadonly cwd?: string;\n\treadonly scope: \"global\" | \"project\";\n}): Promise<{ readonly controller: PluginManagerControllerV1; readonly close: () => Promise<void> }> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market = await createDefaultPluginMarketWiringV1({ agentDir, cwd });\n\tconst cli = buildMarketCli({ agentDir, cwd, market });\n\tconst controller = createPluginManagerControllerV1({\n\t\tregistry: market.registry,\n\t\tstateStore: options.scope === \"project\" ? market.projectStateStore : market.stateStore,\n\t\tcli,\n\t});\n\treturn { controller, close: market.close };\n}\n\n/**\n * Handle the independent ecosystem command namespace before legacy package\n * commands. Install/update/remove default to the disk install store plus an\n * optional configured marketplace origin; host injection of registry and\n * installer still wins entirely.\n */\nexport async function handlePluginEcosystemCommand(\n\targs: readonly string[],\n\toptions: PluginCommandOptionsV1 = {},\n): Promise<boolean> {\n\tif (args[0] !== \"plugin\") return false;\n\tconst write = options.write ?? ((line: string) => console.log(line));\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst response = await cli.execute({ argv: args.slice(1) });\n\t\tprintResponse(response, write);\n\t\treturn true;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plugin-command.d.ts","sourceRoot":"","sources":["../../src/cli/plugin-command.ts"],"names":[],"mappings":"AAQA,OA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;IACxD,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CACxC;AAmDD;;;;GAIG;AACH,wBAAsB,sCAAsC,CAAC,OAAO,EAAE;IACrE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,SAAS,CAAC;CACrC,GAAG,OAAO,CAAC;IAAE,QAAQ,CAAC,UAAU,EAAE,yBAAyB,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAC,CAWnG;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CACjD,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,GAAE,sBAA2B,GAClC,OAAO,CAAC,OAAO,CAAC,CAyBlB","sourcesContent":["import { join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1 } from \"../plugins/ecosystem/bootstrap-factory-manifest.ts\";\nimport { defaultPluginHostFactsV1, projectPluginScopeRefV1 } from \"../plugins/ecosystem/default-active-bindings.ts\";\nimport {\n\tcreateDefaultPluginMarketWiringV1,\n\ttype DefaultPluginMarketWiringV1,\n} from \"../plugins/ecosystem/default-plugin-market.ts\";\nimport {\n\tcreatePluginEcosystemCliV1,\n\tcreatePluginSelectionStoreV1,\n\tcreatePluginStateStoreV1,\n\ttype PluginDistributionV1,\n\ttype PluginEcosystemCliAcquisitionV1,\n\ttype PluginEcosystemCliResponseV1,\n\ttype PluginEcosystemCliV1,\n\ttype PluginEcosystemRegistryV1,\n\ttype PluginInstallerV1,\n\ttype PluginSelectionStoreV1,\n\ttype PluginStateStoreV1,\n} from \"../plugins/ecosystem/index.ts\";\nimport { listBuiltinPluginManifestsV1 } from \"../profile/plugin-profiles.ts\";\nimport type { PluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\nimport { createPluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\n\nexport interface PluginCommandOptionsV1 {\n\treadonly agentDir?: string;\n\t/** Working directory used for the project-local selection store. */\n\treadonly cwd?: string;\n\treadonly host?: {\n\t\treadonly os: string;\n\t\treadonly arch: string;\n\t\treadonly runtime: readonly { readonly name: string; readonly version: string }[];\n\t\treadonly apiVersion: string;\n\t\treadonly hostFeatures: readonly string[];\n\t};\n\t/** Optional host-owned boundaries used by install/update/remove commands. */\n\treadonly registry?: PluginEcosystemRegistryV1;\n\treadonly installer?: PluginInstallerV1;\n\t/** Optional host-owned multi-source package resolution used by install/update. */\n\treadonly acquisition?: PluginEcosystemCliAcquisitionV1;\n\t/** Optional host-owned package download boundary used by install/update. */\n\treadonly distribution?: PluginDistributionV1;\n\t/** Override persistence in tests or an embedding host; defaults remain agentDir files. */\n\treadonly stateStore?: PluginStateStoreV1;\n\t/** Override the project-local persistence boundary in tests or an embedding host. */\n\treadonly projectStateStore?: PluginStateStoreV1;\n\treadonly selectionStore?: PluginSelectionStoreV1;\n\treadonly projectSelectionStore?: PluginSelectionStoreV1;\n\treadonly write?: (line: string) => void;\n}\n\nfunction printResponse(response: PluginEcosystemCliResponseV1, write: (line: string) => void): void {\n\twrite(response.text);\n\tif (response.status !== \"succeeded\") process.exitCode = 1;\n}\n\ninterface MarketCliOptionsV1 {\n\treadonly agentDir: string;\n\treadonly cwd: string;\n\treadonly market?: DefaultPluginMarketWiringV1;\n\treadonly overrides?: PluginCommandOptionsV1;\n}\n\nfunction buildMarketCli(options: MarketCliOptionsV1): PluginEcosystemCliV1 {\n\tconst { market, overrides } = options;\n\treturn createPluginEcosystemCliV1({\n\t\thost: overrides?.host ?? defaultPluginHostFactsV1(),\n\t\tmanifests: listBuiltinPluginManifestsV1(),\n\t\tregistry: overrides?.registry ?? market?.cliRegistry,\n\t\t// Multi-source acquisition (`plugin install <ref>`) rides along with the\n\t\t// default market wiring; a fully host-injected stack replaces it wholesale.\n\t\t...(overrides?.acquisition === undefined && market?.acquisition === undefined\n\t\t\t? {}\n\t\t\t: { acquisition: overrides?.acquisition ?? market?.acquisition }),\n\t\tinstaller: overrides?.installer ?? market?.installer,\n\t\t...(overrides?.distribution !== undefined || market?.distribution !== undefined\n\t\t\t? { distribution: overrides?.distribution ?? market!.distribution }\n\t\t\t: {}),\n\t\tstateStore:\n\t\t\toverrides?.stateStore ??\n\t\t\tmarket?.stateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.agentDir, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectStateStore:\n\t\t\toverrides?.projectStateStore ??\n\t\t\tmarket?.projectStateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.cwd, CONFIG_DIR_NAME, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectScopeRef: projectPluginScopeRefV1(options.cwd),\n\t\tselectionStore:\n\t\t\toverrides?.selectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.agentDir, \".plugin-selection.json\") }),\n\t\tprojectSelectionStore:\n\t\t\toverrides?.projectSelectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.cwd, CONFIG_DIR_NAME, \".plugin-selection.json\") }),\n\t});\n}\n\n/**\n * Default TUI manager controller over the default marketplace wiring. The\n * controller reads the global or project state store per scope; callers must\n * invoke `close` after the config screen closes.\n */\nexport async function createDefaultPluginManagerControllerV1(options: {\n\treadonly agentDir?: string;\n\treadonly cwd?: string;\n\treadonly scope: \"global\" | \"project\";\n}): Promise<{ readonly controller: PluginManagerControllerV1; readonly close: () => Promise<void> }> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market = await createDefaultPluginMarketWiringV1({ agentDir, cwd });\n\tconst cli = buildMarketCli({ agentDir, cwd, market });\n\tconst controller = createPluginManagerControllerV1({\n\t\tregistry: market.registry,\n\t\tstateStore: options.scope === \"project\" ? market.projectStateStore : market.stateStore,\n\t\tcli,\n\t});\n\treturn { controller, close: market.close };\n}\n\n/**\n * Handle the independent ecosystem command namespace before legacy package\n * commands. Install/update/remove default to the disk install store plus an\n * optional configured marketplace origin; host injection of registry and\n * installer still wins entirely.\n */\nexport async function handlePluginEcosystemCommand(\n\targs: readonly string[],\n\toptions: PluginCommandOptionsV1 = {},\n): Promise<boolean> {\n\tif (args[0] !== \"plugin\") return false;\n\tconst write = options.write ?? ((line: string) => console.log(line));\n\t// Batch update convenience (0.85.7 user seat finding: a factory range bump\n\t// left seven plugins outdated and the per-plugin hint meant seven manual\n\t// commands). The ecosystem CLI protocol is unchanged — this outer layer\n\t// composes `state list` + one `update` per active plugin.\n\tif (args[1] === \"update\" && args[2] === \"--all\") {\n\t\tawait runBatchUpdate(args.slice(3), options, write);\n\t\treturn true;\n\t}\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst response = await cli.execute({ argv: args.slice(1) });\n\t\tprintResponse(response, write);\n\t\treturn true;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n\ninterface BatchUpdateEntry {\n\treadonly pluginId: string;\n\treadonly scope: string;\n\treadonly lifecycle: string;\n}\n\nasync function runBatchUpdate(\n\trestArgs: readonly string[],\n\toptions: PluginCommandOptionsV1,\n\twrite: (line: string) => void,\n): Promise<void> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst scopeIndex = restArgs.indexOf(\"--scope\");\n\tconst scope = scopeIndex !== -1 && restArgs[scopeIndex + 1] === \"project\" ? \"project\" : \"global\";\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst listResponse = await cli.execute({ argv: [\"state\", \"list\", \"--scope\", scope] });\n\t\tif (listResponse.status !== \"succeeded\") {\n\t\t\tprintResponse(listResponse, write);\n\t\t\treturn;\n\t\t}\n\t\tconst entries = ((listResponse.data?.entries ?? []) as readonly BatchUpdateEntry[]).filter(\n\t\t\t(entry) => entry.lifecycle === \"active\" && entry.scope === scope,\n\t\t);\n\t\tif (entries.length === 0) {\n\t\t\twrite(\"No active plugins to update.\");\n\t\t\treturn;\n\t\t}\n\t\tconst updated: string[] = [];\n\t\tconst current: string[] = [];\n\t\tconst failed: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\t// Factory-listed first-party plugins upgrade through the npm range the\n\t\t\t// bootstrap warnings name (`install <npmName>@^range`): the default disk\n\t\t\t// registry only resolves already-installed versions, so a bare `update`\n\t\t\t// there re-resolves the current version and reports nothing to do.\n\t\t\t// Non-factory plugins keep the bare `update` registry semantics.\n\t\t\tconst factoryEntry = BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1.find((item) => item.pluginId === entry.pluginId);\n\t\t\tconst argv = factoryEntry\n\t\t\t\t? [\"install\", `${factoryEntry.npmName}@${factoryEntry.range ?? \"latest\"}`, \"--scope\", scope]\n\t\t\t\t: [\"update\", entry.pluginId, \"--scope\", scope];\n\t\t\tconst response = await cli.execute({ argv });\n\t\t\tif (response.status === \"succeeded\") {\n\t\t\t\tupdated.push(entry.pluginId);\n\t\t\t\twrite(response.text);\n\t\t\t} else if (response.error?.code === \"already_installed\") {\n\t\t\t\tcurrent.push(entry.pluginId);\n\t\t\t} else {\n\t\t\t\tfailed.push(entry.pluginId);\n\t\t\t\twrite(response.text);\n\t\t\t}\n\t\t}\n\t\tconst summary = [\n\t\t\t`updated ${updated.length}${updated.length > 0 ? ` (${updated.join(\", \")})` : \"\"}`,\n\t\t\t`already up to date ${current.length}${current.length > 0 ? ` (${current.join(\", \")})` : \"\"}`,\n\t\t\t`failed ${failed.length}${failed.length > 0 ? ` (${failed.join(\", \")})` : \"\"}`,\n\t\t].join(\"; \");\n\t\twrite(`plugin update --all [${scope}]: ${summary}`);\n\t\tif (failed.length > 0) process.exitCode = 1;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
|
|
3
|
+
import { BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1 } from "../plugins/ecosystem/bootstrap-factory-manifest.js";
|
|
3
4
|
import { defaultPluginHostFactsV1, projectPluginScopeRefV1 } from "../plugins/ecosystem/default-active-bindings.js";
|
|
4
5
|
import { createDefaultPluginMarketWiringV1, } from "../plugins/ecosystem/default-plugin-market.js";
|
|
5
6
|
import { createPluginEcosystemCliV1, createPluginSelectionStoreV1, createPluginStateStoreV1, } from "../plugins/ecosystem/index.js";
|
|
@@ -18,7 +19,9 @@ function buildMarketCli(options) {
|
|
|
18
19
|
registry: overrides?.registry ?? market?.cliRegistry,
|
|
19
20
|
// Multi-source acquisition (`plugin install <ref>`) rides along with the
|
|
20
21
|
// default market wiring; a fully host-injected stack replaces it wholesale.
|
|
21
|
-
...(
|
|
22
|
+
...(overrides?.acquisition === undefined && market?.acquisition === undefined
|
|
23
|
+
? {}
|
|
24
|
+
: { acquisition: overrides?.acquisition ?? market?.acquisition }),
|
|
22
25
|
installer: overrides?.installer ?? market?.installer,
|
|
23
26
|
...(overrides?.distribution !== undefined || market?.distribution !== undefined
|
|
24
27
|
? { distribution: overrides?.distribution ?? market.distribution }
|
|
@@ -67,6 +70,14 @@ export async function handlePluginEcosystemCommand(args, options = {}) {
|
|
|
67
70
|
if (args[0] !== "plugin")
|
|
68
71
|
return false;
|
|
69
72
|
const write = options.write ?? ((line) => console.log(line));
|
|
73
|
+
// Batch update convenience (0.85.7 user seat finding: a factory range bump
|
|
74
|
+
// left seven plugins outdated and the per-plugin hint meant seven manual
|
|
75
|
+
// commands). The ecosystem CLI protocol is unchanged — this outer layer
|
|
76
|
+
// composes `state list` + one `update` per active plugin.
|
|
77
|
+
if (args[1] === "update" && args[2] === "--all") {
|
|
78
|
+
await runBatchUpdate(args.slice(3), options, write);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
70
81
|
const agentDir = options.agentDir ?? getAgentDir();
|
|
71
82
|
const cwd = options.cwd ?? process.cwd();
|
|
72
83
|
const market = options.registry === undefined && options.installer === undefined
|
|
@@ -82,4 +93,63 @@ export async function handlePluginEcosystemCommand(args, options = {}) {
|
|
|
82
93
|
await market?.close();
|
|
83
94
|
}
|
|
84
95
|
}
|
|
96
|
+
async function runBatchUpdate(restArgs, options, write) {
|
|
97
|
+
const agentDir = options.agentDir ?? getAgentDir();
|
|
98
|
+
const cwd = options.cwd ?? process.cwd();
|
|
99
|
+
const scopeIndex = restArgs.indexOf("--scope");
|
|
100
|
+
const scope = scopeIndex !== -1 && restArgs[scopeIndex + 1] === "project" ? "project" : "global";
|
|
101
|
+
const market = options.registry === undefined && options.installer === undefined
|
|
102
|
+
? await createDefaultPluginMarketWiringV1({ agentDir, cwd })
|
|
103
|
+
: undefined;
|
|
104
|
+
try {
|
|
105
|
+
const cli = buildMarketCli({ agentDir, cwd, market, overrides: options });
|
|
106
|
+
const listResponse = await cli.execute({ argv: ["state", "list", "--scope", scope] });
|
|
107
|
+
if (listResponse.status !== "succeeded") {
|
|
108
|
+
printResponse(listResponse, write);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const entries = (listResponse.data?.entries ?? []).filter((entry) => entry.lifecycle === "active" && entry.scope === scope);
|
|
112
|
+
if (entries.length === 0) {
|
|
113
|
+
write("No active plugins to update.");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const updated = [];
|
|
117
|
+
const current = [];
|
|
118
|
+
const failed = [];
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
// Factory-listed first-party plugins upgrade through the npm range the
|
|
121
|
+
// bootstrap warnings name (`install <npmName>@^range`): the default disk
|
|
122
|
+
// registry only resolves already-installed versions, so a bare `update`
|
|
123
|
+
// there re-resolves the current version and reports nothing to do.
|
|
124
|
+
// Non-factory plugins keep the bare `update` registry semantics.
|
|
125
|
+
const factoryEntry = BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1.find((item) => item.pluginId === entry.pluginId);
|
|
126
|
+
const argv = factoryEntry
|
|
127
|
+
? ["install", `${factoryEntry.npmName}@${factoryEntry.range ?? "latest"}`, "--scope", scope]
|
|
128
|
+
: ["update", entry.pluginId, "--scope", scope];
|
|
129
|
+
const response = await cli.execute({ argv });
|
|
130
|
+
if (response.status === "succeeded") {
|
|
131
|
+
updated.push(entry.pluginId);
|
|
132
|
+
write(response.text);
|
|
133
|
+
}
|
|
134
|
+
else if (response.error?.code === "already_installed") {
|
|
135
|
+
current.push(entry.pluginId);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
failed.push(entry.pluginId);
|
|
139
|
+
write(response.text);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const summary = [
|
|
143
|
+
`updated ${updated.length}${updated.length > 0 ? ` (${updated.join(", ")})` : ""}`,
|
|
144
|
+
`already up to date ${current.length}${current.length > 0 ? ` (${current.join(", ")})` : ""}`,
|
|
145
|
+
`failed ${failed.length}${failed.length > 0 ? ` (${failed.join(", ")})` : ""}`,
|
|
146
|
+
].join("; ");
|
|
147
|
+
write(`plugin update --all [${scope}]: ${summary}`);
|
|
148
|
+
if (failed.length > 0)
|
|
149
|
+
process.exitCode = 1;
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
await market?.close();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
85
155
|
//# sourceMappingURL=plug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G,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC5D,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC;IACb,CAAC;YAAS,CAAC;QACV,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC;IACvB,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { defaultPluginHostFactsV1, projectPluginScopeRefV1 } from \"../plugins/ecosystem/default-active-bindings.ts\";\nimport {\n\tcreateDefaultPluginMarketWiringV1,\n\ttype DefaultPluginMarketWiringV1,\n} from \"../plugins/ecosystem/default-plugin-market.ts\";\nimport {\n\tcreatePluginEcosystemCliV1,\n\tcreatePluginSelectionStoreV1,\n\tcreatePluginStateStoreV1,\n\ttype PluginDistributionV1,\n\ttype PluginEcosystemCliResponseV1,\n\ttype PluginEcosystemCliV1,\n\ttype PluginEcosystemRegistryV1,\n\ttype PluginInstallerV1,\n\ttype PluginSelectionStoreV1,\n\ttype PluginStateStoreV1,\n} from \"../plugins/ecosystem/index.ts\";\nimport { listBuiltinPluginManifestsV1 } from \"../profile/plugin-profiles.ts\";\nimport type { PluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\nimport { createPluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\n\nexport interface PluginCommandOptionsV1 {\n\treadonly agentDir?: string;\n\t/** Working directory used for the project-local selection store. */\n\treadonly cwd?: string;\n\treadonly host?: {\n\t\treadonly os: string;\n\t\treadonly arch: string;\n\t\treadonly runtime: readonly { readonly name: string; readonly version: string }[];\n\t\treadonly apiVersion: string;\n\t\treadonly hostFeatures: readonly string[];\n\t};\n\t/** Optional host-owned boundaries used by install/update/remove commands. */\n\treadonly registry?: PluginEcosystemRegistryV1;\n\treadonly installer?: PluginInstallerV1;\n\t/** Optional host-owned package download boundary used by install/update. */\n\treadonly distribution?: PluginDistributionV1;\n\t/** Override persistence in tests or an embedding host; defaults remain agentDir files. */\n\treadonly stateStore?: PluginStateStoreV1;\n\t/** Override the project-local persistence boundary in tests or an embedding host. */\n\treadonly projectStateStore?: PluginStateStoreV1;\n\treadonly selectionStore?: PluginSelectionStoreV1;\n\treadonly projectSelectionStore?: PluginSelectionStoreV1;\n\treadonly write?: (line: string) => void;\n}\n\nfunction printResponse(response: PluginEcosystemCliResponseV1, write: (line: string) => void): void {\n\twrite(response.text);\n\tif (response.status !== \"succeeded\") process.exitCode = 1;\n}\n\ninterface MarketCliOptionsV1 {\n\treadonly agentDir: string;\n\treadonly cwd: string;\n\treadonly market?: DefaultPluginMarketWiringV1;\n\treadonly overrides?: PluginCommandOptionsV1;\n}\n\nfunction buildMarketCli(options: MarketCliOptionsV1): PluginEcosystemCliV1 {\n\tconst { market, overrides } = options;\n\treturn createPluginEcosystemCliV1({\n\t\thost: overrides?.host ?? defaultPluginHostFactsV1(),\n\t\tmanifests: listBuiltinPluginManifestsV1(),\n\t\tregistry: overrides?.registry ?? market?.cliRegistry,\n\t\t// Multi-source acquisition (`plugin install <ref>`) rides along with the\n\t\t// default market wiring; a fully host-injected stack replaces it wholesale.\n\t\t...(market?.acquisition === undefined ? {} : { acquisition: market.acquisition }),\n\t\tinstaller: overrides?.installer ?? market?.installer,\n\t\t...(overrides?.distribution !== undefined || market?.distribution !== undefined\n\t\t\t? { distribution: overrides?.distribution ?? market!.distribution }\n\t\t\t: {}),\n\t\tstateStore:\n\t\t\toverrides?.stateStore ??\n\t\t\tmarket?.stateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.agentDir, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectStateStore:\n\t\t\toverrides?.projectStateStore ??\n\t\t\tmarket?.projectStateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.cwd, CONFIG_DIR_NAME, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectScopeRef: projectPluginScopeRefV1(options.cwd),\n\t\tselectionStore:\n\t\t\toverrides?.selectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.agentDir, \".plugin-selection.json\") }),\n\t\tprojectSelectionStore:\n\t\t\toverrides?.projectSelectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.cwd, CONFIG_DIR_NAME, \".plugin-selection.json\") }),\n\t});\n}\n\n/**\n * Default TUI manager controller over the default marketplace wiring. The\n * controller reads the global or project state store per scope; callers must\n * invoke `close` after the config screen closes.\n */\nexport async function createDefaultPluginManagerControllerV1(options: {\n\treadonly agentDir?: string;\n\treadonly cwd?: string;\n\treadonly scope: \"global\" | \"project\";\n}): Promise<{ readonly controller: PluginManagerControllerV1; readonly close: () => Promise<void> }> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market = await createDefaultPluginMarketWiringV1({ agentDir, cwd });\n\tconst cli = buildMarketCli({ agentDir, cwd, market });\n\tconst controller = createPluginManagerControllerV1({\n\t\tregistry: market.registry,\n\t\tstateStore: options.scope === \"project\" ? market.projectStateStore : market.stateStore,\n\t\tcli,\n\t});\n\treturn { controller, close: market.close };\n}\n\n/**\n * Handle the independent ecosystem command namespace before legacy package\n * commands. Install/update/remove default to the disk install store plus an\n * optional configured marketplace origin; host injection of registry and\n * installer still wins entirely.\n */\nexport async function handlePluginEcosystemCommand(\n\targs: readonly string[],\n\toptions: PluginCommandOptionsV1 = {},\n): Promise<boolean> {\n\tif (args[0] !== \"plugin\") return false;\n\tconst write = options.write ?? ((line: string) => console.log(line));\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst response = await cli.execute({ argv: args.slice(1) });\n\t\tprintResponse(response, write);\n\t\treturn true;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plugin-command.js","sourceRoot":"","sources":["../../src/cli/plugin-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,oDAAoD,CAAC;AAC1G,OAAO,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,iDAAiD,CAAC;AACpH,OAAO,EACN,iCAAiC,GAEjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACN,0BAA0B,EAC1B,4BAA4B,EAC5B,wBAAwB,GASxB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AA6BjF,SAAS,aAAa,CAAC,QAAsC,EAAE,KAA6B,EAAQ;IACnG,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACrB,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW;QAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AAAA,CAC1D;AASD,SAAS,cAAc,CAAC,OAA2B,EAAwB;IAC1E,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IACtC,OAAO,0BAA0B,CAAC;QACjC,IAAI,EAAE,SAAS,EAAE,IAAI,IAAI,wBAAwB,EAAE;QACnD,SAAS,EAAE,4BAA4B,EAAE;QACzC,QAAQ,EAAE,SAAS,EAAE,QAAQ,IAAI,MAAM,EAAE,WAAW;QACpD,yEAAyE;QACzE,4EAA4E;QAC5E,GAAG,CAAC,SAAS,EAAE,WAAW,KAAK,SAAS,I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MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;SAC9E,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,KAAK,CAAC,wBAAwB,KAAK,MAAM,OAAO,EAAE,CAAC,CAAC;QACpD,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IAC7C,CAAC;YAAS,CAAC;QACV,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC;IACvB,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1 } from \"../plugins/ecosystem/bootstrap-factory-manifest.ts\";\nimport { defaultPluginHostFactsV1, projectPluginScopeRefV1 } from \"../plugins/ecosystem/default-active-bindings.ts\";\nimport {\n\tcreateDefaultPluginMarketWiringV1,\n\ttype DefaultPluginMarketWiringV1,\n} from \"../plugins/ecosystem/default-plugin-market.ts\";\nimport {\n\tcreatePluginEcosystemCliV1,\n\tcreatePluginSelectionStoreV1,\n\tcreatePluginStateStoreV1,\n\ttype PluginDistributionV1,\n\ttype PluginEcosystemCliAcquisitionV1,\n\ttype PluginEcosystemCliResponseV1,\n\ttype PluginEcosystemCliV1,\n\ttype PluginEcosystemRegistryV1,\n\ttype PluginInstallerV1,\n\ttype PluginSelectionStoreV1,\n\ttype PluginStateStoreV1,\n} from \"../plugins/ecosystem/index.ts\";\nimport { listBuiltinPluginManifestsV1 } from \"../profile/plugin-profiles.ts\";\nimport type { PluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\nimport { createPluginManagerControllerV1 } from \"./plugin-manager-controller.ts\";\n\nexport interface PluginCommandOptionsV1 {\n\treadonly agentDir?: string;\n\t/** Working directory used for the project-local selection store. */\n\treadonly cwd?: string;\n\treadonly host?: {\n\t\treadonly os: string;\n\t\treadonly arch: string;\n\t\treadonly runtime: readonly { readonly name: string; readonly version: string }[];\n\t\treadonly apiVersion: string;\n\t\treadonly hostFeatures: readonly string[];\n\t};\n\t/** Optional host-owned boundaries used by install/update/remove commands. */\n\treadonly registry?: PluginEcosystemRegistryV1;\n\treadonly installer?: PluginInstallerV1;\n\t/** Optional host-owned multi-source package resolution used by install/update. */\n\treadonly acquisition?: PluginEcosystemCliAcquisitionV1;\n\t/** Optional host-owned package download boundary used by install/update. */\n\treadonly distribution?: PluginDistributionV1;\n\t/** Override persistence in tests or an embedding host; defaults remain agentDir files. */\n\treadonly stateStore?: PluginStateStoreV1;\n\t/** Override the project-local persistence boundary in tests or an embedding host. */\n\treadonly projectStateStore?: PluginStateStoreV1;\n\treadonly selectionStore?: PluginSelectionStoreV1;\n\treadonly projectSelectionStore?: PluginSelectionStoreV1;\n\treadonly write?: (line: string) => void;\n}\n\nfunction printResponse(response: PluginEcosystemCliResponseV1, write: (line: string) => void): void {\n\twrite(response.text);\n\tif (response.status !== \"succeeded\") process.exitCode = 1;\n}\n\ninterface MarketCliOptionsV1 {\n\treadonly agentDir: string;\n\treadonly cwd: string;\n\treadonly market?: DefaultPluginMarketWiringV1;\n\treadonly overrides?: PluginCommandOptionsV1;\n}\n\nfunction buildMarketCli(options: MarketCliOptionsV1): PluginEcosystemCliV1 {\n\tconst { market, overrides } = options;\n\treturn createPluginEcosystemCliV1({\n\t\thost: overrides?.host ?? defaultPluginHostFactsV1(),\n\t\tmanifests: listBuiltinPluginManifestsV1(),\n\t\tregistry: overrides?.registry ?? market?.cliRegistry,\n\t\t// Multi-source acquisition (`plugin install <ref>`) rides along with the\n\t\t// default market wiring; a fully host-injected stack replaces it wholesale.\n\t\t...(overrides?.acquisition === undefined && market?.acquisition === undefined\n\t\t\t? {}\n\t\t\t: { acquisition: overrides?.acquisition ?? market?.acquisition }),\n\t\tinstaller: overrides?.installer ?? market?.installer,\n\t\t...(overrides?.distribution !== undefined || market?.distribution !== undefined\n\t\t\t? { distribution: overrides?.distribution ?? market!.distribution }\n\t\t\t: {}),\n\t\tstateStore:\n\t\t\toverrides?.stateStore ??\n\t\t\tmarket?.stateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.agentDir, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectStateStore:\n\t\t\toverrides?.projectStateStore ??\n\t\t\tmarket?.projectStateStore ??\n\t\t\tcreatePluginStateStoreV1({\n\t\t\t\tfilePath: join(options.cwd, CONFIG_DIR_NAME, \"plugin-state.json\"),\n\t\t\t}),\n\t\tprojectScopeRef: projectPluginScopeRefV1(options.cwd),\n\t\tselectionStore:\n\t\t\toverrides?.selectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.agentDir, \".plugin-selection.json\") }),\n\t\tprojectSelectionStore:\n\t\t\toverrides?.projectSelectionStore ??\n\t\t\tcreatePluginSelectionStoreV1({ filePath: join(options.cwd, CONFIG_DIR_NAME, \".plugin-selection.json\") }),\n\t});\n}\n\n/**\n * Default TUI manager controller over the default marketplace wiring. The\n * controller reads the global or project state store per scope; callers must\n * invoke `close` after the config screen closes.\n */\nexport async function createDefaultPluginManagerControllerV1(options: {\n\treadonly agentDir?: string;\n\treadonly cwd?: string;\n\treadonly scope: \"global\" | \"project\";\n}): Promise<{ readonly controller: PluginManagerControllerV1; readonly close: () => Promise<void> }> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market = await createDefaultPluginMarketWiringV1({ agentDir, cwd });\n\tconst cli = buildMarketCli({ agentDir, cwd, market });\n\tconst controller = createPluginManagerControllerV1({\n\t\tregistry: market.registry,\n\t\tstateStore: options.scope === \"project\" ? market.projectStateStore : market.stateStore,\n\t\tcli,\n\t});\n\treturn { controller, close: market.close };\n}\n\n/**\n * Handle the independent ecosystem command namespace before legacy package\n * commands. Install/update/remove default to the disk install store plus an\n * optional configured marketplace origin; host injection of registry and\n * installer still wins entirely.\n */\nexport async function handlePluginEcosystemCommand(\n\targs: readonly string[],\n\toptions: PluginCommandOptionsV1 = {},\n): Promise<boolean> {\n\tif (args[0] !== \"plugin\") return false;\n\tconst write = options.write ?? ((line: string) => console.log(line));\n\t// Batch update convenience (0.85.7 user seat finding: a factory range bump\n\t// left seven plugins outdated and the per-plugin hint meant seven manual\n\t// commands). The ecosystem CLI protocol is unchanged — this outer layer\n\t// composes `state list` + one `update` per active plugin.\n\tif (args[1] === \"update\" && args[2] === \"--all\") {\n\t\tawait runBatchUpdate(args.slice(3), options, write);\n\t\treturn true;\n\t}\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst response = await cli.execute({ argv: args.slice(1) });\n\t\tprintResponse(response, write);\n\t\treturn true;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n\ninterface BatchUpdateEntry {\n\treadonly pluginId: string;\n\treadonly scope: string;\n\treadonly lifecycle: string;\n}\n\nasync function runBatchUpdate(\n\trestArgs: readonly string[],\n\toptions: PluginCommandOptionsV1,\n\twrite: (line: string) => void,\n): Promise<void> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst scopeIndex = restArgs.indexOf(\"--scope\");\n\tconst scope = scopeIndex !== -1 && restArgs[scopeIndex + 1] === \"project\" ? \"project\" : \"global\";\n\tconst market =\n\t\toptions.registry === undefined && options.installer === undefined\n\t\t\t? await createDefaultPluginMarketWiringV1({ agentDir, cwd })\n\t\t\t: undefined;\n\ttry {\n\t\tconst cli = buildMarketCli({ agentDir, cwd, market, overrides: options });\n\t\tconst listResponse = await cli.execute({ argv: [\"state\", \"list\", \"--scope\", scope] });\n\t\tif (listResponse.status !== \"succeeded\") {\n\t\t\tprintResponse(listResponse, write);\n\t\t\treturn;\n\t\t}\n\t\tconst entries = ((listResponse.data?.entries ?? []) as readonly BatchUpdateEntry[]).filter(\n\t\t\t(entry) => entry.lifecycle === \"active\" && entry.scope === scope,\n\t\t);\n\t\tif (entries.length === 0) {\n\t\t\twrite(\"No active plugins to update.\");\n\t\t\treturn;\n\t\t}\n\t\tconst updated: string[] = [];\n\t\tconst current: string[] = [];\n\t\tconst failed: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\t// Factory-listed first-party plugins upgrade through the npm range the\n\t\t\t// bootstrap warnings name (`install <npmName>@^range`): the default disk\n\t\t\t// registry only resolves already-installed versions, so a bare `update`\n\t\t\t// there re-resolves the current version and reports nothing to do.\n\t\t\t// Non-factory plugins keep the bare `update` registry semantics.\n\t\t\tconst factoryEntry = BOOTSTRAP_FACTORY_PLUGIN_MANIFEST_V1.find((item) => item.pluginId === entry.pluginId);\n\t\t\tconst argv = factoryEntry\n\t\t\t\t? [\"install\", `${factoryEntry.npmName}@${factoryEntry.range ?? \"latest\"}`, \"--scope\", scope]\n\t\t\t\t: [\"update\", entry.pluginId, \"--scope\", scope];\n\t\t\tconst response = await cli.execute({ argv });\n\t\t\tif (response.status === \"succeeded\") {\n\t\t\t\tupdated.push(entry.pluginId);\n\t\t\t\twrite(response.text);\n\t\t\t} else if (response.error?.code === \"already_installed\") {\n\t\t\t\tcurrent.push(entry.pluginId);\n\t\t\t} else {\n\t\t\t\tfailed.push(entry.pluginId);\n\t\t\t\twrite(response.text);\n\t\t\t}\n\t\t}\n\t\tconst summary = [\n\t\t\t`updated ${updated.length}${updated.length > 0 ? ` (${updated.join(\", \")})` : \"\"}`,\n\t\t\t`already up to date ${current.length}${current.length > 0 ? ` (${current.join(\", \")})` : \"\"}`,\n\t\t\t`failed ${failed.length}${failed.length > 0 ? ` (${failed.join(\", \")})` : \"\"}`,\n\t\t].join(\"; \");\n\t\twrite(`plugin update --all [${scope}]: ${summary}`);\n\t\tif (failed.length > 0) process.exitCode = 1;\n\t} finally {\n\t\tawait market?.close();\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-bootstrap.d.ts","sourceRoot":"","sources":["../../../src/plugins/ecosystem/plugin-bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAIrF,eAAO,MAAM,2BAA2B,GAAa,CAAC;AAEtD,gFAAgF;AAChF,MAAM,MAAM,2BAA2B,GAAG,CAAC,KAAK,EAAE;IACjD,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B,KAAK,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE3C,qFAAqF;AACrF,MAAM,MAAM,+BAA+B,GAAG,CAAC,KAAK,EAAE;IACrD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B,KAAK,OAAO,CAAC;IAAE,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAE3E,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,UAAU,EAAE,2BAA2B,CAAC;IACjD,QAAQ,CAAC,cAAc,EAAE,+BAA+B,CAAC;IACzD,2EAA2E;IAC3E,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,oEAAoE;IACpE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B;AAED,MAAM,MAAM,6BAA6B,GAAG,SAAS,GAAG,WAAW,GAAG,WAAW,GAAG,QAAQ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E,CAAC;IAC7D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AAWD,0EAA0E;AAC1E,wBAAgB,+BAA+B,CAAC,KAAK,EAAE;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAEpH;AAwBD;;;;GAIG;AACH,wBAAsB,oBAAoB,CAAC,KAAK,EAAE;IACjD,QAAQ,CAAC,QAAQ,EAAE,SAAS,6BAA6B,EAAE,CAAC;IAC5D,QAAQ,CAAC,IAAI,EAAE,qBAAqB,CAAC;CACrC,GAAG,OAAO,CAAC,uBAAuB,CAAC,CA2FnC","sourcesContent":["/**\n * Startup plugin bootstrap orchestrator (design\n * `插件独立分发与启动装配设计.md` §4.4, §0.7). Pure injectable decision loop\n * over the frozen factory manifest: every entry is compared against the\n * locally resolved active installations and only missing plugins are handed\n * to the npm install dependency — bootstrap never acquires through any other\n * source.\n *\n * Coverage rules (G5): an existing active installation is never replaced. A\n * satisfied range is skipped silently (zero acquisition calls, G3); an\n * unsatisfied one produces a diagnostic with a manual install command and no\n * automatic replacement. Failure semantics (G4): one plugin's install\n * failure is recorded and the loop continues; the run itself never throws.\n * All effects live behind the injected dependencies, so the loop is fully\n * deterministic under mocks.\n */\n\nimport type { PluginBootstrapFactoryEntryV1 } from \"./bootstrap-factory-manifest.ts\";\nimport { selectNpmPackageVersionV1 } from \"./node-npm-registry-source.ts\";\nimport { PluginAcquisitionErrorV1 } from \"./plugin-acquisition.ts\";\n\nexport const PLUGIN_BOOTSTRAP_VERSION_V1 = 1 as const;\n\n/** Read-only local lookup of active installation versions (never networked). */\nexport type PluginBootstrapListActiveV1 = (input: {\n\treadonly signal?: AbortSignal;\n}) => Promise<ReadonlyMap<string, string>>;\n\n/** npm-only install action; resolves with the installed version and source label. */\nexport type PluginBootstrapInstallFromNpmV1 = (input: {\n\treadonly npmName: string;\n\treadonly range?: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<{ readonly pluginVersion: string; readonly source: string }>;\n\nexport interface PluginBootstrapDepsV1 {\n\treadonly listActive: PluginBootstrapListActiveV1;\n\treadonly installFromNpm: PluginBootstrapInstallFromNpmV1;\n\t/** Deterministic clock for the observed duration; defaults to Date.now. */\n\treadonly now?: () => number;\n\t/** Cooperative cancellation; checked before each manifest entry. */\n\treadonly signal?: AbortSignal;\n}\n\nexport type PluginBootstrapActionStatusV1 = \"skipped\" | \"diagnosed\" | \"installed\" | \"failed\";\n\nexport type PluginBootstrapActionReasonV1 = \"satisfies_range\" | \"range_not_satisfied\" | \"installed\" | \"install_failed\";\n\n/** One per-entry outcome; the version fields carry what each status observed. */\nexport interface PluginBootstrapActionV1 {\n\treadonly pluginId: string;\n\treadonly status: PluginBootstrapActionStatusV1;\n\treadonly reason: PluginBootstrapActionReasonV1;\n\treadonly npmName: string;\n\treadonly range?: string;\n\t/** Active version that decided a skipped/diagnosed outcome. */\n\treadonly activeVersion?: string;\n\t/** Version reported by the install action. */\n\treadonly installedVersion?: string;\n\t/** npm source label reported by the install action. */\n\treadonly source?: string;\n\t/** Acquisition or install failure code for failed actions. */\n\treadonly errorCode?: string;\n}\n\nexport type PluginBootstrapDiagnosticCodeV1 =\n\t| \"range_not_satisfied\"\n\t| \"install_failed\"\n\t| \"list_active_failed\"\n\t| \"cancelled\"\n\t| \"bootstrap_failed\";\n\nexport interface PluginBootstrapDiagnosticV1 {\n\treadonly code: PluginBootstrapDiagnosticCodeV1;\n\treadonly message: string;\n\treadonly pluginId?: string;\n}\n\nexport type PluginBootstrapStatusV1 = \"succeeded\" | \"degraded\" | \"failed\";\n\nexport interface PluginBootstrapResultV1 {\n\treadonly version: typeof PLUGIN_BOOTSTRAP_VERSION_V1;\n\t/** Aggregated outcome: failed > degraded (diagnosed entries) > succeeded. */\n\treadonly status: PluginBootstrapStatusV1;\n\treadonly actions: readonly PluginBootstrapActionV1[];\n\treadonly diagnostics: readonly PluginBootstrapDiagnosticV1[];\n\treadonly durationMs: number;\n}\n\n/**\n * A version satisfies a factory range under the same selection semantics npm\n * resolution uses: it is the version that would be picked if it were the only\n * candidate. Keeps local comparison and registry resolution consistent.\n */\nfunction satisfiesRangeV1(version: string, range: string | undefined): boolean {\n\treturn selectNpmPackageVersionV1([version], range) === version;\n}\n\n/** Executable repair command for diagnostics (G4/G5 remediation hint). */\nexport function pluginBootstrapInstallCommandV1(entry: { readonly npmName: string; readonly range?: string }): string {\n\treturn `agent-forge plugin install ${entry.npmName}@${entry.range ?? \"latest\"}`;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction acquireErrorCode(error: unknown): string {\n\treturn error instanceof PluginAcquisitionErrorV1 ? error.code : \"install_failed\";\n}\n\nfunction actionOf(\n\tentry: PluginBootstrapFactoryEntryV1,\n\tstatus: PluginBootstrapActionStatusV1,\n\treason: PluginBootstrapActionReasonV1,\n): PluginBootstrapActionV1 {\n\treturn Object.freeze({\n\t\tpluginId: entry.pluginId,\n\t\tstatus,\n\t\treason,\n\t\tnpmName: entry.npmName,\n\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t});\n}\n\n/**\n * Run the bootstrap decision loop. An empty manifest short-circuits before\n * any dependency is touched, so the factory-empty S1-c2 state performs zero\n * reads on real startups.\n */\nexport async function runPluginBootstrapV1(input: {\n\treadonly manifest: readonly PluginBootstrapFactoryEntryV1[];\n\treadonly deps: PluginBootstrapDepsV1;\n}): Promise<PluginBootstrapResultV1> {\n\tconst now = input.deps.now ?? Date.now;\n\tconst startedAt = now();\n\tconst finish = (\n\t\tstatus: PluginBootstrapStatusV1,\n\t\tactions: readonly PluginBootstrapActionV1[],\n\t\tdiagnostics: readonly PluginBootstrapDiagnosticV1[],\n\t): PluginBootstrapResultV1 =>\n\t\tObject.freeze({\n\t\t\tversion: PLUGIN_BOOTSTRAP_VERSION_V1,\n\t\t\tstatus,\n\t\t\tactions: Object.freeze([...actions]),\n\t\t\tdiagnostics: Object.freeze([...diagnostics]),\n\t\t\tdurationMs: Math.max(0, now() - startedAt),\n\t\t});\n\tif (input.manifest.length === 0) return finish(\"succeeded\", [], []);\n\tconst signal = input.deps.signal;\n\tlet active: ReadonlyMap<string, string>;\n\ttry {\n\t\tactive = await input.deps.listActive({ ...(signal === undefined ? {} : { signal }) });\n\t} catch (error) {\n\t\treturn finish(\n\t\t\t\"failed\",\n\t\t\t[],\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\tcode: \"list_active_failed\",\n\t\t\t\t\tmessage: `Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t);\n\t}\n\tconst actions: PluginBootstrapActionV1[] = [];\n\tconst diagnostics: PluginBootstrapDiagnosticV1[] = [];\n\tfor (const entry of input.manifest) {\n\t\tif (signal?.aborted === true) {\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"cancelled\",\n\t\t\t\tmessage: \"Plugin bootstrap was cancelled before all factory entries were processed\",\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tconst activeVersion = active.get(entry.pluginId);\n\t\tif (activeVersion !== undefined) {\n\t\t\tif (satisfiesRangeV1(activeVersion, entry.range)) {\n\t\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"skipped\", \"satisfies_range\"), activeVersion }));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"diagnosed\", \"range_not_satisfied\"), activeVersion }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"range_not_satisfied\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Active version ${activeVersion} of ${entry.pluginId} does not satisfy the factory range ` +\n\t\t\t\t\t`${entry.range ?? \"latest\"}; bootstrap never replaces active installations. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install a matching version.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst installed = await input.deps.installFromNpm({\n\t\t\t\tnpmName: entry.npmName,\n\t\t\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t\t});\n\t\t\tactions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...actionOf(entry, \"installed\", \"installed\"),\n\t\t\t\t\tinstalledVersion: installed.pluginVersion,\n\t\t\t\t\tsource: installed.source,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst errorCode = acquireErrorCode(error);\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"failed\", \"install_failed\"), errorCode }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"install_failed\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Bootstrap could not install ${entry.pluginId} from npm (${errorCode}: ${errorMessage(error)}). ` +\n\t\t\t\t\t`Startup continues without it; its capabilities stay unavailable until installed. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install it manually.`,\n\t\t\t});\n\t\t}\n\t}\n\tconst status: PluginBootstrapStatusV1 = actions.some((action) => action.status === \"failed\")\n\t\t? \"failed\"\n\t\t: actions.some((action) => action.status === \"diagnosed\")\n\t\t\t? \"degraded\"\n\t\t\t: \"succeeded\";\n\treturn finish(status, actions, diagnostics);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plugin-bootstrap.d.ts","sourceRoot":"","sources":["../../../src/plugins/ecosystem/plugin-bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAIrF,eAAO,MAAM,2BAA2B,GAAa,CAAC;AAEtD,gFAAgF;AAChF,MAAM,MAAM,2BAA2B,GAAG,CAAC,KAAK,EAAE;IACjD,QAAQ,CAAC,MAAM,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startup plugin bootstrap orchestrator (design\n * `插件独立分发与启动装配设计.md` §4.4, §0.7). Pure injectable decision loop\n * over the frozen factory manifest: every entry is compared against the\n * locally resolved active installations and only missing plugins are handed\n * to the npm install dependency — bootstrap never acquires through any other\n * source.\n *\n * Coverage rules (G5): an existing active installation is never replaced. A\n * satisfied range is skipped silently (zero acquisition calls, G3); an\n * unsatisfied one produces a diagnostic with a manual install command and no\n * automatic replacement. Failure semantics (G4): one plugin's install\n * failure is recorded and the loop continues; the run itself never throws.\n * All effects live behind the injected dependencies, so the loop is fully\n * deterministic under mocks.\n */\n\nimport type { PluginBootstrapFactoryEntryV1 } from \"./bootstrap-factory-manifest.ts\";\nimport { selectNpmPackageVersionV1 } from \"./node-npm-registry-source.ts\";\nimport { PluginAcquisitionErrorV1 } from \"./plugin-acquisition.ts\";\n\nexport const PLUGIN_BOOTSTRAP_VERSION_V1 = 1 as const;\n\n/** Read-only local lookup of active installation versions (never networked). */\nexport type PluginBootstrapListActiveV1 = (input: {\n\treadonly signal?: AbortSignal;\n}) => Promise<ReadonlyMap<string, string>>;\n\n/** npm-only install action; resolves with the installed version and source label. */\nexport type PluginBootstrapInstallFromNpmV1 = (input: {\n\treadonly npmName: string;\n\treadonly range?: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<{ readonly pluginVersion: string; readonly source: string }>;\n\nexport interface PluginBootstrapDepsV1 {\n\treadonly listActive: PluginBootstrapListActiveV1;\n\treadonly installFromNpm: PluginBootstrapInstallFromNpmV1;\n\t/** Deterministic clock for the observed duration; defaults to Date.now. */\n\treadonly now?: () => number;\n\t/** Cooperative cancellation; checked before each manifest entry. */\n\treadonly signal?: AbortSignal;\n}\n\nexport type PluginBootstrapActionStatusV1 = \"skipped\" | \"diagnosed\" | \"installed\" | \"failed\";\n\nexport type PluginBootstrapActionReasonV1 = \"satisfies_range\" | \"range_not_satisfied\" | \"installed\" | \"install_failed\";\n\n/** One per-entry outcome; the version fields carry what each status observed. */\nexport interface PluginBootstrapActionV1 {\n\treadonly pluginId: string;\n\treadonly status: PluginBootstrapActionStatusV1;\n\treadonly reason: PluginBootstrapActionReasonV1;\n\treadonly npmName: string;\n\treadonly range?: string;\n\t/** Active version that decided a skipped/diagnosed outcome. */\n\treadonly activeVersion?: string;\n\t/** Version reported by the install action. */\n\treadonly installedVersion?: string;\n\t/** npm source label reported by the install action. */\n\treadonly source?: string;\n\t/** Acquisition or install failure code for failed actions. */\n\treadonly errorCode?: string;\n}\n\nexport type PluginBootstrapDiagnosticCodeV1 =\n\t| \"range_not_satisfied\"\n\t| \"install_failed\"\n\t| \"list_active_failed\"\n\t| \"cancelled\"\n\t| \"bootstrap_failed\";\n\nexport interface PluginBootstrapDiagnosticV1 {\n\treadonly code: PluginBootstrapDiagnosticCodeV1;\n\treadonly message: string;\n\treadonly pluginId?: string;\n}\n\nexport type PluginBootstrapStatusV1 = \"succeeded\" | \"degraded\" | \"failed\";\n\nexport interface PluginBootstrapResultV1 {\n\treadonly version: typeof PLUGIN_BOOTSTRAP_VERSION_V1;\n\t/** Aggregated outcome: failed > degraded (diagnosed entries) > succeeded. */\n\treadonly status: PluginBootstrapStatusV1;\n\treadonly actions: readonly PluginBootstrapActionV1[];\n\treadonly diagnostics: readonly PluginBootstrapDiagnosticV1[];\n\treadonly durationMs: number;\n}\n\n/**\n * A version satisfies a factory range under the same selection semantics npm\n * resolution uses: it is the version that would be picked if it were the only\n * candidate. Keeps local comparison and registry resolution consistent.\n */\nfunction satisfiesRangeV1(version: string, range: string | undefined): boolean {\n\treturn selectNpmPackageVersionV1([version], range) === version;\n}\n\n/** Executable repair command for diagnostics (G4/G5 remediation hint). */\nexport function pluginBootstrapInstallCommandV1(entry: { readonly npmName: string; readonly range?: string }): string {\n\treturn `agent-forge plugin install ${entry.npmName}@${entry.range ?? \"latest\"}`;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction acquireErrorCode(error: unknown): string {\n\treturn error instanceof PluginAcquisitionErrorV1 ? error.code : \"install_failed\";\n}\n\nfunction actionOf(\n\tentry: PluginBootstrapFactoryEntryV1,\n\tstatus: PluginBootstrapActionStatusV1,\n\treason: PluginBootstrapActionReasonV1,\n): PluginBootstrapActionV1 {\n\treturn Object.freeze({\n\t\tpluginId: entry.pluginId,\n\t\tstatus,\n\t\treason,\n\t\tnpmName: entry.npmName,\n\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t});\n}\n\n/**\n * Run the bootstrap decision loop. An empty manifest short-circuits before\n * any dependency is touched, so the factory-empty S1-c2 state performs zero\n * reads on real startups.\n */\nexport async function runPluginBootstrapV1(input: {\n\treadonly manifest: readonly PluginBootstrapFactoryEntryV1[];\n\treadonly deps: PluginBootstrapDepsV1;\n}): Promise<PluginBootstrapResultV1> {\n\tconst now = input.deps.now ?? Date.now;\n\tconst startedAt = now();\n\tconst finish = (\n\t\tstatus: PluginBootstrapStatusV1,\n\t\tactions: readonly PluginBootstrapActionV1[],\n\t\tdiagnostics: readonly PluginBootstrapDiagnosticV1[],\n\t): PluginBootstrapResultV1 =>\n\t\tObject.freeze({\n\t\t\tversion: PLUGIN_BOOTSTRAP_VERSION_V1,\n\t\t\tstatus,\n\t\t\tactions: Object.freeze([...actions]),\n\t\t\tdiagnostics: Object.freeze([...diagnostics]),\n\t\t\tdurationMs: Math.max(0, now() - startedAt),\n\t\t});\n\tif (input.manifest.length === 0) return finish(\"succeeded\", [], []);\n\tconst signal = input.deps.signal;\n\tlet active: ReadonlyMap<string, string>;\n\ttry {\n\t\tactive = await input.deps.listActive({ ...(signal === undefined ? {} : { signal }) });\n\t} catch (error) {\n\t\treturn finish(\n\t\t\t\"failed\",\n\t\t\t[],\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\tcode: \"list_active_failed\",\n\t\t\t\t\tmessage: `Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t);\n\t}\n\tconst actions: PluginBootstrapActionV1[] = [];\n\tconst diagnostics: PluginBootstrapDiagnosticV1[] = [];\n\tfor (const entry of input.manifest) {\n\t\tif (signal?.aborted === true) {\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"cancelled\",\n\t\t\t\tmessage: \"Plugin bootstrap was cancelled before all factory entries were processed\",\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tconst activeVersion = active.get(entry.pluginId);\n\t\tif (activeVersion !== undefined) {\n\t\t\tif (satisfiesRangeV1(activeVersion, entry.range)) {\n\t\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"skipped\", \"satisfies_range\"), activeVersion }));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"diagnosed\", \"range_not_satisfied\"), activeVersion }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"range_not_satisfied\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Active version ${activeVersion} of ${entry.pluginId} does not satisfy the factory range ` +\n\t\t\t\t\t`${entry.range ?? \"latest\"}; bootstrap never replaces active installations. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install a matching version, ` +\n\t\t\t\t\t`or \\`agent-forge plugin update --all\\` to upgrade every outdated plugin at once.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst installed = await input.deps.installFromNpm({\n\t\t\t\tnpmName: entry.npmName,\n\t\t\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t\t});\n\t\t\tactions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...actionOf(entry, \"installed\", \"installed\"),\n\t\t\t\t\tinstalledVersion: installed.pluginVersion,\n\t\t\t\t\tsource: installed.source,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst errorCode = acquireErrorCode(error);\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"failed\", \"install_failed\"), errorCode }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"install_failed\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Bootstrap could not install ${entry.pluginId} from npm (${errorCode}: ${errorMessage(error)}). ` +\n\t\t\t\t\t`Startup continues without it; its capabilities stay unavailable until installed. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install it manually.`,\n\t\t\t});\n\t\t}\n\t}\n\tconst status: PluginBootstrapStatusV1 = actions.some((action) => action.status === \"failed\")\n\t\t? \"failed\"\n\t\t: actions.some((action) => action.status === \"diagnosed\")\n\t\t\t? \"degraded\"\n\t\t\t: \"succeeded\";\n\treturn finish(status, actions, diagnostics);\n}\n"]}
|
|
@@ -96,7 +96,8 @@ export async function runPluginBootstrapV1(input) {
|
|
|
96
96
|
pluginId: entry.pluginId,
|
|
97
97
|
message: `Active version ${activeVersion} of ${entry.pluginId} does not satisfy the factory range ` +
|
|
98
98
|
`${entry.range ?? "latest"}; bootstrap never replaces active installations. ` +
|
|
99
|
-
`Run \`${pluginBootstrapInstallCommandV1(entry)}\` to install a matching version
|
|
99
|
+
`Run \`${pluginBootstrapInstallCommandV1(entry)}\` to install a matching version, ` +
|
|
100
|
+
`or \`agent-forge plugin update --all\` to upgrade every outdated plugin at once.`,
|
|
100
101
|
});
|
|
101
102
|
continue;
|
|
102
103
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-bootstrap.js","sourceRoot":"","sources":["../../../src/plugins/ecosystem/plugin-bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAU,CAAC;AAoEtD;;;;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分发与启动装配设计.md` §4.4, §0.7). Pure injectable decision loop\n * over the frozen factory manifest: every entry is compared against the\n * locally resolved active installations and only missing plugins are handed\n * to the npm install dependency — bootstrap never acquires through any other\n * source.\n *\n * Coverage rules (G5): an existing active installation is never replaced. A\n * satisfied range is skipped silently (zero acquisition calls, G3); an\n * unsatisfied one produces a diagnostic with a manual install command and no\n * automatic replacement. Failure semantics (G4): one plugin's install\n * failure is recorded and the loop continues; the run itself never throws.\n * All effects live behind the injected dependencies, so the loop is fully\n * deterministic under mocks.\n */\n\nimport type { PluginBootstrapFactoryEntryV1 } from \"./bootstrap-factory-manifest.ts\";\nimport { selectNpmPackageVersionV1 } from \"./node-npm-registry-source.ts\";\nimport { PluginAcquisitionErrorV1 } from \"./plugin-acquisition.ts\";\n\nexport const PLUGIN_BOOTSTRAP_VERSION_V1 = 1 as const;\n\n/** Read-only local lookup of active installation versions (never networked). */\nexport type PluginBootstrapListActiveV1 = (input: {\n\treadonly signal?: AbortSignal;\n}) => Promise<ReadonlyMap<string, string>>;\n\n/** npm-only install action; resolves with the installed version and source label. */\nexport type PluginBootstrapInstallFromNpmV1 = (input: {\n\treadonly npmName: string;\n\treadonly range?: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<{ readonly pluginVersion: string; readonly source: string }>;\n\nexport interface PluginBootstrapDepsV1 {\n\treadonly listActive: PluginBootstrapListActiveV1;\n\treadonly installFromNpm: PluginBootstrapInstallFromNpmV1;\n\t/** Deterministic clock for the observed duration; defaults to Date.now. */\n\treadonly now?: () => number;\n\t/** Cooperative cancellation; checked before each manifest entry. */\n\treadonly signal?: AbortSignal;\n}\n\nexport type PluginBootstrapActionStatusV1 = \"skipped\" | \"diagnosed\" | \"installed\" | \"failed\";\n\nexport type PluginBootstrapActionReasonV1 = \"satisfies_range\" | \"range_not_satisfied\" | \"installed\" | \"install_failed\";\n\n/** One per-entry outcome; the version fields carry what each status observed. */\nexport interface PluginBootstrapActionV1 {\n\treadonly pluginId: string;\n\treadonly status: PluginBootstrapActionStatusV1;\n\treadonly reason: PluginBootstrapActionReasonV1;\n\treadonly npmName: string;\n\treadonly range?: string;\n\t/** Active version that decided a skipped/diagnosed outcome. */\n\treadonly activeVersion?: string;\n\t/** Version reported by the install action. */\n\treadonly installedVersion?: string;\n\t/** npm source label reported by the install action. */\n\treadonly source?: string;\n\t/** Acquisition or install failure code for failed actions. */\n\treadonly errorCode?: string;\n}\n\nexport type PluginBootstrapDiagnosticCodeV1 =\n\t| \"range_not_satisfied\"\n\t| \"install_failed\"\n\t| \"list_active_failed\"\n\t| \"cancelled\"\n\t| \"bootstrap_failed\";\n\nexport interface PluginBootstrapDiagnosticV1 {\n\treadonly code: PluginBootstrapDiagnosticCodeV1;\n\treadonly message: string;\n\treadonly pluginId?: string;\n}\n\nexport type PluginBootstrapStatusV1 = \"succeeded\" | \"degraded\" | \"failed\";\n\nexport interface PluginBootstrapResultV1 {\n\treadonly version: typeof PLUGIN_BOOTSTRAP_VERSION_V1;\n\t/** Aggregated outcome: failed > degraded (diagnosed entries) > succeeded. */\n\treadonly status: PluginBootstrapStatusV1;\n\treadonly actions: readonly PluginBootstrapActionV1[];\n\treadonly diagnostics: readonly PluginBootstrapDiagnosticV1[];\n\treadonly durationMs: number;\n}\n\n/**\n * A version satisfies a factory range under the same selection semantics npm\n * resolution uses: it is the version that would be picked if it were the only\n * candidate. Keeps local comparison and registry resolution consistent.\n */\nfunction satisfiesRangeV1(version: string, range: string | undefined): boolean {\n\treturn selectNpmPackageVersionV1([version], range) === version;\n}\n\n/** Executable repair command for diagnostics (G4/G5 remediation hint). */\nexport function pluginBootstrapInstallCommandV1(entry: { readonly npmName: string; readonly range?: string }): string {\n\treturn `agent-forge plugin install ${entry.npmName}@${entry.range ?? \"latest\"}`;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction acquireErrorCode(error: unknown): string {\n\treturn error instanceof PluginAcquisitionErrorV1 ? error.code : \"install_failed\";\n}\n\nfunction actionOf(\n\tentry: PluginBootstrapFactoryEntryV1,\n\tstatus: PluginBootstrapActionStatusV1,\n\treason: PluginBootstrapActionReasonV1,\n): PluginBootstrapActionV1 {\n\treturn Object.freeze({\n\t\tpluginId: entry.pluginId,\n\t\tstatus,\n\t\treason,\n\t\tnpmName: entry.npmName,\n\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t});\n}\n\n/**\n * Run the bootstrap decision loop. An empty manifest short-circuits before\n * any dependency is touched, so the factory-empty S1-c2 state performs zero\n * reads on real startups.\n */\nexport async function runPluginBootstrapV1(input: {\n\treadonly manifest: readonly PluginBootstrapFactoryEntryV1[];\n\treadonly deps: PluginBootstrapDepsV1;\n}): Promise<PluginBootstrapResultV1> {\n\tconst now = input.deps.now ?? Date.now;\n\tconst startedAt = now();\n\tconst finish = (\n\t\tstatus: PluginBootstrapStatusV1,\n\t\tactions: readonly PluginBootstrapActionV1[],\n\t\tdiagnostics: readonly PluginBootstrapDiagnosticV1[],\n\t): PluginBootstrapResultV1 =>\n\t\tObject.freeze({\n\t\t\tversion: PLUGIN_BOOTSTRAP_VERSION_V1,\n\t\t\tstatus,\n\t\t\tactions: Object.freeze([...actions]),\n\t\t\tdiagnostics: Object.freeze([...diagnostics]),\n\t\t\tdurationMs: Math.max(0, now() - startedAt),\n\t\t});\n\tif (input.manifest.length === 0) return finish(\"succeeded\", [], []);\n\tconst signal = input.deps.signal;\n\tlet active: ReadonlyMap<string, string>;\n\ttry {\n\t\tactive = await input.deps.listActive({ ...(signal === undefined ? {} : { signal }) });\n\t} catch (error) {\n\t\treturn finish(\n\t\t\t\"failed\",\n\t\t\t[],\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\tcode: \"list_active_failed\",\n\t\t\t\t\tmessage: `Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t);\n\t}\n\tconst actions: PluginBootstrapActionV1[] = [];\n\tconst diagnostics: PluginBootstrapDiagnosticV1[] = [];\n\tfor (const entry of input.manifest) {\n\t\tif (signal?.aborted === true) {\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"cancelled\",\n\t\t\t\tmessage: \"Plugin bootstrap was cancelled before all factory entries were processed\",\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tconst activeVersion = active.get(entry.pluginId);\n\t\tif (activeVersion !== undefined) {\n\t\t\tif (satisfiesRangeV1(activeVersion, entry.range)) {\n\t\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"skipped\", \"satisfies_range\"), activeVersion }));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"diagnosed\", \"range_not_satisfied\"), activeVersion }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"range_not_satisfied\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Active version ${activeVersion} of ${entry.pluginId} does not satisfy the factory range ` +\n\t\t\t\t\t`${entry.range ?? \"latest\"}; bootstrap never replaces active installations. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install a matching version.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst installed = await input.deps.installFromNpm({\n\t\t\t\tnpmName: entry.npmName,\n\t\t\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t\t});\n\t\t\tactions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...actionOf(entry, \"installed\", \"installed\"),\n\t\t\t\t\tinstalledVersion: installed.pluginVersion,\n\t\t\t\t\tsource: installed.source,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst errorCode = acquireErrorCode(error);\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"failed\", \"install_failed\"), errorCode }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"install_failed\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Bootstrap could not install ${entry.pluginId} from npm (${errorCode}: ${errorMessage(error)}). ` +\n\t\t\t\t\t`Startup continues without it; its capabilities stay unavailable until installed. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install it manually.`,\n\t\t\t});\n\t\t}\n\t}\n\tconst status: PluginBootstrapStatusV1 = actions.some((action) => action.status === \"failed\")\n\t\t? \"failed\"\n\t\t: actions.some((action) => action.status === \"diagnosed\")\n\t\t\t? \"degraded\"\n\t\t\t: \"succeeded\";\n\treturn finish(status, actions, diagnostics);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"plugin-bootstrap.js","sourceRoot":"","sources":["../../../src/plugins/ecosystem/plugin-bootstrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAU,CAAC;AAoEtD;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,OAAe,EAAE,KAAyB,EAAW;IAC9E,OAAO,yBAAyB,CAAC,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,KAAK,OAAO,CAAC;AAAA,CAC/D;AAED,0EAA0E;AAC1E,MAAM,UAAU,+BAA+B,CAAC,KAA4D,EAAU;IACrH,OAAO,8BAA8B,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,KAAK,IAAI,QAAQ,EAAE,CAAC;AAAA,CAChF;AAED,SAAS,YAAY,CAAC,KAAc,EAAU;IAC7C,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CAC9D;AAED,SAAS,gBAAgB,CAAC,KAAc,EAAU;I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CAAC;YAC3F,WAAW,CAAC,IAAI,CAAC;gBAChB,IAAI,EAAE,gBAAgB;gBACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,OAAO,EACN,+BAA+B,KAAK,CAAC,QAAQ,cAAc,SAAS,KAAK,YAAY,CAAC,KAAK,CAAC,KAAK;oBACjG,mFAAmF;oBACnF,SAAS,+BAA+B,CAAC,KAAK,CAAC,4BAA4B;aAC5E,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IACD,MAAM,MAAM,GAA4B,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC;QAC3F,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC;YACxD,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,WAAW,CAAC;IAChB,OAAO,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;AAAA,CAC5C","sourcesContent":["/**\n * Startup plugin bootstrap orchestrator (design\n * `插件独立分发与启动装配设计.md` §4.4, §0.7). Pure injectable decision loop\n * over the frozen factory manifest: every entry is compared against the\n * locally resolved active installations and only missing plugins are handed\n * to the npm install dependency — bootstrap never acquires through any other\n * source.\n *\n * Coverage rules (G5): an existing active installation is never replaced. A\n * satisfied range is skipped silently (zero acquisition calls, G3); an\n * unsatisfied one produces a diagnostic with a manual install command and no\n * automatic replacement. Failure semantics (G4): one plugin's install\n * failure is recorded and the loop continues; the run itself never throws.\n * All effects live behind the injected dependencies, so the loop is fully\n * deterministic under mocks.\n */\n\nimport type { PluginBootstrapFactoryEntryV1 } from \"./bootstrap-factory-manifest.ts\";\nimport { selectNpmPackageVersionV1 } from \"./node-npm-registry-source.ts\";\nimport { PluginAcquisitionErrorV1 } from \"./plugin-acquisition.ts\";\n\nexport const PLUGIN_BOOTSTRAP_VERSION_V1 = 1 as const;\n\n/** Read-only local lookup of active installation versions (never networked). */\nexport type PluginBootstrapListActiveV1 = (input: {\n\treadonly signal?: AbortSignal;\n}) => Promise<ReadonlyMap<string, string>>;\n\n/** npm-only install action; resolves with the installed version and source label. */\nexport type PluginBootstrapInstallFromNpmV1 = (input: {\n\treadonly npmName: string;\n\treadonly range?: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<{ readonly pluginVersion: string; readonly source: string }>;\n\nexport interface PluginBootstrapDepsV1 {\n\treadonly listActive: PluginBootstrapListActiveV1;\n\treadonly installFromNpm: PluginBootstrapInstallFromNpmV1;\n\t/** Deterministic clock for the observed duration; defaults to Date.now. */\n\treadonly now?: () => number;\n\t/** Cooperative cancellation; checked before each manifest entry. */\n\treadonly signal?: AbortSignal;\n}\n\nexport type PluginBootstrapActionStatusV1 = \"skipped\" | \"diagnosed\" | \"installed\" | \"failed\";\n\nexport type PluginBootstrapActionReasonV1 = \"satisfies_range\" | \"range_not_satisfied\" | \"installed\" | \"install_failed\";\n\n/** One per-entry outcome; the version fields carry what each status observed. */\nexport interface PluginBootstrapActionV1 {\n\treadonly pluginId: string;\n\treadonly status: PluginBootstrapActionStatusV1;\n\treadonly reason: PluginBootstrapActionReasonV1;\n\treadonly npmName: string;\n\treadonly range?: string;\n\t/** Active version that decided a skipped/diagnosed outcome. */\n\treadonly activeVersion?: string;\n\t/** Version reported by the install action. */\n\treadonly installedVersion?: string;\n\t/** npm source label reported by the install action. */\n\treadonly source?: string;\n\t/** Acquisition or install failure code for failed actions. */\n\treadonly errorCode?: string;\n}\n\nexport type PluginBootstrapDiagnosticCodeV1 =\n\t| \"range_not_satisfied\"\n\t| \"install_failed\"\n\t| \"list_active_failed\"\n\t| \"cancelled\"\n\t| \"bootstrap_failed\";\n\nexport interface PluginBootstrapDiagnosticV1 {\n\treadonly code: PluginBootstrapDiagnosticCodeV1;\n\treadonly message: string;\n\treadonly pluginId?: string;\n}\n\nexport type PluginBootstrapStatusV1 = \"succeeded\" | \"degraded\" | \"failed\";\n\nexport interface PluginBootstrapResultV1 {\n\treadonly version: typeof PLUGIN_BOOTSTRAP_VERSION_V1;\n\t/** Aggregated outcome: failed > degraded (diagnosed entries) > succeeded. */\n\treadonly status: PluginBootstrapStatusV1;\n\treadonly actions: readonly PluginBootstrapActionV1[];\n\treadonly diagnostics: readonly PluginBootstrapDiagnosticV1[];\n\treadonly durationMs: number;\n}\n\n/**\n * A version satisfies a factory range under the same selection semantics npm\n * resolution uses: it is the version that would be picked if it were the only\n * candidate. Keeps local comparison and registry resolution consistent.\n */\nfunction satisfiesRangeV1(version: string, range: string | undefined): boolean {\n\treturn selectNpmPackageVersionV1([version], range) === version;\n}\n\n/** Executable repair command for diagnostics (G4/G5 remediation hint). */\nexport function pluginBootstrapInstallCommandV1(entry: { readonly npmName: string; readonly range?: string }): string {\n\treturn `agent-forge plugin install ${entry.npmName}@${entry.range ?? \"latest\"}`;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction acquireErrorCode(error: unknown): string {\n\treturn error instanceof PluginAcquisitionErrorV1 ? error.code : \"install_failed\";\n}\n\nfunction actionOf(\n\tentry: PluginBootstrapFactoryEntryV1,\n\tstatus: PluginBootstrapActionStatusV1,\n\treason: PluginBootstrapActionReasonV1,\n): PluginBootstrapActionV1 {\n\treturn Object.freeze({\n\t\tpluginId: entry.pluginId,\n\t\tstatus,\n\t\treason,\n\t\tnpmName: entry.npmName,\n\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t});\n}\n\n/**\n * Run the bootstrap decision loop. An empty manifest short-circuits before\n * any dependency is touched, so the factory-empty S1-c2 state performs zero\n * reads on real startups.\n */\nexport async function runPluginBootstrapV1(input: {\n\treadonly manifest: readonly PluginBootstrapFactoryEntryV1[];\n\treadonly deps: PluginBootstrapDepsV1;\n}): Promise<PluginBootstrapResultV1> {\n\tconst now = input.deps.now ?? Date.now;\n\tconst startedAt = now();\n\tconst finish = (\n\t\tstatus: PluginBootstrapStatusV1,\n\t\tactions: readonly PluginBootstrapActionV1[],\n\t\tdiagnostics: readonly PluginBootstrapDiagnosticV1[],\n\t): PluginBootstrapResultV1 =>\n\t\tObject.freeze({\n\t\t\tversion: PLUGIN_BOOTSTRAP_VERSION_V1,\n\t\t\tstatus,\n\t\t\tactions: Object.freeze([...actions]),\n\t\t\tdiagnostics: Object.freeze([...diagnostics]),\n\t\t\tdurationMs: Math.max(0, now() - startedAt),\n\t\t});\n\tif (input.manifest.length === 0) return finish(\"succeeded\", [], []);\n\tconst signal = input.deps.signal;\n\tlet active: ReadonlyMap<string, string>;\n\ttry {\n\t\tactive = await input.deps.listActive({ ...(signal === undefined ? {} : { signal }) });\n\t} catch (error) {\n\t\treturn finish(\n\t\t\t\"failed\",\n\t\t\t[],\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\tcode: \"list_active_failed\",\n\t\t\t\t\tmessage: `Active plugin state could not be read; bootstrap installed nothing: ${errorMessage(error)}`,\n\t\t\t\t},\n\t\t\t],\n\t\t);\n\t}\n\tconst actions: PluginBootstrapActionV1[] = [];\n\tconst diagnostics: PluginBootstrapDiagnosticV1[] = [];\n\tfor (const entry of input.manifest) {\n\t\tif (signal?.aborted === true) {\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"cancelled\",\n\t\t\t\tmessage: \"Plugin bootstrap was cancelled before all factory entries were processed\",\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tconst activeVersion = active.get(entry.pluginId);\n\t\tif (activeVersion !== undefined) {\n\t\t\tif (satisfiesRangeV1(activeVersion, entry.range)) {\n\t\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"skipped\", \"satisfies_range\"), activeVersion }));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"diagnosed\", \"range_not_satisfied\"), activeVersion }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"range_not_satisfied\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Active version ${activeVersion} of ${entry.pluginId} does not satisfy the factory range ` +\n\t\t\t\t\t`${entry.range ?? \"latest\"}; bootstrap never replaces active installations. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install a matching version, ` +\n\t\t\t\t\t`or \\`agent-forge plugin update --all\\` to upgrade every outdated plugin at once.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst installed = await input.deps.installFromNpm({\n\t\t\t\tnpmName: entry.npmName,\n\t\t\t\t...(entry.range === undefined ? {} : { range: entry.range }),\n\t\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t\t});\n\t\t\tactions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...actionOf(entry, \"installed\", \"installed\"),\n\t\t\t\t\tinstalledVersion: installed.pluginVersion,\n\t\t\t\t\tsource: installed.source,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst errorCode = acquireErrorCode(error);\n\t\t\tactions.push(Object.freeze({ ...actionOf(entry, \"failed\", \"install_failed\"), errorCode }));\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: \"install_failed\",\n\t\t\t\tpluginId: entry.pluginId,\n\t\t\t\tmessage:\n\t\t\t\t\t`Bootstrap could not install ${entry.pluginId} from npm (${errorCode}: ${errorMessage(error)}). ` +\n\t\t\t\t\t`Startup continues without it; its capabilities stay unavailable until installed. ` +\n\t\t\t\t\t`Run \\`${pluginBootstrapInstallCommandV1(entry)}\\` to install it manually.`,\n\t\t\t});\n\t\t}\n\t}\n\tconst status: PluginBootstrapStatusV1 = actions.some((action) => action.status === \"failed\")\n\t\t? \"failed\"\n\t\t: actions.some((action) => action.status === \"diagnosed\")\n\t\t\t? \"degraded\"\n\t\t\t: \"succeeded\";\n\treturn finish(status, actions, diagnostics);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools-manager.d.ts","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AA2HA,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAmB5D;AAQD,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CA4BpE;AAED;;;;GAIG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,YAAY,GAAG,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAKpE;CACD;AAMD,wBAAsB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAgC/G;AA2OD,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC/B,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,GACrC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAiD7B","sourcesContent":["import type { ReadableStream as NodeWebReadableStream } from \"node:stream/web\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable, Transform } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.AGENT_FORGE_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\t/**\n\t * Suffix appended to the asset download URL to locate the release's\n\t * per-asset checksum companion file (e.g., \".sha256\"). When present, the\n\t * download is verified against it; when absent, no trusted automatic\n\t * checksum source exists for that release channel and the download runs\n\t * unverified.\n\t */\n\tchecksumSuffix?: string;\n\t/**\n\t * Release version pinned in-repo, used instead of the latest-release\n\t * redirect. Always paired with `digests`: the release channel publishes no\n\t * trustworthy automatic checksum, so the repo commits one digest per asset\n\t * (computed from the official release download) and upgrades adopt a new\n\t * release by bumping the pin and refreshing the digests.\n\t */\n\tpinnedVersion?: string;\n\t/**\n\t * Repo-committed sha256 digest per asset name for `pinnedVersion`. A\n\t * missing entry fails the install visibly — it is never silently skipped\n\t * into an unverified download.\n\t */\n\tdigests?: Record<string, string>;\n}\n\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\t// fd publishes no per-asset checksum (probed: asset and .sha256 companions\n\t\t// are absent), so the release is pinned in-repo and each asset's digest is\n\t\t// committed here. Upgrades adopt a new release by bumping pinnedVersion\n\t\t// and refreshing the digests from the official release assets.\n\t\tpinnedVersion: \"10.5.0\",\n\t\tdigests: {\n\t\t\t\"fd-v10.5.0-x86_64-apple-darwin.tar.gz\": \"7e31028c62c6955877735d0406807aa484c2a5e6f86235a59e26c29c301da590\",\n\t\t\t\"fd-v10.5.0-aarch64-apple-darwin.tar.gz\": \"b67e1836c468e42e411984b56e52fa7abec08c2bd22c867398e7cc134aac5e12\",\n\t\t\t\"fd-v10.5.0-x86_64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"761c72dc8e120d85b22292063be8a796e2eeb20eb3e4f38b8fa2343ccf3514a7\",\n\t\t\t\"fd-v10.5.0-aarch64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"d76c4317f7d5dba69f8a2a15856c90c777e7f0dd4e85f0de8c76de6992c374d4\",\n\t\t\t\"fd-v10.5.0-x86_64-pc-windows-msvc.zip\": \"a227701b8551c35a9931d9f6da75503cf86d88e182d71fb849a70864c5d57cd7\",\n\t\t\t\"fd-v10.5.0-aarch64-pc-windows-msvc.zip\": \"a2bcddcfd259b05357a77bbc6cd671fdb30f63fd266a0e748305890a8c5ceaa6\",\n\t\t},\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\t// Every ripgrep release asset ships a sha256sum-format companion file.\n\t\tchecksumSuffix: \".sha256\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Resolve the latest release version from the release page redirect.\n// The api.github.com releases endpoint counts against the anonymous API\n// quota (60 requests/hour per IP), which is permanently exhausted behind\n// shared egress IPs such as corporate proxies and CI runners. The web\n// endpoint answers with a redirect to the tagged release at no quota cost\n// and lives on the same origin as the binary download itself.\nexport async function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetchWithRetry(\n\t\t`https://github.com/${repo}/releases/latest`,\n\t\t{\n\t\t\theaders: { \"User-Agent\": `${APP_NAME}-agent-forge` },\n\t\t\tredirect: \"manual\",\n\t\t},\n\t\t{ timeoutMs: NETWORK_TIMEOUT_MS },\n\t);\n\n\t// Only the status and headers matter here. Discard the body so the\n\t// connection can be reused.\n\ttry {\n\t\tawait response.body?.cancel();\n\t} catch {\n\t\t// Discarding the body is best-effort.\n\t}\n\n\tconst location = response.status >= 300 && response.status < 400 ? response.headers.get(\"location\") : null;\n\tif (!location) {\n\t\tthrow new Error(`Failed to resolve latest ${repo} release: HTTP ${response.status} without redirect`);\n\t}\n\n\tconst tag = new URL(location, \"https://github.com\").pathname.split(\"/\").pop();\n\tif (!tag || !location.includes(\"/releases/tag/\")) {\n\t\tthrow new Error(`Failed to resolve latest ${repo} release: unexpected redirect to ${location}`);\n\t}\n\treturn decodeURIComponent(tag).replace(/^v/, \"\");\n}\n\n/**\n * Integrity failure for a verified download. Carries both digests so callers\n * (and tests) can inspect the mismatch structurally instead of parsing the\n * message.\n */\nexport class DownloadIntegrityError extends Error {\n\treadonly expectedSha256: string;\n\treadonly actualSha256: string;\n\n\tconstructor(url: string, expectedSha256: string, actualSha256: string) {\n\t\tsuper(`Download integrity check failed for ${url}: expected sha256 ${expectedSha256}, got ${actualSha256}`);\n\t\tthis.name = \"DownloadIntegrityError\";\n\t\tthis.expectedSha256 = expectedSha256;\n\t\tthis.actualSha256 = actualSha256;\n\t}\n}\n\n// Download a file from URL. When `expectedSha256` is provided, the response\n// stream is hashed while it is written; a mismatch deletes the partial file\n// and rejects with a DownloadIntegrityError. Without it, behavior is\n// unchanged (unverified write).\nexport async function downloadFile(url: string, dest: string, expectedSha256: string | undefined): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Download failed with HTTP ${response.status}: ${url}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst hash = createHash(\"sha256\");\n\tconst digestTap = new Transform({\n\t\ttransform(\n\t\t\tchunk: Buffer,\n\t\t\t_encoding: BufferEncoding,\n\t\t\tcallback: (error?: Error | null, data?: Buffer) => void,\n\t\t): void {\n\t\t\thash.update(chunk);\n\t\t\tcallback(null, chunk);\n\t\t},\n\t});\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as NodeWebReadableStream), digestTap, fileStream);\n\n\tif (expectedSha256 === undefined) return;\n\tconst actual = hash.digest(\"hex\");\n\tconst expected = expectedSha256.trim().toLowerCase();\n\tif (actual !== expected) {\n\t\trmSync(dest, { force: true });\n\t\tthrow new DownloadIntegrityError(url, expected, actual);\n\t}\n}\n\nconst SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;\n\n// Resolve the expected sha256 for an asset from the tool's trusted checksum\n// source: the repo-committed digest map when present, otherwise the release's\n// per-asset companion checksum file. Undefined means no trusted source exists\n// for the channel and the download runs unverified.\nasync function resolveExpectedSha256(\n\tconfig: ToolConfig,\n\tdownloadUrl: string,\n\tassetName: string,\n): Promise<string | undefined> {\n\tconst digests = config.digests;\n\tif (digests) {\n\t\tconst digest = digests[assetName];\n\t\tif (digest === undefined) {\n\t\t\tthrow new Error(`No committed sha256 for ${config.name} asset ${assetName}; refresh the pin and its digests`);\n\t\t}\n\t\treturn digest;\n\t}\n\tif (config.checksumSuffix !== undefined) {\n\t\treturn fetchReleaseSha256(`${downloadUrl}${config.checksumSuffix}`);\n\t}\n\treturn undefined;\n}\n\n// Fetch a release's per-asset checksum companion file (sha256sum format:\n// \"<hex> <asset name>\") and return the lowercase hex digest.\nasync function fetchReleaseSha256(checksumUrl: string): Promise<string> {\n\tconst response = await fetchWithRetry(checksumUrl, undefined, { timeoutMs: NETWORK_TIMEOUT_MS });\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to fetch release checksum: HTTP ${response.status}: ${checksumUrl}`);\n\t}\n\tconst digest = (await response.text()).trim().split(/\\s+/)[0]?.toLowerCase() ?? \"\";\n\tif (!SHA256_HEX_PATTERN.test(digest)) {\n\t\tthrow new Error(`Release checksum has an unexpected format: ${checksumUrl}`);\n\t}\n\treturn digest;\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\t// v8 ignore next -- 循环条件保证栈非空,pop() 不会返回 undefined\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\t// v8 ignore next -- getAssetName 仅在 win32 产出 .zip 资产,非 win32 不会进入 zip 解包分支\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\t// v8 ignore start -- fd/rg 在非 Windows 平台的资产恒为 .tar.gz,unzip 分支不可达\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t\t// v8 ignore stop\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\t// v8 ignore next -- ensureTool 已做同样检查,此兜底经公共 API 不可达\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned releases (fd) skip the version lookup entirely: the digest map only\n\t// covers the pinned release, so tracking latest would break verification.\n\tconst version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\t// The expected digest comes from whichever trusted source the channel has:\n\t// a repo-committed per-asset digest (fd) or an upstream companion checksum\n\t// file (rg). A digest that cannot be obtained or matched fails the install\n\t// visibly (ensureTool surfaces it as a warning); it is never silently skipped.\n\tconst expectedSha256 = await resolveExpectedSha256(config, downloadUrl, assetName);\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath, expectedSha256);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\t// v8 ignore next -- getAssetName 产出的资产名恒为 .tar.gz 或 .zip,此兜底不可达\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\nexport interface ToolStatus {\n\ttype: \"info\" | \"warning\";\n\tmessage: string;\n}\n\n/**\n * Ensure a tool is available, downloading if necessary.\n * Reports progress through `onStatus`; status messages are otherwise silent.\n * Returns the tool path, or undefined if unavailable.\n */\nexport async function ensureTool(\n\ttool: \"fd\" | \"rg\",\n\tonStatus?: (status: ToolStatus) => void,\n): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Offline mode enabled, skipping download.` });\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\t// v8 ignore next -- TERMUX_PACKAGES 覆盖全部受支持工具,?? 回退不可达\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Install with: pkg install ${pkgName}` });\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tonStatus?.({ type: \"info\", message: `${config.name} not found. Downloading...` });\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tonStatus?.({ type: \"info\", message: `${config.name} installed to ${path}` });\n\t\treturn path;\n\t} catch (e) {\n\t\t// Include the error cause chain: fetch failures surface as a bare\n\t\t// \"fetch failed\" TypeError with the actionable detail (DNS, TLS,\n\t\t// timeout) hidden in the cause. Depth-capped to guard against\n\t\t// circular cause chains.\n\t\tconst messages: string[] = [];\n\t\tfor (\n\t\t\tlet current: unknown = e, depth = 0;\n\t\t\tcurrent instanceof Error && depth < 5;\n\t\t\tcurrent = current.cause, depth++\n\t\t) {\n\t\t\tif (!messages.includes(current.message)) messages.push(current.message);\n\t\t}\n\t\tonStatus?.({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Failed to download ${config.name}: ${messages.length > 0 ? messages.join(\": \") : String(e)}`,\n\t\t});\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tools-manager.d.ts","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AA4HA,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAmB5D;AAQD,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CA4BpE;AAED;;;;GAIG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAE9B,YAAY,GAAG,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAKpE;CACD;AAMD,wBAAsB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAgC/G;AAkPD,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC/B,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,GACrC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgE7B","sourcesContent":["import type { ReadableStream as NodeWebReadableStream } from \"node:stream/web\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { createHash } from \"crypto\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable, Transform } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\nconst DOWNLOAD_PROGRESS_INTERVAL_MS = 15_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.AGENT_FORGE_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n\t/**\n\t * Suffix appended to the asset download URL to locate the release's\n\t * per-asset checksum companion file (e.g., \".sha256\"). When present, the\n\t * download is verified against it; when absent, no trusted automatic\n\t * checksum source exists for that release channel and the download runs\n\t * unverified.\n\t */\n\tchecksumSuffix?: string;\n\t/**\n\t * Release version pinned in-repo, used instead of the latest-release\n\t * redirect. Always paired with `digests`: the release channel publishes no\n\t * trustworthy automatic checksum, so the repo commits one digest per asset\n\t * (computed from the official release download) and upgrades adopt a new\n\t * release by bumping the pin and refreshing the digests.\n\t */\n\tpinnedVersion?: string;\n\t/**\n\t * Repo-committed sha256 digest per asset name for `pinnedVersion`. A\n\t * missing entry fails the install visibly — it is never silently skipped\n\t * into an unverified download.\n\t */\n\tdigests?: Record<string, string>;\n}\n\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\t// fd publishes no per-asset checksum (probed: asset and .sha256 companions\n\t\t// are absent), so the release is pinned in-repo and each asset's digest is\n\t\t// committed here. Upgrades adopt a new release by bumping pinnedVersion\n\t\t// and refreshing the digests from the official release assets.\n\t\tpinnedVersion: \"10.5.0\",\n\t\tdigests: {\n\t\t\t\"fd-v10.5.0-x86_64-apple-darwin.tar.gz\": \"7e31028c62c6955877735d0406807aa484c2a5e6f86235a59e26c29c301da590\",\n\t\t\t\"fd-v10.5.0-aarch64-apple-darwin.tar.gz\": \"b67e1836c468e42e411984b56e52fa7abec08c2bd22c867398e7cc134aac5e12\",\n\t\t\t\"fd-v10.5.0-x86_64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"761c72dc8e120d85b22292063be8a796e2eeb20eb3e4f38b8fa2343ccf3514a7\",\n\t\t\t\"fd-v10.5.0-aarch64-unknown-linux-musl.tar.gz\":\n\t\t\t\t\"d76c4317f7d5dba69f8a2a15856c90c777e7f0dd4e85f0de8c76de6992c374d4\",\n\t\t\t\"fd-v10.5.0-x86_64-pc-windows-msvc.zip\": \"a227701b8551c35a9931d9f6da75503cf86d88e182d71fb849a70864c5d57cd7\",\n\t\t\t\"fd-v10.5.0-aarch64-pc-windows-msvc.zip\": \"a2bcddcfd259b05357a77bbc6cd671fdb30f63fd266a0e748305890a8c5ceaa6\",\n\t\t},\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\t// Every ripgrep release asset ships a sha256sum-format companion file.\n\t\tchecksumSuffix: \".sha256\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Resolve the latest release version from the release page redirect.\n// The api.github.com releases endpoint counts against the anonymous API\n// quota (60 requests/hour per IP), which is permanently exhausted behind\n// shared egress IPs such as corporate proxies and CI runners. The web\n// endpoint answers with a redirect to the tagged release at no quota cost\n// and lives on the same origin as the binary download itself.\nexport async function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetchWithRetry(\n\t\t`https://github.com/${repo}/releases/latest`,\n\t\t{\n\t\t\theaders: { \"User-Agent\": `${APP_NAME}-agent-forge` },\n\t\t\tredirect: \"manual\",\n\t\t},\n\t\t{ timeoutMs: NETWORK_TIMEOUT_MS },\n\t);\n\n\t// Only the status and headers matter here. Discard the body so the\n\t// connection can be reused.\n\ttry {\n\t\tawait response.body?.cancel();\n\t} catch {\n\t\t// Discarding the body is best-effort.\n\t}\n\n\tconst location = response.status >= 300 && response.status < 400 ? response.headers.get(\"location\") : null;\n\tif (!location) {\n\t\tthrow new Error(`Failed to resolve latest ${repo} release: HTTP ${response.status} without redirect`);\n\t}\n\n\tconst tag = new URL(location, \"https://github.com\").pathname.split(\"/\").pop();\n\tif (!tag || !location.includes(\"/releases/tag/\")) {\n\t\tthrow new Error(`Failed to resolve latest ${repo} release: unexpected redirect to ${location}`);\n\t}\n\treturn decodeURIComponent(tag).replace(/^v/, \"\");\n}\n\n/**\n * Integrity failure for a verified download. Carries both digests so callers\n * (and tests) can inspect the mismatch structurally instead of parsing the\n * message.\n */\nexport class DownloadIntegrityError extends Error {\n\treadonly expectedSha256: string;\n\treadonly actualSha256: string;\n\n\tconstructor(url: string, expectedSha256: string, actualSha256: string) {\n\t\tsuper(`Download integrity check failed for ${url}: expected sha256 ${expectedSha256}, got ${actualSha256}`);\n\t\tthis.name = \"DownloadIntegrityError\";\n\t\tthis.expectedSha256 = expectedSha256;\n\t\tthis.actualSha256 = actualSha256;\n\t}\n}\n\n// Download a file from URL. When `expectedSha256` is provided, the response\n// stream is hashed while it is written; a mismatch deletes the partial file\n// and rejects with a DownloadIntegrityError. Without it, behavior is\n// unchanged (unverified write).\nexport async function downloadFile(url: string, dest: string, expectedSha256: string | undefined): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Download failed with HTTP ${response.status}: ${url}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst hash = createHash(\"sha256\");\n\tconst digestTap = new Transform({\n\t\ttransform(\n\t\t\tchunk: Buffer,\n\t\t\t_encoding: BufferEncoding,\n\t\t\tcallback: (error?: Error | null, data?: Buffer) => void,\n\t\t): void {\n\t\t\thash.update(chunk);\n\t\t\tcallback(null, chunk);\n\t\t},\n\t});\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as NodeWebReadableStream), digestTap, fileStream);\n\n\tif (expectedSha256 === undefined) return;\n\tconst actual = hash.digest(\"hex\");\n\tconst expected = expectedSha256.trim().toLowerCase();\n\tif (actual !== expected) {\n\t\trmSync(dest, { force: true });\n\t\tthrow new DownloadIntegrityError(url, expected, actual);\n\t}\n}\n\nconst SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;\n\n// Resolve the expected sha256 for an asset from the tool's trusted checksum\n// source: the repo-committed digest map when present, otherwise the release's\n// per-asset companion checksum file. Undefined means no trusted source exists\n// for the channel and the download runs unverified.\nasync function resolveExpectedSha256(\n\tconfig: ToolConfig,\n\tdownloadUrl: string,\n\tassetName: string,\n): Promise<string | undefined> {\n\tconst digests = config.digests;\n\tif (digests) {\n\t\tconst digest = digests[assetName];\n\t\tif (digest === undefined) {\n\t\t\tthrow new Error(`No committed sha256 for ${config.name} asset ${assetName}; refresh the pin and its digests`);\n\t\t}\n\t\treturn digest;\n\t}\n\tif (config.checksumSuffix !== undefined) {\n\t\treturn fetchReleaseSha256(`${downloadUrl}${config.checksumSuffix}`);\n\t}\n\treturn undefined;\n}\n\n// Fetch a release's per-asset checksum companion file (sha256sum format:\n// \"<hex> <asset name>\") and return the lowercase hex digest.\nasync function fetchReleaseSha256(checksumUrl: string): Promise<string> {\n\tconst response = await fetchWithRetry(checksumUrl, undefined, { timeoutMs: NETWORK_TIMEOUT_MS });\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to fetch release checksum: HTTP ${response.status}: ${checksumUrl}`);\n\t}\n\tconst digest = (await response.text()).trim().split(/\\s+/)[0]?.toLowerCase() ?? \"\";\n\tif (!SHA256_HEX_PATTERN.test(digest)) {\n\t\tthrow new Error(`Release checksum has an unexpected format: ${checksumUrl}`);\n\t}\n\treturn digest;\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\t// v8 ignore next -- 循环条件保证栈非空,pop() 不会返回 undefined\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\t// v8 ignore next -- getAssetName 仅在 win32 产出 .zip 资产,非 win32 不会进入 zip 解包分支\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\t// v8 ignore start -- fd/rg 在非 Windows 平台的资产恒为 .tar.gz,unzip 分支不可达\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t\t// v8 ignore stop\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\t// v8 ignore next -- ensureTool 已做同样检查,此兜底经公共 API 不可达\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Pinned releases (fd) skip the version lookup entirely: the digest map only\n\t// covers the pinned release, so tracking latest would break verification.\n\tconst version = config.pinnedVersion ?? (await getLatestVersion(config.repo));\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\t// The expected digest comes from whichever trusted source the channel has:\n\t// a repo-committed per-asset digest (fd) or an upstream companion checksum\n\t// file (rg). A digest that cannot be obtained or matched fails the install\n\t// visibly (ensureTool surfaces it as a warning); it is never silently skipped.\n\tconst expectedSha256 = await resolveExpectedSha256(config, downloadUrl, assetName);\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// A failed or interrupted download leaves a partial archive on disk (the\n\t// checksum-mismatch path already deletes its own); remove it here so a\n\t// later retry never mistakes the residue for a usable artifact.\n\ttry {\n\t\tawait downloadFile(downloadUrl, archivePath, expectedSha256);\n\t} catch (error) {\n\t\trmSync(archivePath, { force: true });\n\t\tthrow error;\n\t}\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\t// v8 ignore next -- getAssetName 产出的资产名恒为 .tar.gz 或 .zip,此兜底不可达\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\nexport interface ToolStatus {\n\ttype: \"info\" | \"warning\";\n\tmessage: string;\n}\n\n/**\n * Ensure a tool is available, downloading if necessary.\n * Reports progress through `onStatus`; status messages are otherwise silent.\n * Returns the tool path, or undefined if unavailable.\n */\nexport async function ensureTool(\n\ttool: \"fd\" | \"rg\",\n\tonStatus?: (status: ToolStatus) => void,\n): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Offline mode enabled, skipping download.` });\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\t// v8 ignore next -- TERMUX_PACKAGES 覆盖全部受支持工具,?? 回退不可达\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Install with: pkg install ${pkgName}` });\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tonStatus?.({\n\t\ttype: \"info\",\n\t\tmessage: `${config.name} not found. Downloading from GitHub releases (slow networks can take up to ${Math.round(DOWNLOAD_TIMEOUT_MS / 1000)}s; set AGENT_FORGE_OFFLINE=1 to skip)...`,\n\t});\n\n\t// A slow download otherwise looks like a hung startup: report elapsed time\n\t// periodically so the wait stays legible without touching the timeout budget.\n\tconst startedAt = Date.now();\n\tconst progressTicker = setInterval(() => {\n\t\tonStatus?.({\n\t\t\ttype: \"info\",\n\t\t\tmessage: `${config.name} still downloading... ${Math.round((Date.now() - startedAt) / 1000)}s elapsed`,\n\t\t});\n\t}, DOWNLOAD_PROGRESS_INTERVAL_MS);\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tonStatus?.({ type: \"info\", message: `${config.name} installed to ${path}` });\n\t\treturn path;\n\t} catch (e) {\n\t\t// Include the error cause chain: fetch failures surface as a bare\n\t\t// \"fetch failed\" TypeError with the actionable detail (DNS, TLS,\n\t\t// timeout) hidden in the cause. Depth-capped to guard against\n\t\t// circular cause chains.\n\t\tconst messages: string[] = [];\n\t\tfor (\n\t\t\tlet current: unknown = e, depth = 0;\n\t\t\tcurrent instanceof Error && depth < 5;\n\t\t\tcurrent = current.cause, depth++\n\t\t) {\n\t\t\tif (!messages.includes(current.message)) messages.push(current.message);\n\t\t}\n\t\tonStatus?.({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Failed to download ${config.name}: ${messages.length > 0 ? messages.join(\": \") : String(e)}`,\n\t\t});\n\t\treturn undefined;\n\t} finally {\n\t\tclearInterval(progressTicker);\n\t}\n}\n"]}
|
|
@@ -10,6 +10,7 @@ import { fetchWithRetry } from "./management-http.js";
|
|
|
10
10
|
const TOOLS_DIR = getBinDir();
|
|
11
11
|
const NETWORK_TIMEOUT_MS = 10_000;
|
|
12
12
|
const DOWNLOAD_TIMEOUT_MS = 120_000;
|
|
13
|
+
const DOWNLOAD_PROGRESS_INTERVAL_MS = 15_000;
|
|
13
14
|
function isOfflineModeEnabled() {
|
|
14
15
|
const value = process.env.AGENT_FORGE_OFFLINE;
|
|
15
16
|
if (!value)
|
|
@@ -336,8 +337,16 @@ async function downloadTool(tool) {
|
|
|
336
337
|
const archivePath = join(TOOLS_DIR, assetName);
|
|
337
338
|
const binaryExt = plat === "win32" ? ".exe" : "";
|
|
338
339
|
const binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);
|
|
339
|
-
//
|
|
340
|
-
|
|
340
|
+
// A failed or interrupted download leaves a partial archive on disk (the
|
|
341
|
+
// checksum-mismatch path already deletes its own); remove it here so a
|
|
342
|
+
// later retry never mistakes the residue for a usable artifact.
|
|
343
|
+
try {
|
|
344
|
+
await downloadFile(downloadUrl, archivePath, expectedSha256);
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
rmSync(archivePath, { force: true });
|
|
348
|
+
throw error;
|
|
349
|
+
}
|
|
341
350
|
// Extract into a unique temp directory. fd and rg downloads can run concurrently
|
|
342
351
|
// during startup, so sharing a fixed directory causes races.
|
|
343
352
|
const extractDir = join(TOOLS_DIR, `extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`);
|
|
@@ -411,7 +420,19 @@ export async function ensureTool(tool, onStatus) {
|
|
|
411
420
|
return undefined;
|
|
412
421
|
}
|
|
413
422
|
// Tool not found - download it
|
|
414
|
-
onStatus?.({
|
|
423
|
+
onStatus?.({
|
|
424
|
+
type: "info",
|
|
425
|
+
message: `${config.name} not found. Downloading from GitHub releases (slow networks can take up to ${Math.round(DOWNLOAD_TIMEOUT_MS / 1000)}s; set AGENT_FORGE_OFFLINE=1 to skip)...`,
|
|
426
|
+
});
|
|
427
|
+
// A slow download otherwise looks like a hung startup: report elapsed time
|
|
428
|
+
// periodically so the wait stays legible without touching the timeout budget.
|
|
429
|
+
const startedAt = Date.now();
|
|
430
|
+
const progressTicker = setInterval(() => {
|
|
431
|
+
onStatus?.({
|
|
432
|
+
type: "info",
|
|
433
|
+
message: `${config.name} still downloading... ${Math.round((Date.now() - startedAt) / 1000)}s elapsed`,
|
|
434
|
+
});
|
|
435
|
+
}, DOWNLOAD_PROGRESS_INTERVAL_MS);
|
|
415
436
|
try {
|
|
416
437
|
const path = await downloadTool(tool);
|
|
417
438
|
onStatus?.({ type: "info", message: `${config.name} installed to ${path}` });
|
|
@@ -433,5 +454,8 @@ export async function ensureTool(tool, onStatus) {
|
|
|
433
454
|
});
|
|
434
455
|
return undefined;
|
|
435
456
|
}
|
|
457
|
+
finally {
|
|
458
|
+
clearInterval(progressTicker);
|
|
459
|
+
}
|
|
436
460
|
}
|
|
437
461
|
//# sourceMappingURL=tools-manager.js.map
|