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":"extension-supervisor.js","sourceRoot":"","sources":["../../src/runtime/extension-supervisor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAA+D,MAAM,0BAA0B,CAAC;AACjI,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAA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AAC;AACvE,CAAC;AAED,SAAS,YAAY,CAAC,IAAY,EAAE,SAAiB;IACnD,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACzC,OAAO,MAAM,KAAK,EAAE,IAAI,CAAC,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;AACrG,CAAC","sourcesContent":["import { isAbsolute, relative, sep } from \"node:path\";\nimport { discoverExtensionCatalog, type ExtensionCatalogEntry, type ValidExtensionCatalogEntry } from \"../extensions/catalog.js\";\nimport { quoteDiagnosticPath } from \"../config/access-provenance.js\";\nimport { isExtensionEnabled, readExtensionConsent } from \"../extensions/consent.js\";\nimport { extensionIdentity, extensionLogPath } from \"../extensions/identity.js\";\nimport type { AdmissionObservers, OwnerEventRegistration } from \"./types.js\";\nimport type {\n ExtensionAdmissionDiagnostic,\n ExtensionDiagnostic,\n ExtensionIdentity,\n ExtensionStatusRecord,\n ExtensionStatusSnapshot,\n} from \"./extension-protocol.js\";\nimport {\n EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT,\n EXTENSION_STATUS_DIAGNOSTIC_LIMIT,\n validateExtensionIdentity,\n} from \"./extension-protocol.js\";\nimport { SupervisedExtensionInstance } from \"./extension-instance.js\";\n\nexport interface ExtensionSupervisorOptions {\n readonly stateDirectory: string;\n readonly homeDirectory?: string;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly setupTimeoutMs?: number;\n readonly handlerTimeoutMs?: number;\n readonly disposalTimeoutMs?: number;\n readonly now?: () => number;\n}\n\ninterface Generation {\n readonly identity: ExtensionIdentity;\n readonly logPath: string;\n installation?: ValidExtensionCatalogEntry;\n instance?: SupervisedExtensionInstance;\n eligible: boolean;\n state: \"idle\" | \"disabled\";\n readonly diagnostics: ExtensionDiagnostic[];\n}\n\ntype AdmissionCandidate =\n | { readonly kind: \"valid\"; readonly installation: ValidExtensionCatalogEntry }\n | { readonly kind: \"failure\"; readonly identity: ExtensionIdentity; readonly diagnostic: ExtensionDiagnostic };\n\nexport class ExtensionSupervisor {\n private readonly generations = new Map<string, Generation[]>();\n private readonly admissionDiagnostics: ExtensionAdmissionDiagnostic[] = [];\n private closed = false;\n private closePromise?: Promise<void>;\n\n constructor(private readonly options: ExtensionSupervisorOptions) {}\n\n async prepareAdmission(cwd: string): Promise<AdmissionObservers> {\n if (this.closed) return { attach() {} };\n let catalog;\n try {\n catalog = await discoverExtensionCatalog(cwd, { homeDirectory: this.options.homeDirectory });\n } catch {\n this.recordAdmissionDiagnostic(admissionDiagnostic(\n \"Extension discovery failed during session admission.\",\n this.knownWorkspace(cwd),\n this.now(),\n ));\n return { attach() {} };\n }\n let consent;\n try { consent = await readExtensionConsent({ homeDirectory: this.options.homeDirectory }); }\n catch {\n this.recordAdmissionDiagnostic(admissionDiagnostic(\n \"Extension consent could not be read during session admission.\",\n catalog.workspace,\n this.now(),\n ));\n return { attach() {} };\n }\n const selected: AdmissionCandidate[] = [];\n for (const installation of catalog.installations) {\n const identity = catalogIdentity(installation, catalog.workspace);\n if (!identity || !isExtensionEnabled(consent, identity)) continue;\n selected.push(installation.status === \"valid\"\n ? { kind: \"valid\", installation }\n : {\n kind: \"failure\",\n identity,\n diagnostic: staticDiagnostic(\n identity,\n installation.status === \"incompatible\" ? \"EXTENSION_INCOMPATIBLE\" : \"EXTENSION_LOAD_FAILED\",\n this.now(),\n ),\n });\n }\n return {\n attach: (sessionId, owner) => {\n if (this.closed) return;\n for (const candidate of selected) {\n try { this.attach(sessionId, owner, candidate); }\n catch { /* One broken observation registration cannot remove healthy extension assignments. */ }\n }\n },\n };\n }\n\n async status(workspace: string): Promise<ExtensionStatusSnapshot> {\n const result: ExtensionStatusRecord[] = [];\n for (const generations of this.generations.values()) {\n for (const generation of generations) {\n const { instance, identity } = generation;\n if (identity.workspace !== undefined && identity.workspace !== workspace) continue;\n result.push({\n identity: { ...identity },\n state: statusState(generation),\n logPath: generation.logPath,\n diagnostics: [...generation.diagnostics, ...(instance?.diagnostics ?? [])]\n .sort((left, right) => left.at - right.at)\n .slice(-EXTENSION_STATUS_DIAGNOSTIC_LIMIT)\n .map(diagnostic => ({ ...diagnostic })),\n });\n }\n }\n return {\n instances: result,\n admissionDiagnostics: this.admissionDiagnostics\n .filter(diagnostic => diagnostic.workspace === undefined || diagnostic.workspace === workspace)\n .slice(-EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT)\n .map(diagnostic => ({ ...diagnostic })),\n };\n }\n\n async reenable(value: ExtensionIdentity): Promise<void> {\n const validated = validateExtensionIdentity(value);\n const identity: ExtensionIdentity = {\n reference: validated.reference,\n ...(validated.workspace === undefined ? {} : { workspace: validated.workspace }),\n };\n const generations = this.generations.get(identityKey(identity));\n const current = generations?.at(-1);\n if (!current || current.eligible) return;\n this.createPlaceholder(identity);\n }\n\n close(): Promise<void> {\n this.closed = true;\n this.closePromise ??= this.closeAll();\n return this.closePromise;\n }\n\n private attach(\n sessionId: string,\n owner: OwnerEventRegistration,\n candidate: AdmissionCandidate,\n ): void {\n const identity = candidate.kind === \"valid\" ? candidate.installation.identity : candidate.identity;\n const key = identityKey(identity);\n let generation = this.generations.get(key)?.at(-1);\n if (candidate.kind === \"failure\") {\n if (!generation) generation = this.createPlaceholder(identity);\n if (!generation.eligible) return;\n if (!generation.instance) {\n this.failStatic(generation, candidate.diagnostic);\n return;\n }\n this.recordRunningStaticFailure(generation, candidate.diagnostic);\n generation.instance.addSession(sessionId, owner);\n return;\n }\n if (!generation) generation = this.createGeneration(candidate.installation);\n if (!generation.eligible) return;\n if (!generation.instance) this.materialize(generation, candidate.installation);\n generation.instance!.addSession(sessionId, owner);\n }\n\n private createGeneration(installation: ValidExtensionCatalogEntry): Generation {\n const generation = this.createPlaceholder(installation.identity);\n this.materialize(generation, installation);\n return generation;\n }\n\n private createPlaceholder(identity: ExtensionIdentity): Generation {\n const key = identityKey(identity);\n const generation: Generation = {\n identity,\n logPath: extensionLogPath(this.options.stateDirectory, identity),\n eligible: true,\n state: \"idle\",\n diagnostics: [],\n };\n const generations = this.generations.get(key) ?? [];\n generations.push(generation);\n this.generations.set(key, generations);\n return generation;\n }\n\n private materialize(generation: Generation, installation: ValidExtensionCatalogEntry): void {\n generation.installation = installation;\n const instance = new SupervisedExtensionInstance({\n installation,\n logPath: generation.logPath,\n environment: this.options.environment,\n setupTimeoutMs: this.options.setupTimeoutMs,\n handlerTimeoutMs: this.options.handlerTimeoutMs,\n disposalTimeoutMs: this.options.disposalTimeoutMs,\n now: this.options.now,\n onFailure: () => { generation.eligible = false; },\n });\n generation.instance = instance;\n }\n\n private failStatic(generation: Generation, diagnostic: ExtensionDiagnostic): void {\n generation.eligible = false;\n generation.state = \"disabled\";\n // Re-enablement creates a new generation, so a pre-start generation can fail statically only once.\n generation.diagnostics.push(diagnostic);\n }\n\n private recordRunningStaticFailure(generation: Generation, diagnostic: ExtensionDiagnostic): void {\n const previous = generation.diagnostics.at(-1);\n if (previous?.code === diagnostic.code && previous.message === diagnostic.message && !previous.disabling) return;\n generation.diagnostics.push({ ...diagnostic, disabling: false });\n if (generation.diagnostics.length > EXTENSION_STATUS_DIAGNOSTIC_LIMIT) {\n generation.diagnostics.splice(0, generation.diagnostics.length - EXTENSION_STATUS_DIAGNOSTIC_LIMIT);\n }\n }\n\n private recordAdmissionDiagnostic(diagnostic: ExtensionAdmissionDiagnostic): void {\n this.admissionDiagnostics.push(diagnostic);\n if (this.admissionDiagnostics.length > EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT) {\n this.admissionDiagnostics.splice(\n 0,\n this.admissionDiagnostics.length - EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT,\n );\n }\n }\n\n private knownWorkspace(cwd: string): string | undefined {\n let nearest: string | undefined;\n for (const generations of this.generations.values()) {\n const workspace = generations.at(-1)?.identity.workspace;\n if (!workspace || !containsPath(workspace, cwd)) continue;\n if (!nearest || workspace.length > nearest.length) nearest = workspace;\n }\n return nearest;\n }\n\n private now(): number {\n return (this.options.now ?? Date.now)();\n }\n\n private async closeAll(): Promise<void> {\n const instances = [...this.generations.values()].flatMap(value => value.flatMap(item => item.instance ? [item.instance] : []));\n const results = await Promise.allSettled(instances.map(instance => instance.close()));\n const failures = results.flatMap(result => result.status === \"rejected\" ? [result.reason] : []);\n if (failures.length) throw new AggregateError(failures, \"Extension supervisor cleanup failed.\");\n }\n}\n\nfunction identityKey(identity: ExtensionIdentity): string {\n return `${identity.reference}\\0${identity.workspace ?? \"\"}`;\n}\n\nfunction catalogIdentity(entry: ExtensionCatalogEntry, workspace: string): ExtensionIdentity | undefined {\n if (entry.status === \"valid\") return entry.identity;\n try { return extensionIdentity(entry.reference, entry.scope === \"repo\" ? workspace : undefined); }\n catch { return; }\n}\n\nfunction staticDiagnostic(\n identity: ExtensionIdentity,\n code: \"EXTENSION_LOAD_FAILED\" | \"EXTENSION_INCOMPATIBLE\",\n at: number,\n): ExtensionDiagnostic {\n const phase = code === \"EXTENSION_INCOMPATIBLE\" ? \"compatibility\" : \"load\";\n const source = `${identity.reference}${identity.workspace ? ` in ${quoteDiagnosticPath(identity.workspace)}` : \"\"} failed during ${phase}.`;\n let message = \"\";\n let bytes = 0;\n for (const character of source) {\n const width = Buffer.byteLength(character);\n if (bytes + width > 1024) break;\n message += character;\n bytes += width;\n }\n return { code, message, disabling: true, at };\n}\n\nfunction admissionDiagnostic(message: string, workspace: string | undefined, at: number): ExtensionAdmissionDiagnostic {\n return {\n code: \"EXTENSION_LOAD_FAILED\",\n message,\n ...(workspace === undefined ? {} : { workspace }),\n at,\n };\n}\n\nfunction statusState(generation: Generation): ExtensionStatusRecord[\"state\"] {\n if (!generation.eligible || generation.state === \"disabled\"\n || generation.instance?.state === \"failed\" || generation.instance?.state === \"stopped\") return \"disabled\";\n return generation.instance?.state === \"running\" ? \"running\" : \"idle\";\n}\n\nfunction containsPath(root: string, candidate: string): boolean {\n const nested = relative(root, candidate);\n return nested === \"\" || (nested !== \"..\" && !nested.startsWith(`..${sep}`) && !isAbsolute(nested));\n}\n"]}
1
+ {"version":3,"file":"extension-supervisor.js","sourceRoot":"","sources":["../../src/runtime/extension-supervisor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAA+D,MAAM,0BAA0B,CAAC;AACjI,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAShF,OAAO,EACL,2CAA2C,EAC3C,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AA0BtE,MAAM,OAAO,mBAAmB;IAMD,OAAO;IALnB,WAAW,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC9C,oBAAoB,GAAmC,EAAE,CAAC;IACnE,MAAM,GAAG,KAAK,CAAC;IACf,YAAY,CAAiB;IAErC,YAA6B,OAAmC;uBAAnC,OAAO;IAA+B,CAAC;IAEpE,KAAK,CAAC,gBAAgB,CAAC,GAAW,EAAE,WAAoB;QACtD,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO,EAAE,MAAM,KAAI,CAAC,EAAE,CAAC;QACxC,IAAI,OAAO,CAAC;QACZ,IAAI,CAAC;YACH,OAAO,GAAG,MAAM,wBAAwB,CAAC,GAAG,EAAE;gBAC5C,aAAa,EAAE,IAAI,CAAC,OAAO,CAAC,aAAa;gBACzC,WAAW;aACZ,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,CAAC,yBAAyB,CAAC,mBAAmB,CAChD,s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AuB;QAC7B,OAAO;QACP,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC;QACjD,EAAE;KACH,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,UAAsB;IACzC,IAAI,CAAC,UAAU,CAAC,QAAQ,IAAI,UAAU,CAAC,KAAK,KAAK,UAAU;WACtD,UAAU,CAAC,QAAQ,EAAE,KAAK,KAAK,QAAQ,IAAI,UAAU,CAAC,QAAQ,EAAE,KAAK,KAAK,SAAS;QAAE,OAAO,UAAU,CAAC;IAC5G,OAAO,UAAU,CAAC,QAAQ,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;AACvE,CAAC;AAED,SAAS,YAAY,CAAC,IAAY,EAAE,SAAiB;IACnD,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACzC,OAAO,MAAM,KAAK,EAAE,IAAI,CAAC,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;AACrG,CAAC","sourcesContent":["import { isAbsolute, relative, sep } from \"node:path\";\nimport { discoverExtensionCatalog, type ExtensionCatalogEntry, type ValidExtensionCatalogEntry } from \"../extensions/catalog.js\";\nimport { quoteDiagnosticPath } from \"../config/access-provenance.js\";\nimport { isExtensionEnabled, readExtensionConsent } from \"../extensions/consent.js\";\nimport { extensionIdentity, extensionLogPath } from \"../extensions/identity.js\";\nimport type { AdmissionObservers, OwnerEventRegistration } from \"./types.js\";\nimport type {\n ExtensionAdmissionDiagnostic,\n ExtensionDiagnostic,\n ExtensionIdentity,\n ExtensionStatusRecord,\n ExtensionStatusSnapshot,\n} from \"./extension-protocol.js\";\nimport {\n EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT,\n EXTENSION_STATUS_DIAGNOSTIC_LIMIT,\n validateExtensionIdentity,\n} from \"./extension-protocol.js\";\nimport { SupervisedExtensionInstance } from \"./extension-instance.js\";\n\nexport interface ExtensionSupervisorOptions {\n readonly stateDirectory: string;\n readonly homeDirectory?: string;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly setupTimeoutMs?: number;\n readonly handlerTimeoutMs?: number;\n readonly disposalTimeoutMs?: number;\n readonly now?: () => number;\n}\n\ninterface Generation {\n readonly identity: ExtensionIdentity;\n readonly logPath: string;\n installation?: ValidExtensionCatalogEntry;\n instance?: SupervisedExtensionInstance;\n eligible: boolean;\n state: \"idle\" | \"disabled\";\n readonly diagnostics: ExtensionDiagnostic[];\n}\n\ntype AdmissionCandidate =\n | { readonly kind: \"valid\"; readonly installation: ValidExtensionCatalogEntry }\n | { readonly kind: \"failure\"; readonly identity: ExtensionIdentity; readonly diagnostic: ExtensionDiagnostic };\n\nexport class ExtensionSupervisor {\n private readonly generations = new Map<string, Generation[]>();\n private readonly admissionDiagnostics: ExtensionAdmissionDiagnostic[] = [];\n private closed = false;\n private closePromise?: Promise<void>;\n\n constructor(private readonly options: ExtensionSupervisorOptions) {}\n\n async prepareAdmission(cwd: string, projectRoot?: string): Promise<AdmissionObservers> {\n if (this.closed) return { attach() {} };\n let catalog;\n try {\n catalog = await discoverExtensionCatalog(cwd, {\n homeDirectory: this.options.homeDirectory,\n projectRoot,\n });\n } catch {\n this.recordAdmissionDiagnostic(admissionDiagnostic(\n \"Extension discovery failed during session admission.\",\n projectRoot ?? this.knownWorkspace(cwd),\n this.now(),\n ));\n return { attach() {} };\n }\n let consent;\n try { consent = await readExtensionConsent({ homeDirectory: this.options.homeDirectory }); }\n catch {\n this.recordAdmissionDiagnostic(admissionDiagnostic(\n \"Extension consent could not be read during session admission.\",\n catalog.workspace,\n this.now(),\n ));\n return { attach() {} };\n }\n const selected: AdmissionCandidate[] = [];\n for (const installation of catalog.installations) {\n const identity = catalogIdentity(installation, catalog.workspace);\n if (!identity || !isExtensionEnabled(consent, identity)) continue;\n selected.push(installation.status === \"valid\"\n ? { kind: \"valid\", installation }\n : {\n kind: \"failure\",\n identity,\n diagnostic: staticDiagnostic(\n identity,\n installation.status === \"incompatible\" ? \"EXTENSION_INCOMPATIBLE\" : \"EXTENSION_LOAD_FAILED\",\n this.now(),\n ),\n });\n }\n return {\n attach: (sessionId, owner) => {\n if (this.closed) return;\n for (const candidate of selected) {\n try { this.attach(sessionId, owner, candidate); }\n catch { /* One broken observation registration cannot remove healthy extension assignments. */ }\n }\n },\n };\n }\n\n async status(workspace: string): Promise<ExtensionStatusSnapshot> {\n const result: ExtensionStatusRecord[] = [];\n for (const generations of this.generations.values()) {\n for (const generation of generations) {\n const { instance, identity } = generation;\n if (identity.workspace !== undefined && identity.workspace !== workspace) continue;\n result.push({\n identity: { ...identity },\n state: statusState(generation),\n logPath: generation.logPath,\n diagnostics: [...generation.diagnostics, ...(instance?.diagnostics ?? [])]\n .sort((left, right) => left.at - right.at)\n .slice(-EXTENSION_STATUS_DIAGNOSTIC_LIMIT)\n .map(diagnostic => ({ ...diagnostic })),\n });\n }\n }\n return {\n instances: result,\n admissionDiagnostics: this.admissionDiagnostics\n .filter(diagnostic => diagnostic.workspace === undefined || diagnostic.workspace === workspace)\n .slice(-EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT)\n .map(diagnostic => ({ ...diagnostic })),\n };\n }\n\n async reenable(value: ExtensionIdentity): Promise<void> {\n const validated = validateExtensionIdentity(value);\n const identity: ExtensionIdentity = {\n reference: validated.reference,\n ...(validated.workspace === undefined ? {} : { workspace: validated.workspace }),\n };\n const generations = this.generations.get(identityKey(identity));\n const current = generations?.at(-1);\n if (!current || current.eligible) return;\n this.createPlaceholder(identity);\n }\n\n close(): Promise<void> {\n this.closed = true;\n this.closePromise ??= this.closeAll();\n return this.closePromise;\n }\n\n private attach(\n sessionId: string,\n owner: OwnerEventRegistration,\n candidate: AdmissionCandidate,\n ): void {\n const identity = candidate.kind === \"valid\" ? candidate.installation.identity : candidate.identity;\n const key = identityKey(identity);\n let generation = this.generations.get(key)?.at(-1);\n if (candidate.kind === \"failure\") {\n if (!generation) generation = this.createPlaceholder(identity);\n if (!generation.eligible) return;\n if (!generation.instance) {\n this.failStatic(generation, candidate.diagnostic);\n return;\n }\n this.recordRunningStaticFailure(generation, candidate.diagnostic);\n generation.instance.addSession(sessionId, owner);\n return;\n }\n if (!generation) generation = this.createGeneration(candidate.installation);\n if (!generation.eligible) return;\n if (!generation.instance) this.materialize(generation, candidate.installation);\n generation.instance!.addSession(sessionId, owner);\n }\n\n private createGeneration(installation: ValidExtensionCatalogEntry): Generation {\n const generation = this.createPlaceholder(installation.identity);\n this.materialize(generation, installation);\n return generation;\n }\n\n private createPlaceholder(identity: ExtensionIdentity): Generation {\n const key = identityKey(identity);\n const generation: Generation = {\n identity,\n logPath: extensionLogPath(this.options.stateDirectory, identity),\n eligible: true,\n state: \"idle\",\n diagnostics: [],\n };\n const generations = this.generations.get(key) ?? [];\n generations.push(generation);\n this.generations.set(key, generations);\n return generation;\n }\n\n private materialize(generation: Generation, installation: ValidExtensionCatalogEntry): void {\n generation.installation = installation;\n const instance = new SupervisedExtensionInstance({\n installation,\n logPath: generation.logPath,\n environment: this.options.environment,\n setupTimeoutMs: this.options.setupTimeoutMs,\n handlerTimeoutMs: this.options.handlerTimeoutMs,\n disposalTimeoutMs: this.options.disposalTimeoutMs,\n now: this.options.now,\n onFailure: () => { generation.eligible = false; },\n });\n generation.instance = instance;\n }\n\n private failStatic(generation: Generation, diagnostic: ExtensionDiagnostic): void {\n generation.eligible = false;\n generation.state = \"disabled\";\n // Re-enablement creates a new generation, so a pre-start generation can fail statically only once.\n generation.diagnostics.push(diagnostic);\n }\n\n private recordRunningStaticFailure(generation: Generation, diagnostic: ExtensionDiagnostic): void {\n const previous = generation.diagnostics.at(-1);\n if (previous?.code === diagnostic.code && previous.message === diagnostic.message && !previous.disabling) return;\n generation.diagnostics.push({ ...diagnostic, disabling: false });\n if (generation.diagnostics.length > EXTENSION_STATUS_DIAGNOSTIC_LIMIT) {\n generation.diagnostics.splice(0, generation.diagnostics.length - EXTENSION_STATUS_DIAGNOSTIC_LIMIT);\n }\n }\n\n private recordAdmissionDiagnostic(diagnostic: ExtensionAdmissionDiagnostic): void {\n this.admissionDiagnostics.push(diagnostic);\n if (this.admissionDiagnostics.length > EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT) {\n this.admissionDiagnostics.splice(\n 0,\n this.admissionDiagnostics.length - EXTENSION_STATUS_ADMISSION_DIAGNOSTIC_LIMIT,\n );\n }\n }\n\n private knownWorkspace(cwd: string): string | undefined {\n let nearest: string | undefined;\n for (const generations of this.generations.values()) {\n const workspace = generations.at(-1)?.identity.workspace;\n if (!workspace || !containsPath(workspace, cwd)) continue;\n if (!nearest || workspace.length > nearest.length) nearest = workspace;\n }\n return nearest;\n }\n\n private now(): number {\n return (this.options.now ?? Date.now)();\n }\n\n private async closeAll(): Promise<void> {\n const instances = [...this.generations.values()].flatMap(value => value.flatMap(item => item.instance ? [item.instance] : []));\n const results = await Promise.allSettled(instances.map(instance => instance.close()));\n const failures = results.flatMap(result => result.status === \"rejected\" ? [result.reason] : []);\n if (failures.length) throw new AggregateError(failures, \"Extension supervisor cleanup failed.\");\n }\n}\n\nfunction identityKey(identity: ExtensionIdentity): string {\n return `${identity.reference}\\0${identity.workspace ?? \"\"}`;\n}\n\nfunction catalogIdentity(entry: ExtensionCatalogEntry, workspace: string): ExtensionIdentity | undefined {\n if (entry.status === \"valid\") return entry.identity;\n try { return extensionIdentity(entry.reference, entry.scope === \"repo\" ? workspace : undefined); }\n catch { return; }\n}\n\nfunction staticDiagnostic(\n identity: ExtensionIdentity,\n code: \"EXTENSION_LOAD_FAILED\" | \"EXTENSION_INCOMPATIBLE\",\n at: number,\n): ExtensionDiagnostic {\n const phase = code === \"EXTENSION_INCOMPATIBLE\" ? \"compatibility\" : \"load\";\n const source = `${identity.reference}${identity.workspace ? ` in ${quoteDiagnosticPath(identity.workspace)}` : \"\"} failed during ${phase}.`;\n let message = \"\";\n let bytes = 0;\n for (const character of source) {\n const width = Buffer.byteLength(character);\n if (bytes + width > 1024) break;\n message += character;\n bytes += width;\n }\n return { code, message, disabling: true, at };\n}\n\nfunction admissionDiagnostic(message: string, workspace: string | undefined, at: number): ExtensionAdmissionDiagnostic {\n return {\n code: \"EXTENSION_LOAD_FAILED\",\n message,\n ...(workspace === undefined ? {} : { workspace }),\n at,\n };\n}\n\nfunction statusState(generation: Generation): ExtensionStatusRecord[\"state\"] {\n if (!generation.eligible || generation.state === \"disabled\"\n || generation.instance?.state === \"failed\" || generation.instance?.state === \"stopped\") return \"disabled\";\n return generation.instance?.state === \"running\" ? \"running\" : \"idle\";\n}\n\nfunction containsPath(root: string, candidate: string): boolean {\n const nested = relative(root, candidate);\n return nested === \"\" || (nested !== \"..\" && !nested.startsWith(`..${sep}`) && !isAbsolute(nested));\n}\n"]}
@@ -3,7 +3,8 @@ import type { AdapterOptions, ExecutionDefinition, NativeSession } from '../adap
3
3
  import { type AccessConfig } from '../config/access.js';
4
4
  import type { ApprovalHandler } from '../approvals/types.js';
5
5
  import type { AdapterEventPort } from '../adapters/event-types.js';
6
+ import type { SelectedProject } from '../config/project-context.js';
6
7
  export interface NativeSelectionDiagnosticContext {
7
8
  readonly origin: 'cli' | 'sdk';
8
9
  }
9
- export declare function selectNative(agent: ExecutionDefinition, cwd: string, env: NodeJS.ProcessEnv, settings: AccessConfig, open?: (options: AdapterOptions) => Promise<NativeSession>, selected?: (kind: HarnessKind) => void, onApproval?: ApprovalHandler, diagnosticContext?: NativeSelectionDiagnosticContext, events?: AdapterEventPort): Promise<NativeSession>;
10
+ export declare function selectNative(agent: ExecutionDefinition, cwd: string, env: NodeJS.ProcessEnv, settings: AccessConfig, open?: (options: AdapterOptions) => Promise<NativeSession>, selected?: (kind: HarnessKind) => void, onApproval?: ApprovalHandler, diagnosticContext?: NativeSelectionDiagnosticContext, events?: AdapterEventPort, project?: SelectedProject): Promise<NativeSession>;
@@ -1,5 +1,6 @@
1
+ import { join } from 'node:path';
1
2
  import { resolveAccess } from '../config/access.js';
2
- import { accessAttemptContext } from '../config/access-provenance.js';
3
+ import { accessAttemptContext, quoteDiagnosticPath } from '../config/access-provenance.js';
3
4
  import { AgentError } from '../errors.js';
4
5
  import { EVENT_SECRET_RECEIVER, registerEventSecrets } from '../adapters/event-secrets.js';
5
6
  import { withAccessContext, withSessionAccessContext } from './access-errors.js';
@@ -11,7 +12,7 @@ const openers = {
11
12
  copilot: async (options) => (await import('../adapters/copilot.js')).openCopilot(options),
12
13
  cursor: async (options) => (await import('../adapters/cursor.js')).openCursor(options),
13
14
  };
14
- export async function selectNative(agent, cwd, env, settings, open = (options) => openers[options.harness.kind](options), selected = () => { }, onApproval, diagnosticContext = { origin: 'cli' }, events) {
15
+ export async function selectNative(agent, cwd, env, settings, open = (options) => openers[options.harness.kind](options), selected = () => { }, onApproval, diagnosticContext = { origin: 'cli' }, events, project) {
15
16
  const alternatives = Array.isArray(agent.harness) ? agent.harness : [agent.harness];
16
17
  const unavailable = [];
17
18
  for (const harness of alternatives) {
@@ -22,7 +23,9 @@ export async function selectNative(agent, cwd, env, settings, open = (options) =
22
23
  if (configuredConnections?.length === 0) {
23
24
  unavailable.push(diagnosticContext.origin === 'sdk'
24
25
  ? `${harness.kind}: Access is disabled by the empty connection list in RunnerOptions.access.`
25
- : `${harness.kind}: Access is disabled in the main checkout's .subharness/agents.local.json.`);
26
+ : project
27
+ ? `${harness.kind}: Access is disabled by the empty connection list in personal access settings at ${quoteDiagnosticPath(join(project.accessRoot, '.subharness', 'agents.local.json'))}.`
28
+ : `${harness.kind}: Access is disabled in the main checkout's .subharness/agents.local.json.`);
26
29
  }
27
30
  else if (!connections.length && explicitAccessRequired) {
28
31
  const setting = diagnosticContext.origin === 'sdk' ? 'RunnerOptions.access' : 'personal access settings';
@@ -33,7 +36,7 @@ export async function selectNative(agent, cwd, env, settings, open = (options) =
33
36
  for (const [index, connection] of connections.entries()) {
34
37
  const context = accessAttemptContext(settings, harness.kind, connection, index, connections.length);
35
38
  try {
36
- const access = await resolveAccess(connection, harness.kind, cwd, env);
39
+ const access = await resolveAccess(connection, harness.kind, cwd, env, project);
37
40
  registerEventSecrets(events, [access.token]);
38
41
  let committed = false;
39
42
  let metadata;
@@ -1 +1 @@
1
- {"version":3,"file":"select-native.js","sourceRoot":"","sources":["../../src/runtime/select-native.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAqB,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAoC,MAAM,8BAA8B,CAAC;AAC7H,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAEjF,MAAM,OAAO,GAAG;IACd,KAAK,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,sBAAsB,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC;IACnG,UAAU,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC;IAC1G,EAAE,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;IAC1F,QAAQ,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC;IAC5G,OAAO,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAA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AAC,KAAK,CAAC,IAAI,CAAC;oBAAE,MAAM,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;gBAChH,WAAW,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,KAAK,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YACpF,CAAC;QACH,CAAC;IACH,CAAC;IACD,MAAM,IAAI,UAAU,CAAC,oBAAoB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,yCAAyC,CAAC,CAAC;AACtI,CAAC","sourcesContent":["import type { HarnessKind } from '../sdk/types.js';\nimport type { AdapterOptions, ExecutionDefinition, NativeSession } from '../adapters/types.js';\nimport { resolveAccess, type AccessConfig } from '../config/access.js';\nimport { accessAttemptContext } from '../config/access-provenance.js';\nimport { AgentError } from '../errors.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { AdapterEventPort } from '../adapters/event-types.js';\nimport { EVENT_SECRET_RECEIVER, registerEventSecrets, type SecretAwareAdapterEventPort } from '../adapters/event-secrets.js';\nimport { withAccessContext, withSessionAccessContext } from './access-errors.js';\n\nconst openers = {\n codex: async (options: AdapterOptions) => (await import('../adapters/codex.js')).openCodex(options),\n claudeCode: async (options: AdapterOptions) => (await import('../adapters/claude.js')).openClaude(options),\n fx: async (options: AdapterOptions) => (await import('../adapters/fx.js')).openFx(options),\n opencode: async (options: AdapterOptions) => (await import('../adapters/opencode.js')).openOpencode(options),\n copilot: async (options: AdapterOptions) => (await import('../adapters/copilot.js')).openCopilot(options),\n cursor: async (options: AdapterOptions) => (await import('../adapters/cursor.js')).openCursor(options),\n} satisfies Record<HarnessKind, (options: AdapterOptions) => Promise<NativeSession>>;\n\nexport interface NativeSelectionDiagnosticContext {\n readonly origin: 'cli' | 'sdk';\n}\n\nexport async function selectNative(\n agent: ExecutionDefinition, cwd: string, env: NodeJS.ProcessEnv, settings: AccessConfig,\n open = (options: AdapterOptions): Promise<NativeSession> => openers[options.harness.kind](options),\n selected: (kind: HarnessKind) => void = () => {},\n onApproval?: ApprovalHandler,\n diagnosticContext: NativeSelectionDiagnosticContext = {origin: 'cli'},\n events?: AdapterEventPort,\n): Promise<NativeSession> {\n const alternatives = Array.isArray(agent.harness) ? agent.harness : [agent.harness];\n const unavailable: string[] = [];\n for (const harness of alternatives) {\n const configuredConnections = settings.access?.[harness.kind as HarnessKind];\n const explicitAccessRequired = ['fx','opencode','copilot','cursor'].includes(harness.kind);\n const connections = configuredConnections ??\n (explicitAccessRequired ? [] : [{type:'subscription' as const}]);\n if (configuredConnections?.length === 0) {\n unavailable.push(diagnosticContext.origin === 'sdk'\n ? `${harness.kind}: Access is disabled by the empty connection list in RunnerOptions.access.`\n : `${harness.kind}: Access is disabled in the main checkout's .subharness/agents.local.json.`);\n } else if (!connections.length && explicitAccessRequired) {\n const setting = diagnosticContext.origin === 'sdk' ? 'RunnerOptions.access' : 'personal access settings';\n const guidance = harness.kind === 'cursor' ? 'Cursor subscription or API-key'\n : 'native login, API-key, or Gateway';\n unavailable.push(`${harness.kind}: Enable an explicit ${guidance} connection in ${setting}.`);\n }\n for (const [index, connection] of connections.entries()) {\n const context = accessAttemptContext(settings, harness.kind, connection, index, connections.length);\n try {\n const access = await resolveAccess(connection, harness.kind, cwd, env);\n registerEventSecrets(events,[access.token]);\n let committed = false;\n let metadata: Parameters<AdapterEventPort['selected']>[0] | undefined;\n const candidateEvents: AdapterEventPort | undefined = events ? ({\n currentOperation: () => committed ? events.currentOperation() : undefined,\n selected: value => {\n try {\n metadata = structuredClone(value);\n if (committed) events.selected(metadata);\n } catch { /* Malformed observation metadata cannot fail native selection. */ }\n },\n [EVENT_SECRET_RECEIVER]: (values: readonly string[]) => { registerEventSecrets(events, values); },\n } as SecretAwareAdapterEventPort) : undefined;\n const native = await open({agent,harness,cwd,env,access,...(onApproval ? {onApproval} : {}),\n ...(candidateEvents ? {events:candidateEvents} : {})});\n committed = true;\n selected(harness.kind);\n if (metadata) {\n try { events!.selected(metadata); } catch { /* Observation metadata cannot fail native selection. */ }\n }\n return withSessionAccessContext(native, context);\n } catch (error) {\n if (!(error instanceof AgentError)) throw error;\n if (!['HARNESS_UNAVAILABLE','ACCESS_UNAVAILABLE'].includes(error.code)) throw withAccessContext(error, context);\n unavailable.push(`${harness.kind}: ${withAccessContext(error, context).message}`);\n }\n }\n }\n throw new AgentError('ACCESS_UNAVAILABLE', unavailable.length ? unavailable.join('\\n') : 'No declared harness has enabled access.');\n}\n"]}
1
+ {"version":3,"file":"select-native.js","sourceRoot":"","sources":["../../src/runtime/select-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,aAAa,EAAqB,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAoC,MAAM,8BAA8B,CAAC;AAC7H,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAGjF,MAAM,OAAO,GAAG;IACd,KAAK,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,sBAAsB,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC;IACnG,UAAU,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC;IAC1G,EAAE,EAAE,KAAK,EAAE,OAAuB,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;IAC1F,QAAQ,EAAE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BAAC,MAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;oBAAC,CAAC;oBAAC,MAAM,CAAC,CAAC,wDAAwD,CAAC,CAAC;gBACxG,CAAC;gBACD,OAAO,wBAAwB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACnD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC;oBAAE,MAAM,KAAK,CAAC;gBAChD,IAAI,CAAC,CAAC,qBAAqB,EAAC,oBAAoB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC;oBAAE,MAAM,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;gBAChH,WAAW,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,KAAK,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YACpF,CAAC;QACH,CAAC;IACH,CAAC;IACD,MAAM,IAAI,UAAU,CAAC,oBAAoB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,yCAAyC,CAAC,CAAC;AACtI,CAAC","sourcesContent":["import { join } from 'node:path';\nimport type { HarnessKind } from '../sdk/types.js';\nimport type { AdapterOptions, ExecutionDefinition, NativeSession } from '../adapters/types.js';\nimport { resolveAccess, type AccessConfig } from '../config/access.js';\nimport { accessAttemptContext, quoteDiagnosticPath } from '../config/access-provenance.js';\nimport { AgentError } from '../errors.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { AdapterEventPort } from '../adapters/event-types.js';\nimport { EVENT_SECRET_RECEIVER, registerEventSecrets, type SecretAwareAdapterEventPort } from '../adapters/event-secrets.js';\nimport { withAccessContext, withSessionAccessContext } from './access-errors.js';\nimport type { SelectedProject } from '../config/project-context.js';\n\nconst openers = {\n codex: async (options: AdapterOptions) => (await import('../adapters/codex.js')).openCodex(options),\n claudeCode: async (options: AdapterOptions) => (await import('../adapters/claude.js')).openClaude(options),\n fx: async (options: AdapterOptions) => (await import('../adapters/fx.js')).openFx(options),\n opencode: async (options: AdapterOptions) => (await import('../adapters/opencode.js')).openOpencode(options),\n copilot: async (options: AdapterOptions) => (await import('../adapters/copilot.js')).openCopilot(options),\n cursor: async (options: AdapterOptions) => (await import('../adapters/cursor.js')).openCursor(options),\n} satisfies Record<HarnessKind, (options: AdapterOptions) => Promise<NativeSession>>;\n\nexport interface NativeSelectionDiagnosticContext {\n readonly origin: 'cli' | 'sdk';\n}\n\nexport async function selectNative(\n agent: ExecutionDefinition, cwd: string, env: NodeJS.ProcessEnv, settings: AccessConfig,\n open = (options: AdapterOptions): Promise<NativeSession> => openers[options.harness.kind](options),\n selected: (kind: HarnessKind) => void = () => {},\n onApproval?: ApprovalHandler,\n diagnosticContext: NativeSelectionDiagnosticContext = {origin: 'cli'},\n events?: AdapterEventPort,\n project?: SelectedProject,\n): Promise<NativeSession> {\n const alternatives = Array.isArray(agent.harness) ? agent.harness : [agent.harness];\n const unavailable: string[] = [];\n for (const harness of alternatives) {\n const configuredConnections = settings.access?.[harness.kind as HarnessKind];\n const explicitAccessRequired = ['fx','opencode','copilot','cursor'].includes(harness.kind);\n const connections = configuredConnections ??\n (explicitAccessRequired ? [] : [{type:'subscription' as const}]);\n if (configuredConnections?.length === 0) {\n unavailable.push(diagnosticContext.origin === 'sdk'\n ? `${harness.kind}: Access is disabled by the empty connection list in RunnerOptions.access.`\n : project\n ? `${harness.kind}: Access is disabled by the empty connection list in personal access settings at ${quoteDiagnosticPath(join(project.accessRoot,'.subharness','agents.local.json'))}.`\n : `${harness.kind}: Access is disabled in the main checkout's .subharness/agents.local.json.`);\n } else if (!connections.length && explicitAccessRequired) {\n const setting = diagnosticContext.origin === 'sdk' ? 'RunnerOptions.access' : 'personal access settings';\n const guidance = harness.kind === 'cursor' ? 'Cursor subscription or API-key'\n : 'native login, API-key, or Gateway';\n unavailable.push(`${harness.kind}: Enable an explicit ${guidance} connection in ${setting}.`);\n }\n for (const [index, connection] of connections.entries()) {\n const context = accessAttemptContext(settings, harness.kind, connection, index, connections.length);\n try {\n const access = await resolveAccess(connection, harness.kind, cwd, env, project);\n registerEventSecrets(events,[access.token]);\n let committed = false;\n let metadata: Parameters<AdapterEventPort['selected']>[0] | undefined;\n const candidateEvents: AdapterEventPort | undefined = events ? ({\n currentOperation: () => committed ? events.currentOperation() : undefined,\n selected: value => {\n try {\n metadata = structuredClone(value);\n if (committed) events.selected(metadata);\n } catch { /* Malformed observation metadata cannot fail native selection. */ }\n },\n [EVENT_SECRET_RECEIVER]: (values: readonly string[]) => { registerEventSecrets(events, values); },\n } as SecretAwareAdapterEventPort) : undefined;\n const native = await open({agent,harness,cwd,env,access,...(onApproval ? {onApproval} : {}),\n ...(candidateEvents ? {events:candidateEvents} : {})});\n committed = true;\n selected(harness.kind);\n if (metadata) {\n try { events!.selected(metadata); } catch { /* Observation metadata cannot fail native selection. */ }\n }\n return withSessionAccessContext(native, context);\n } catch (error) {\n if (!(error instanceof AgentError)) throw error;\n if (!['HARNESS_UNAVAILABLE','ACCESS_UNAVAILABLE'].includes(error.code)) throw withAccessContext(error, context);\n unavailable.push(`${harness.kind}: ${withAccessContext(error, context).message}`);\n }\n }\n }\n throw new AgentError('ACCESS_UNAVAILABLE', unavailable.length ? unavailable.join('\\n') : 'No declared harness has enabled access.');\n}\n"]}
@@ -8,6 +8,7 @@ import { checkAgent, listAgents } from './catalog.js';
8
8
  import { resolveStateDirectory } from './state.js';
9
9
  import { dispatchSessionEventRequest, isSessionEventCommand, writeSessionEventRecord } from './session-events-service.js';
10
10
  import { dispatchExtensionManagement, isExtensionManagementCommand } from './extension-service.js';
11
+ import { canonicalProjectRoot, retainSelectedProject } from '../config/project-context.js';
11
12
  export async function startService(engine, token, instanceId, state, options = {}) {
12
13
  const directory = resolveStateDirectory(state);
13
14
  const captures = new Map(options.initialCaptures);
@@ -47,7 +48,7 @@ export async function startService(engine, token, instanceId, state, options = {
47
48
  type: 'coordinator-health',
48
49
  instanceId,
49
50
  protocolVersion: 1,
50
- capabilities: ['sdk-v1', 'cli-v1', ...(eventSource ? ['session-events-v1'] : [])],
51
+ capabilities: ['sdk-v1', 'cli-v1', 'cli-root-v1', ...(eventSource ? ['session-events-v1'] : [])],
51
52
  }));
52
53
  return;
53
54
  }
@@ -139,6 +140,7 @@ export async function startService(engine, token, instanceId, state, options = {
139
140
  break;
140
141
  case 'parent-catalog': {
141
142
  const { captured } = bindParent(engine, captures, data.parentToken);
143
+ rejectManagedProjectOverride(data);
142
144
  write({ version: 1, type: 'agents', agents: captured.children.map(child => ({
143
145
  id: `subagent:${child.name}`, name: child.name, description: child.description, scope: 'subagent',
144
146
  })) });
@@ -146,7 +148,8 @@ export async function startService(engine, token, instanceId, state, options = {
146
148
  }
147
149
  case 'parent-check': {
148
150
  const binding = bindParent(engine, captures, data.parentToken);
149
- const input = await catalogInput(data, directory);
151
+ rejectManagedProjectOverride(data);
152
+ const input = await catalogInput(data, directory, binding.project);
150
153
  const captured = binding.captured;
151
154
  const child = await captured.child(childName(data.agent));
152
155
  try {
@@ -161,14 +164,15 @@ export async function startService(engine, token, instanceId, state, options = {
161
164
  }
162
165
  case 'parent-run': {
163
166
  const binding = bindParent(engine, captures, data.parentToken);
164
- const input = await catalogInput(data, directory);
167
+ rejectManagedProjectOverride(data);
168
+ const input = await catalogInput(data, directory, binding.project);
165
169
  const captured = binding.captured;
166
170
  const child = await captured.child(childName(data.agent));
167
171
  try {
168
172
  validateParentBinding(engine, binding);
169
- const observers = await extensions?.prepareAdmission(input.cwd);
173
+ const observers = await extensions?.prepareAdmission(input.cwd, input.project?.root);
170
174
  receipt = engine.run({ reference: child.reference, cwd: input.cwd, env: input.env,
171
- prompt: data.prompt, parentToken: binding.token }, child.prepared, observers);
175
+ prompt: data.prompt, parentToken: binding.token, project: binding.project }, child.prepared, observers);
172
176
  captures.set(receipt.sessionId, child);
173
177
  }
174
178
  catch (error) {
@@ -177,14 +181,16 @@ export async function startService(engine, token, instanceId, state, options = {
177
181
  break;
178
182
  }
179
183
  case 'cli-run': {
180
- const input = await catalogInput(data, directory);
184
+ if (data.parentToken !== undefined)
185
+ throw new AgentError('INVALID_PARENT', 'Managed execution must use a declared child operation.');
186
+ const input = await catalogInput(data, directory, undefined, true);
181
187
  const captured = data.reference
182
188
  ? await captureOperations.captureReference(data.reference, input)
183
189
  : await captureOperations.captureExecution(connectedAgent(data.agent), input);
184
190
  try {
185
- const observers = await extensions?.prepareAdmission(input.cwd);
191
+ const observers = await extensions?.prepareAdmission(input.cwd, input.project?.root);
186
192
  receipt = engine.run({ reference: captured.reference, cwd: input.cwd, env: input.env,
187
- prompt: data.prompt, parentToken: data.parentToken }, captured.prepared, observers);
193
+ prompt: data.prompt, project: input.project }, captured.prepared, observers);
188
194
  captures.set(receipt.sessionId, captured);
189
195
  }
190
196
  catch (error) {
@@ -193,9 +199,13 @@ export async function startService(engine, token, instanceId, state, options = {
193
199
  break;
194
200
  }
195
201
  case 'run': {
202
+ if (data.projectRoot !== undefined || data.accessRoot !== undefined)
203
+ throw new AgentError('INVALID_ARGUMENT', 'Legacy execution does not accept project-root selection.');
196
204
  if (!data.input || typeof data.input !== 'object' || Array.isArray(data.input))
197
205
  throw new AgentError('INVALID_ARGUMENT', 'Invalid legacy run input.');
198
206
  const legacy = data.input;
207
+ if ('project' in legacy || 'projectRoot' in legacy || 'accessRoot' in legacy)
208
+ throw new AgentError('INVALID_ARGUMENT', 'Legacy execution does not accept project-root selection.');
199
209
  if (!legacy.reference || typeof legacy.reference !== 'object' || Array.isArray(legacy.reference)
200
210
  || typeof legacy.cwd !== 'string')
201
211
  throw new AgentError('INVALID_ARGUMENT', 'Invalid legacy run input.');
@@ -297,7 +307,7 @@ function serviceErrorInfo(error) {
297
307
  }
298
308
  return errorInfo(error);
299
309
  }
300
- async function catalogInput(data, directory) {
310
+ async function catalogInput(data, directory, inherited, allowProjectRoot = false) {
301
311
  const cwd = data.cwd;
302
312
  if (typeof cwd !== 'string' || !isAbsolute(cwd))
303
313
  throw new AgentError('INVALID_ARGUMENT', 'Execution cwd must be an existing absolute directory.');
@@ -324,7 +334,17 @@ async function catalogInput(data, directory) {
324
334
  delete env.AGENT_PARENT_TOKEN;
325
335
  delete env.AGENT_CLI_PATH;
326
336
  env.AGENT_STATE_DIR = directory;
327
- return { cwd, env };
337
+ if (data.accessRoot !== undefined || data.project !== undefined)
338
+ throw new AgentError('INVALID_ARGUMENT', 'Personal-access roots and retained project context are coordinator-owned.');
339
+ let project = inherited;
340
+ if (data.projectRoot !== undefined) {
341
+ if (!allowProjectRoot || typeof data.projectRoot !== 'string')
342
+ throw new AgentError('INVALID_ARGUMENT', 'Project-root selection is unavailable for this operation.');
343
+ if (!isAbsolute(data.projectRoot))
344
+ throw new AgentError('INVALID_ARGUMENT', 'Project root must be an absolute directory.');
345
+ project = await retainSelectedProject(await canonicalProjectRoot(data.projectRoot));
346
+ }
347
+ return { cwd, env, project };
328
348
  }
329
349
  function connectedAgent(value) {
330
350
  if (typeof value === 'string' || (value !== null && typeof value === 'object' && !Array.isArray(value)))
@@ -338,7 +358,11 @@ function bindParent(engine, captures, token) {
338
358
  const captured = captures.get(context.sessionId);
339
359
  if (!captured)
340
360
  throw new AgentError('INVALID_PARENT', 'The active parent does not own a captured definition graph.');
341
- return { token, taskId: context.taskId, sessionId: context.sessionId, captured };
361
+ return { token, taskId: context.taskId, sessionId: context.sessionId, captured, project: context.project };
362
+ }
363
+ function rejectManagedProjectOverride(data) {
364
+ if (data.projectRoot !== undefined || data.accessRoot !== undefined)
365
+ throw new AgentError('INVALID_ARGUMENT', 'Managed list, run, and check inherit the parent project and do not accept --root.');
342
366
  }
343
367
  function validateParentBinding(engine, binding) {
344
368
  const current = engine.parentContext(binding.token);
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/runtime/service.ts"],"names":[],"mappings":"AAAA,O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AAC,CAAC,CAAC;QACzE,MAAM,IAAI,UAAU,CAAC,gBAAgB,EAAC,8DAA8D,CAAC,CAAC;IACxG,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACxB,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,QAA0B,EAAC,cAAsB;IAC9E,IAAI,CAAC;QAAC,MAAM,QAAQ,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IAAC,CAAC;IACxC,MAAM,CAAC;QAAC,MAAM,IAAI,UAAU,CAAC,gBAAgB,EAAC,iEAAiE,CAAC,CAAC;IAAC,CAAC;IACnH,MAAM,cAAc,CAAC;AACvB,CAAC;AAED,SAAS,kBAAkB,CAAC,QAA0B,EAAC,SAAgB;IACrE,OAAO;QACL,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAC,OAAO,EAAC,QAAQ,CAAC,OAAO,EAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,IAAI,EAAC,KAAK,CAAA,EAAE,CAAA,QAAQ,CAAC,IAAI,CAAC,EAAC,GAAG,KAAK,EAAC,GAAG,EAAC,EAAC,GAAG,KAAK,CAAC,GAAG,EAAC,eAAe,EAAC,SAAS,EAAC,EAAC,CAAC;QAClF,KAAK,EAAC,GAAE,EAAE,CAAA,QAAQ,CAAC,KAAK,EAAE;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { stat } from 'node:fs/promises';\nimport { isAbsolute } from 'node:path';\nimport { AgentError, errorInfo } from '../errors.js';\nimport { Coordinator } from './coordinator.js';\nimport type { Delivery, ExecutionReference, PreparedExecution, Receipt, SessionInput } from './types.js';\nimport { dispatchSdkRequest, isSdkCommand } from './sdk-service.js';\nimport { captureExecution, captureReference, checkCapturedExecution, type CapturedExecution } from './capture.js';\nimport { checkAgent, listAgents, type CatalogEnvironment } from './catalog.js';\nimport { resolveStateDirectory } from './state.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport type { SessionEventSource } from '../sdk/event-types.js';\nimport { dispatchSessionEventRequest, isSessionEventCommand, writeSessionEventRecord } from './session-events-service.js';\nimport { dispatchExtensionManagement, isExtensionManagementCommand,\n type CoordinatorExtensionService } from './extension-service.js';\n\ninterface Request {\n command: string; input?: SessionInput; id?: string; after?: string;\n prompt?: string; delivery?: Delivery; full?: boolean; detach?: boolean; parentToken?: string;\n content?: unknown;\n includePrompt?: boolean; knownResponseId?: string;\n agent?: unknown; cwd?: string; env?: NodeJS.ProcessEnv;\n reference?: ExecutionReference;\n}\n\nexport interface ServiceCaptureOperations {\n captureExecution:typeof captureExecution;\n captureReference:typeof captureReference;\n checkCapturedExecution:typeof checkCapturedExecution;\n}\nexport interface ServiceOptions {\n readonly initialCaptures?:ReadonlyMap<string,CapturedExecution>;\n readonly capture?:Partial<ServiceCaptureOperations>;\n readonly events?:SessionEventSource;\n readonly heartbeatIntervalMs?:number;\n readonly extensions?:CoordinatorExtensionService;\n}\n\nexport async function startService(engine: Coordinator, token: string, instanceId: string, state?:string,\n options:ServiceOptions={}) {\n const directory=resolveStateDirectory(state);\n const captures=new Map<string,CapturedExecution>(options.initialCaptures);\n const captureOperations:ServiceCaptureOperations={captureExecution,captureReference,checkCapturedExecution,...options.capture};\n const eventSource=options.events ?? (engine as Coordinator & {readonly events?:SessionEventSource}).events;\n const extensions=options.extensions;\n const sdkOperations={\n listAgents:async(data:Record<string,unknown>)=>listAgents(await catalogInput(data,directory)),\n checkAgent:async(data:Record<string,unknown>)=>{\n const input=await catalogInput(data,directory); await checkAgent(connectedAgent(data.agent),input);\n },\n createSession:async(data:Record<string,unknown>):Promise<string>=>{\n const input=await catalogInput(data,directory);\n const captured=await captureOperations.captureExecution(connectedAgent(data.agent),input);\n try {\n const observers=await extensions?.prepareAdmission(input.cwd);\n const id=engine.createSession({reference:captured.reference,cwd:input.cwd,env:input.env},captured.prepared,observers);\n captures.set(id,captured); return id;\n } catch(error) { return releaseRejected(captured,error); }\n },\n closeSession:async(id:string)=>{ await engine.closeSession(id); captures.delete(id); },\n };\n const server = createServer(async (request, response) => {\n if (request.headers.authorization !== `Bearer ${token}`) { response.writeHead(401).end(); return; }\n if (request.method === 'GET' && request.url === '/health') {\n response.setHeader('content-type','application/json');\n response.end(JSON.stringify({\n version:1,\n type:'coordinator-health',\n instanceId,\n protocolVersion:1,\n capabilities:['sdk-v1','cli-v1',...(eventSource ? ['session-events-v1'] : [])],\n }));\n return;\n }\n if (request.method !== 'POST' || request.url !== '/') { response.writeHead(404).end(); return; }\n if (request.headers['x-subharness-instance'] !== instanceId) { response.writeHead(409).end(); return; }\n response.setHeader('content-type', 'application/x-ndjson');\n const observer = new AbortController();\n // Keep long, quiet observations alive without exposing progress records to callers.\n const heartbeat = setInterval(() => {\n if (!response.destroyed && !response.writableNeedDrain) response.write('\\n');\n }, options.heartbeatIntervalMs ?? 15_000);\n response.once('close', () => { clearInterval(heartbeat); observer.abort(); });\n const write = (record: unknown) => { if (!response.destroyed) response.write(JSON.stringify(record) + '\\n'); };\n try {\n let body = '';\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 4 * 1024 * 1024) throw new AgentError('INVALID_ARGUMENT','Request exceeds 4 MiB.');\n }\n let data: Request;\n try { data = JSON.parse(body) as Request; }\n catch { throw new AgentError('INVALID_ARGUMENT','Coordinator input must be valid JSON.'); }\n if (!data || typeof data !== 'object' || Array.isArray(data))\n throw new AgentError('INVALID_ARGUMENT','Coordinator input must be a JSON object.');\n if (isSessionEventCommand(data.command)) {\n if (!eventSource) {\n const unsupported=new AgentError('COORDINATOR_INCOMPATIBLE','The coordinator does not support live session events.');\n if (data.command === 'sdk.events.open') {\n await writeSessionEventRecord(response,{version:1,type:'events.error',error:errorInfo(unsupported)},observer.signal);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n throw unsupported;\n }\n for await (const record of dispatchSessionEventRequest(eventSource,data as unknown as Record<string,unknown>,observer.signal))\n await writeSessionEventRecord(response,record,observer.signal);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n if (isExtensionManagementCommand(data.command)) {\n if (!extensions) throw new AgentError('INVALID_ARGUMENT','Unknown coordinator operation.');\n write(await dispatchExtensionManagement(extensions,data as unknown as Record<string,unknown>));\n clearInterval(heartbeat);\n response.end();\n return;\n }\n if (isSdkCommand(data.command)) {\n for await (const record of dispatchSdkRequest(engine,data as unknown as Record<string,unknown>,observer.signal,sdkOperations)) write(record);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n let receipt: Receipt | undefined;\n switch (data.command) {\n case 'dashboard': write(await engine.dashboard()); break;\n case 'dashboard-session':\n if (typeof data.id !== 'string')\n throw new AgentError('INVALID_ARGUMENT', 'Invalid dashboard session request fields.');\n write(await engine.dashboardSession(data.id)); break;\n case 'dashboard-detail':\n if (typeof data.id !== 'string' ||\n (data.includePrompt !== undefined && typeof data.includePrompt !== 'boolean') ||\n (data.knownResponseId !== undefined && typeof data.knownResponseId !== 'string'))\n throw new AgentError('INVALID_ARGUMENT', 'Invalid dashboard detail request fields.');\n write(await engine.dashboardDetail(data.id, data.includePrompt ?? true, data.knownResponseId)); break;\n case 'parent': write(engine.parentContext(data.parentToken!)); break;\n case 'parent-catalog': {\n const {captured}=bindParent(engine,captures,data.parentToken);\n write({version:1,type:'agents',agents:captured.children.map(child=>({\n id:`subagent:${child.name}`,name:child.name,description:child.description,scope:'subagent',\n }))});\n break;\n }\n case 'parent-check': {\n const binding=bindParent(engine,captures,data.parentToken);\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory);\n const captured=binding.captured;\n const child=await captured.child(childName(data.agent));\n try { validateParentBinding(engine,binding); }\n catch(error) { await releaseRejected(child,error); }\n await captureOperations.checkCapturedExecution(child,input);\n write({version:1,type:'ack'}); break;\n }\n case 'parent-run': {\n const binding=bindParent(engine,captures,data.parentToken);\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory);\n const captured=binding.captured;\n const child=await captured.child(childName(data.agent));\n try {\n validateParentBinding(engine,binding);\n const observers=await extensions?.prepareAdmission(input.cwd);\n receipt=engine.run({reference:child.reference,cwd:input.cwd,env:input.env,\n prompt:data.prompt!,parentToken:binding.token},child.prepared,observers);\n captures.set(receipt.sessionId,child);\n } catch(error) { await releaseRejected(child,error); }\n break;\n }\n case 'cli-run': {\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory);\n const captured=data.reference\n ? await captureOperations.captureReference(data.reference,input)\n : await captureOperations.captureExecution(connectedAgent(data.agent),input);\n try {\n const observers=await extensions?.prepareAdmission(input.cwd);\n receipt=engine.run({reference:captured.reference,cwd:input.cwd,env:input.env,\n prompt:data.prompt!,parentToken:data.parentToken},captured.prepared,observers);\n captures.set(receipt.sessionId,captured);\n } catch(error) { await releaseRejected(captured,error); }\n break;\n }\n case 'run': {\n if (!data.input || typeof data.input !== 'object' || Array.isArray(data.input))\n throw new AgentError('INVALID_ARGUMENT','Invalid legacy run input.');\n const legacy=data.input;\n if (!legacy.reference || typeof legacy.reference !== 'object' || Array.isArray(legacy.reference)\n || typeof legacy.cwd !== 'string')\n throw new AgentError('INVALID_ARGUMENT','Invalid legacy run input.');\n const observers=await extensions?.prepareAdmission(legacy.cwd);\n if ('kind' in legacy.reference && legacy.reference.kind === 'inline') {\n receipt=engine.run(legacy,undefined,observers);\n break;\n }\n const captured=await captureOperations.captureReference(legacy.reference,{cwd:legacy.cwd,env:legacy.env});\n try {\n receipt=engine.run({...legacy,reference:captured.reference},withStateDirectory(captured.prepared,directory),observers);\n captures.set(receipt.sessionId,captured);\n } catch(error) { await releaseRejected(captured,error); }\n break;\n }\n case 'send':\n if (data.detach && data.delivery === 'steer') throw new AgentError('INVALID_ARGUMENT','--detach cannot be combined with --delivery steer.');\n receipt = await engine.send(data.id!, data.prompt!, data.delivery ?? 'queue', data.parentToken); break;\n case 'resume': {\n const active = engine.queue(data.id!).active;\n if (!active || active.state !== 'failed') throw new AgentError('NOT_FAILED','This session has no failed task to resume.');\n const after = engine.status(active.taskId).response?.responseId;\n receipt = await engine.resume(data.id!);\n write(receipt); write(await engine.observe(receipt.taskId, after, data.parentToken, observer.signal));\n receipt = undefined; break;\n }\n case 'wait': write(await engine.observe(data.id!, data.after, data.parentToken, observer.signal)); break;\n case 'status': write(engine.status(data.id!, data.full)); break;\n case 'queue': write(engine.queue(data.id!)); break;\n case 'cancel': write(await engine.cancel(data.id!)); break;\n case 'respond': write(engine.respond(data.id!,data.content,data.parentToken)); break;\n default: throw new AgentError('INVALID_ARGUMENT','Unknown coordinator operation.');\n }\n if (receipt) {\n write(receipt);\n if (receipt.type === 'started' && !data.detach) {\n write(await engine.observe(receipt.taskId, undefined, data.parentToken ?? data.input?.parentToken, observer.signal));\n }\n }\n } catch (error) { write({version:1,type:'error',error:serviceErrorInfo(error)}); }\n clearInterval(heartbeat);\n response.end();\n });\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n return {\n url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/`,\n async close() {\n let failure: unknown;\n try { await engine.close(); }\n catch (error) { failure = error; }\n try { await extensions?.close(); }\n catch (error) { failure = failure ? new AggregateError([failure,error],'Coordinator service cleanup failed.') : error; }\n finally {\n server.closeAllConnections();\n await new Promise<void>(resolve => server.close(() => resolve()));\n }\n if (failure) throw failure;\n },\n };\n}\n\nfunction serviceErrorInfo(error: unknown): ReturnType<typeof errorInfo> {\n if (error instanceof AggregateError) {\n const safe = [...error.errors].find((entry): entry is AgentError => entry instanceof AgentError);\n if (safe) return errorInfo(safe);\n }\n return errorInfo(error);\n}\n\nasync function catalogInput(data:Record<string,unknown>,directory:string):Promise<CatalogEnvironment> {\n const cwd=data.cwd;\n if(typeof cwd!=='string'||!isAbsolute(cwd))throw new AgentError('INVALID_ARGUMENT','Execution cwd must be an existing absolute directory.');\n try{if(!(await stat(cwd)).isDirectory())throw new Error();}\n catch{throw new AgentError('INVALID_ARGUMENT','Execution cwd must be an existing absolute directory.');}\n const source=data.env;\n if(!source||typeof source!=='object'||Array.isArray(source))throw new AgentError('INVALID_ARGUMENT','Connected environment must be an object.');\n const env:NodeJS.ProcessEnv={};\n for(const key of Reflect.ownKeys(source)){\n if(typeof key!=='string')throw new AgentError('INVALID_ARGUMENT','Connected environment keys must be strings.');\n const value=(source as Record<string,unknown>)[key];\n if(value!==undefined&&typeof value!=='string')throw new AgentError('INVALID_ARGUMENT','Connected environment values must be strings or undefined.');\n if(typeof value==='string')env[key]=value;\n }\n delete env.AGENT_PARENT_TOKEN;delete env.AGENT_CLI_PATH;env.AGENT_STATE_DIR=directory;\n return {cwd,env};\n}\n\nfunction connectedAgent(value:unknown):string|HarnessConfig {\n if(typeof value==='string'||(value!==null&&typeof value==='object'&&!Array.isArray(value)))return value as string|HarnessConfig;\n throw new AgentError('INVALID_ARGUMENT','Connected agent must be an ID or harness configuration.');\n}\n\ninterface ParentBinding {readonly token:string;readonly taskId:string;readonly sessionId:string;readonly captured:CapturedExecution}\n\nfunction bindParent(engine:Coordinator,captures:Map<string,CapturedExecution>,token:unknown):ParentBinding {\n if(typeof token!=='string'||!token)throw new AgentError('INVALID_PARENT','The parent context is no longer active.');\n const context=engine.parentContext(token);\n const captured=captures.get(context.sessionId);\n if(!captured)throw new AgentError('INVALID_PARENT','The active parent does not own a captured definition graph.');\n return {token,taskId:context.taskId,sessionId:context.sessionId,captured};\n}\n\nfunction validateParentBinding(engine:Coordinator,binding:ParentBinding):void {\n const current=engine.parentContext(binding.token);\n if(current.taskId!==binding.taskId||current.sessionId!==binding.sessionId)\n throw new AgentError('INVALID_PARENT','The parent context is no longer active.');\n}\n\nfunction childName(value:unknown):string {\n if(typeof value!=='string'||!value.startsWith('subagent:')||!value.slice(9))\n throw new AgentError('INVALID_PARENT','This subagent is not available in the active parent context.');\n return value.slice(9);\n}\n\nasync function releaseRejected(captured:CapturedExecution,admissionError:unknown):Promise<never> {\n try { await captured.prepared.close(); }\n catch { throw new AgentError('HARNESS_FAILED','Captured execution cleanup failed after admission was rejected.'); }\n throw admissionError;\n}\n\nfunction withStateDirectory(prepared:PreparedExecution,directory:string):PreparedExecution {\n return {\n ...(prepared.display ? {display:prepared.display} : {}),\n open:input=>prepared.open({...input,env:{...input.env,AGENT_STATE_DIR:directory}}),\n close:()=>prepared.close(),\n };\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/runtime/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGrD,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,sBAAsB,EAA0B,MAAM,cAAc,CAAC;AAClH,OAAO,EAAE,UAAU,EAAE,UAAU,EAA6B,MAAM,cAAc,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAGnD,OAAO,EAAE,2BAA2B,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAC1H,OAAO,EAAE,2BAA2B,EAAE,4BAA4B,EAC9B,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAwB,MAAM,8BAA8B,CAAC;AAyBjH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,MAAmB,EAAE,KAAa,EAAE,UAAkB,EAAE,KAAa,EACtG,OAAO,GAAgB,EAAE;IACzB,MAAM,SAAS,GAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC;IAC7C,MAAM,QAAQ,GAAC,IAAI,GAAG,CAA2B,OAAO,CAAC,eAAe,CAAC,CAAC;IAC1E,MAAM,iBAAiB,GAA0B,EAAC,gB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QAAQ,CAAC,OAAO,EAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,IAAI,EAAC,KAAK,CAAA,EAAE,CAAA,QAAQ,CAAC,IAAI,CAAC,EAAC,GAAG,KAAK,EAAC,GAAG,EAAC,EAAC,GAAG,KAAK,CAAC,GAAG,EAAC,eAAe,EAAC,SAAS,EAAC,EAAC,CAAC;QAClF,KAAK,EAAC,GAAE,EAAE,CAAA,QAAQ,CAAC,KAAK,EAAE;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { stat } from 'node:fs/promises';\nimport { isAbsolute } from 'node:path';\nimport { AgentError, errorInfo } from '../errors.js';\nimport { Coordinator } from './coordinator.js';\nimport type { Delivery, ExecutionReference, PreparedExecution, Receipt, SessionInput } from './types.js';\nimport { dispatchSdkRequest, isSdkCommand } from './sdk-service.js';\nimport { captureExecution, captureReference, checkCapturedExecution, type CapturedExecution } from './capture.js';\nimport { checkAgent, listAgents, type ExecutionEnvironment } from './catalog.js';\nimport { resolveStateDirectory } from './state.js';\nimport type { HarnessConfig } from '../sdk/types.js';\nimport type { SessionEventSource } from '../sdk/event-types.js';\nimport { dispatchSessionEventRequest, isSessionEventCommand, writeSessionEventRecord } from './session-events-service.js';\nimport { dispatchExtensionManagement, isExtensionManagementCommand,\n type CoordinatorExtensionService } from './extension-service.js';\nimport { canonicalProjectRoot, retainSelectedProject, type SelectedProject } from '../config/project-context.js';\n\ninterface Request {\n command: string; input?: SessionInput; id?: string; after?: string;\n prompt?: string; delivery?: Delivery; full?: boolean; detach?: boolean; parentToken?: string;\n content?: unknown;\n includePrompt?: boolean; knownResponseId?: string;\n agent?: unknown; cwd?: string; env?: NodeJS.ProcessEnv;\n reference?: ExecutionReference;\n projectRoot?: string;\n}\n\nexport interface ServiceCaptureOperations {\n captureExecution:typeof captureExecution;\n captureReference:typeof captureReference;\n checkCapturedExecution:typeof checkCapturedExecution;\n}\nexport interface ServiceOptions {\n readonly initialCaptures?:ReadonlyMap<string,CapturedExecution>;\n readonly capture?:Partial<ServiceCaptureOperations>;\n readonly events?:SessionEventSource;\n readonly heartbeatIntervalMs?:number;\n readonly extensions?:CoordinatorExtensionService;\n}\n\nexport async function startService(engine: Coordinator, token: string, instanceId: string, state?:string,\n options:ServiceOptions={}) {\n const directory=resolveStateDirectory(state);\n const captures=new Map<string,CapturedExecution>(options.initialCaptures);\n const captureOperations:ServiceCaptureOperations={captureExecution,captureReference,checkCapturedExecution,...options.capture};\n const eventSource=options.events ?? (engine as Coordinator & {readonly events?:SessionEventSource}).events;\n const extensions=options.extensions;\n const sdkOperations={\n listAgents:async(data:Record<string,unknown>)=>listAgents(await catalogInput(data,directory)),\n checkAgent:async(data:Record<string,unknown>)=>{\n const input=await catalogInput(data,directory); await checkAgent(connectedAgent(data.agent),input);\n },\n createSession:async(data:Record<string,unknown>):Promise<string>=>{\n const input=await catalogInput(data,directory);\n const captured=await captureOperations.captureExecution(connectedAgent(data.agent),input);\n try {\n const observers=await extensions?.prepareAdmission(input.cwd);\n const id=engine.createSession({reference:captured.reference,cwd:input.cwd,env:input.env},captured.prepared,observers);\n captures.set(id,captured); return id;\n } catch(error) { return releaseRejected(captured,error); }\n },\n closeSession:async(id:string)=>{ await engine.closeSession(id); captures.delete(id); },\n };\n const server = createServer(async (request, response) => {\n if (request.headers.authorization !== `Bearer ${token}`) { response.writeHead(401).end(); return; }\n if (request.method === 'GET' && request.url === '/health') {\n response.setHeader('content-type','application/json');\n response.end(JSON.stringify({\n version:1,\n type:'coordinator-health',\n instanceId,\n protocolVersion:1,\n capabilities:['sdk-v1','cli-v1','cli-root-v1',...(eventSource ? ['session-events-v1'] : [])],\n }));\n return;\n }\n if (request.method !== 'POST' || request.url !== '/') { response.writeHead(404).end(); return; }\n if (request.headers['x-subharness-instance'] !== instanceId) { response.writeHead(409).end(); return; }\n response.setHeader('content-type', 'application/x-ndjson');\n const observer = new AbortController();\n // Keep long, quiet observations alive without exposing progress records to callers.\n const heartbeat = setInterval(() => {\n if (!response.destroyed && !response.writableNeedDrain) response.write('\\n');\n }, options.heartbeatIntervalMs ?? 15_000);\n response.once('close', () => { clearInterval(heartbeat); observer.abort(); });\n const write = (record: unknown) => { if (!response.destroyed) response.write(JSON.stringify(record) + '\\n'); };\n try {\n let body = '';\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 4 * 1024 * 1024) throw new AgentError('INVALID_ARGUMENT','Request exceeds 4 MiB.');\n }\n let data: Request;\n try { data = JSON.parse(body) as Request; }\n catch { throw new AgentError('INVALID_ARGUMENT','Coordinator input must be valid JSON.'); }\n if (!data || typeof data !== 'object' || Array.isArray(data))\n throw new AgentError('INVALID_ARGUMENT','Coordinator input must be a JSON object.');\n if (isSessionEventCommand(data.command)) {\n if (!eventSource) {\n const unsupported=new AgentError('COORDINATOR_INCOMPATIBLE','The coordinator does not support live session events.');\n if (data.command === 'sdk.events.open') {\n await writeSessionEventRecord(response,{version:1,type:'events.error',error:errorInfo(unsupported)},observer.signal);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n throw unsupported;\n }\n for await (const record of dispatchSessionEventRequest(eventSource,data as unknown as Record<string,unknown>,observer.signal))\n await writeSessionEventRecord(response,record,observer.signal);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n if (isExtensionManagementCommand(data.command)) {\n if (!extensions) throw new AgentError('INVALID_ARGUMENT','Unknown coordinator operation.');\n write(await dispatchExtensionManagement(extensions,data as unknown as Record<string,unknown>));\n clearInterval(heartbeat);\n response.end();\n return;\n }\n if (isSdkCommand(data.command)) {\n for await (const record of dispatchSdkRequest(engine,data as unknown as Record<string,unknown>,observer.signal,sdkOperations)) write(record);\n clearInterval(heartbeat);\n response.end();\n return;\n }\n let receipt: Receipt | undefined;\n switch (data.command) {\n case 'dashboard': write(await engine.dashboard()); break;\n case 'dashboard-session':\n if (typeof data.id !== 'string')\n throw new AgentError('INVALID_ARGUMENT', 'Invalid dashboard session request fields.');\n write(await engine.dashboardSession(data.id)); break;\n case 'dashboard-detail':\n if (typeof data.id !== 'string' ||\n (data.includePrompt !== undefined && typeof data.includePrompt !== 'boolean') ||\n (data.knownResponseId !== undefined && typeof data.knownResponseId !== 'string'))\n throw new AgentError('INVALID_ARGUMENT', 'Invalid dashboard detail request fields.');\n write(await engine.dashboardDetail(data.id, data.includePrompt ?? true, data.knownResponseId)); break;\n case 'parent': write(engine.parentContext(data.parentToken!)); break;\n case 'parent-catalog': {\n const {captured}=bindParent(engine,captures,data.parentToken);\n rejectManagedProjectOverride(data);\n write({version:1,type:'agents',agents:captured.children.map(child=>({\n id:`subagent:${child.name}`,name:child.name,description:child.description,scope:'subagent',\n }))});\n break;\n }\n case 'parent-check': {\n const binding=bindParent(engine,captures,data.parentToken);\n rejectManagedProjectOverride(data);\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory,binding.project);\n const captured=binding.captured;\n const child=await captured.child(childName(data.agent));\n try { validateParentBinding(engine,binding); }\n catch(error) { await releaseRejected(child,error); }\n await captureOperations.checkCapturedExecution(child,input);\n write({version:1,type:'ack'}); break;\n }\n case 'parent-run': {\n const binding=bindParent(engine,captures,data.parentToken);\n rejectManagedProjectOverride(data);\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory,binding.project);\n const captured=binding.captured;\n const child=await captured.child(childName(data.agent));\n try {\n validateParentBinding(engine,binding);\n const observers=await extensions?.prepareAdmission(input.cwd,input.project?.root);\n receipt=engine.run({reference:child.reference,cwd:input.cwd,env:input.env,\n prompt:data.prompt!,parentToken:binding.token,project:binding.project},child.prepared,observers);\n captures.set(receipt.sessionId,child);\n } catch(error) { await releaseRejected(child,error); }\n break;\n }\n case 'cli-run': {\n if(data.parentToken!==undefined)throw new AgentError('INVALID_PARENT','Managed execution must use a declared child operation.');\n const input=await catalogInput(data as unknown as Record<string,unknown>,directory,undefined,true);\n const captured=data.reference\n ? await captureOperations.captureReference(data.reference,input)\n : await captureOperations.captureExecution(connectedAgent(data.agent),input);\n try {\n const observers=await extensions?.prepareAdmission(input.cwd,input.project?.root);\n receipt=engine.run({reference:captured.reference,cwd:input.cwd,env:input.env,\n prompt:data.prompt!,project:input.project},captured.prepared,observers);\n captures.set(receipt.sessionId,captured);\n } catch(error) { await releaseRejected(captured,error); }\n break;\n }\n case 'run': {\n if(data.projectRoot!==undefined||(data as unknown as Record<string,unknown>).accessRoot!==undefined)\n throw new AgentError('INVALID_ARGUMENT','Legacy execution does not accept project-root selection.');\n if (!data.input || typeof data.input !== 'object' || Array.isArray(data.input))\n throw new AgentError('INVALID_ARGUMENT','Invalid legacy run input.');\n const legacy=data.input;\n if('project' in legacy||'projectRoot' in legacy||'accessRoot' in legacy)\n throw new AgentError('INVALID_ARGUMENT','Legacy execution does not accept project-root selection.');\n if (!legacy.reference || typeof legacy.reference !== 'object' || Array.isArray(legacy.reference)\n || typeof legacy.cwd !== 'string')\n throw new AgentError('INVALID_ARGUMENT','Invalid legacy run input.');\n const observers=await extensions?.prepareAdmission(legacy.cwd);\n if ('kind' in legacy.reference && legacy.reference.kind === 'inline') {\n receipt=engine.run(legacy,undefined,observers);\n break;\n }\n const captured=await captureOperations.captureReference(legacy.reference,{cwd:legacy.cwd,env:legacy.env});\n try {\n receipt=engine.run({...legacy,reference:captured.reference},withStateDirectory(captured.prepared,directory),observers);\n captures.set(receipt.sessionId,captured);\n } catch(error) { await releaseRejected(captured,error); }\n break;\n }\n case 'send':\n if (data.detach && data.delivery === 'steer') throw new AgentError('INVALID_ARGUMENT','--detach cannot be combined with --delivery steer.');\n receipt = await engine.send(data.id!, data.prompt!, data.delivery ?? 'queue', data.parentToken); break;\n case 'resume': {\n const active = engine.queue(data.id!).active;\n if (!active || active.state !== 'failed') throw new AgentError('NOT_FAILED','This session has no failed task to resume.');\n const after = engine.status(active.taskId).response?.responseId;\n receipt = await engine.resume(data.id!);\n write(receipt); write(await engine.observe(receipt.taskId, after, data.parentToken, observer.signal));\n receipt = undefined; break;\n }\n case 'wait': write(await engine.observe(data.id!, data.after, data.parentToken, observer.signal)); break;\n case 'status': write(engine.status(data.id!, data.full)); break;\n case 'queue': write(engine.queue(data.id!)); break;\n case 'cancel': write(await engine.cancel(data.id!)); break;\n case 'respond': write(engine.respond(data.id!,data.content,data.parentToken)); break;\n default: throw new AgentError('INVALID_ARGUMENT','Unknown coordinator operation.');\n }\n if (receipt) {\n write(receipt);\n if (receipt.type === 'started' && !data.detach) {\n write(await engine.observe(receipt.taskId, undefined, data.parentToken ?? data.input?.parentToken, observer.signal));\n }\n }\n } catch (error) { write({version:1,type:'error',error:serviceErrorInfo(error)}); }\n clearInterval(heartbeat);\n response.end();\n });\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', resolve);\n });\n return {\n url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/`,\n async close() {\n let failure: unknown;\n try { await engine.close(); }\n catch (error) { failure = error; }\n try { await extensions?.close(); }\n catch (error) { failure = failure ? new AggregateError([failure,error],'Coordinator service cleanup failed.') : error; }\n finally {\n server.closeAllConnections();\n await new Promise<void>(resolve => server.close(() => resolve()));\n }\n if (failure) throw failure;\n },\n };\n}\n\nfunction serviceErrorInfo(error: unknown): ReturnType<typeof errorInfo> {\n if (error instanceof AggregateError) {\n const safe = [...error.errors].find((entry): entry is AgentError => entry instanceof AgentError);\n if (safe) return errorInfo(safe);\n }\n return errorInfo(error);\n}\n\nasync function catalogInput(data:Record<string,unknown>,directory:string,inherited?:SelectedProject,\n allowProjectRoot=false):Promise<ExecutionEnvironment> {\n const cwd=data.cwd;\n if(typeof cwd!=='string'||!isAbsolute(cwd))throw new AgentError('INVALID_ARGUMENT','Execution cwd must be an existing absolute directory.');\n try{if(!(await stat(cwd)).isDirectory())throw new Error();}\n catch{throw new AgentError('INVALID_ARGUMENT','Execution cwd must be an existing absolute directory.');}\n const source=data.env;\n if(!source||typeof source!=='object'||Array.isArray(source))throw new AgentError('INVALID_ARGUMENT','Connected environment must be an object.');\n const env:NodeJS.ProcessEnv={};\n for(const key of Reflect.ownKeys(source)){\n if(typeof key!=='string')throw new AgentError('INVALID_ARGUMENT','Connected environment keys must be strings.');\n const value=(source as Record<string,unknown>)[key];\n if(value!==undefined&&typeof value!=='string')throw new AgentError('INVALID_ARGUMENT','Connected environment values must be strings or undefined.');\n if(typeof value==='string')env[key]=value;\n }\n delete env.AGENT_PARENT_TOKEN;delete env.AGENT_CLI_PATH;env.AGENT_STATE_DIR=directory;\n if(data.accessRoot!==undefined||data.project!==undefined)\n throw new AgentError('INVALID_ARGUMENT','Personal-access roots and retained project context are coordinator-owned.');\n let project=inherited;\n if(data.projectRoot!==undefined){\n if(!allowProjectRoot||typeof data.projectRoot!=='string')\n throw new AgentError('INVALID_ARGUMENT','Project-root selection is unavailable for this operation.');\n if(!isAbsolute(data.projectRoot))\n throw new AgentError('INVALID_ARGUMENT','Project root must be an absolute directory.');\n project=await retainSelectedProject(await canonicalProjectRoot(data.projectRoot));\n }\n return {cwd,env,project};\n}\n\nfunction connectedAgent(value:unknown):string|HarnessConfig {\n if(typeof value==='string'||(value!==null&&typeof value==='object'&&!Array.isArray(value)))return value as string|HarnessConfig;\n throw new AgentError('INVALID_ARGUMENT','Connected agent must be an ID or harness configuration.');\n}\n\ninterface ParentBinding {readonly token:string;readonly taskId:string;readonly sessionId:string;readonly captured:CapturedExecution;\n readonly project?:SelectedProject}\n\nfunction bindParent(engine:Coordinator,captures:Map<string,CapturedExecution>,token:unknown):ParentBinding {\n if(typeof token!=='string'||!token)throw new AgentError('INVALID_PARENT','The parent context is no longer active.');\n const context=engine.parentContext(token);\n const captured=captures.get(context.sessionId);\n if(!captured)throw new AgentError('INVALID_PARENT','The active parent does not own a captured definition graph.');\n return {token,taskId:context.taskId,sessionId:context.sessionId,captured,project:context.project};\n}\n\nfunction rejectManagedProjectOverride(data:Request):void{\n if(data.projectRoot!==undefined||(data as unknown as Record<string,unknown>).accessRoot!==undefined)\n throw new AgentError('INVALID_ARGUMENT','Managed list, run, and check inherit the parent project and do not accept --root.');\n}\n\nfunction validateParentBinding(engine:Coordinator,binding:ParentBinding):void {\n const current=engine.parentContext(binding.token);\n if(current.taskId!==binding.taskId||current.sessionId!==binding.sessionId)\n throw new AgentError('INVALID_PARENT','The parent context is no longer active.');\n}\n\nfunction childName(value:unknown):string {\n if(typeof value!=='string'||!value.startsWith('subagent:')||!value.slice(9))\n throw new AgentError('INVALID_PARENT','This subagent is not available in the active parent context.');\n return value.slice(9);\n}\n\nasync function releaseRejected(captured:CapturedExecution,admissionError:unknown):Promise<never> {\n try { await captured.prepared.close(); }\n catch { throw new AgentError('HARNESS_FAILED','Captured execution cleanup failed after admission was rejected.'); }\n throw admissionError;\n}\n\nfunction withStateDirectory(prepared:PreparedExecution,directory:string):PreparedExecution {\n return {\n ...(prepared.display ? {display:prepared.display} : {}),\n open:input=>prepared.open({...input,env:{...input.env,AGENT_STATE_DIR:directory}}),\n close:()=>prepared.close(),\n };\n}\n"]}
@@ -5,7 +5,7 @@ export interface Endpoint {
5
5
  instanceId: string;
6
6
  readonly capabilities?: readonly string[];
7
7
  }
8
- export type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'session-events-v1';
8
+ export type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'cli-root-v1' | 'session-events-v1';
9
9
  export type OwnerState = 'alive' | 'dead' | 'unknown';
10
10
  export type EndpointProbe = {
11
11
  readonly kind: 'absent';
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["../../src/runtime/state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,cA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MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,SAAS,EAAC,EAAC,UAAU,EAAC,QAAQ,EAAC,CAAC,CAAC;IACnE,OAAO,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AACD,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IAChE,OAAO,EAAE,IAAI,EAAC,aAAa,CAAC,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7E,QAAQ,EAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,EAAC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACjF,CAAC","sourcesContent":["import { homedir } from 'node:os';\nimport { isAbsolute, join, normalize } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { mkdir, readFile, chmod } from 'node:fs/promises';\nimport { AgentError } from '../errors.js';\n\nexport interface Endpoint {\n url: string;\n token: string;\n pid: number;\n instanceId: string;\n readonly capabilities?: readonly string[];\n}\nexport type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'session-events-v1';\nexport type OwnerState = 'alive' | 'dead' | 'unknown';\nexport type EndpointProbe =\n | { readonly kind: 'absent' }\n | { readonly kind: 'malformed' }\n | { readonly kind: 'reachable'; readonly endpoint: Endpoint }\n | { readonly kind: 'authentication-failed' | 'incompatible' | 'instance-mismatch'; readonly endpoint: Endpoint }\n | { readonly kind: 'unresponsive'; readonly endpoint: Endpoint; readonly owner: OwnerState };\nexport interface EndpointProbeOptions {\n readonly capability?: EndpointCapability;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly checkPid?: (pid: number) => OwnerState;\n}\nexport function resolveStateDirectory(\n explicit?: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const selected = explicit ?? env.AGENT_STATE_DIR ?? join(homedir(),'.subharness','state','shared');\n if (!selected || !isAbsolute(selected)) {\n throw new AgentError('INVALID_CONFIG','Coordinator state directory must be a nonempty absolute local path.');\n }\n return normalize(selected);\n}\nexport function stateDirectory() {\n return resolveStateDirectory();\n}\nexport async function privateDirectory(directory: string) {\n await mkdir(directory,{recursive:true,mode:0o700});\n await chmod(directory,0o700);\n}\nexport async function probeEndpoint(directory: string, options: EndpointProbeOptions = {}): Promise<EndpointProbe> {\n let source: string;\n try { source = await readFile(join(directory,'coordinator.json'),'utf8'); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {kind:'absent'};\n return {kind:'malformed'};\n }\n let candidate: unknown;\n try { candidate = JSON.parse(source); }\n catch { return {kind:'malformed'}; }\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return {kind:'malformed'};\n const endpoint = candidate as Partial<Endpoint>;\n if (!/^http:\\/\\/127\\.0\\.0\\.1:\\d+\\/$/.test(String(endpoint.url))\n || typeof endpoint.token !== 'string' || !endpoint.token\n || !Number.isSafeInteger(endpoint.pid) || endpoint.pid! <= 0\n || typeof endpoint.instanceId !== 'string' || !endpoint.instanceId) return {kind:'malformed'};\n const parsed = endpoint as Endpoint;\n let response: Response;\n try {\n const timeout = AbortSignal.timeout(Math.max(1,options.timeoutMs ?? 500));\n response = await fetch(parsed.url + 'health', {\n headers:{authorization:`Bearer ${parsed.token}`},\n signal:options.signal ? AbortSignal.any([options.signal,timeout]) : timeout,\n });\n } catch {\n return {kind:'unresponsive',endpoint:parsed,owner:(options.checkPid ?? processOwnerState)(parsed.pid)};\n }\n if (response.status === 401 || response.status === 403) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'authentication-failed',endpoint:parsed};\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'incompatible',endpoint:parsed};\n }\n let health: unknown;\n try { health = await response.json(); }\n catch { return {kind:'incompatible',endpoint:parsed}; }\n if (!health || typeof health !== 'object' || Array.isArray(health)) return {kind:'incompatible',endpoint:parsed};\n const record = health as Record<string,unknown>;\n if (record.instanceId !== parsed.instanceId) return {kind:'instance-mismatch',endpoint:parsed};\n if (record.version !== 1 || record.type !== 'coordinator-health' || record.protocolVersion !== 1\n || !Array.isArray(record.capabilities) || !record.capabilities.every(item => typeof item === 'string')\n || (options.capability && !record.capabilities.includes(options.capability))) {\n return {kind:'incompatible',endpoint:parsed};\n }\n // Capabilities are live health metadata, not part of the persisted owner-private endpoint record.\n Object.defineProperty(parsed,'capabilities',{\n value:Object.freeze([...record.capabilities]),enumerable:false,writable:false,configurable:false,\n });\n return {kind:'reachable',endpoint:parsed};\n}\n\nexport function processOwnerState(pid: number): OwnerState {\n try { process.kill(pid,0); return 'alive'; }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === 'ESRCH' ? 'dead' : 'unknown';\n }\n}\nexport async function readEndpoint(directory: string): Promise<Endpoint | undefined> {\n const probe = await probeEndpoint(directory,{capability:'cli-v1'});\n return probe.kind === 'reachable' ? probe.endpoint : undefined;\n}\nexport function localProgram(name: string) {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n return { file:fileURLToPath(new URL(`./${name}.${extension}`, import.meta.url)),\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [] };\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../src/runtime/state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE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C,CAAC,SAAS,CAAC;IAC/C,CAAC;AACH,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,SAAiB;IAClD,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,SAAS,EAAC,EAAC,UAAU,EAAC,QAAQ,EAAC,CAAC,CAAC;IACnE,OAAO,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AACD,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IAChE,OAAO,EAAE,IAAI,EAAC,aAAa,CAAC,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7E,QAAQ,EAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,EAAC,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;AACjF,CAAC","sourcesContent":["import { homedir } from 'node:os';\nimport { isAbsolute, join, normalize } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { mkdir, readFile, chmod } from 'node:fs/promises';\nimport { AgentError } from '../errors.js';\n\nexport interface Endpoint {\n url: string;\n token: string;\n pid: number;\n instanceId: string;\n readonly capabilities?: readonly string[];\n}\nexport type EndpointCapability = 'sdk-v1' | 'cli-v1' | 'cli-root-v1' | 'session-events-v1';\nexport type OwnerState = 'alive' | 'dead' | 'unknown';\nexport type EndpointProbe =\n | { readonly kind: 'absent' }\n | { readonly kind: 'malformed' }\n | { readonly kind: 'reachable'; readonly endpoint: Endpoint }\n | { readonly kind: 'authentication-failed' | 'incompatible' | 'instance-mismatch'; readonly endpoint: Endpoint }\n | { readonly kind: 'unresponsive'; readonly endpoint: Endpoint; readonly owner: OwnerState };\nexport interface EndpointProbeOptions {\n readonly capability?: EndpointCapability;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly checkPid?: (pid: number) => OwnerState;\n}\nexport function resolveStateDirectory(\n explicit?: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const selected = explicit ?? env.AGENT_STATE_DIR ?? join(homedir(),'.subharness','state','shared');\n if (!selected || !isAbsolute(selected)) {\n throw new AgentError('INVALID_CONFIG','Coordinator state directory must be a nonempty absolute local path.');\n }\n return normalize(selected);\n}\nexport function stateDirectory() {\n return resolveStateDirectory();\n}\nexport async function privateDirectory(directory: string) {\n await mkdir(directory,{recursive:true,mode:0o700});\n await chmod(directory,0o700);\n}\nexport async function probeEndpoint(directory: string, options: EndpointProbeOptions = {}): Promise<EndpointProbe> {\n let source: string;\n try { source = await readFile(join(directory,'coordinator.json'),'utf8'); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {kind:'absent'};\n return {kind:'malformed'};\n }\n let candidate: unknown;\n try { candidate = JSON.parse(source); }\n catch { return {kind:'malformed'}; }\n if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return {kind:'malformed'};\n const endpoint = candidate as Partial<Endpoint>;\n if (!/^http:\\/\\/127\\.0\\.0\\.1:\\d+\\/$/.test(String(endpoint.url))\n || typeof endpoint.token !== 'string' || !endpoint.token\n || !Number.isSafeInteger(endpoint.pid) || endpoint.pid! <= 0\n || typeof endpoint.instanceId !== 'string' || !endpoint.instanceId) return {kind:'malformed'};\n const parsed = endpoint as Endpoint;\n let response: Response;\n try {\n const timeout = AbortSignal.timeout(Math.max(1,options.timeoutMs ?? 500));\n response = await fetch(parsed.url + 'health', {\n headers:{authorization:`Bearer ${parsed.token}`},\n signal:options.signal ? AbortSignal.any([options.signal,timeout]) : timeout,\n });\n } catch {\n return {kind:'unresponsive',endpoint:parsed,owner:(options.checkPid ?? processOwnerState)(parsed.pid)};\n }\n if (response.status === 401 || response.status === 403) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'authentication-failed',endpoint:parsed};\n }\n if (!response.ok) {\n void response.body?.cancel().catch(()=>{});\n return {kind:'incompatible',endpoint:parsed};\n }\n let health: unknown;\n try { health = await response.json(); }\n catch { return {kind:'incompatible',endpoint:parsed}; }\n if (!health || typeof health !== 'object' || Array.isArray(health)) return {kind:'incompatible',endpoint:parsed};\n const record = health as Record<string,unknown>;\n if (record.instanceId !== parsed.instanceId) return {kind:'instance-mismatch',endpoint:parsed};\n if (record.version !== 1 || record.type !== 'coordinator-health' || record.protocolVersion !== 1\n || !Array.isArray(record.capabilities) || !record.capabilities.every(item => typeof item === 'string')\n || (options.capability && !record.capabilities.includes(options.capability))) {\n return {kind:'incompatible',endpoint:parsed};\n }\n // Capabilities are live health metadata, not part of the persisted owner-private endpoint record.\n Object.defineProperty(parsed,'capabilities',{\n value:Object.freeze([...record.capabilities]),enumerable:false,writable:false,configurable:false,\n });\n return {kind:'reachable',endpoint:parsed};\n}\n\nexport function processOwnerState(pid: number): OwnerState {\n try { process.kill(pid,0); return 'alive'; }\n catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n return code === 'ESRCH' ? 'dead' : 'unknown';\n }\n}\nexport async function readEndpoint(directory: string): Promise<Endpoint | undefined> {\n const probe = await probeEndpoint(directory,{capability:'cli-v1'});\n return probe.kind === 'reachable' ? probe.endpoint : undefined;\n}\nexport function localProgram(name: string) {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n return { file:fileURLToPath(new URL(`./${name}.${extension}`, import.meta.url)),\n execArgv:extension === 'ts' ? ['--import',import.meta.resolve('tsx')] : [] };\n}\n"]}
@@ -8,6 +8,7 @@ import type { ApprovalRequest, TaskState } from './task-data.js';
8
8
  import type { AdapterEventPort } from '../adapters/event-types.js';
9
9
  import type { SessionEvent, SessionEventCapabilities } from '../sdk/event-types.js';
10
10
  import type { OwnerEventOperation } from './event-operation.js';
11
+ import type { SelectedProject } from '../config/project-context.js';
11
12
  export type { ApprovalRequest, TaskState } from './task-data.js';
12
13
  export type Delivery = 'queue' | 'steer' | 'interrupt';
13
14
  export interface AgentReference {
@@ -29,6 +30,7 @@ export interface SessionInput {
29
30
  env: NodeJS.ProcessEnv;
30
31
  prompt: string;
31
32
  parentToken?: string;
33
+ project?: SelectedProject;
32
34
  }
33
35
  export type SessionCreateInput = Omit<SessionInput, 'prompt' | 'parentToken'>;
34
36
  export interface DriverInput extends Omit<SessionInput, 'prompt' | 'parentToken'> {