subharness 0.0.9 → 0.0.10

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.
Files changed (72) hide show
  1. package/README.md +25 -6
  2. package/dist/cli/args.d.ts +3 -0
  3. package/dist/cli/args.js +46 -12
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/cli/catalog-worker.js +3 -2
  6. package/dist/cli/catalog-worker.js.map +1 -1
  7. package/dist/cli/extensions.d.ts +1 -0
  8. package/dist/cli/extensions.js +10 -4
  9. package/dist/cli/extensions.js.map +1 -1
  10. package/dist/cli/help.js +20 -13
  11. package/dist/cli/help.js.map +1 -1
  12. package/dist/cli/main.js +48 -10
  13. package/dist/cli/main.js.map +1 -1
  14. package/dist/cli/output.js +4 -1
  15. package/dist/cli/output.js.map +1 -1
  16. package/dist/config/access.d.ts +2 -1
  17. package/dist/config/access.js +18 -7
  18. package/dist/config/access.js.map +1 -1
  19. package/dist/config/loader.d.ts +2 -0
  20. package/dist/config/loader.js +20 -6
  21. package/dist/config/loader.js.map +1 -1
  22. package/dist/config/project-context.d.ts +9 -0
  23. package/dist/config/project-context.js +41 -0
  24. package/dist/config/project-context.js.map +1 -0
  25. package/dist/config/resolve-access.d.ts +2 -1
  26. package/dist/config/resolve-access.js +5 -2
  27. package/dist/config/resolve-access.js.map +1 -1
  28. package/dist/extensions/catalog.d.ts +1 -0
  29. package/dist/extensions/catalog.js +4 -2
  30. package/dist/extensions/catalog.js.map +1 -1
  31. package/dist/runtime/capture.d.ts +4 -4
  32. package/dist/runtime/capture.js +14 -2
  33. package/dist/runtime/capture.js.map +1 -1
  34. package/dist/runtime/catalog.d.ts +6 -1
  35. package/dist/runtime/catalog.js +1 -1
  36. package/dist/runtime/catalog.js.map +1 -1
  37. package/dist/runtime/coordinator.d.ts +1 -0
  38. package/dist/runtime/coordinator.js +2 -1
  39. package/dist/runtime/coordinator.js.map +1 -1
  40. package/dist/runtime/definition.d.ts +1 -1
  41. package/dist/runtime/definition.js +2 -2
  42. package/dist/runtime/definition.js.map +1 -1
  43. package/dist/runtime/extension-service.d.ts +1 -1
  44. package/dist/runtime/extension-service.js.map +1 -1
  45. package/dist/runtime/extension-supervisor.d.ts +1 -1
  46. package/dist/runtime/extension-supervisor.js +6 -3
  47. package/dist/runtime/extension-supervisor.js.map +1 -1
  48. package/dist/runtime/select-native.d.ts +2 -1
  49. package/dist/runtime/select-native.js +7 -4
  50. package/dist/runtime/select-native.js.map +1 -1
  51. package/dist/runtime/service.js +35 -11
  52. package/dist/runtime/service.js.map +1 -1
  53. package/dist/runtime/state.d.ts +1 -1
  54. package/dist/runtime/state.js.map +1 -1
  55. package/dist/runtime/types.d.ts +2 -0
  56. package/dist/runtime/types.js.map +1 -1
  57. package/dist/runtime/worker-server.js +3 -3
  58. package/dist/runtime/worker-server.js.map +1 -1
  59. package/package.json +1 -1
  60. package/sdk/access-config.md +9 -7
  61. package/sdk/agent-skill.md +5 -3
  62. package/sdk/cli/extensions.md +10 -10
  63. package/sdk/cli/index.md +30 -14
  64. package/sdk/cli/output.md +1 -1
  65. package/sdk/config.md +39 -14
  66. package/sdk/diagnostics.md +2 -2
  67. package/sdk/execution.md +7 -4
  68. package/sdk/extensions.md +17 -9
  69. package/sdk/index.md +1 -0
  70. package/sdk/plugins/sub-agents.md +3 -1
  71. package/sdk/project-root.md +97 -0
  72. package/sdk/v1-runtime.md +9 -5
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sourceRoot":"","sources":["../../src/config/loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,U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;YACpJ,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAC3B,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,GAAG,KAAK,IAAI,UAAU,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QAC3I,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { readdir } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { tsImport } from \"tsx/esm/api\";\nimport { AgentError } from \"../errors.js\";\nimport { agent } from \"../sdk/definitions.js\";\nimport type { AgentDefinition } from \"../sdk/types.js\";\nimport { resolveProject } from \"./project.js\";\n\nexport interface CatalogEntry {\n id: string;\n name: string;\n description: string;\n scope: \"repo\" | \"global\";\n file: string;\n definition: AgentDefinition;\n}\n\n// Only fixed SDK diagnostics may cross the module-evaluation boundary.\n// User exceptions can contain credential values, including exceptions named AgentError.\nconst safeDiagnostics = new Set([\n \"Expected a configuration object.\", \"Unknown configuration field.\",\n \"Names must start with a letter and contain at most 64 letters, digits, underscores, or hyphens.\",\n \"fast must be a boolean.\", \"Unsupported harness kind.\", \"At least one harness is required.\",\n \"Claude effort must be low, medium, high, xhigh, or max.\",\n \"Cursor sandboxMode must be enabled or disabled.\",\n \"Subagent definitions cannot contain recursive references.\",\n \"Tools require a Zod 4 object schema.\", \"Tool execute must be a function.\",\n \"Tool input schema cannot be represented as JSON Schema.\",\n ...[\"Model\", \"Effort\", \"Description\", \"Instructions\", \"Tool description\"].map(label => `${label} must be a nonempty string.`),\n]);\n\nexport async function loadDefinition(file: string, subagents: string[] = []): Promise<AgentDefinition> {\n let definition: AgentDefinition;\n try {\n const url = pathToFileURL(resolve(file));\n url.searchParams.set(\"load\", crypto.randomUUID());\n const loaded = await tsImport(url.href, import.meta.url);\n const exported = loaded.default?.__esModule ? loaded.default.default : loaded.default;\n definition = agent(exported);\n } catch (error) {\n const reason = error instanceof Error && safeDiagnostics.has(error.message)\n && (error as AgentError).code === \"INVALID_DEFINITION\" ? error.message\n : \"Definition could not be loaded. Check its imports, dependencies, and module initialization.\";\n throw new AgentError(\"INVALID_DEFINITION\", `${file}: ${reason}`);\n }\n for (const name of subagents) {\n const children = definition.subagents ?? {};\n const child = Object.hasOwn(children, name) ? children[name] : undefined;\n if (!child) throw new AgentError(\"INVALID_DEFINITION\", `${file}: Subagent '${name}' is not declared.`);\n definition = child;\n }\n return definition;\n}\n\nasync function files(directory: string): Promise<string[]> {\n let entries;\n try { entries = await readdir(directory, { withFileTypes: true }); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw new AgentError(\"INVALID_CONFIG\", `Cannot read agent directory: ${directory}`);\n }\n const found: string[] = [];\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n const file = join(directory, entry.name);\n if (entry.isDirectory()) found.push(...await files(file));\n else if (entry.isFile() && entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".d.ts\")) found.push(file);\n }\n return found;\n}\n\nexport async function discover(cwd: string, options: { home?: string } = {}): Promise<CatalogEntry[]> {\n const { root } = await resolveProject(cwd);\n const entries: CatalogEntry[] = [];\n for (const [scope, base] of [[\"repo\", root], [\"global\", options.home ?? homedir()]] as const) {\n const names = new Set<string>();\n for (const file of await files(join(base, \".subharness\", \"agents\"))) {\n const definition = await loadDefinition(file);\n if (names.has(definition.name)) throw new AgentError(\"INVALID_DEFINITION\", `${file}: Duplicate agent name '${definition.name}' in ${scope} scope.`);\n names.add(definition.name);\n entries.push({ id: `${scope}:${definition.name}`, name: definition.name, description: definition.description, scope, file, definition });\n }\n }\n return entries;\n}\n"]}
1
+ {"version":3,"file":"loader.js","sourceRoot":"","sources":["../../src/config/loader.ts"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AE,UAAU,CAAC,WAAW,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QAC3I,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { readdir, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { tsImport } from \"tsx/esm/api\";\nimport { AgentError } from \"../errors.js\";\nimport { agent } from \"../sdk/definitions.js\";\nimport type { AgentDefinition } from \"../sdk/types.js\";\nimport { quoteDiagnosticPath } from \"./access-provenance.js\";\nimport { resolveProject } from \"./project.js\";\nimport type { ProjectSelection } from \"./project-context.js\";\n\nexport interface CatalogEntry {\n id: string;\n name: string;\n description: string;\n scope: \"repo\" | \"global\";\n file: string;\n definition: AgentDefinition;\n}\n\n// Only fixed SDK diagnostics may cross the module-evaluation boundary.\n// User exceptions can contain credential values, including exceptions named AgentError.\nconst safeDiagnostics = new Set([\n \"Expected a configuration object.\", \"Unknown configuration field.\",\n \"Names must start with a letter and contain at most 64 letters, digits, underscores, or hyphens.\",\n \"fast must be a boolean.\", \"Unsupported harness kind.\", \"At least one harness is required.\",\n \"Claude effort must be low, medium, high, xhigh, or max.\",\n \"Cursor sandboxMode must be enabled or disabled.\",\n \"Subagent definitions cannot contain recursive references.\",\n \"Tools require a Zod 4 object schema.\", \"Tool execute must be a function.\",\n \"Tool input schema cannot be represented as JSON Schema.\",\n ...[\"Model\", \"Effort\", \"Description\", \"Instructions\", \"Tool description\"].map(label => `${label} must be a nonempty string.`),\n]);\n\nexport async function loadDefinition(file: string, subagents: string[] = []): Promise<AgentDefinition> {\n await assertDefinitionFile(file);\n let definition: AgentDefinition;\n try {\n const url = pathToFileURL(resolve(file));\n url.searchParams.set(\"load\", crypto.randomUUID());\n const loaded = await tsImport(url.href, import.meta.url);\n const exported = loaded.default?.__esModule ? loaded.default.default : loaded.default;\n definition = agent(exported);\n } catch (error) {\n const reason = error instanceof Error && safeDiagnostics.has(error.message)\n && (error as AgentError).code === \"INVALID_DEFINITION\" ? error.message\n : \"Definition could not be loaded. Check its imports, dependencies, and module initialization.\";\n throw new AgentError(\"INVALID_DEFINITION\", `${quoteDiagnosticPath(file)}: ${reason}`);\n }\n for (const name of subagents) {\n const children = definition.subagents ?? {};\n const child = Object.hasOwn(children, name) ? children[name] : undefined;\n if (!child) throw new AgentError(\"INVALID_DEFINITION\", `${quoteDiagnosticPath(file)}: Subagent '${name}' is not declared.`);\n definition = child;\n }\n return definition;\n}\n\nasync function assertDefinitionFile(file: string): Promise<void> {\n let regular = false;\n if (file.endsWith(\".ts\") && !file.endsWith(\".d.ts\")) {\n try { regular = (await stat(file)).isFile(); } catch {}\n }\n if (!regular) {\n throw new AgentError(\n \"INVALID_DEFINITION\",\n `${quoteDiagnosticPath(file)}: Definition target must be an accessible regular .ts file, excluding .d.ts declarations.`,\n );\n }\n}\n\nasync function files(directory: string): Promise<string[]> {\n let entries;\n try { entries = await readdir(directory, { withFileTypes: true }); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw new AgentError(\"INVALID_CONFIG\", `Cannot read agent directory: ${quoteDiagnosticPath(directory)}`);\n }\n const found: string[] = [];\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n const file = join(directory, entry.name);\n if (entry.isDirectory()) found.push(...await files(file));\n else if (entry.isFile() && entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".d.ts\")) found.push(file);\n }\n return found;\n}\n\nexport async function discover(cwd: string, options: { home?: string; project?: ProjectSelection } = {}): Promise<CatalogEntry[]> {\n const root = options.project?.root ?? (await resolveProject(cwd)).root;\n const entries: CatalogEntry[] = [];\n for (const [scope, base] of [[\"repo\", root], [\"global\", options.home ?? homedir()]] as const) {\n const names = new Set<string>();\n for (const file of await files(join(base, \".subharness\", \"agents\"))) {\n const definition = await loadDefinition(file);\n if (names.has(definition.name)) throw new AgentError(\"INVALID_DEFINITION\", `${quoteDiagnosticPath(file)}: Duplicate agent name '${definition.name}' in ${scope} scope.`);\n names.add(definition.name);\n entries.push({ id: `${scope}:${definition.name}`, name: definition.name, description: definition.description, scope, file, definition });\n }\n }\n return entries;\n}\n"]}
@@ -0,0 +1,9 @@
1
+ export interface ProjectSelection {
2
+ readonly root: string;
3
+ }
4
+ export interface SelectedProject extends ProjectSelection {
5
+ readonly accessRoot: string;
6
+ }
7
+ export declare function canonicalProjectRoot(requested: string): Promise<ProjectSelection>;
8
+ export declare function retainSelectedProject(selection: ProjectSelection): Promise<SelectedProject>;
9
+ export declare function validateAccessRoot(project: SelectedProject): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import { realpath, stat } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
3
+ import { AgentError } from '../errors.js';
4
+ import { quoteDiagnosticPath } from './access-provenance.js';
5
+ import { resolveProject } from './project.js';
6
+ export async function canonicalProjectRoot(requested) {
7
+ if (typeof requested !== 'string' || !requested.trim()) {
8
+ throw new AgentError('INVALID_ARGUMENT', '--root requires a nonempty directory.');
9
+ }
10
+ let root;
11
+ try {
12
+ root = await realpath(requested);
13
+ if (!(await stat(root)).isDirectory())
14
+ throw new Error();
15
+ }
16
+ catch {
17
+ throw new AgentError('INVALID_CONFIG', `Project root is not an accessible directory: ${quoteDiagnosticPath(requested)}`);
18
+ }
19
+ return { root };
20
+ }
21
+ export async function retainSelectedProject(selection) {
22
+ if (!isAbsolute(selection.root))
23
+ throw new AgentError('INVALID_ARGUMENT', 'Project root must be an absolute directory.');
24
+ const project = await resolveProject(selection.root);
25
+ const appPath = relative(project.root, selection.root);
26
+ if (appPath === '..' || appPath.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`)) {
27
+ throw new AgentError('INVALID_CONFIG', 'The selected project root is outside its containing worktree.');
28
+ }
29
+ return { root: selection.root, accessRoot: resolve(project.mainRoot, appPath) };
30
+ }
31
+ export async function validateAccessRoot(project) {
32
+ try {
33
+ const actual = await realpath(project.accessRoot);
34
+ if (actual !== resolve(project.accessRoot) || !(await stat(actual)).isDirectory())
35
+ throw new Error();
36
+ }
37
+ catch {
38
+ throw new AgentError('INVALID_CONFIG', `The selected project's personal-access counterpart is not an accessible canonical directory: ${quoteDiagnosticPath(project.accessRoot)}`);
39
+ }
40
+ }
41
+ //# sourceMappingURL=project-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-context.js","sourceRoot":"","sources":["../../src/config/project-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAU9C,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,SAAiB;IAC1D,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,CAAC;QACvD,MAAM,IAAI,UAAU,CAAC,kBAAkB,EAAE,uCAAuC,CAAC,CAAC;IACpF,CAAC;IACD,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAC,MAAM,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC/B,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE;YAAE,MAAM,IAAI,KAAK,EAAE,CAAC;IAC3D,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,UAAU,CAAC,gBAAgB,EAAE,gDAAgD,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAC3H,CAAC;IACD,OAAO,EAAC,IAAI,EAAC,CAAC;AAChB,CAAC;AAED,MA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ute, relative, resolve } from 'node:path';\nimport { AgentError } from '../errors.js';\nimport { quoteDiagnosticPath } from './access-provenance.js';\nimport { resolveProject } from './project.js';\n\nexport interface ProjectSelection {\n readonly root: string;\n}\n\nexport interface SelectedProject extends ProjectSelection {\n readonly accessRoot: string;\n}\n\nexport async function canonicalProjectRoot(requested: string): Promise<ProjectSelection> {\n if (typeof requested !== 'string' || !requested.trim()) {\n throw new AgentError('INVALID_ARGUMENT', '--root requires a nonempty directory.');\n }\n let root: string;\n try {\n root=await realpath(requested);\n if (!(await stat(root)).isDirectory()) throw new Error();\n } catch {\n throw new AgentError('INVALID_CONFIG', `Project root is not an accessible directory: ${quoteDiagnosticPath(requested)}`);\n }\n return {root};\n}\n\nexport async function retainSelectedProject(selection: ProjectSelection): Promise<SelectedProject> {\n if (!isAbsolute(selection.root)) throw new AgentError('INVALID_ARGUMENT','Project root must be an absolute directory.');\n const project=await resolveProject(selection.root);\n const appPath=relative(project.root,selection.root);\n if (appPath === '..' || appPath.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new AgentError('INVALID_CONFIG','The selected project root is outside its containing worktree.');\n }\n return {root:selection.root,accessRoot:resolve(project.mainRoot,appPath)};\n}\n\nexport async function validateAccessRoot(project: SelectedProject): Promise<void> {\n try {\n const actual=await realpath(project.accessRoot);\n if (actual !== resolve(project.accessRoot) || !(await stat(actual)).isDirectory()) throw new Error();\n } catch {\n throw new AgentError('INVALID_CONFIG',\n `The selected project's personal-access counterpart is not an accessible canonical directory: ${quoteDiagnosticPath(project.accessRoot)}`);\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { ResolvedAccess } from "../adapters/types.js";
2
2
  import type { HarnessConfig, HarnessKind } from "../sdk/types.js";
3
3
  import { type AccessConnection } from "./access.js";
4
- export declare function resolveAccess(connection: AccessConnection, harness: HarnessKind | HarnessConfig, cwd: string, env?: NodeJS.ProcessEnv): Promise<ResolvedAccess>;
4
+ import { type SelectedProject } from "./project-context.js";
5
+ export declare function resolveAccess(connection: AccessConnection, harness: HarnessKind | HarnessConfig, cwd: string, env?: NodeJS.ProcessEnv, project?: SelectedProject): Promise<ResolvedAccess>;
@@ -6,7 +6,8 @@ import { configError, parseConnection } from "./access.js";
6
6
  import { quoteDiagnosticPath } from "./access-provenance.js";
7
7
  import { resolveProject } from "./project.js";
8
8
  import { validateOidc } from "./oidc.js";
9
- export async function resolveAccess(connection, harness, cwd, env = process.env) {
9
+ import { validateAccessRoot } from "./project-context.js";
10
+ export async function resolveAccess(connection, harness, cwd, env = process.env, project) {
10
11
  const kind = typeof harness === "string" ? harness : harness.kind;
11
12
  parseConnection(connection, kind);
12
13
  if (connection.type === "subscription") {
@@ -15,7 +16,9 @@ export async function resolveAccess(connection, harness, cwd, env = process.env)
15
16
  const variable = connection.env ?? (connection.type === "api-key"
16
17
  ? defaultApiKeyVariable(kind, connection.provider)
17
18
  : connection.type === "vercel-api-key" ? "AI_GATEWAY_API_KEY" : "VERCEL_OIDC_TOKEN");
18
- const { mainRoot } = await resolveProject(cwd);
19
+ if (project)
20
+ await validateAccessRoot(project);
21
+ const mainRoot = project?.accessRoot ?? (await resolveProject(cwd)).mainRoot;
19
22
  let token;
20
23
  if (connection.envFile !== undefined) {
21
24
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-access.js","sourceRoot":"","sources":["../../src/config/resolve-access.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,OAAO,EAAyB,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AA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;QAAE,OAAO,mBAAmB,CAAC;IACtD,OAAO,WAAW,CAAC,GAAG,IAAI,+BAA+B,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { parseEnv } from \"node:util\";\nimport type { ResolvedAccess } from \"../adapters/types.js\";\nimport { AgentError } from \"../errors.js\";\nimport type { HarnessConfig, HarnessKind } from \"../sdk/types.js\";\nimport { type AccessConnection, configError, parseConnection } from \"./access.js\";\nimport { quoteDiagnosticPath } from \"./access-provenance.js\";\nimport { resolveProject } from \"./project.js\";\nimport { validateOidc } from \"./oidc.js\";\n\nexport async function resolveAccess(\n connection: AccessConnection,\n harness: HarnessKind | HarnessConfig,\n cwd: string,\n env: NodeJS.ProcessEnv = process.env,\n): Promise<ResolvedAccess> {\n const kind = typeof harness === \"string\" ? harness : harness.kind;\n parseConnection(connection, kind);\n if (connection.type === \"subscription\") {\n return { ...connection };\n }\n const variable = connection.env ?? (connection.type === \"api-key\"\n ? defaultApiKeyVariable(kind, connection.provider)\n : connection.type === \"vercel-api-key\" ? \"AI_GATEWAY_API_KEY\" : \"VERCEL_OIDC_TOKEN\");\n const { mainRoot } = await resolveProject(cwd);\n let token: string | undefined;\n if (connection.envFile !== undefined) {\n try { token = parseEnv(await readFile(resolve(mainRoot, connection.envFile), \"utf8\"))[variable]; }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") throw new AgentError(\"ACCESS_UNAVAILABLE\", `Credential file is missing: ${quoteDiagnosticPath(connection.envFile)}`);\n configError(`Cannot read credential variable ${variable} from its configured file.`);\n }\n } else token = env[variable];\n if (!token?.trim()) throw new AgentError(\"ACCESS_UNAVAILABLE\", `Credential variable ${variable} is missing or empty.`);\n if (connection.type === \"vercel-oidc\") await validateOidc(token, mainRoot, connection.project, env);\n const access: ResolvedAccess = { type: connection.type, token };\n if (connection.type === \"api-key\") {\n for (const field of [\"provider\", \"baseUrl\", \"wireApi\", \"apiVersion\", \"wireModel\"] as const) {\n if (connection[field] !== undefined) Object.assign(access, { [field]: connection[field] });\n }\n }\n return access;\n}\n\nfunction defaultApiKeyVariable(kind: HarnessKind, provider?: string): string {\n if (kind === \"copilot\") return ({ github: \"COPILOT_GITHUB_TOKEN\", openai: \"OPENAI_API_KEY\", anthropic: \"ANTHROPIC_API_KEY\", azure: \"AZURE_OPENAI_API_KEY\" })[provider as \"github\" | \"openai\" | \"anthropic\" | \"azure\"];\n if (kind === \"codex\") return \"OPENAI_API_KEY\";\n if (kind === \"cursor\") return \"CURSOR_API_KEY\";\n if (kind === \"claudeCode\") return \"ANTHROPIC_API_KEY\";\n return configError(`${kind} direct API keys require env.`);\n}\n"]}
1
+ {"version":3,"file":"resolve-access.js","sourceRoot":"","sources":["../../src/config/resolve-access.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,OAAO,EAAyB,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAwB,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAEhF,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,UAA4B,EAC5B,OAAoC,EACpC,GAAW,EACX,GAAG,GAAsB,OAAO,CAAC,GAAG,EACpC,OAAyB;IAEzB,MAAM,IAAI,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;IAClE,eAAe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,CAAC,oBAAoB,EAAE,uBAAuB,QAAQ,uBAAuB,CAAC,CAAC;IACvH,IAAI,UAAU,CAAC,IAAI,KAAK,aAAa;QAAE,MAAM,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IACpG,MAAM,MAAM,GAAmB,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC;IAChE,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAClC,KAAK,MAAM,KAAK,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,CAAU,EAAE,CAAC;YAC3F,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,SAAS;gBAAE,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,qBAAqB,CAAC,IAAiB,EAAE,QAAiB;IACjE,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,sBAAsB,EAAE,MAAM,EAAE,gBAAgB,EAAE,SAAS,EAAE,mBAAmB,EAAE,KAAK,EAAE,sBAAsB,EAAE,CAAC,CAAC,QAAuD,CAAC,CAAC;IACtN,IAAI,IAAI,KAAK,OAAO;QAAE,OAAO,gBAAgB,CAAC;IAC9C,IAAI,IAAI,KAAK,QAAQ;QAAE,OAAO,gBAAgB,CAAC;IAC/C,IAAI,IAAI,KAAK,YAAY;QAAE,OAAO,mBAAmB,CAAC;IACtD,OAAO,WAAW,CAAC,GAAG,IAAI,+BAA+B,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { parseEnv } from \"node:util\";\nimport type { ResolvedAccess } from \"../adapters/types.js\";\nimport { AgentError } from \"../errors.js\";\nimport type { HarnessConfig, HarnessKind } from \"../sdk/types.js\";\nimport { type AccessConnection, configError, parseConnection } from \"./access.js\";\nimport { quoteDiagnosticPath } from \"./access-provenance.js\";\nimport { resolveProject } from \"./project.js\";\nimport { validateOidc } from \"./oidc.js\";\nimport { type SelectedProject, validateAccessRoot } from \"./project-context.js\";\n\nexport async function resolveAccess(\n connection: AccessConnection,\n harness: HarnessKind | HarnessConfig,\n cwd: string,\n env: NodeJS.ProcessEnv = process.env,\n project?: SelectedProject,\n): Promise<ResolvedAccess> {\n const kind = typeof harness === \"string\" ? harness : harness.kind;\n parseConnection(connection, kind);\n if (connection.type === \"subscription\") {\n return { ...connection };\n }\n const variable = connection.env ?? (connection.type === \"api-key\"\n ? defaultApiKeyVariable(kind, connection.provider)\n : connection.type === \"vercel-api-key\" ? \"AI_GATEWAY_API_KEY\" : \"VERCEL_OIDC_TOKEN\");\n if(project)await validateAccessRoot(project);\n const mainRoot = project?.accessRoot ?? (await resolveProject(cwd)).mainRoot;\n let token: string | undefined;\n if (connection.envFile !== undefined) {\n try { token = parseEnv(await readFile(resolve(mainRoot, connection.envFile), \"utf8\"))[variable]; }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") throw new AgentError(\"ACCESS_UNAVAILABLE\", `Credential file is missing: ${quoteDiagnosticPath(connection.envFile)}`);\n configError(`Cannot read credential variable ${variable} from its configured file.`);\n }\n } else token = env[variable];\n if (!token?.trim()) throw new AgentError(\"ACCESS_UNAVAILABLE\", `Credential variable ${variable} is missing or empty.`);\n if (connection.type === \"vercel-oidc\") await validateOidc(token, mainRoot, connection.project, env);\n const access: ResolvedAccess = { type: connection.type, token };\n if (connection.type === \"api-key\") {\n for (const field of [\"provider\", \"baseUrl\", \"wireApi\", \"apiVersion\", \"wireModel\"] as const) {\n if (connection[field] !== undefined) Object.assign(access, { [field]: connection[field] });\n }\n }\n return access;\n}\n\nfunction defaultApiKeyVariable(kind: HarnessKind, provider?: string): string {\n if (kind === \"copilot\") return ({ github: \"COPILOT_GITHUB_TOKEN\", openai: \"OPENAI_API_KEY\", anthropic: \"ANTHROPIC_API_KEY\", azure: \"AZURE_OPENAI_API_KEY\" })[provider as \"github\" | \"openai\" | \"anthropic\" | \"azure\"];\n if (kind === \"codex\") return \"OPENAI_API_KEY\";\n if (kind === \"cursor\") return \"CURSOR_API_KEY\";\n if (kind === \"claudeCode\") return \"ANTHROPIC_API_KEY\";\n return configError(`${kind} direct API keys require env.`);\n}\n"]}
@@ -28,6 +28,7 @@ export interface ExtensionCatalog {
28
28
  }
29
29
  export interface ExtensionCatalogOptions {
30
30
  readonly homeDirectory?: string;
31
+ readonly projectRoot?: string;
31
32
  }
32
33
  export declare function discoverExtensionCatalog(cwd: string, options?: ExtensionCatalogOptions): Promise<ExtensionCatalog>;
33
34
  export declare function resolveExtensionInstallation(cwd: string, reference: string, options?: ExtensionCatalogOptions): Promise<ValidExtensionCatalogEntry>;
@@ -7,7 +7,7 @@ import { resolveProject } from "../config/project.js";
7
7
  import { validateExtensionInstallation } from "./manifest.js";
8
8
  import { extensionIdentity, parseExtensionReference } from "./identity.js";
9
9
  export async function discoverExtensionCatalog(cwd, options = {}) {
10
- const workspace = (await resolveProject(cwd)).root;
10
+ const workspace = options.projectRoot ?? (await resolveProject(cwd)).root;
11
11
  const home = await canonicalHome(options.homeDirectory ?? homedir());
12
12
  const installations = [
13
13
  ...await discoverScope("global", join(home, ".subharness", "extensions"), workspace),
@@ -17,7 +17,9 @@ export async function discoverExtensionCatalog(cwd, options = {}) {
17
17
  }
18
18
  export async function resolveExtensionInstallation(cwd, reference, options = {}) {
19
19
  const parsed = parseExtensionReference(reference);
20
- const workspace = parsed.scope === "repo" ? (await resolveProject(cwd)).root : undefined;
20
+ const workspace = parsed.scope === "repo"
21
+ ? options.projectRoot ?? (await resolveProject(cwd)).root
22
+ : undefined;
21
23
  const base = parsed.scope === "global"
22
24
  ? await canonicalHome(options.homeDirectory ?? homedir())
23
25
  : workspace;
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/extensions/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,6BAA6B,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAiC3E,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,GAAW,EACX,OAAO,GAA4B,EAAE;IAErC,MAAM,SAAS,GAAG,CAAC,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;IACnD,MAAM,IAAI,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,aAAa,IAAI,OAAO,EAAE,CAAC,CAAC;IACrE,MAAM,aAAa,GAAG;QACpB,GAAG,MAAM,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,YAAY,CAAC,EAAE,SAAS,CAAC;QACpF,GAAG,MAAM,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,aAAa,EAAE,YAAY,CAAC,EAAE,SAAS,CAAC;KACxF,CAAC;IACF,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC;AACtC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,GAAW,EACX,SAAiB,EACjB,OAAO,GAA4B,EAAE;IAErC,MAAM,MAA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S,CAAC,SAAS;gBAC9B,QAAQ,EAAE,SAAS,CAAC,QAAQ;aAC7B,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,wBAAwB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,MAAM,KAAK,CAAC;YACzH,MAAM,CAAC,IAAI,CAAC;gBACV,MAAM,EAAE,KAAK,CAAC,IAAI,KAAK,wBAAwB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS;gBAC5E,KAAK;gBACL,EAAE,EAAE,KAAK,CAAC,IAAI;gBACd,SAAS;gBACT,SAAS;gBACT,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;aACpD,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,SAAiB;IAC5C,IAAI,CAAC;QAAC,OAAO,MAAM,QAAQ,CAAC,SAAS,CAAC,CAAC;IAAC,CAAC;IACzC,MAAM,CAAC;QAAC,MAAM,IAAI,UAAU,CAAC,4BAA4B,EAAE,yCAAyC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC;AAC1I,CAAC","sourcesContent":["import { lstat, readdir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { AgentError } from \"../errors.js\";\nimport { quoteDiagnosticPath } from \"../config/access-provenance.js\";\nimport { resolveProject } from \"../config/project.js\";\nimport type { ExtensionIdentity } from \"../runtime/extension-protocol.js\";\nimport type { ExtensionManifest } from \"./types.js\";\nimport { validateExtensionInstallation } from \"./manifest.js\";\nimport { extensionIdentity, parseExtensionReference } from \"./identity.js\";\n\nexport interface ValidExtensionCatalogEntry {\n readonly status: \"valid\";\n readonly scope: \"global\" | \"repo\";\n readonly id: string;\n readonly reference: string;\n readonly identity: ExtensionIdentity;\n readonly directory: string;\n readonly entryPath: string;\n readonly manifest: ExtensionManifest;\n}\n\nexport interface InvalidExtensionCatalogEntry {\n readonly status: \"invalid\" | \"incompatible\";\n readonly scope: \"global\" | \"repo\";\n readonly id: string;\n readonly reference: string;\n readonly directory: string;\n readonly error: { readonly code: string; readonly message: string };\n}\n\nexport type ExtensionCatalogEntry = ValidExtensionCatalogEntry | InvalidExtensionCatalogEntry;\n\nexport interface ExtensionCatalog {\n readonly workspace: string;\n readonly installations: readonly ExtensionCatalogEntry[];\n}\n\nexport interface ExtensionCatalogOptions {\n readonly homeDirectory?: string;\n}\n\nexport async function discoverExtensionCatalog(\n cwd: string,\n options: ExtensionCatalogOptions = {},\n): Promise<ExtensionCatalog> {\n const workspace = (await resolveProject(cwd)).root;\n const home = await canonicalHome(options.homeDirectory ?? homedir());\n const installations = [\n ...await discoverScope(\"global\", join(home, \".subharness\", \"extensions\"), workspace),\n ...await discoverScope(\"repo\", join(workspace, \".subharness\", \"extensions\"), workspace),\n ];\n return { workspace, installations };\n}\n\nexport async function resolveExtensionInstallation(\n cwd: string,\n reference: string,\n options: ExtensionCatalogOptions = {},\n): Promise<ValidExtensionCatalogEntry> {\n const parsed = parseExtensionReference(reference);\n const workspace = parsed.scope === \"repo\" ? (await resolveProject(cwd)).root : undefined;\n const base = parsed.scope === \"global\"\n ? await canonicalHome(options.homeDirectory ?? homedir())\n : workspace!;\n const directory = join(base, \".subharness\", \"extensions\", parsed.id);\n try { await lstat(directory); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new AgentError(\"UNKNOWN_EXTENSION\", `No ${reference} installation exists in the selected scope.`);\n }\n throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Extension installation could not be accessed. ${quoteDiagnosticPath(directory)}`);\n }\n const validated = await validateExtensionInstallation(directory);\n return {\n status: \"valid\",\n scope: parsed.scope,\n id: parsed.id,\n reference,\n identity: extensionIdentity(reference, workspace),\n directory: validated.directory,\n entryPath: validated.entryPath,\n manifest: validated.manifest,\n };\n}\n\nasync function discoverScope(\n scope: \"global\" | \"repo\",\n root: string,\n workspace: string,\n): Promise<ExtensionCatalogEntry[]> {\n let entries;\n try { entries = await readdir(root, { withFileTypes: true }); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Extension directory could not be read. ${quoteDiagnosticPath(root)}`);\n }\n const result: ExtensionCatalogEntry[] = [];\n for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n const directory = join(root, entry.name);\n const reference = `${scope}:${entry.name}`;\n try {\n const validated = await validateExtensionInstallation(directory);\n const identity: ExtensionIdentity = scope === \"global\"\n ? { reference }\n : { reference, workspace };\n result.push({\n status: \"valid\",\n scope,\n id: entry.name,\n reference,\n identity,\n directory: validated.directory,\n entryPath: validated.entryPath,\n manifest: validated.manifest,\n });\n } catch (error) {\n if (!(error instanceof AgentError) || ![\"INVALID_EXTENSION\", \"EXTENSION_INCOMPATIBLE\"].includes(error.code)) throw error;\n result.push({\n status: error.code === \"EXTENSION_INCOMPATIBLE\" ? \"incompatible\" : \"invalid\",\n scope,\n id: entry.name,\n reference,\n directory,\n error: { code: error.code, message: error.message },\n });\n }\n }\n return result;\n}\n\nasync function canonicalHome(directory: string): Promise<string> {\n try { return await realpath(directory); }\n catch { throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Home directory could not be accessed. ${quoteDiagnosticPath(directory)}`); }\n}\n"]}
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/extensions/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5D,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,CAAC,IAAI,CAAC,CAAC,mBAAmB,EAAE,wBAAwB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,MAAM,KAAK,CAAC;YACzH,MAAM,CAAC,IAAI,CAAC;gBACV,MAAM,EAAE,KAAK,CAAC,IAAI,KAAK,wBAAwB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS;gBAC5E,KAAK;gBACL,EAAE,EAAE,KAAK,CAAC,IAAI;gBACd,SAAS;gBACT,SAAS;gBACT,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;aACpD,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,SAAiB;IAC5C,IAAI,CAAC;QAAC,OAAO,MAAM,QAAQ,CAAC,SAAS,CAAC,CAAC;IAAC,CAAC;IACzC,MAAM,CAAC;QAAC,MAAM,IAAI,UAAU,CAAC,4BAA4B,EAAE,yCAAyC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC;AAC1I,CAAC","sourcesContent":["import { lstat, readdir, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { AgentError } from \"../errors.js\";\nimport { quoteDiagnosticPath } from \"../config/access-provenance.js\";\nimport { resolveProject } from \"../config/project.js\";\nimport type { ExtensionIdentity } from \"../runtime/extension-protocol.js\";\nimport type { ExtensionManifest } from \"./types.js\";\nimport { validateExtensionInstallation } from \"./manifest.js\";\nimport { extensionIdentity, parseExtensionReference } from \"./identity.js\";\n\nexport interface ValidExtensionCatalogEntry {\n readonly status: \"valid\";\n readonly scope: \"global\" | \"repo\";\n readonly id: string;\n readonly reference: string;\n readonly identity: ExtensionIdentity;\n readonly directory: string;\n readonly entryPath: string;\n readonly manifest: ExtensionManifest;\n}\n\nexport interface InvalidExtensionCatalogEntry {\n readonly status: \"invalid\" | \"incompatible\";\n readonly scope: \"global\" | \"repo\";\n readonly id: string;\n readonly reference: string;\n readonly directory: string;\n readonly error: { readonly code: string; readonly message: string };\n}\n\nexport type ExtensionCatalogEntry = ValidExtensionCatalogEntry | InvalidExtensionCatalogEntry;\n\nexport interface ExtensionCatalog {\n readonly workspace: string;\n readonly installations: readonly ExtensionCatalogEntry[];\n}\n\nexport interface ExtensionCatalogOptions {\n readonly homeDirectory?: string;\n readonly projectRoot?: string;\n}\n\nexport async function discoverExtensionCatalog(\n cwd: string,\n options: ExtensionCatalogOptions = {},\n): Promise<ExtensionCatalog> {\n const workspace = options.projectRoot ?? (await resolveProject(cwd)).root;\n const home = await canonicalHome(options.homeDirectory ?? homedir());\n const installations = [\n ...await discoverScope(\"global\", join(home, \".subharness\", \"extensions\"), workspace),\n ...await discoverScope(\"repo\", join(workspace, \".subharness\", \"extensions\"), workspace),\n ];\n return { workspace, installations };\n}\n\nexport async function resolveExtensionInstallation(\n cwd: string,\n reference: string,\n options: ExtensionCatalogOptions = {},\n): Promise<ValidExtensionCatalogEntry> {\n const parsed = parseExtensionReference(reference);\n const workspace = parsed.scope === \"repo\"\n ? options.projectRoot ?? (await resolveProject(cwd)).root\n : undefined;\n const base = parsed.scope === \"global\"\n ? await canonicalHome(options.homeDirectory ?? homedir())\n : workspace!;\n const directory = join(base, \".subharness\", \"extensions\", parsed.id);\n try { await lstat(directory); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new AgentError(\"UNKNOWN_EXTENSION\", `No ${reference} installation exists in the selected scope.`);\n }\n throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Extension installation could not be accessed. ${quoteDiagnosticPath(directory)}`);\n }\n const validated = await validateExtensionInstallation(directory);\n return {\n status: \"valid\",\n scope: parsed.scope,\n id: parsed.id,\n reference,\n identity: extensionIdentity(reference, workspace),\n directory: validated.directory,\n entryPath: validated.entryPath,\n manifest: validated.manifest,\n };\n}\n\nasync function discoverScope(\n scope: \"global\" | \"repo\",\n root: string,\n workspace: string,\n): Promise<ExtensionCatalogEntry[]> {\n let entries;\n try { entries = await readdir(root, { withFileTypes: true }); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Extension directory could not be read. ${quoteDiagnosticPath(root)}`);\n }\n const result: ExtensionCatalogEntry[] = [];\n for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n const directory = join(root, entry.name);\n const reference = `${scope}:${entry.name}`;\n try {\n const validated = await validateExtensionInstallation(directory);\n const identity: ExtensionIdentity = scope === \"global\"\n ? { reference }\n : { reference, workspace };\n result.push({\n status: \"valid\",\n scope,\n id: entry.name,\n reference,\n identity,\n directory: validated.directory,\n entryPath: validated.entryPath,\n manifest: validated.manifest,\n });\n } catch (error) {\n if (!(error instanceof AgentError) || ![\"INVALID_EXTENSION\", \"EXTENSION_INCOMPATIBLE\"].includes(error.code)) throw error;\n result.push({\n status: error.code === \"EXTENSION_INCOMPATIBLE\" ? \"incompatible\" : \"invalid\",\n scope,\n id: entry.name,\n reference,\n directory,\n error: { code: error.code, message: error.message },\n });\n }\n }\n return result;\n}\n\nasync function canonicalHome(directory: string): Promise<string> {\n try { return await realpath(directory); }\n catch { throw new AgentError(\"EXTENSION_DISCOVERY_FAILED\", `Home directory could not be accessed. ${quoteDiagnosticPath(directory)}`); }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { HarnessConfig } from '../sdk/types.js';
2
- import type { CatalogEnvironment } from './catalog.js';
2
+ import type { ExecutionEnvironment } from './catalog.js';
3
3
  import type { ExecutionReference, PreparedExecution } from './types.js';
4
4
  export interface CapturedChild {
5
5
  readonly name: string;
@@ -15,8 +15,8 @@ interface CaptureOptions {
15
15
  workerModule?: URL;
16
16
  shutdownTimeoutMs?: number;
17
17
  }
18
- export declare function captureExecution(agent: string | HarnessConfig, input: CatalogEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
18
+ export declare function captureExecution(agent: string | HarnessConfig, input: ExecutionEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
19
19
  /** Captures an already resolved private CLI reference without applying public connected validation. */
20
- export declare function captureReference(reference: ExecutionReference, input: CatalogEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
21
- export declare function checkCapturedExecution(captured: CapturedExecution, input: CatalogEnvironment): Promise<void>;
20
+ export declare function captureReference(reference: ExecutionReference, input: ExecutionEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
21
+ export declare function checkCapturedExecution(captured: CapturedExecution, input: ExecutionEnvironment): Promise<void>;
22
22
  export {};
@@ -1,6 +1,7 @@
1
1
  import { fork } from 'node:child_process';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { randomUUID } from 'node:crypto';
4
+ import { isAbsolute } from 'node:path';
4
5
  import { AgentError, errorInfo } from '../errors.js';
5
6
  import { createSessionLauncher } from './session-launcher.js';
6
7
  import { processExitDescription } from '../process-diagnostics.js';
@@ -291,7 +292,7 @@ class CaptureLease {
291
292
  }
292
293
  }
293
294
  export async function captureExecution(agent, input, options = {}) {
294
- return captureRequest(input, options, { method: 'capture', agent });
295
+ return captureRequest(input, options, { method: 'capture', agent, projectRoot: input.project?.root });
295
296
  }
296
297
  /** Captures an already resolved private CLI reference without applying public connected validation. */
297
298
  export async function captureReference(reference, input, options = {}) {
@@ -326,8 +327,10 @@ export async function checkCapturedExecution(captured, input) {
326
327
  let native;
327
328
  let failure;
328
329
  try {
330
+ const project = retainedProject(input.project);
329
331
  native = await captured.prepared.open({ reference: captured.reference, cwd: input.cwd, env: input.env,
330
- token: randomUUID(), sessionId: `check_${randomUUID()}` });
332
+ token: randomUUID(), sessionId: `check_${randomUUID()}`,
333
+ ...(project ? { project } : {}) });
331
334
  await native.close();
332
335
  }
333
336
  catch (error) {
@@ -349,4 +352,13 @@ export async function checkCapturedExecution(captured, input) {
349
352
  if (failure)
350
353
  throw failure;
351
354
  }
355
+ function retainedProject(project) {
356
+ if (project === undefined)
357
+ return undefined;
358
+ if (!project || typeof project !== 'object' || Array.isArray(project)
359
+ || typeof project.root !== 'string' || !isAbsolute(project.root)
360
+ || typeof project.accessRoot !== 'string' || !isAbsolute(project.accessRoot))
361
+ throw new AgentError('INVALID_ARGUMENT', 'Retained project context must include absolute project and access roots.');
362
+ return project;
363
+ }
352
364
  //# sourceMappingURL=capture.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/runtime/capture.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAqB,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAkB,MAAM,cAAc,CAAC;AAMrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAqBvD,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC,MAAM,eAAe;IAcU,KAAK;IAA+B,OAAO;IAbhE,MAAM,GAAC,CAAC,CAAC;IACT,OAAO,GAAC,IAAI,GAAG,EACmC,CAAC;IACnD,SAAS,GAAC,IAAI,GAAG,EAA0B,CAAC;IAC5C,QAAQ,GAAC,IAAI,GAAG,EAAoC,CAAC;IACrD,MAAM,GAAC,KAAK,CAAC;IACb,MAAM,GAAC,IAAI,GAAG,EAAU,CAAC;IACzB,eAAe,GAAC,IAAI,GAAG,EAAU,CAAC;IAClC,YAAY,GAAC,EAAE,CAAC;IACP,WAAW,CAAe;IAC1B,YAAY,CAAmB;IACxC,UAAU,CAAW;IAE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crypto';\nimport { AgentError, errorInfo, type ErrorInfo } from '../errors.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { HarnessConfig, HarnessKind } from '../sdk/types.js';\nimport type { CatalogEnvironment } from './catalog.js';\nimport type { DriverInput, ExecutionReference, ManagedNativeSession, PreparedExecution } from './types.js';\nimport type { ApprovalEvent } from './worker-approvals.js';\nimport { createSessionLauncher } from './session-launcher.js';\nimport { processExitDescription } from '../process-diagnostics.js';\nimport { WorkerEventClient } from './worker-events.js';\nimport type { Readable } from 'node:stream';\nimport type { WorkerObservationCompletion, WorkerOpenResult } from './worker-event-protocol.js';\n\nexport interface CapturedChild {\n readonly name: string;\n readonly description: string;\n}\n\nexport interface CapturedExecution {\n readonly reference: ExecutionReference;\n readonly prepared: PreparedExecution;\n readonly children: readonly CapturedChild[];\n child(name: string): Promise<CapturedExecution>;\n}\n\ninterface CaptureOptions { workerModule?: URL; shutdownTimeoutMs?: number }\ninterface CaptureResult {leaseId:number;reference:ExecutionReference;name:string;children:CapturedChild[]}\ntype WorkerReply = ApprovalEvent & {leaseId:number} | {id:number;result?:unknown;error?:ErrorInfo;\n observation?:WorkerObservationCompletion};\n\nconst shutdownTimeoutMs = 1_000;\n\nclass GraphConnection {\n private nextId=1;\n private pending=new Map<number,{operation:string;leaseId?:number;observationOperationId?:string;\n resolve(value:unknown):void;reject(error:Error):void}>();\n private approvals=new Map<string,AbortController>();\n private handlers=new Map<number,ApprovalHandler|undefined>();\n private exited=false;\n private leases=new Set<number>();\n private abandonedLeases=new Set<number>();\n private observedExit='';\n private readonly processExit:Promise<void>;\n private readonly workerEvents:WorkerEventClient;\n private markExited!:()=>void;\n\n constructor(private readonly child:ChildProcess,private readonly timeout:number) {\n this.processExit=new Promise(resolve=>{this.markExited=resolve;});\n this.workerEvents=new WorkerEventClient(child.stdio[4] as Readable,(method,data)=>this.request(method,data));\n child.once('error',()=>this.exit(undefined,undefined,true));\n child.once('exit',(code,signal)=>this.exit(code,signal));\n child.on('message',(message:WorkerReply)=>this.message(message));\n }\n\n setApprovalHandler(leaseId:number,handler:ApprovalHandler|undefined) { this.handlers.set(leaseId,handler); }\n deleteApprovalHandler(leaseId:number) { this.handlers.delete(leaseId); }\n setEventPort(leaseId:number,port:DriverInput['events']) { this.workerEvents.attach(leaseId,port); }\n deleteEventPort(leaseId:number) { this.workerEvents.detach(leaseId); }\n retainLease(leaseId:number) { this.leases.add(leaseId); }\n async releaseLease(leaseId:number) {\n this.leases.delete(leaseId);\n await this.retryAbandonedLeases();\n const retained=[...this.leases].filter(id=>!this.abandonedLeases.has(id));\n if(retained.length!==0)return;\n if(this.abandonedLeases.size){this.abandonedLeases.clear();this.leases.clear();await this.stop();return;}\n if(await this.waitWithin(this.timeout))return;\n await this.stop();\n }\n async abandonLease(leaseId:number) {\n if(!this.leases.has(leaseId))return;\n const siblings=[...this.leases].filter(id=>id!==leaseId&&!this.abandonedLeases.has(id));\n if(siblings.length){this.abandonedLeases.add(leaseId);return;}\n this.leases.delete(leaseId);\n await this.stop();\n }\n\n private async retryAbandonedLeases() {\n for(const leaseId of [...this.abandonedLeases]){\n try{\n await this.request('lease.close',{leaseId});\n this.abandonedLeases.delete(leaseId);this.leases.delete(leaseId);\n }catch{/* Retain ownership until the remaining graph leases close. */}\n }\n }\n\n request(method:string,extra:Record<string,unknown>={}):Promise<unknown> {\n return new Promise((resolve,reject)=>{\n if(this.exited){reject(new AgentError('HARNESS_FAILED',`The captured definition worker is unavailable while ${method} was pending${this.observedExit}.`));return;}\n const id=this.nextId++;\n const observationOperationId=typeof extra.observation==='object'&&extra.observation!==null\n &&typeof (extra.observation as {operationId?:unknown}).operationId==='string'\n ?(extra.observation as {operationId:string}).operationId:undefined;\n this.pending.set(id,{operation:method,leaseId:typeof extra.leaseId==='number'?extra.leaseId:undefined,\n observationOperationId,resolve,reject});\n this.child.send({id,method,...extra},error=>{\n if(!error)return;\n setImmediate(()=>{\n const waiting=this.pending.get(id);\n if(!waiting||this.exited)return;\n this.pending.delete(id);\n waiting.reject(new AgentError('HARNESS_FAILED',`Cannot reach the captured definition worker while ${method} was pending.`));\n });\n });\n });\n }\n\n private message(message:WorkerReply) {\n if(this.workerEvents.acceptControl(message))return;\n if('event' in message){\n const key=`${message.leaseId}:${message.requestId}`;\n if(message.event==='approval.withdraw'){\n this.approvals.get(key)?.abort();this.approvals.delete(key);return;\n }\n const controller=new AbortController();\n this.approvals.set(key,controller);\n void Promise.resolve().then(()=>{\n const handler=this.handlers.get(message.leaseId);\n if(!handler)throw new AgentError('INPUT_REQUIRED','Native tool approval requires an observing caller.');\n return handler(message.request,controller.signal);\n }).then(\n content=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,content});},\n error=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)});},\n ).catch(error=>{\n if(!controller.signal.aborted&&!this.exited)\n return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)}).catch(()=>{});\n }).finally(()=>this.approvals.delete(key));\n return;\n }\n const waiting=this.pending.get(message.id);\n if(!waiting)return;\n this.pending.delete(message.id);\n const operationError=message.error?new AgentError(message.error.code,message.error.message):undefined;\n void this.workerEvents.complete(waiting.leaseId!,message.observation,waiting.observationOperationId).then(()=>{\n if(operationError)waiting.reject(operationError);else waiting.resolve(message.result);\n },()=>{if(operationError)waiting.reject(operationError);else waiting.resolve(message.result);});\n }\n\n private exit(code:unknown,signal:unknown,spawnFailure=false) {\n if(this.exited)return;\n this.exited=true;\n this.observedExit=spawnFailure?'':processExitDescription(code,signal);\n for(const controller of this.approvals.values())controller.abort();\n this.approvals.clear();this.workerEvents.close();this.markExited();\n for(const waiting of this.pending.values())waiting.reject(new AgentError('HARNESS_FAILED',spawnFailure\n ?`The captured definition worker process failed while ${waiting.operation} was pending.`\n :`The captured definition worker exited while ${waiting.operation} was pending${this.observedExit}.`));\n this.pending.clear();\n }\n\n async stop() {\n if(this.exited)return;\n if(this.child.connected)try{this.child.disconnect();}catch{}\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGTERM');\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGKILL');\n if(!await this.waitWithin(this.timeout))throw new AgentError('HARNESS_FAILED','The captured definition worker did not confirm termination.');\n }\n\n run(leaseId:number,method:'turn'|'resume',extra:Record<string,unknown>={}):Promise<unknown>{\n const observation=this.workerEvents.begin(leaseId);\n return this.request(method,{leaseId,...extra,...(observation?{observation}:{})});\n }\n\n selected(leaseId:number,opened:WorkerOpenResult):void{\n this.workerEvents.metadata(leaseId,opened);\n }\n\n private waitWithin(timeout:number):Promise<boolean>{\n return new Promise(resolve=>{\n const timer=setTimeout(()=>resolve(false),timeout);\n this.processExit.then(()=>{clearTimeout(timer);resolve(true);});\n });\n }\n}\n\nclass CaptureLease implements CapturedExecution {\n readonly prepared:PreparedExecution;\n readonly children:readonly CapturedChild[];\n private launcher?:Awaited<ReturnType<typeof createSessionLauncher>>;\n private nativeClosed=false;\n private released=false;\n private closing=false;\n private opening?:Promise<ManagedNativeSession>;\n\n constructor(\n private readonly graph:GraphConnection,\n private readonly leaseId:number,\n readonly reference:ExecutionReference,\n children:readonly CapturedChild[],\n agentName:string,\n ) {\n this.graph.retainLease(leaseId);\n this.children=Object.freeze(children.map(child=>Object.freeze({...child})));\n this.prepared={display:{agentName},open:input=>this.open(input),close:()=>this.close()};\n }\n\n async child(name:string):Promise<CapturedExecution>{\n if(this.released)throw new AgentError('INVALID_PARENT','The captured parent context is closed.');\n const result=await this.graph.request('child',{leaseId:this.leaseId,name}) as CaptureResult;\n return new CaptureLease(this.graph,result.leaseId,result.reference,result.children,result.name);\n }\n\n private async open(input:DriverInput):Promise<ManagedNativeSession>{\n if(this.released||this.closing||this.opening)throw new AgentError('HARNESS_FAILED','Native session startup is unavailable.');\n const opening=this.startOpen(input);\n this.opening=opening;\n return opening;\n }\n\n private async startOpen(input:DriverInput):Promise<ManagedNativeSession>{\n const state=input.env.AGENT_STATE_DIR;\n if(typeof state!=='string'||!state)throw new AgentError('INVALID_CONFIG','AGENT_STATE_DIR must select the coordinator state directory.');\n const launcher=await createSessionLauncher(state,input.token);\n this.launcher=launcher;\n if(this.closing){\n await launcher.close();this.launcher=undefined;\n throw new AgentError('COORDINATOR_UNAVAILABLE','The captured session closed during startup.');\n }\n const {onApproval,events,...serializedInput}=input;\n let selectedHarness:HarnessKind|undefined;\n try{\n this.graph.setApprovalHandler(this.leaseId,onApproval);\n this.graph.setEventPort(this.leaseId,events);\n const opened=await this.graph.request('open',{leaseId:this.leaseId,input:serializedInput,\n handlesApprovals:!!onApproval,launcherPath:launcher.path}) as WorkerOpenResult;\n selectedHarness=opened.selectedHarness;\n this.graph.selected(this.leaseId,opened);\n }catch(error){\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n this.launcher=undefined;\n await launcher.close();\n throw error;\n }\n const request=(method:string,extra:Record<string,unknown>={})=>this.graph.request(method,{leaseId:this.leaseId,...extra});\n return {\n selectedHarness,\n turn:prompt=>this.graph.run(this.leaseId,'turn',{prompt}) as Promise<string>,\n steer:async prompt=>{await request('steer',{prompt});},\n interrupt:async()=>{await request('interrupt');},\n resume:()=>this.graph.run(this.leaseId,'resume') as Promise<string>,\n close:async()=>{\n if(this.nativeClosed)return;\n await request('native.close');\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n },\n };\n }\n\n private async close():Promise<void>{\n this.closing=true;\n if(!this.released){\n await this.graph.request('lease.close',{leaseId:this.leaseId});\n this.released=true;\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n }\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close();this.launcher=undefined;}\n await this.graph.releaseLease(this.leaseId);\n }\n\n async abandonFailedCheck():Promise<void>{\n this.closing=true;this.released=true;this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close().catch(()=>{});this.launcher=undefined;}\n await this.graph.abandonLease(this.leaseId);\n }\n}\n\nexport async function captureExecution(\n agent:string|HarnessConfig,\n input:CatalogEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n return captureRequest(input,options,{method:'capture',agent});\n}\n\n/** Captures an already resolved private CLI reference without applying public connected validation. */\nexport async function captureReference(\n reference:ExecutionReference,\n input:CatalogEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n if('kind' in reference&&reference.kind==='inline')\n throw new AgentError('INVALID_DEFINITION','Inline agent definitions cannot be loaded by native CLI workers.');\n return captureRequest(input,options,{method:'capture.reference',reference});\n}\n\nasync function captureRequest(\n input:CatalogEnvironment,\n options:CaptureOptions,\n request:{method:'capture';agent:string|HarnessConfig}|{method:'capture.reference';reference:ExecutionReference},\n):Promise<CapturedExecution>{\n const {AGENT_PARENT_TOKEN:_parent,AGENT_CLI_PATH:_launcher,...environment}=input.env;\n const workerModule=options.workerModule??new URL(`./worker.${import.meta.url.endsWith('.ts')?'ts':'js'}`,import.meta.url);\n const extension=workerModule.pathname.endsWith('.ts')?'ts':'js';\n let child:ChildProcess;\n try{\n child=fork(fileURLToPath(workerModule),[],{cwd:input.cwd,env:environment,stdio:['ignore','ignore','ignore','ipc','pipe'],\n execArgv:extension==='ts'?['--import',import.meta.resolve('tsx')]:[]});\n }catch{throw new AgentError('INVALID_DEFINITION','The captured definition worker could not be spawned.');}\n const graph=new GraphConnection(child,options.shutdownTimeoutMs??shutdownTimeoutMs);\n try{\n const {method,...data}=request;\n const result=await graph.request(method,data) as CaptureResult;\n return new CaptureLease(graph,result.leaseId,result.reference,result.children,result.name);\n }catch(error){await graph.stop().catch(()=>{});throw error;}\n}\n\nexport async function checkCapturedExecution(captured:CapturedExecution,input:CatalogEnvironment):Promise<void>{\n let native:ManagedNativeSession|undefined;\n let failure:unknown;\n try{\n native=await captured.prepared.open({reference:captured.reference,cwd:input.cwd,env:input.env,\n token:randomUUID(),sessionId:`check_${randomUUID()}`});\n await native.close();\n }catch(error){failure=error;}\n try{await captured.prepared.close();}catch(error){\n failure??=error;\n try{await captured.prepared.close();}\n catch{if(captured instanceof CaptureLease)await captured.abandonFailedCheck();}\n }\n if(failure)throw failure;\n}\n"]}
1
+ {"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/runtime/capture.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAqB,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAkB,MAAM,cAAc,CAAC;AAOrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAqBvD,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC,MAAM,eAAe;IAcU,KAAK;IAA+B,OAAO;IAbhE,MAAM,GAAC,CAAC,CAAC;IACT,OAAO,GAAC,IAAI,GAAG,EACmC,CAAC;IACnD,SAAS,GAAC,IAAI,GAAG,EAA0B,CAAC;IAC5C,QAAQ,GAAC,IAAI,GAAG,EAAoC,CAAC;IACrD,MAAM,GAAC,KAAK,CAAC;IACb,MAAM,GAAC,IAAI,GAAG,EAAU,CAAC;IACzB,eAAe,GAAC,IAAI,GAAG,EAAU,CAAC;IAClC,YAAY,GAAC,EAAE,CAAC;IACP,WAAW,CAAe;IAC1B,YAAY,CAAmB;IACxC,UAAU,CAAW;IAE7B,YAA6B,KA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AM,QAAQ,CAAC,kBAAkB,EAAE,CAAC;QAAA,CAAC;IACjF,CAAC;IACD,IAAG,OAAO;QAAC,MAAM,OAAO,CAAC;AAC3B,CAAC;AAED,SAAS,eAAe,CAAC,OAAiC;IACxD,IAAG,OAAO,KAAG,SAAS;QAAC,OAAO,SAAS,CAAC;IACxC,IAAG,CAAC,OAAO,IAAE,OAAO,OAAO,KAAG,QAAQ,IAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;WAC1D,OAAO,OAAO,CAAC,IAAI,KAAG,QAAQ,IAAE,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC;WACzD,OAAO,OAAO,CAAC,UAAU,KAAG,QAAQ,IAAE,CAAC,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC;QACvE,MAAM,IAAI,UAAU,CAAC,kBAAkB,EAAC,0EAA0E,CAAC,CAAC;IACtH,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { fork, type ChildProcess } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { randomUUID } from 'node:crypto';\nimport { isAbsolute } from 'node:path';\nimport { AgentError, errorInfo, type ErrorInfo } from '../errors.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { HarnessConfig, HarnessKind } from '../sdk/types.js';\nimport type { ExecutionEnvironment } from './catalog.js';\nimport type { SelectedProject } from '../config/project-context.js';\nimport type { DriverInput, ExecutionReference, ManagedNativeSession, PreparedExecution } from './types.js';\nimport type { ApprovalEvent } from './worker-approvals.js';\nimport { createSessionLauncher } from './session-launcher.js';\nimport { processExitDescription } from '../process-diagnostics.js';\nimport { WorkerEventClient } from './worker-events.js';\nimport type { Readable } from 'node:stream';\nimport type { WorkerObservationCompletion, WorkerOpenResult } from './worker-event-protocol.js';\n\nexport interface CapturedChild {\n readonly name: string;\n readonly description: string;\n}\n\nexport interface CapturedExecution {\n readonly reference: ExecutionReference;\n readonly prepared: PreparedExecution;\n readonly children: readonly CapturedChild[];\n child(name: string): Promise<CapturedExecution>;\n}\n\ninterface CaptureOptions { workerModule?: URL; shutdownTimeoutMs?: number }\ninterface CaptureResult {leaseId:number;reference:ExecutionReference;name:string;children:CapturedChild[]}\ntype WorkerReply = ApprovalEvent & {leaseId:number} | {id:number;result?:unknown;error?:ErrorInfo;\n observation?:WorkerObservationCompletion};\n\nconst shutdownTimeoutMs = 1_000;\n\nclass GraphConnection {\n private nextId=1;\n private pending=new Map<number,{operation:string;leaseId?:number;observationOperationId?:string;\n resolve(value:unknown):void;reject(error:Error):void}>();\n private approvals=new Map<string,AbortController>();\n private handlers=new Map<number,ApprovalHandler|undefined>();\n private exited=false;\n private leases=new Set<number>();\n private abandonedLeases=new Set<number>();\n private observedExit='';\n private readonly processExit:Promise<void>;\n private readonly workerEvents:WorkerEventClient;\n private markExited!:()=>void;\n\n constructor(private readonly child:ChildProcess,private readonly timeout:number) {\n this.processExit=new Promise(resolve=>{this.markExited=resolve;});\n this.workerEvents=new WorkerEventClient(child.stdio[4] as Readable,(method,data)=>this.request(method,data));\n child.once('error',()=>this.exit(undefined,undefined,true));\n child.once('exit',(code,signal)=>this.exit(code,signal));\n child.on('message',(message:WorkerReply)=>this.message(message));\n }\n\n setApprovalHandler(leaseId:number,handler:ApprovalHandler|undefined) { this.handlers.set(leaseId,handler); }\n deleteApprovalHandler(leaseId:number) { this.handlers.delete(leaseId); }\n setEventPort(leaseId:number,port:DriverInput['events']) { this.workerEvents.attach(leaseId,port); }\n deleteEventPort(leaseId:number) { this.workerEvents.detach(leaseId); }\n retainLease(leaseId:number) { this.leases.add(leaseId); }\n async releaseLease(leaseId:number) {\n this.leases.delete(leaseId);\n await this.retryAbandonedLeases();\n const retained=[...this.leases].filter(id=>!this.abandonedLeases.has(id));\n if(retained.length!==0)return;\n if(this.abandonedLeases.size){this.abandonedLeases.clear();this.leases.clear();await this.stop();return;}\n if(await this.waitWithin(this.timeout))return;\n await this.stop();\n }\n async abandonLease(leaseId:number) {\n if(!this.leases.has(leaseId))return;\n const siblings=[...this.leases].filter(id=>id!==leaseId&&!this.abandonedLeases.has(id));\n if(siblings.length){this.abandonedLeases.add(leaseId);return;}\n this.leases.delete(leaseId);\n await this.stop();\n }\n\n private async retryAbandonedLeases() {\n for(const leaseId of [...this.abandonedLeases]){\n try{\n await this.request('lease.close',{leaseId});\n this.abandonedLeases.delete(leaseId);this.leases.delete(leaseId);\n }catch{/* Retain ownership until the remaining graph leases close. */}\n }\n }\n\n request(method:string,extra:Record<string,unknown>={}):Promise<unknown> {\n return new Promise((resolve,reject)=>{\n if(this.exited){reject(new AgentError('HARNESS_FAILED',`The captured definition worker is unavailable while ${method} was pending${this.observedExit}.`));return;}\n const id=this.nextId++;\n const observationOperationId=typeof extra.observation==='object'&&extra.observation!==null\n &&typeof (extra.observation as {operationId?:unknown}).operationId==='string'\n ?(extra.observation as {operationId:string}).operationId:undefined;\n this.pending.set(id,{operation:method,leaseId:typeof extra.leaseId==='number'?extra.leaseId:undefined,\n observationOperationId,resolve,reject});\n this.child.send({id,method,...extra},error=>{\n if(!error)return;\n setImmediate(()=>{\n const waiting=this.pending.get(id);\n if(!waiting||this.exited)return;\n this.pending.delete(id);\n waiting.reject(new AgentError('HARNESS_FAILED',`Cannot reach the captured definition worker while ${method} was pending.`));\n });\n });\n });\n }\n\n private message(message:WorkerReply) {\n if(this.workerEvents.acceptControl(message))return;\n if('event' in message){\n const key=`${message.leaseId}:${message.requestId}`;\n if(message.event==='approval.withdraw'){\n this.approvals.get(key)?.abort();this.approvals.delete(key);return;\n }\n const controller=new AbortController();\n this.approvals.set(key,controller);\n void Promise.resolve().then(()=>{\n const handler=this.handlers.get(message.leaseId);\n if(!handler)throw new AgentError('INPUT_REQUIRED','Native tool approval requires an observing caller.');\n return handler(message.request,controller.signal);\n }).then(\n content=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,content});},\n error=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)});},\n ).catch(error=>{\n if(!controller.signal.aborted&&!this.exited)\n return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)}).catch(()=>{});\n }).finally(()=>this.approvals.delete(key));\n return;\n }\n const waiting=this.pending.get(message.id);\n if(!waiting)return;\n this.pending.delete(message.id);\n const operationError=message.error?new AgentError(message.error.code,message.error.message):undefined;\n void this.workerEvents.complete(waiting.leaseId!,message.observation,waiting.observationOperationId).then(()=>{\n if(operationError)waiting.reject(operationError);else waiting.resolve(message.result);\n },()=>{if(operationError)waiting.reject(operationError);else waiting.resolve(message.result);});\n }\n\n private exit(code:unknown,signal:unknown,spawnFailure=false) {\n if(this.exited)return;\n this.exited=true;\n this.observedExit=spawnFailure?'':processExitDescription(code,signal);\n for(const controller of this.approvals.values())controller.abort();\n this.approvals.clear();this.workerEvents.close();this.markExited();\n for(const waiting of this.pending.values())waiting.reject(new AgentError('HARNESS_FAILED',spawnFailure\n ?`The captured definition worker process failed while ${waiting.operation} was pending.`\n :`The captured definition worker exited while ${waiting.operation} was pending${this.observedExit}.`));\n this.pending.clear();\n }\n\n async stop() {\n if(this.exited)return;\n if(this.child.connected)try{this.child.disconnect();}catch{}\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGTERM');\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGKILL');\n if(!await this.waitWithin(this.timeout))throw new AgentError('HARNESS_FAILED','The captured definition worker did not confirm termination.');\n }\n\n run(leaseId:number,method:'turn'|'resume',extra:Record<string,unknown>={}):Promise<unknown>{\n const observation=this.workerEvents.begin(leaseId);\n return this.request(method,{leaseId,...extra,...(observation?{observation}:{})});\n }\n\n selected(leaseId:number,opened:WorkerOpenResult):void{\n this.workerEvents.metadata(leaseId,opened);\n }\n\n private waitWithin(timeout:number):Promise<boolean>{\n return new Promise(resolve=>{\n const timer=setTimeout(()=>resolve(false),timeout);\n this.processExit.then(()=>{clearTimeout(timer);resolve(true);});\n });\n }\n}\n\nclass CaptureLease implements CapturedExecution {\n readonly prepared:PreparedExecution;\n readonly children:readonly CapturedChild[];\n private launcher?:Awaited<ReturnType<typeof createSessionLauncher>>;\n private nativeClosed=false;\n private released=false;\n private closing=false;\n private opening?:Promise<ManagedNativeSession>;\n\n constructor(\n private readonly graph:GraphConnection,\n private readonly leaseId:number,\n readonly reference:ExecutionReference,\n children:readonly CapturedChild[],\n agentName:string,\n ) {\n this.graph.retainLease(leaseId);\n this.children=Object.freeze(children.map(child=>Object.freeze({...child})));\n this.prepared={display:{agentName},open:input=>this.open(input),close:()=>this.close()};\n }\n\n async child(name:string):Promise<CapturedExecution>{\n if(this.released)throw new AgentError('INVALID_PARENT','The captured parent context is closed.');\n const result=await this.graph.request('child',{leaseId:this.leaseId,name}) as CaptureResult;\n return new CaptureLease(this.graph,result.leaseId,result.reference,result.children,result.name);\n }\n\n private async open(input:DriverInput):Promise<ManagedNativeSession>{\n if(this.released||this.closing||this.opening)throw new AgentError('HARNESS_FAILED','Native session startup is unavailable.');\n const opening=this.startOpen(input);\n this.opening=opening;\n return opening;\n }\n\n private async startOpen(input:DriverInput):Promise<ManagedNativeSession>{\n const state=input.env.AGENT_STATE_DIR;\n if(typeof state!=='string'||!state)throw new AgentError('INVALID_CONFIG','AGENT_STATE_DIR must select the coordinator state directory.');\n const launcher=await createSessionLauncher(state,input.token);\n this.launcher=launcher;\n if(this.closing){\n await launcher.close();this.launcher=undefined;\n throw new AgentError('COORDINATOR_UNAVAILABLE','The captured session closed during startup.');\n }\n const {onApproval,events,...serializedInput}=input;\n let selectedHarness:HarnessKind|undefined;\n try{\n this.graph.setApprovalHandler(this.leaseId,onApproval);\n this.graph.setEventPort(this.leaseId,events);\n const opened=await this.graph.request('open',{leaseId:this.leaseId,input:serializedInput,\n handlesApprovals:!!onApproval,launcherPath:launcher.path}) as WorkerOpenResult;\n selectedHarness=opened.selectedHarness;\n this.graph.selected(this.leaseId,opened);\n }catch(error){\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n this.launcher=undefined;\n await launcher.close();\n throw error;\n }\n const request=(method:string,extra:Record<string,unknown>={})=>this.graph.request(method,{leaseId:this.leaseId,...extra});\n return {\n selectedHarness,\n turn:prompt=>this.graph.run(this.leaseId,'turn',{prompt}) as Promise<string>,\n steer:async prompt=>{await request('steer',{prompt});},\n interrupt:async()=>{await request('interrupt');},\n resume:()=>this.graph.run(this.leaseId,'resume') as Promise<string>,\n close:async()=>{\n if(this.nativeClosed)return;\n await request('native.close');\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n },\n };\n }\n\n private async close():Promise<void>{\n this.closing=true;\n if(!this.released){\n await this.graph.request('lease.close',{leaseId:this.leaseId});\n this.released=true;\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n }\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close();this.launcher=undefined;}\n await this.graph.releaseLease(this.leaseId);\n }\n\n async abandonFailedCheck():Promise<void>{\n this.closing=true;this.released=true;this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n this.graph.deleteEventPort(this.leaseId);\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close().catch(()=>{});this.launcher=undefined;}\n await this.graph.abandonLease(this.leaseId);\n }\n}\n\nexport async function captureExecution(\n agent:string|HarnessConfig,\n input:ExecutionEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n return captureRequest(input,options,{method:'capture',agent,projectRoot:input.project?.root});\n}\n\n/** Captures an already resolved private CLI reference without applying public connected validation. */\nexport async function captureReference(\n reference:ExecutionReference,\n input:ExecutionEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n if('kind' in reference&&reference.kind==='inline')\n throw new AgentError('INVALID_DEFINITION','Inline agent definitions cannot be loaded by native CLI workers.');\n return captureRequest(input,options,{method:'capture.reference',reference});\n}\n\nasync function captureRequest(\n input:ExecutionEnvironment,\n options:CaptureOptions,\n request:{method:'capture';agent:string|HarnessConfig;projectRoot?:string}|{method:'capture.reference';reference:ExecutionReference},\n):Promise<CapturedExecution>{\n const {AGENT_PARENT_TOKEN:_parent,AGENT_CLI_PATH:_launcher,...environment}=input.env;\n const workerModule=options.workerModule??new URL(`./worker.${import.meta.url.endsWith('.ts')?'ts':'js'}`,import.meta.url);\n const extension=workerModule.pathname.endsWith('.ts')?'ts':'js';\n let child:ChildProcess;\n try{\n child=fork(fileURLToPath(workerModule),[],{cwd:input.cwd,env:environment,stdio:['ignore','ignore','ignore','ipc','pipe'],\n execArgv:extension==='ts'?['--import',import.meta.resolve('tsx')]:[]});\n }catch{throw new AgentError('INVALID_DEFINITION','The captured definition worker could not be spawned.');}\n const graph=new GraphConnection(child,options.shutdownTimeoutMs??shutdownTimeoutMs);\n try{\n const {method,...data}=request;\n const result=await graph.request(method,data) as CaptureResult;\n return new CaptureLease(graph,result.leaseId,result.reference,result.children,result.name);\n }catch(error){await graph.stop().catch(()=>{});throw error;}\n}\n\nexport async function checkCapturedExecution(captured:CapturedExecution,input:ExecutionEnvironment):Promise<void>{\n let native:ManagedNativeSession|undefined;\n let failure:unknown;\n try{\n const project=retainedProject(input.project);\n native=await captured.prepared.open({reference:captured.reference,cwd:input.cwd,env:input.env,\n token:randomUUID(),sessionId:`check_${randomUUID()}`,\n ...(project ? {project} : {})});\n await native.close();\n }catch(error){failure=error;}\n try{await captured.prepared.close();}catch(error){\n failure??=error;\n try{await captured.prepared.close();}\n catch{if(captured instanceof CaptureLease)await captured.abandonFailedCheck();}\n }\n if(failure)throw failure;\n}\n\nfunction retainedProject(project:SelectedProject|undefined):SelectedProject|undefined {\n if(project===undefined)return undefined;\n if(!project||typeof project!=='object'||Array.isArray(project)\n ||typeof project.root!=='string'||!isAbsolute(project.root)\n ||typeof project.accessRoot!=='string'||!isAbsolute(project.accessRoot))\n throw new AgentError('INVALID_ARGUMENT','Retained project context must include absolute project and access roots.');\n return project;\n}\n"]}
@@ -1,9 +1,14 @@
1
1
  import { type ErrorInfo } from '../errors.js';
2
2
  import type { HarnessConfig } from '../sdk/types.js';
3
3
  import type { ExecutionReference } from './types.js';
4
+ import type { ProjectSelection, SelectedProject } from '../config/project-context.js';
4
5
  export interface CatalogEnvironment {
5
6
  readonly cwd: string;
6
7
  readonly env: NodeJS.ProcessEnv;
8
+ readonly project?: ProjectSelection;
9
+ }
10
+ export interface ExecutionEnvironment extends Omit<CatalogEnvironment, 'project'> {
11
+ readonly project?: SelectedProject;
7
12
  }
8
13
  export interface CatalogAgent {
9
14
  readonly id: string;
@@ -35,5 +40,5 @@ export declare function listAgents(input: CatalogEnvironment): Promise<{
35
40
  readonly items: readonly CatalogAgent[];
36
41
  }>;
37
42
  export declare function resolveAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<ExecutionReference>;
38
- export declare function checkAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<void>;
43
+ export declare function checkAgent(agent: string | HarnessConfig, input: ExecutionEnvironment): Promise<void>;
39
44
  export declare function loadCatalogSnapshot(input: CatalogEnvironment, parent?: ExecutionReference, discover?: boolean): Promise<CatalogSnapshot>;
@@ -75,7 +75,7 @@ export function loadCatalogSnapshot(input, parent, discover = true) {
75
75
  child.send({ received: true }, error => { if (error)
76
76
  child.kill(); });
77
77
  });
78
- child.send({ cwd: input.cwd, parent, discover }, error => { if (error) {
78
+ child.send({ cwd: input.cwd, parent, discover, projectRoot: input.project?.root }, error => { if (error) {
79
79
  child.kill();
80
80
  fail();
81
81
  } });
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/runtime/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAkB,MA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CAAC,CAAC,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,EAAC,GAAG,EAAC,KAAK,CAAC,GAAG,EAAC,MAAM,EAAC,QAAQ,EAAC,EAAC,KAAK,CAAA,EAAE,GAAC,IAAG,KAAK,EAAC,CAAC;YAAA,KAAK,CAAC,IAAI,EAAE,CAAC;YAAA,IAAI,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC,CAAC,CAAC;IACvF,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { fork } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { AgentError, type ErrorInfo } from '../errors.js';\nimport { validateAgent } from '../sdk/definitions.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport { harnessReference } from './definition.js';\nimport type { ExecutionReference } from './types.js';\n\nexport interface CatalogEnvironment {\n readonly cwd: string;\n readonly env: NodeJS.ProcessEnv;\n}\n\nexport interface CatalogAgent {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly scope: 'harness' | 'repo' | 'global';\n}\n\nexport interface CatalogSnapshot {\n entries: {id:string;name:string;description:string;scope:'repo'|'global';file:string}[];\n children: {name:string;description:string}[];\n}\n\nexport type CatalogReply = {result:CatalogSnapshot;error?:never}|{result?:never;error:ErrorInfo};\n\nconst nativeAgents: readonly CatalogAgent[] = [\n {id:'codex',name:'codex',description:'Run the native Codex harness.',scope:'harness'},\n {id:'claude',name:'claude',description:'Run the native Claude Code harness.',scope:'harness'},\n {id:'fx',name:'fx',description:'Run the native fx harness through AI Gateway.',scope:'harness'},\n {id:'opencode',name:'opencode',description:'Run the native OpenCode harness through AI Gateway.',scope:'harness'},\n {id:'copilot',name:'copilot',description:'Run the native GitHub Copilot harness through AI Gateway.',scope:'harness'},\n {id:'cursor',name:'cursor',description:'Run the native Cursor harness.',scope:'harness'},\n];\n\nexport async function listAgents(input: CatalogEnvironment): Promise<{readonly items:readonly CatalogAgent[]}> {\n const snapshot = await loadCatalogSnapshot(input);\n return {items:[...nativeAgents,...snapshot.entries.map(({id,name,description,scope})=>({id,name,description,scope}))]};\n}\n\nexport async function resolveAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<ExecutionReference> {\n if (typeof agent !== 'string') {\n validateAgent({name:'direct',description:'Direct native harness.',instructions:'Run.',harness:agent});\n return {kind:'harness',harness:agent};\n }\n if (agent === 'codex') return harnessReference('codex');\n if (agent === 'claude') return harnessReference('claudeCode');\n if (agent === 'fx') return harnessReference('fx');\n if (agent === 'opencode' || agent === 'copilot' || agent === 'cursor')\n throw new AgentError('INVALID_CONFIG', `${agent} requires an explicit model configuration.`);\n if (agent.startsWith('subagent:'))\n throw new AgentError('UNKNOWN_AGENT', 'Managed subagents require an active parent context.');\n const {entries} = await loadCatalogSnapshot(input);\n const matches = entries.filter(entry => entry.id === agent || entry.name === agent);\n if (matches.length !== 1) throw new AgentError(matches.length ? 'AMBIGUOUS_AGENT' : 'UNKNOWN_AGENT',\n matches.length ? `Choose ${matches.map(entry=>entry.id).join(' or ')}.` : 'Agent not found.');\n return {file:matches[0]!.file,subagents:[]};\n}\n\nexport async function checkAgent(agent:string|HarnessConfig,input:CatalogEnvironment):Promise<void>{\n const {captureExecution,checkCapturedExecution}=await import('./capture.js');\n const captured=await captureExecution(agent,input);\n await checkCapturedExecution(captured,input);\n}\n\nexport function loadCatalogSnapshot(\n input: CatalogEnvironment,\n parent?: ExecutionReference,\n discover = true,\n): Promise<CatalogSnapshot> {\n if (parent && 'kind' in parent && parent.kind === 'inline')\n return Promise.reject(new AgentError('INVALID_PARENT','Inline SDK definitions are unavailable to the CLI catalog.'));\n return new Promise((resolve,reject) => {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n const child = fork(fileURLToPath(new URL(`../cli/catalog-worker.${extension}`,import.meta.url)),[],{\n cwd:input.cwd,env:input.env,stdio:['ignore','ignore','ignore','ipc'],\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [],\n });\n let reply: CatalogReply | undefined;\n let settled = false;\n const fail = () => {\n if (settled) return;\n settled = true;\n reject(new AgentError('INVALID_DEFINITION','The agent catalog worker exited before returning its catalog.'));\n };\n child.once('error',fail);\n child.once('exit',()=>{\n if (!reply) fail();\n else if (!settled) {\n settled = true;\n if (reply.error) reject(new AgentError(reply.error.code,reply.error.message));\n else resolve(reply.result);\n }\n });\n child.once('message',(message:CatalogReply)=>{\n reply=message;\n child.send({received:true},error=>{if(error)child.kill();});\n });\n child.send({cwd:input.cwd,parent,discover},error=>{if(error){child.kill();fail();}});\n });\n}\n"]}
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/runtime/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAkB,MAAM,cAAc,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AA4BnD,MAAM,YAAY,GAA4B;IAC5C,EAAC,EAAE,EAAC,OAAO,EAAC,IAAI,EAAC,OAAO,EAAC,WAAW,EAAC,+BAA+B,EAAC,KAAK,EAAC,SAAS,EAAC;IACrF,EAAC,EAAE,EAAC,QAAQ,EAAC,IAAI,EAAC,QAAQ,EAAC,WAAW,EAAC,qCAAqC,EAAC,KAAK,EAAC,SAAS,EAAC;IAC7F,EAAC,EAAE,EAAC,IAAI,EAAC,IAAI,EAAC,IAAI,EAAC,WAAW,EAAC,+CAA+C,EAAC,KAAK,EAAC,SAAS,EAAC;IAC/F,EAAC,EAAE,EAAC,UAAU,EAAC,IAAI,EAAC,UAAU,EAAC,WAAW,EAAC,qDAAqD,EAAC,KAAK,EAAC,SAAS,EAAC;IACjH,EAAC,EAAE,EAAC,SAAS,EAAC,IAAI,EAAC,SAAS,EAAC,WAAW,EAAC,2DAA2D,EAAC,KAAK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AAC;gBAClB,OAAO,GAAG,IAAI,CAAC;gBACf,IAAI,KAAK,CAAC,KAAK;oBAAE,MAAM,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;;oBACzE,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC7B,CAAC;QACH,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,SAAS,EAAC,CAAC,OAAoB,EAAC,EAAE;YAC3C,KAAK,GAAC,OAAO,CAAC;YACd,KAAK,CAAC,IAAI,CAAC,EAAC,QAAQ,EAAC,IAAI,EAAC,EAAC,KAAK,CAAA,EAAE,GAAC,IAAG,KAAK;gBAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA,CAAC,CAAC,CAAC;QAC9D,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,EAAC,GAAG,EAAC,KAAK,CAAC,GAAG,EAAC,MAAM,EAAC,QAAQ,EAAC,WAAW,EAAC,KAAK,CAAC,OAAO,EAAE,IAAI,EAAC,EAAC,KAAK,CAAA,EAAE,GAAC,IAAG,KAAK,EAAC,CAAC;YAAA,KAAK,CAAC,IAAI,EAAE,CAAC;YAAA,IAAI,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC,CAAC,CAAC;IACvH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { fork } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { AgentError, type ErrorInfo } from '../errors.js';\nimport { validateAgent } from '../sdk/definitions.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport { harnessReference } from './definition.js';\nimport type { ExecutionReference } from './types.js';\nimport type { ProjectSelection, SelectedProject } from '../config/project-context.js';\n\nexport interface CatalogEnvironment {\n readonly cwd: string;\n readonly env: NodeJS.ProcessEnv;\n readonly project?: ProjectSelection;\n}\n\nexport interface ExecutionEnvironment extends Omit<CatalogEnvironment,'project'> {\n readonly project?: SelectedProject;\n}\n\nexport interface CatalogAgent {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly scope: 'harness' | 'repo' | 'global';\n}\n\nexport interface CatalogSnapshot {\n entries: {id:string;name:string;description:string;scope:'repo'|'global';file:string}[];\n children: {name:string;description:string}[];\n}\n\nexport type CatalogReply = {result:CatalogSnapshot;error?:never}|{result?:never;error:ErrorInfo};\n\nconst nativeAgents: readonly CatalogAgent[] = [\n {id:'codex',name:'codex',description:'Run the native Codex harness.',scope:'harness'},\n {id:'claude',name:'claude',description:'Run the native Claude Code harness.',scope:'harness'},\n {id:'fx',name:'fx',description:'Run the native fx harness through AI Gateway.',scope:'harness'},\n {id:'opencode',name:'opencode',description:'Run the native OpenCode harness through AI Gateway.',scope:'harness'},\n {id:'copilot',name:'copilot',description:'Run the native GitHub Copilot harness through AI Gateway.',scope:'harness'},\n {id:'cursor',name:'cursor',description:'Run the native Cursor harness.',scope:'harness'},\n];\n\nexport async function listAgents(input: CatalogEnvironment): Promise<{readonly items:readonly CatalogAgent[]}> {\n const snapshot = await loadCatalogSnapshot(input);\n return {items:[...nativeAgents,...snapshot.entries.map(({id,name,description,scope})=>({id,name,description,scope}))]};\n}\n\nexport async function resolveAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<ExecutionReference> {\n if (typeof agent !== 'string') {\n validateAgent({name:'direct',description:'Direct native harness.',instructions:'Run.',harness:agent});\n return {kind:'harness',harness:agent};\n }\n if (agent === 'codex') return harnessReference('codex');\n if (agent === 'claude') return harnessReference('claudeCode');\n if (agent === 'fx') return harnessReference('fx');\n if (agent === 'opencode' || agent === 'copilot' || agent === 'cursor')\n throw new AgentError('INVALID_CONFIG', `${agent} requires an explicit model configuration.`);\n if (agent.startsWith('subagent:'))\n throw new AgentError('UNKNOWN_AGENT', 'Managed subagents require an active parent context.');\n const {entries} = await loadCatalogSnapshot(input);\n const matches = entries.filter(entry => entry.id === agent || entry.name === agent);\n if (matches.length !== 1) throw new AgentError(matches.length ? 'AMBIGUOUS_AGENT' : 'UNKNOWN_AGENT',\n matches.length ? `Choose ${matches.map(entry=>entry.id).join(' or ')}.` : 'Agent not found.');\n return {file:matches[0]!.file,subagents:[]};\n}\n\nexport async function checkAgent(agent:string|HarnessConfig,input:ExecutionEnvironment):Promise<void>{\n const {captureExecution,checkCapturedExecution}=await import('./capture.js');\n const captured=await captureExecution(agent,input);\n await checkCapturedExecution(captured,input);\n}\n\nexport function loadCatalogSnapshot(\n input: CatalogEnvironment,\n parent?: ExecutionReference,\n discover = true,\n): Promise<CatalogSnapshot> {\n if (parent && 'kind' in parent && parent.kind === 'inline')\n return Promise.reject(new AgentError('INVALID_PARENT','Inline SDK definitions are unavailable to the CLI catalog.'));\n return new Promise((resolve,reject) => {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n const child = fork(fileURLToPath(new URL(`../cli/catalog-worker.${extension}`,import.meta.url)),[],{\n cwd:input.cwd,env:input.env,stdio:['ignore','ignore','ignore','ipc'],\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [],\n });\n let reply: CatalogReply | undefined;\n let settled = false;\n const fail = () => {\n if (settled) return;\n settled = true;\n reject(new AgentError('INVALID_DEFINITION','The agent catalog worker exited before returning its catalog.'));\n };\n child.once('error',fail);\n child.once('exit',()=>{\n if (!reply) fail();\n else if (!settled) {\n settled = true;\n if (reply.error) reject(new AgentError(reply.error.code,reply.error.message));\n else resolve(reply.result);\n }\n });\n child.once('message',(message:CatalogReply)=>{\n reply=message;\n child.send({received:true},error=>{if(error)child.kill();});\n });\n child.send({cwd:input.cwd,parent,discover,projectRoot:input.project?.root},error=>{if(error){child.kill();fail();}});\n });\n}\n"]}
@@ -23,6 +23,7 @@ export declare class Coordinator {
23
23
  sessionId: string;
24
24
  reference: import("./types.js").ExecutionReference;
25
25
  cwd: string;
26
+ project: import("../config/project-context.ts").SelectedProject | undefined;
26
27
  };
27
28
  createSession(input: SessionCreateInput, prepared?: PreparedExecution, observers?: AdmissionObservers): string;
28
29
  run(input: SessionInput, prepared?: PreparedExecution, observers?: AdmissionObservers): Receipt;
@@ -43,7 +43,8 @@ export class Coordinator {
43
43
  const task = session?.active ? this.task(session.active) : undefined;
44
44
  if (!session || !task || task.stopping || terminal(task.state))
45
45
  throw new AgentError('INVALID_PARENT', 'The parent context is no longer active.');
46
- return { taskId: task.id, sessionId: session.id, reference: session.input.reference, cwd: session.input.cwd };
46
+ return { taskId: task.id, sessionId: session.id, reference: session.input.reference, cwd: session.input.cwd,
47
+ project: session.input.project };
47
48
  }
48
49
  createSession(input, prepared, observers) {
49
50
  if (this.closed)