subharness 0.0.5 → 0.0.7

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 (148) hide show
  1. package/README.md +59 -3
  2. package/dist/adapters/claude-process.js +8 -1
  3. package/dist/adapters/claude-process.js.map +1 -1
  4. package/dist/adapters/claude-tools.d.ts +6 -2
  5. package/dist/adapters/claude-tools.js +14 -12
  6. package/dist/adapters/claude-tools.js.map +1 -1
  7. package/dist/adapters/claude-worker-client.d.ts +49 -0
  8. package/dist/adapters/claude-worker-client.js +359 -0
  9. package/dist/adapters/claude-worker-client.js.map +1 -0
  10. package/dist/adapters/claude-worker-process.d.ts +20 -0
  11. package/dist/adapters/claude-worker-process.js +76 -0
  12. package/dist/adapters/claude-worker-process.js.map +1 -0
  13. package/dist/adapters/claude-worker-protocol.d.ts +38 -0
  14. package/dist/adapters/claude-worker-protocol.js +2 -0
  15. package/dist/adapters/claude-worker-protocol.js.map +1 -0
  16. package/dist/adapters/claude-worker.d.ts +1 -0
  17. package/dist/adapters/claude-worker.js +126 -0
  18. package/dist/adapters/claude-worker.js.map +1 -0
  19. package/dist/adapters/claude.d.ts +16 -6
  20. package/dist/adapters/claude.js +138 -68
  21. package/dist/adapters/claude.js.map +1 -1
  22. package/dist/cli/catalog-worker.js.map +1 -1
  23. package/dist/cli/dashboard-client.js +19 -30
  24. package/dist/cli/dashboard-client.js.map +1 -1
  25. package/dist/cli/main.js +53 -45
  26. package/dist/cli/main.js.map +1 -1
  27. package/dist/errors.d.ts +2 -2
  28. package/dist/errors.js.map +1 -1
  29. package/dist/index.d.ts +6 -0
  30. package/dist/index.js +3 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/runtime/approval-registry.d.ts +9 -0
  33. package/dist/runtime/approval-registry.js +143 -4
  34. package/dist/runtime/approval-registry.js.map +1 -1
  35. package/dist/runtime/capture.d.ts +22 -0
  36. package/dist/runtime/capture.js +320 -0
  37. package/dist/runtime/capture.js.map +1 -0
  38. package/dist/runtime/catalog.d.ts +39 -0
  39. package/dist/runtime/catalog.js +84 -0
  40. package/dist/runtime/catalog.js.map +1 -0
  41. package/dist/runtime/client.d.ts +2 -1
  42. package/dist/runtime/client.js +52 -65
  43. package/dist/runtime/client.js.map +1 -1
  44. package/dist/runtime/coordinator.d.ts +44 -7
  45. package/dist/runtime/coordinator.js +265 -31
  46. package/dist/runtime/coordinator.js.map +1 -1
  47. package/dist/runtime/daemon.js +12 -6
  48. package/dist/runtime/daemon.js.map +1 -1
  49. package/dist/runtime/dashboard-workspace.js +5 -1
  50. package/dist/runtime/dashboard-workspace.js.map +1 -1
  51. package/dist/runtime/definition.d.ts +6 -1
  52. package/dist/runtime/definition.js +31 -1
  53. package/dist/runtime/definition.js.map +1 -1
  54. package/dist/runtime/native-owner.js +7 -1
  55. package/dist/runtime/native-owner.js.map +1 -1
  56. package/dist/runtime/pagination.d.ts +9 -0
  57. package/dist/runtime/pagination.js +36 -0
  58. package/dist/runtime/pagination.js.map +1 -0
  59. package/dist/runtime/sdk-observation.d.ts +8 -0
  60. package/dist/runtime/sdk-observation.js +75 -0
  61. package/dist/runtime/sdk-observation.js.map +1 -0
  62. package/dist/runtime/sdk-projection.d.ts +8 -0
  63. package/dist/runtime/sdk-projection.js +19 -0
  64. package/dist/runtime/sdk-projection.js.map +1 -0
  65. package/dist/runtime/sdk-service.d.ts +11 -0
  66. package/dist/runtime/sdk-service.js +109 -0
  67. package/dist/runtime/sdk-service.js.map +1 -0
  68. package/dist/runtime/select-native.d.ts +4 -1
  69. package/dist/runtime/select-native.js +14 -17
  70. package/dist/runtime/select-native.js.map +1 -1
  71. package/dist/runtime/service.d.ts +11 -1
  72. package/dist/runtime/service.js +178 -3
  73. package/dist/runtime/service.js.map +1 -1
  74. package/dist/runtime/session-launcher.js +1 -1
  75. package/dist/runtime/session-launcher.js.map +1 -1
  76. package/dist/runtime/snapshots.d.ts +103 -0
  77. package/dist/runtime/snapshots.js +124 -0
  78. package/dist/runtime/snapshots.js.map +1 -0
  79. package/dist/runtime/state.d.ts +26 -0
  80. package/dist/runtime/state.js +86 -17
  81. package/dist/runtime/state.js.map +1 -1
  82. package/dist/runtime/task-data.d.ts +38 -0
  83. package/dist/runtime/task-data.js +2 -0
  84. package/dist/runtime/task-data.js.map +1 -0
  85. package/dist/runtime/transport.d.ts +13 -0
  86. package/dist/runtime/transport.js +166 -0
  87. package/dist/runtime/transport.js.map +1 -0
  88. package/dist/runtime/types.d.ts +28 -9
  89. package/dist/runtime/types.js.map +1 -1
  90. package/dist/runtime/worker-client.js +2 -0
  91. package/dist/runtime/worker-client.js.map +1 -1
  92. package/dist/runtime/worker-server.js +105 -24
  93. package/dist/runtime/worker-server.js.map +1 -1
  94. package/dist/sdk/connected-types.d.ts +42 -0
  95. package/dist/sdk/connected-types.js +2 -0
  96. package/dist/sdk/connected-types.js.map +1 -0
  97. package/dist/sdk/connected.d.ts +3 -0
  98. package/dist/sdk/connected.js +232 -0
  99. package/dist/sdk/connected.js.map +1 -0
  100. package/dist/sdk/execution-definition.d.ts +3 -0
  101. package/dist/sdk/execution-definition.js +59 -0
  102. package/dist/sdk/execution-definition.js.map +1 -0
  103. package/dist/sdk/execution-driver.d.ts +6 -0
  104. package/dist/sdk/execution-driver.js +86 -0
  105. package/dist/sdk/execution-driver.js.map +1 -0
  106. package/dist/sdk/execution-observation.d.ts +3 -0
  107. package/dist/sdk/execution-observation.js +35 -0
  108. package/dist/sdk/execution-observation.js.map +1 -0
  109. package/dist/sdk/execution-options.d.ts +17 -0
  110. package/dist/sdk/execution-options.js +115 -0
  111. package/dist/sdk/execution-options.js.map +1 -0
  112. package/dist/sdk/execution-types.d.ts +72 -0
  113. package/dist/sdk/execution-types.js +2 -0
  114. package/dist/sdk/execution-types.js.map +1 -0
  115. package/dist/sdk/execution.d.ts +3 -0
  116. package/dist/sdk/execution.js +3 -0
  117. package/dist/sdk/execution.js.map +1 -0
  118. package/dist/sdk/hosted-error.d.ts +3 -0
  119. package/dist/sdk/hosted-error.js +14 -0
  120. package/dist/sdk/hosted-error.js.map +1 -0
  121. package/dist/sdk/hosted.d.ts +23 -0
  122. package/dist/sdk/hosted.js +204 -0
  123. package/dist/sdk/hosted.js.map +1 -0
  124. package/dist/sdk/runner.d.ts +5 -0
  125. package/dist/sdk/runner.js +107 -0
  126. package/dist/sdk/runner.js.map +1 -0
  127. package/dist/sdk/tools.js +4 -1
  128. package/dist/sdk/tools.js.map +1 -1
  129. package/package.json +3 -3
  130. package/sdk/access-config.md +2 -0
  131. package/sdk/adapter-contract.md +8 -0
  132. package/sdk/agent.md +1 -1
  133. package/sdk/approvals.md +2 -0
  134. package/sdk/completion-notifications.md +2 -0
  135. package/sdk/distribution.md +4 -2
  136. package/sdk/examples/chat-tool.ts +126 -0
  137. package/sdk/execution.md +743 -0
  138. package/sdk/index.md +45 -21
  139. package/sdk/message-delivery.md +2 -0
  140. package/sdk/permissions.md +2 -0
  141. package/sdk/plugins/sub-agents.md +4 -2
  142. package/sdk/project-team.md +23 -1
  143. package/sdk/sessions.md +2 -0
  144. package/sdk/tools.md +3 -1
  145. package/sdk/v1-runtime.md +7 -5
  146. package/dist/cli/catalog.d.ts +0 -26
  147. package/dist/cli/catalog.js +0 -41
  148. package/dist/cli/catalog.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"approval-registry.js","sourceRoot":"","sources":["../../src/runtime/approval-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAmBzF,MAAM,oBAAoB,GAAG,KAAK,CAAC;AACnC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAC,qDAAqD,CAAC,CAA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AS;YACtF,MAAM,EAAC,OAAO,CAAC,MAAM,EAAC,SAAS,EAAC,OAAO,CAAC,SAAS,EAAC,CAAC;IACvD,CAAC;CACF","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { AgentError } from '../errors.js';\nimport { validateApprovalContent, validateApprovalSchema } from '../approvals/schema.js';\nimport type { ApprovalContent, NativeApprovalRequest } from '../approvals/types.js';\nimport type { ApprovalRequest } from './types.js';\n\ntype RequestIdentity = Pick<ApprovalRequest,'requestId'|'taskId'|'sessionId'>;\ninterface Continuation {\n resolve(content: ApprovalContent): void;\n reject(error: AgentError): void;\n cleanup(): void;\n}\ninterface PendingEntry {\n outcome: 'pending';\n request: ApprovalRequest;\n continuation: Continuation;\n}\ninterface AnsweredEntry { outcome: 'answered'; identity: RequestIdentity; answer: ApprovalContent }\ninterface WithdrawnEntry { outcome: 'withdrawn'; identity: RequestIdentity }\ntype SettledEntry = AnsweredEntry | WithdrawnEntry;\n\nconst MAX_SETTLED_REQUESTS = 1_024;\nconst expired = () => new AgentError('REQUEST_EXPIRED','The native permission request is no longer pending.');\nconst unknown = () => new AgentError('UNKNOWN_REQUEST','Permission request is unavailable in this coordinator.');\nconst identity = (request: ApprovalRequest): RequestIdentity => ({\n requestId:request.requestId,taskId:request.taskId,sessionId:request.sessionId,\n});\n\n/** Retains pending requests and a bounded settlement-ordered outcome history. */\nexport class ApprovalRegistry {\n private pending = new Map<string,PendingEntry>();\n private settled = new Map<string,SettledEntry>();\n constructor(private readonly changed: (taskId: string) => void) {}\n\n async register(taskId: string, sessionId: string, request: NativeApprovalRequest, signal: AbortSignal): Promise<ApprovalContent> {\n if (signal.aborted) throw expired();\n if (this.pendingFor(taskId).length >= 32)\n throw new AgentError('INPUT_REQUIRED','A task cannot wait on more than 32 permission requests.');\n let copy: NativeApprovalRequest;\n try {\n const serialized = JSON.stringify(request);\n if (Buffer.byteLength(serialized) > 64 * 1024) throw new Error();\n copy = JSON.parse(serialized) as NativeApprovalRequest;\n } catch { throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented within 64 KiB.'); }\n if (copy.kind !== 'permission' || !['codex','claudeCode','fx','opencode','copilot','cursor'].includes(copy.harness) || typeof copy.message !== 'string')\n throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented.');\n validateApprovalSchema(copy.requestedSchema);\n const requestId = `req_${randomUUID()}`;\n const snapshot: ApprovalRequest = {...copy,requestId,taskId,sessionId};\n if (Buffer.byteLength(JSON.stringify(snapshot)) > 64 * 1024)\n throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented within 64 KiB.');\n const answer = new Promise<ApprovalContent>((resolve,reject) => {\n const abort = () => this.retire(requestId);\n this.pending.set(requestId,{outcome:'pending',request:snapshot,\n continuation:{resolve,reject,cleanup:() => signal.removeEventListener('abort',abort)}});\n signal.addEventListener('abort',abort,{once:true});\n });\n this.changed(taskId);\n return answer;\n }\n\n request(id: string): RequestIdentity {\n const pending = this.pending.get(id);\n if (pending) return identity(pending.request);\n const settled = this.settled.get(id);\n if (!settled) throw unknown();\n return {...settled.identity};\n }\n\n respond(id: string, content: unknown) {\n const pending = this.pending.get(id);\n if (!pending) {\n const settled = this.settled.get(id);\n if (!settled) throw unknown();\n if (settled.outcome === 'withdrawn') throw expired();\n this.validateBoundedContent(content);\n if (!isDeepStrictEqual(settled.answer,content))\n throw new AgentError('INVALID_APPROVAL_RESPONSE','This permission request already has a different answer.');\n return this.receipt(settled.identity);\n }\n this.validateBoundedContent(content);\n const answer = validateApprovalContent(pending.request.requestedSchema,content);\n const requestIdentity = identity(pending.request);\n this.pending.delete(id);\n pending.continuation.cleanup();\n this.retain({outcome:'answered',identity:requestIdentity,answer:structuredClone(answer)});\n pending.continuation.resolve(answer);\n this.changed(requestIdentity.taskId);\n return this.receipt(requestIdentity);\n }\n\n pendingFor(taskId: string): ApprovalRequest[] {\n return [...this.pending.values()].filter(entry => entry.request.taskId === taskId)\n .map(entry => structuredClone(entry.request));\n }\n\n retireTask(taskId: string) {\n for (const [id,entry] of this.pending) if (entry.request.taskId === taskId) this.retire(id);\n }\n\n close() { for (const id of [...this.pending.keys()]) this.retire(id); }\n\n private retire(id: string) {\n const entry = this.pending.get(id);\n if (!entry) return;\n const requestIdentity = identity(entry.request);\n this.pending.delete(id);\n entry.continuation.cleanup();\n this.retain({outcome:'withdrawn',identity:requestIdentity});\n entry.continuation.reject(expired());\n this.changed(requestIdentity.taskId);\n }\n\n private retain(entry: SettledEntry) {\n this.settled.set(entry.identity.requestId,entry);\n while (this.settled.size > MAX_SETTLED_REQUESTS) {\n const oldest = this.settled.keys().next().value;\n if (oldest !== undefined) this.settled.delete(oldest);\n }\n }\n\n private validateBoundedContent(content: unknown) {\n let serialized: string | undefined;\n try { serialized = JSON.stringify(content); } catch { /* Report no submitted data. */ }\n if (!serialized || Buffer.byteLength(serialized) > 16 * 1024)\n throw new AgentError('INVALID_APPROVAL_RESPONSE','Approval content must be a JSON object within 16 KiB.');\n }\n\n private receipt(request: RequestIdentity) {\n return {version:1 as const,type:'approval_answered' as const,requestId:request.requestId,\n taskId:request.taskId,sessionId:request.sessionId};\n }\n}\n"]}
1
+ {"version":3,"file":"approval-registry.js","sourceRoot":"","sources":["../../src/runtime/approval-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAuBzF,MAAM,oBAAoB,GAAG,KAAK,CAAC;AACnC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAC,qDAAqD,CAAC,CAAC;AAC9G,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,iBAAiB,EAAC,wDAA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AC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { AgentError } from '../errors.js';\nimport { validateApprovalContent, validateApprovalSchema } from '../approvals/schema.js';\nimport type { ApprovalContent, ApprovalSchema, NativeApprovalRequest } from '../approvals/types.js';\nimport type { ApprovalRequest } from './types.js';\nimport type { ApprovalAction, ApprovalResponse, SdkApprovalRequest } from './task-data.js';\n\ntype RequestIdentity = Pick<ApprovalRequest,'requestId'|'taskId'|'sessionId'>;\ninterface Continuation {\n resolve(content: ApprovalContent): void;\n reject(error: AgentError): void;\n cleanup(): void;\n}\ninterface PendingEntry {\n outcome: 'pending';\n request: ApprovalRequest;\n continuation: Continuation;\n sdk: SdkApprovalRequest | AgentError;\n actions: Map<string, ActionMapping>;\n}\ninterface AnsweredEntry { outcome: 'answered'; identity: RequestIdentity; answer: ApprovalContent; schema: ApprovalSchema; actions: Map<string, ActionMapping> }\ninterface WithdrawnEntry { outcome: 'withdrawn'; identity: RequestIdentity }\ntype SettledEntry = AnsweredEntry | WithdrawnEntry;\ninterface ActionMapping { action: ApprovalAction; native: ApprovalContent; grants?: readonly string[] }\n\nconst MAX_SETTLED_REQUESTS = 1_024;\nconst expired = () => new AgentError('REQUEST_EXPIRED','The native permission request is no longer pending.');\nconst unknown = () => new AgentError('UNKNOWN_REQUEST','Permission request is unavailable in this coordinator.');\nconst identity = (request: ApprovalRequest): RequestIdentity => ({\n requestId:request.requestId,taskId:request.taskId,sessionId:request.sessionId,\n});\n\n/** Retains pending requests and a bounded settlement-ordered outcome history. */\nexport class ApprovalRegistry {\n private pending = new Map<string,PendingEntry>();\n private settled = new Map<string,SettledEntry>();\n constructor(private readonly changed: (taskId: string) => void) {}\n\n async register(taskId: string, sessionId: string, request: NativeApprovalRequest, signal: AbortSignal): Promise<ApprovalContent> {\n if (signal.aborted) throw expired();\n if (this.pendingFor(taskId).length >= 32)\n throw new AgentError('INPUT_REQUIRED','A task cannot wait on more than 32 permission requests.');\n let copy: NativeApprovalRequest;\n try {\n const serialized = JSON.stringify(request);\n if (Buffer.byteLength(serialized) > 64 * 1024) throw new Error();\n copy = JSON.parse(serialized) as NativeApprovalRequest;\n } catch { throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented within 64 KiB.'); }\n if (copy.kind !== 'permission' || !['codex','claudeCode','fx','opencode','copilot','cursor'].includes(copy.harness) || typeof copy.message !== 'string')\n throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented.');\n validateApprovalSchema(copy.requestedSchema);\n const requestId = `req_${randomUUID()}`;\n const snapshot: ApprovalRequest = {...copy,requestId,taskId,sessionId};\n if (Buffer.byteLength(JSON.stringify(snapshot)) > 64 * 1024)\n throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented within 64 KiB.');\n let sdk:SdkApprovalRequest|AgentError;\n let actions:Map<string,ActionMapping>;\n try { const normalized=normalize(snapshot); sdk=normalized.request; actions=normalized.actions; }\n catch(error) {\n if (!(error instanceof AgentError) || error.code !== 'INPUT_REQUIRED') throw error;\n sdk=error; actions=new Map();\n }\n const answer = new Promise<ApprovalContent>((resolve,reject) => {\n const abort = () => this.retire(requestId);\n this.pending.set(requestId,{outcome:'pending',request:snapshot,sdk,actions,\n continuation:{resolve,reject,cleanup:() => signal.removeEventListener('abort',abort)}});\n signal.addEventListener('abort',abort,{once:true});\n });\n this.changed(taskId);\n return answer;\n }\n\n request(id: string): RequestIdentity {\n const pending = this.pending.get(id);\n if (pending) return identity(pending.request);\n const settled = this.settled.get(id);\n if (!settled) throw unknown();\n return {...settled.identity};\n }\n\n respond(id: string, content: unknown) {\n const pending = this.pending.get(id);\n if (!pending) {\n const settled = this.settled.get(id);\n if (!settled) throw unknown();\n if (settled.outcome === 'withdrawn') throw expired();\n this.validateBoundedContent(content);\n let answer:ApprovalContent;\n try { answer=canonicalBySchema(settled.schema,validateApprovalContent(settled.schema,content)); }\n catch { invalidResponse(); }\n if (!isDeepStrictEqual(settled.answer,answer))\n throw new AgentError('INVALID_APPROVAL_RESPONSE','This permission request already has a different answer.');\n return this.receipt(settled.identity);\n }\n this.validateBoundedContent(content);\n const answer = canonicalBySchema(pending.request.requestedSchema,validateApprovalContent(pending.request.requestedSchema,content));\n const requestIdentity = identity(pending.request);\n this.pending.delete(id);\n pending.continuation.cleanup();\n this.retain({outcome:'answered',identity:requestIdentity,answer:structuredClone(answer),\n schema:structuredClone(pending.request.requestedSchema),actions:pending.actions});\n pending.continuation.resolve(answer);\n this.changed(requestIdentity.taskId);\n return this.receipt(requestIdentity);\n }\n\n pendingFor(taskId: string): ApprovalRequest[] {\n return [...this.pending.values()].filter(entry => entry.request.taskId === taskId)\n .map(entry => structuredClone(entry.request));\n }\n\n sdkPendingFor(taskId: string): SdkApprovalRequest[] {\n return [...this.pending.values()].filter(entry => entry.request.taskId === taskId)\n .map(entry => {\n if (entry.sdk instanceof AgentError) throw new AgentError(entry.sdk.code,entry.sdk.message);\n return structuredClone(entry.sdk);\n });\n }\n\n respondSdk(id: string, response: unknown) {\n const entry = this.pending.get(id) ?? this.settled.get(id);\n if (!entry) throw unknown();\n if (entry.outcome === 'withdrawn') throw expired();\n this.validateBoundedContent(response);\n if (!plain(response) || Reflect.ownKeys(response).some(key => typeof key !== 'string' || !['actionId','grants'].includes(key))\n || typeof response.actionId !== 'string') invalidResponse();\n const mapping = entry.actions.get(response.actionId);\n if (!mapping) invalidResponse();\n const submitted = response as unknown as ApprovalResponse;\n let native = structuredClone(mapping.native);\n if (mapping.grants) {\n if (mapping.action.decision !== 'allow' || !Array.isArray(submitted.grants)\n || submitted.grants.some(value => typeof value !== 'string') || new Set(submitted.grants).size !== submitted.grants.length\n || submitted.grants.some(value => !mapping.grants!.includes(value))) invalidResponse();\n const selected = new Set(submitted.grants);\n native = {...native, grants: mapping.grants.filter(id => selected.has(id))};\n } else if (Object.hasOwn(response,'grants')) invalidResponse();\n return this.respond(id,native);\n }\n\n retireTask(taskId: string) {\n for (const [id,entry] of this.pending) if (entry.request.taskId === taskId) this.retire(id);\n }\n\n close() { for (const id of [...this.pending.keys()]) this.retire(id); }\n\n private retire(id: string) {\n const entry = this.pending.get(id);\n if (!entry) return;\n const requestIdentity = identity(entry.request);\n this.pending.delete(id);\n entry.continuation.cleanup();\n this.retain({outcome:'withdrawn',identity:requestIdentity});\n entry.continuation.reject(expired());\n this.changed(requestIdentity.taskId);\n }\n\n private retain(entry: SettledEntry) {\n this.settled.set(entry.identity.requestId,entry);\n while (this.settled.size > MAX_SETTLED_REQUESTS) {\n const oldest = this.settled.keys().next().value;\n if (oldest !== undefined) this.settled.delete(oldest);\n }\n }\n\n private validateBoundedContent(content: unknown) {\n let serialized: string | undefined;\n try { serialized = JSON.stringify(content); } catch { /* Report no submitted data. */ }\n if (!serialized || Buffer.byteLength(serialized) > 16 * 1024)\n throw new AgentError('INVALID_APPROVAL_RESPONSE','Approval content must be a JSON object within 16 KiB.');\n }\n\n private receipt(request: RequestIdentity) {\n return {version:1 as const,type:'approval_answered' as const,requestId:request.requestId,\n taskId:request.taskId,sessionId:request.sessionId};\n }\n}\n\nfunction invalidResponse(): never {\n throw new AgentError('INVALID_APPROVAL_RESPONSE','The approval response does not match the requested actions.');\n}\n\nfunction plain(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n && [Object.prototype,null].includes(Object.getPrototypeOf(value));\n}\n\nfunction normalize(request: ApprovalRequest): {request: SdkApprovalRequest; actions: Map<string,ActionMapping>} {\n const actions = new Map<string,ActionMapping>();\n const grantsField = request.requestedSchema.properties.grants;\n const scopeField = request.requestedSchema.properties.scope;\n let grants: {id:string;label:string}[] | undefined;\n if (grantsField?.type === 'array' && grantsField.items.anyOf && scopeField?.type === 'string' && scopeField.oneOf) {\n grants = grantsField.items.anyOf.map(choice => ({id:choice.const,label:choice.title}));\n for (const choice of scopeField.oneOf) {\n const scope = choice.const === 'session' ? 'session' : 'turn';\n const action: ApprovalAction = {id:`act_${randomUUID()}`,label:`Allow for this ${scope}`,decision:'allow',scope};\n actions.set(action.id,{action,native:{scope:choice.const},grants:grants.map(grant=>grant.id)});\n }\n } else {\n const decision = request.requestedSchema.properties.decision;\n const choices=decision?.type === 'string'\n ? (decision.oneOf ?? decision.enum?.map(value=>({const:value,title:value}))) : undefined;\n if (!choices?.length) invalidNative();\n for (const choice of choices) {\n const metadata = decisionMetadata(request,choice.const);\n const action: ApprovalAction = metadata.decision === 'cancel'\n ? {id:`act_${randomUUID()}`,label:choice.title,decision:'cancel'}\n : {id:`act_${randomUUID()}`,label:choice.title,decision:metadata.decision,scope:metadata.scope,\n ...(metadata.scope === 'session' ? {description:'Applies to this native conversation.'} : {})};\n actions.set(action.id,{action,native:{decision:choice.const}});\n }\n }\n if (!actions.size) invalidNative();\n const groups=new Map<string,ActionMapping[]>();\n for (const mapping of actions.values()) {\n const key=mapping.action.decision === 'cancel' ? 'cancel' : `${mapping.action.decision}:${mapping.action.scope}`;\n const group=groups.get(key) ?? []; group.push(mapping); groups.set(key,group);\n }\n for (const group of groups.values()) if (group.length > 1) for (const mapping of group) {\n const native=typeof mapping.native.decision === 'string' ? mapping.native.decision : String(mapping.native.scope);\n mapping.action={...mapping.action,description:[mapping.action.description,`Native option: ${native}`].filter(Boolean).join(' ')};\n }\n return {request:{id:request.requestId,taskId:request.taskId,sessionId:request.sessionId,harness:request.harness,\n message:request.message,actions:[...actions.values()].map(value=>value.action),\n ...(grants ? {grants} : {}),...(request.context ? {context:structuredClone(request.context)} : {})},actions};\n}\n\nfunction invalidNative(): never {\n throw new AgentError('INPUT_REQUIRED','The native permission request cannot be represented.');\n}\n\nfunction decisionMetadata(request: ApprovalRequest, value: string): {decision:'allow'|'deny';scope:'once'|'session'} | {decision:'cancel'} {\n const options = Array.isArray(request.context?.options) ? request.context.options : [];\n const offered = options.find(option => plain(option) && (option.optionId === value));\n const kind = plain(offered) && typeof offered.kind === 'string' ? offered.kind : value;\n if (kind === 'cancel') return {decision:'cancel'};\n if (['acceptForSession','allow_session','allow_always'].includes(kind)) return {decision:'allow',scope:'session'};\n if (kind === 'reject_always') return {decision:'deny',scope:'session'};\n if (['accept','allow','allow_once','once','approve-once'].includes(kind)) return {decision:'allow',scope:'once'};\n if (['decline','deny','reject','reject_once'].includes(kind)) return {decision:'deny',scope:'once'};\n invalidNative();\n}\n\nfunction canonicalBySchema(schema:ApprovalSchema,answer:ApprovalContent):ApprovalContent {\n if (!Array.isArray(answer.grants)) return answer;\n const field=schema.properties.grants;\n if (field?.type !== 'array') return answer;\n const order=(field.items.anyOf ?? field.items.enum?.map(value=>({const:value,title:value})) ?? []).map(choice=>choice.const);\n const selected=new Set(answer.grants);\n return {...answer,grants:order.filter(value=>selected.has(value))};\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { HarnessConfig } from '../sdk/types.js';
2
+ import type { CatalogEnvironment } from './catalog.js';
3
+ import type { ExecutionReference, PreparedExecution } from './types.js';
4
+ export interface CapturedChild {
5
+ readonly name: string;
6
+ readonly description: string;
7
+ }
8
+ export interface CapturedExecution {
9
+ readonly reference: ExecutionReference;
10
+ readonly prepared: PreparedExecution;
11
+ readonly children: readonly CapturedChild[];
12
+ child(name: string): Promise<CapturedExecution>;
13
+ }
14
+ interface CaptureOptions {
15
+ workerModule?: URL;
16
+ shutdownTimeoutMs?: number;
17
+ }
18
+ export declare function captureExecution(agent: string | HarnessConfig, input: CatalogEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
19
+ /** Captures an already resolved private CLI reference without applying public connected validation. */
20
+ export declare function captureReference(reference: ExecutionReference, input: CatalogEnvironment, options?: CaptureOptions): Promise<CapturedExecution>;
21
+ export declare function checkCapturedExecution(captured: CapturedExecution, input: CatalogEnvironment): Promise<void>;
22
+ export {};
@@ -0,0 +1,320 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { AgentError, errorInfo } from '../errors.js';
5
+ import { createSessionLauncher } from './session-launcher.js';
6
+ import { processExitDescription } from '../process-diagnostics.js';
7
+ const shutdownTimeoutMs = 1_000;
8
+ class GraphConnection {
9
+ child;
10
+ timeout;
11
+ nextId = 1;
12
+ pending = new Map();
13
+ approvals = new Map();
14
+ handlers = new Map();
15
+ exited = false;
16
+ leases = new Set();
17
+ abandonedLeases = new Set();
18
+ observedExit = '';
19
+ processExit;
20
+ markExited;
21
+ constructor(child, timeout) {
22
+ this.child = child;
23
+ this.timeout = timeout;
24
+ this.processExit = new Promise(resolve => { this.markExited = resolve; });
25
+ child.once('error', () => this.exit(undefined, undefined, true));
26
+ child.once('exit', (code, signal) => this.exit(code, signal));
27
+ child.on('message', (message) => this.message(message));
28
+ }
29
+ setApprovalHandler(leaseId, handler) { this.handlers.set(leaseId, handler); }
30
+ deleteApprovalHandler(leaseId) { this.handlers.delete(leaseId); }
31
+ retainLease(leaseId) { this.leases.add(leaseId); }
32
+ async releaseLease(leaseId) {
33
+ this.leases.delete(leaseId);
34
+ await this.retryAbandonedLeases();
35
+ const retained = [...this.leases].filter(id => !this.abandonedLeases.has(id));
36
+ if (retained.length !== 0)
37
+ return;
38
+ if (this.abandonedLeases.size) {
39
+ this.abandonedLeases.clear();
40
+ this.leases.clear();
41
+ await this.stop();
42
+ return;
43
+ }
44
+ if (await this.waitWithin(this.timeout))
45
+ return;
46
+ await this.stop();
47
+ }
48
+ async abandonLease(leaseId) {
49
+ if (!this.leases.has(leaseId))
50
+ return;
51
+ const siblings = [...this.leases].filter(id => id !== leaseId && !this.abandonedLeases.has(id));
52
+ if (siblings.length) {
53
+ this.abandonedLeases.add(leaseId);
54
+ return;
55
+ }
56
+ this.leases.delete(leaseId);
57
+ await this.stop();
58
+ }
59
+ async retryAbandonedLeases() {
60
+ for (const leaseId of [...this.abandonedLeases]) {
61
+ try {
62
+ await this.request('lease.close', { leaseId });
63
+ this.abandonedLeases.delete(leaseId);
64
+ this.leases.delete(leaseId);
65
+ }
66
+ catch { /* Retain ownership until the remaining graph leases close. */ }
67
+ }
68
+ }
69
+ request(method, extra = {}) {
70
+ return new Promise((resolve, reject) => {
71
+ if (this.exited) {
72
+ reject(new AgentError('HARNESS_FAILED', `The captured definition worker is unavailable while ${method} was pending${this.observedExit}.`));
73
+ return;
74
+ }
75
+ const id = this.nextId++;
76
+ this.pending.set(id, { operation: method, resolve, reject });
77
+ this.child.send({ id, method, ...extra }, error => {
78
+ if (!error)
79
+ return;
80
+ setImmediate(() => {
81
+ const waiting = this.pending.get(id);
82
+ if (!waiting || this.exited)
83
+ return;
84
+ this.pending.delete(id);
85
+ waiting.reject(new AgentError('HARNESS_FAILED', `Cannot reach the captured definition worker while ${method} was pending.`));
86
+ });
87
+ });
88
+ });
89
+ }
90
+ message(message) {
91
+ if ('event' in message) {
92
+ const key = `${message.leaseId}:${message.requestId}`;
93
+ if (message.event === 'approval.withdraw') {
94
+ this.approvals.get(key)?.abort();
95
+ this.approvals.delete(key);
96
+ return;
97
+ }
98
+ const controller = new AbortController();
99
+ this.approvals.set(key, controller);
100
+ void Promise.resolve().then(() => {
101
+ const handler = this.handlers.get(message.leaseId);
102
+ if (!handler)
103
+ throw new AgentError('INPUT_REQUIRED', 'Native tool approval requires an observing caller.');
104
+ return handler(message.request, controller.signal);
105
+ }).then(content => { if (!controller.signal.aborted && !this.exited)
106
+ return this.request('approval.respond', { leaseId: message.leaseId, requestId: message.requestId, content }); }, error => { if (!controller.signal.aborted && !this.exited)
107
+ return this.request('approval.respond', { leaseId: message.leaseId, requestId: message.requestId, error: errorInfo(error) }); }).catch(error => {
108
+ if (!controller.signal.aborted && !this.exited)
109
+ return this.request('approval.respond', { leaseId: message.leaseId, requestId: message.requestId, error: errorInfo(error) }).catch(() => { });
110
+ }).finally(() => this.approvals.delete(key));
111
+ return;
112
+ }
113
+ const waiting = this.pending.get(message.id);
114
+ if (!waiting)
115
+ return;
116
+ this.pending.delete(message.id);
117
+ if (message.error)
118
+ waiting.reject(new AgentError(message.error.code, message.error.message));
119
+ else
120
+ waiting.resolve(message.result);
121
+ }
122
+ exit(code, signal, spawnFailure = false) {
123
+ if (this.exited)
124
+ return;
125
+ this.exited = true;
126
+ this.observedExit = spawnFailure ? '' : processExitDescription(code, signal);
127
+ for (const controller of this.approvals.values())
128
+ controller.abort();
129
+ this.approvals.clear();
130
+ this.markExited();
131
+ for (const waiting of this.pending.values())
132
+ waiting.reject(new AgentError('HARNESS_FAILED', spawnFailure
133
+ ? `The captured definition worker process failed while ${waiting.operation} was pending.`
134
+ : `The captured definition worker exited while ${waiting.operation} was pending${this.observedExit}.`));
135
+ this.pending.clear();
136
+ }
137
+ async stop() {
138
+ if (this.exited)
139
+ return;
140
+ if (this.child.connected)
141
+ try {
142
+ this.child.disconnect();
143
+ }
144
+ catch { }
145
+ if (await this.waitWithin(this.timeout))
146
+ return;
147
+ this.child.kill('SIGTERM');
148
+ if (await this.waitWithin(this.timeout))
149
+ return;
150
+ this.child.kill('SIGKILL');
151
+ if (!await this.waitWithin(this.timeout))
152
+ throw new AgentError('HARNESS_FAILED', 'The captured definition worker did not confirm termination.');
153
+ }
154
+ waitWithin(timeout) {
155
+ return new Promise(resolve => {
156
+ const timer = setTimeout(() => resolve(false), timeout);
157
+ this.processExit.then(() => { clearTimeout(timer); resolve(true); });
158
+ });
159
+ }
160
+ }
161
+ class CaptureLease {
162
+ graph;
163
+ leaseId;
164
+ reference;
165
+ prepared;
166
+ children;
167
+ launcher;
168
+ nativeClosed = false;
169
+ released = false;
170
+ closing = false;
171
+ opening;
172
+ constructor(graph, leaseId, reference, children) {
173
+ this.graph = graph;
174
+ this.leaseId = leaseId;
175
+ this.reference = reference;
176
+ this.graph.retainLease(leaseId);
177
+ this.children = Object.freeze(children.map(child => Object.freeze({ ...child })));
178
+ this.prepared = { open: input => this.open(input), close: () => this.close() };
179
+ }
180
+ async child(name) {
181
+ if (this.released)
182
+ throw new AgentError('INVALID_PARENT', 'The captured parent context is closed.');
183
+ const result = await this.graph.request('child', { leaseId: this.leaseId, name });
184
+ return new CaptureLease(this.graph, result.leaseId, result.reference, result.children);
185
+ }
186
+ async open(input) {
187
+ if (this.released || this.closing || this.opening)
188
+ throw new AgentError('HARNESS_FAILED', 'Native session startup is unavailable.');
189
+ const opening = this.startOpen(input);
190
+ this.opening = opening;
191
+ return opening;
192
+ }
193
+ async startOpen(input) {
194
+ const state = input.env.AGENT_STATE_DIR;
195
+ if (typeof state !== 'string' || !state)
196
+ throw new AgentError('INVALID_CONFIG', 'AGENT_STATE_DIR must select the coordinator state directory.');
197
+ const launcher = await createSessionLauncher(state, input.token);
198
+ this.launcher = launcher;
199
+ if (this.closing) {
200
+ await launcher.close();
201
+ this.launcher = undefined;
202
+ throw new AgentError('COORDINATOR_UNAVAILABLE', 'The captured session closed during startup.');
203
+ }
204
+ const { onApproval, ...serializedInput } = input;
205
+ let selectedHarness;
206
+ try {
207
+ this.graph.setApprovalHandler(this.leaseId, onApproval);
208
+ selectedHarness = await this.graph.request('open', { leaseId: this.leaseId, input: serializedInput,
209
+ handlesApprovals: !!onApproval, launcherPath: launcher.path });
210
+ }
211
+ catch (error) {
212
+ this.graph.deleteApprovalHandler(this.leaseId);
213
+ this.launcher = undefined;
214
+ await launcher.close();
215
+ throw error;
216
+ }
217
+ const request = (method, extra = {}) => this.graph.request(method, { leaseId: this.leaseId, ...extra });
218
+ return {
219
+ selectedHarness,
220
+ turn: prompt => request('turn', { prompt }),
221
+ steer: async (prompt) => { await request('steer', { prompt }); },
222
+ interrupt: async () => { await request('interrupt'); },
223
+ resume: () => request('resume'),
224
+ close: async () => {
225
+ if (this.nativeClosed)
226
+ return;
227
+ await request('native.close');
228
+ this.nativeClosed = true;
229
+ this.graph.deleteApprovalHandler(this.leaseId);
230
+ },
231
+ };
232
+ }
233
+ async close() {
234
+ this.closing = true;
235
+ if (!this.released) {
236
+ await this.graph.request('lease.close', { leaseId: this.leaseId });
237
+ this.released = true;
238
+ this.nativeClosed = true;
239
+ this.graph.deleteApprovalHandler(this.leaseId);
240
+ }
241
+ await this.opening?.catch(() => undefined);
242
+ if (this.launcher) {
243
+ await this.launcher.close();
244
+ this.launcher = undefined;
245
+ }
246
+ await this.graph.releaseLease(this.leaseId);
247
+ }
248
+ async abandonFailedCheck() {
249
+ this.closing = true;
250
+ this.released = true;
251
+ this.nativeClosed = true;
252
+ this.graph.deleteApprovalHandler(this.leaseId);
253
+ await this.opening?.catch(() => undefined);
254
+ if (this.launcher) {
255
+ await this.launcher.close().catch(() => { });
256
+ this.launcher = undefined;
257
+ }
258
+ await this.graph.abandonLease(this.leaseId);
259
+ }
260
+ }
261
+ export async function captureExecution(agent, input, options = {}) {
262
+ return captureRequest(input, options, { method: 'capture', agent });
263
+ }
264
+ /** Captures an already resolved private CLI reference without applying public connected validation. */
265
+ export async function captureReference(reference, input, options = {}) {
266
+ if ('kind' in reference && reference.kind === 'inline')
267
+ throw new AgentError('INVALID_DEFINITION', 'Inline agent definitions cannot be loaded by native CLI workers.');
268
+ return captureRequest(input, options, { method: 'capture.reference', reference });
269
+ }
270
+ async function captureRequest(input, options, request) {
271
+ const { AGENT_PARENT_TOKEN: _parent, AGENT_CLI_PATH: _launcher, ...environment } = input.env;
272
+ const workerModule = options.workerModule ?? new URL(`./worker.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`, import.meta.url);
273
+ const extension = workerModule.pathname.endsWith('.ts') ? 'ts' : 'js';
274
+ let child;
275
+ try {
276
+ child = fork(fileURLToPath(workerModule), [], { cwd: input.cwd, env: environment, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
277
+ execArgv: extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : [] });
278
+ }
279
+ catch {
280
+ throw new AgentError('INVALID_DEFINITION', 'The captured definition worker could not be spawned.');
281
+ }
282
+ const graph = new GraphConnection(child, options.shutdownTimeoutMs ?? shutdownTimeoutMs);
283
+ try {
284
+ const { method, ...data } = request;
285
+ const result = await graph.request(method, data);
286
+ return new CaptureLease(graph, result.leaseId, result.reference, result.children);
287
+ }
288
+ catch (error) {
289
+ await graph.stop().catch(() => { });
290
+ throw error;
291
+ }
292
+ }
293
+ export async function checkCapturedExecution(captured, input) {
294
+ let native;
295
+ let failure;
296
+ try {
297
+ native = await captured.prepared.open({ reference: captured.reference, cwd: input.cwd, env: input.env,
298
+ token: randomUUID(), sessionId: `check_${randomUUID()}` });
299
+ await native.close();
300
+ }
301
+ catch (error) {
302
+ failure = error;
303
+ }
304
+ try {
305
+ await captured.prepared.close();
306
+ }
307
+ catch (error) {
308
+ failure ??= error;
309
+ try {
310
+ await captured.prepared.close();
311
+ }
312
+ catch {
313
+ if (captured instanceof CaptureLease)
314
+ await captured.abandonFailedCheck();
315
+ }
316
+ }
317
+ if (failure)
318
+ throw failure;
319
+ }
320
+ //# sourceMappingURL=capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/runtime/capture.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAqB,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAkB,MAAM,cAAc,CAAC;AAMrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAkBnE,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC,MAAM,eAAe;IAYU,KAAK;IAA+B,OAAO;IAXhE,MAAM,GAAC,CAAC,CAAC;IACT,OAAO,GAAC,IAAI,GAAG,EAAkF,CAAC;IAClG,SAAS,GAAC,IAAI,GAAG,EAA0B,CAAC;IAC5C,QAAQ,GAAC,IAAI,GAAG,EAAoC,CAAC;IACrD,MAAM,GAAC,KAAK,CAAC;IACb,MAAM,GAAC,IAAI,GAAG,EAAU,CAAC;IACzB,eAAe,GAAC,IAAI,GAAG,EAAU,CAAC;IAClC,YAAY,GAAC,EAAE,C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C,QAAQ,CAAC,CAAC;IACjF,CAAC;IAAA,OAAM,KAAK,EAAC,CAAC;QAAA,MAAM,KAAK,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAE,EAAE,GAAC,CAAC,CAAC,CAAC;QAAA,MAAM,KAAK,CAAC;IAAA,CAAC;AAC9D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,QAA0B,EAAC,KAAwB;IAC9F,IAAI,MAAqC,CAAC;IAC1C,IAAI,OAAe,CAAC;IACpB,IAAG,CAAC;QACF,MAAM,GAAC,MAAM,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAC,SAAS,EAAC,QAAQ,CAAC,SAAS,EAAC,GAAG,EAAC,KAAK,CAAC,GAAG,EAAC,GAAG,EAAC,KAAK,CAAC,GAAG;YAC3F,KAAK,EAAC,UAAU,EAAE,EAAC,SAAS,EAAC,SAAS,UAAU,EAAE,EAAE,EAAC,CAAC,CAAC;QACzD,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;IAAA,OAAM,KAAK,EAAC,CAAC;QAAA,OAAO,GAAC,KAAK,CAAC;IAAA,CAAC;IAC7B,IAAG,CAAC;QAAA,MAAM,QAAQ,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IAAA,CAAC;IAAA,OAAM,KAAK,EAAC,CAAC;QAChD,OAAO,KAAG,KAAK,CAAC;QAChB,IAAG,CAAC;YAAA,MAAM,QAAQ,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAAA,CAAC;QACrC,MAAK,CAAC;YAAA,IAAG,QAAQ,YAAY,YAAY;gBAAC,MAAM,QAAQ,CAAC,kBAAkB,EAAE,CAAC;QAAA,CAAC;IACjF,CAAC;IACD,IAAG,OAAO;QAAC,MAAM,OAAO,CAAC;AAC3B,CAAC","sourcesContent":["import { fork, type ChildProcess } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { randomUUID } from 'node:crypto';\nimport { AgentError, errorInfo, type ErrorInfo } from '../errors.js';\nimport type { ApprovalHandler } from '../approvals/types.js';\nimport type { HarnessConfig, HarnessKind } from '../sdk/types.js';\nimport type { CatalogEnvironment } from './catalog.js';\nimport type { DriverInput, ExecutionReference, ManagedNativeSession, PreparedExecution } from './types.js';\nimport type { ApprovalEvent } from './worker-approvals.js';\nimport { createSessionLauncher } from './session-launcher.js';\nimport { processExitDescription } from '../process-diagnostics.js';\n\nexport interface CapturedChild {\n readonly name: string;\n readonly description: string;\n}\n\nexport interface CapturedExecution {\n readonly reference: ExecutionReference;\n readonly prepared: PreparedExecution;\n readonly children: readonly CapturedChild[];\n child(name: string): Promise<CapturedExecution>;\n}\n\ninterface CaptureOptions { workerModule?: URL; shutdownTimeoutMs?: number }\ninterface CaptureResult {leaseId:number;reference:ExecutionReference;children:CapturedChild[]}\ntype WorkerReply = ApprovalEvent & {leaseId:number} | {id:number;result?:unknown;error?:ErrorInfo};\n\nconst shutdownTimeoutMs = 1_000;\n\nclass GraphConnection {\n private nextId=1;\n private pending=new Map<number,{operation:string;resolve(value:unknown):void;reject(error:Error):void}>();\n private approvals=new Map<string,AbortController>();\n private handlers=new Map<number,ApprovalHandler|undefined>();\n private exited=false;\n private leases=new Set<number>();\n private abandonedLeases=new Set<number>();\n private observedExit='';\n private readonly processExit:Promise<void>;\n private markExited!:()=>void;\n\n constructor(private readonly child:ChildProcess,private readonly timeout:number) {\n this.processExit=new Promise(resolve=>{this.markExited=resolve;});\n child.once('error',()=>this.exit(undefined,undefined,true));\n child.once('exit',(code,signal)=>this.exit(code,signal));\n child.on('message',(message:WorkerReply)=>this.message(message));\n }\n\n setApprovalHandler(leaseId:number,handler:ApprovalHandler|undefined) { this.handlers.set(leaseId,handler); }\n deleteApprovalHandler(leaseId:number) { this.handlers.delete(leaseId); }\n retainLease(leaseId:number) { this.leases.add(leaseId); }\n async releaseLease(leaseId:number) {\n this.leases.delete(leaseId);\n await this.retryAbandonedLeases();\n const retained=[...this.leases].filter(id=>!this.abandonedLeases.has(id));\n if(retained.length!==0)return;\n if(this.abandonedLeases.size){this.abandonedLeases.clear();this.leases.clear();await this.stop();return;}\n if(await this.waitWithin(this.timeout))return;\n await this.stop();\n }\n async abandonLease(leaseId:number) {\n if(!this.leases.has(leaseId))return;\n const siblings=[...this.leases].filter(id=>id!==leaseId&&!this.abandonedLeases.has(id));\n if(siblings.length){this.abandonedLeases.add(leaseId);return;}\n this.leases.delete(leaseId);\n await this.stop();\n }\n\n private async retryAbandonedLeases() {\n for(const leaseId of [...this.abandonedLeases]){\n try{\n await this.request('lease.close',{leaseId});\n this.abandonedLeases.delete(leaseId);this.leases.delete(leaseId);\n }catch{/* Retain ownership until the remaining graph leases close. */}\n }\n }\n\n request(method:string,extra:Record<string,unknown>={}):Promise<unknown> {\n return new Promise((resolve,reject)=>{\n if(this.exited){reject(new AgentError('HARNESS_FAILED',`The captured definition worker is unavailable while ${method} was pending${this.observedExit}.`));return;}\n const id=this.nextId++;\n this.pending.set(id,{operation:method,resolve,reject});\n this.child.send({id,method,...extra},error=>{\n if(!error)return;\n setImmediate(()=>{\n const waiting=this.pending.get(id);\n if(!waiting||this.exited)return;\n this.pending.delete(id);\n waiting.reject(new AgentError('HARNESS_FAILED',`Cannot reach the captured definition worker while ${method} was pending.`));\n });\n });\n });\n }\n\n private message(message:WorkerReply) {\n if('event' in message){\n const key=`${message.leaseId}:${message.requestId}`;\n if(message.event==='approval.withdraw'){\n this.approvals.get(key)?.abort();this.approvals.delete(key);return;\n }\n const controller=new AbortController();\n this.approvals.set(key,controller);\n void Promise.resolve().then(()=>{\n const handler=this.handlers.get(message.leaseId);\n if(!handler)throw new AgentError('INPUT_REQUIRED','Native tool approval requires an observing caller.');\n return handler(message.request,controller.signal);\n }).then(\n content=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,content});},\n error=>{if(!controller.signal.aborted&&!this.exited)return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)});},\n ).catch(error=>{\n if(!controller.signal.aborted&&!this.exited)\n return this.request('approval.respond',{leaseId:message.leaseId,requestId:message.requestId,error:errorInfo(error)}).catch(()=>{});\n }).finally(()=>this.approvals.delete(key));\n return;\n }\n const waiting=this.pending.get(message.id);\n if(!waiting)return;\n this.pending.delete(message.id);\n if(message.error)waiting.reject(new AgentError(message.error.code,message.error.message));\n else waiting.resolve(message.result);\n }\n\n private exit(code:unknown,signal:unknown,spawnFailure=false) {\n if(this.exited)return;\n this.exited=true;\n this.observedExit=spawnFailure?'':processExitDescription(code,signal);\n for(const controller of this.approvals.values())controller.abort();\n this.approvals.clear();this.markExited();\n for(const waiting of this.pending.values())waiting.reject(new AgentError('HARNESS_FAILED',spawnFailure\n ?`The captured definition worker process failed while ${waiting.operation} was pending.`\n :`The captured definition worker exited while ${waiting.operation} was pending${this.observedExit}.`));\n this.pending.clear();\n }\n\n async stop() {\n if(this.exited)return;\n if(this.child.connected)try{this.child.disconnect();}catch{}\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGTERM');\n if(await this.waitWithin(this.timeout))return;\n this.child.kill('SIGKILL');\n if(!await this.waitWithin(this.timeout))throw new AgentError('HARNESS_FAILED','The captured definition worker did not confirm termination.');\n }\n\n private waitWithin(timeout:number):Promise<boolean>{\n return new Promise(resolve=>{\n const timer=setTimeout(()=>resolve(false),timeout);\n this.processExit.then(()=>{clearTimeout(timer);resolve(true);});\n });\n }\n}\n\nclass CaptureLease implements CapturedExecution {\n readonly prepared:PreparedExecution;\n readonly children:readonly CapturedChild[];\n private launcher?:Awaited<ReturnType<typeof createSessionLauncher>>;\n private nativeClosed=false;\n private released=false;\n private closing=false;\n private opening?:Promise<ManagedNativeSession>;\n\n constructor(\n private readonly graph:GraphConnection,\n private readonly leaseId:number,\n readonly reference:ExecutionReference,\n children:readonly CapturedChild[],\n ) {\n this.graph.retainLease(leaseId);\n this.children=Object.freeze(children.map(child=>Object.freeze({...child})));\n this.prepared={open:input=>this.open(input),close:()=>this.close()};\n }\n\n async child(name:string):Promise<CapturedExecution>{\n if(this.released)throw new AgentError('INVALID_PARENT','The captured parent context is closed.');\n const result=await this.graph.request('child',{leaseId:this.leaseId,name}) as CaptureResult;\n return new CaptureLease(this.graph,result.leaseId,result.reference,result.children);\n }\n\n private async open(input:DriverInput):Promise<ManagedNativeSession>{\n if(this.released||this.closing||this.opening)throw new AgentError('HARNESS_FAILED','Native session startup is unavailable.');\n const opening=this.startOpen(input);\n this.opening=opening;\n return opening;\n }\n\n private async startOpen(input:DriverInput):Promise<ManagedNativeSession>{\n const state=input.env.AGENT_STATE_DIR;\n if(typeof state!=='string'||!state)throw new AgentError('INVALID_CONFIG','AGENT_STATE_DIR must select the coordinator state directory.');\n const launcher=await createSessionLauncher(state,input.token);\n this.launcher=launcher;\n if(this.closing){\n await launcher.close();this.launcher=undefined;\n throw new AgentError('COORDINATOR_UNAVAILABLE','The captured session closed during startup.');\n }\n const {onApproval,...serializedInput}=input;\n let selectedHarness:HarnessKind|undefined;\n try{\n this.graph.setApprovalHandler(this.leaseId,onApproval);\n selectedHarness=await this.graph.request('open',{leaseId:this.leaseId,input:serializedInput,\n handlesApprovals:!!onApproval,launcherPath:launcher.path}) as HarnessKind;\n }catch(error){\n this.graph.deleteApprovalHandler(this.leaseId);\n this.launcher=undefined;\n await launcher.close();\n throw error;\n }\n const request=(method:string,extra:Record<string,unknown>={})=>this.graph.request(method,{leaseId:this.leaseId,...extra});\n return {\n selectedHarness,\n turn:prompt=>request('turn',{prompt}) as Promise<string>,\n steer:async prompt=>{await request('steer',{prompt});},\n interrupt:async()=>{await request('interrupt');},\n resume:()=>request('resume') as Promise<string>,\n close:async()=>{\n if(this.nativeClosed)return;\n await request('native.close');\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n },\n };\n }\n\n private async close():Promise<void>{\n this.closing=true;\n if(!this.released){\n await this.graph.request('lease.close',{leaseId:this.leaseId});\n this.released=true;\n this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n }\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close();this.launcher=undefined;}\n await this.graph.releaseLease(this.leaseId);\n }\n\n async abandonFailedCheck():Promise<void>{\n this.closing=true;this.released=true;this.nativeClosed=true;\n this.graph.deleteApprovalHandler(this.leaseId);\n await this.opening?.catch(()=>undefined);\n if(this.launcher){await this.launcher.close().catch(()=>{});this.launcher=undefined;}\n await this.graph.abandonLease(this.leaseId);\n }\n}\n\nexport async function captureExecution(\n agent:string|HarnessConfig,\n input:CatalogEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n return captureRequest(input,options,{method:'capture',agent});\n}\n\n/** Captures an already resolved private CLI reference without applying public connected validation. */\nexport async function captureReference(\n reference:ExecutionReference,\n input:CatalogEnvironment,\n options:CaptureOptions={},\n):Promise<CapturedExecution>{\n if('kind' in reference&&reference.kind==='inline')\n throw new AgentError('INVALID_DEFINITION','Inline agent definitions cannot be loaded by native CLI workers.');\n return captureRequest(input,options,{method:'capture.reference',reference});\n}\n\nasync function captureRequest(\n input:CatalogEnvironment,\n options:CaptureOptions,\n request:{method:'capture';agent:string|HarnessConfig}|{method:'capture.reference';reference:ExecutionReference},\n):Promise<CapturedExecution>{\n const {AGENT_PARENT_TOKEN:_parent,AGENT_CLI_PATH:_launcher,...environment}=input.env;\n const workerModule=options.workerModule??new URL(`./worker.${import.meta.url.endsWith('.ts')?'ts':'js'}`,import.meta.url);\n const extension=workerModule.pathname.endsWith('.ts')?'ts':'js';\n let child:ChildProcess;\n try{\n child=fork(fileURLToPath(workerModule),[],{cwd:input.cwd,env:environment,stdio:['ignore','ignore','ignore','ipc'],\n execArgv:extension==='ts'?['--import',import.meta.resolve('tsx')]:[]});\n }catch{throw new AgentError('INVALID_DEFINITION','The captured definition worker could not be spawned.');}\n const graph=new GraphConnection(child,options.shutdownTimeoutMs??shutdownTimeoutMs);\n try{\n const {method,...data}=request;\n const result=await graph.request(method,data) as CaptureResult;\n return new CaptureLease(graph,result.leaseId,result.reference,result.children);\n }catch(error){await graph.stop().catch(()=>{});throw error;}\n}\n\nexport async function checkCapturedExecution(captured:CapturedExecution,input:CatalogEnvironment):Promise<void>{\n let native:ManagedNativeSession|undefined;\n let failure:unknown;\n try{\n native=await captured.prepared.open({reference:captured.reference,cwd:input.cwd,env:input.env,\n token:randomUUID(),sessionId:`check_${randomUUID()}`});\n await native.close();\n }catch(error){failure=error;}\n try{await captured.prepared.close();}catch(error){\n failure??=error;\n try{await captured.prepared.close();}\n catch{if(captured instanceof CaptureLease)await captured.abandonFailedCheck();}\n }\n if(failure)throw failure;\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { type ErrorInfo } from '../errors.js';
2
+ import type { HarnessConfig } from '../sdk/types.js';
3
+ import type { ExecutionReference } from './types.js';
4
+ export interface CatalogEnvironment {
5
+ readonly cwd: string;
6
+ readonly env: NodeJS.ProcessEnv;
7
+ }
8
+ export interface CatalogAgent {
9
+ readonly id: string;
10
+ readonly name: string;
11
+ readonly description: string;
12
+ readonly scope: 'harness' | 'repo' | 'global';
13
+ }
14
+ export interface CatalogSnapshot {
15
+ entries: {
16
+ id: string;
17
+ name: string;
18
+ description: string;
19
+ scope: 'repo' | 'global';
20
+ file: string;
21
+ }[];
22
+ children: {
23
+ name: string;
24
+ description: string;
25
+ }[];
26
+ }
27
+ export type CatalogReply = {
28
+ result: CatalogSnapshot;
29
+ error?: never;
30
+ } | {
31
+ result?: never;
32
+ error: ErrorInfo;
33
+ };
34
+ export declare function listAgents(input: CatalogEnvironment): Promise<{
35
+ readonly items: readonly CatalogAgent[];
36
+ }>;
37
+ export declare function resolveAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<ExecutionReference>;
38
+ export declare function checkAgent(agent: string | HarnessConfig, input: CatalogEnvironment): Promise<void>;
39
+ export declare function loadCatalogSnapshot(input: CatalogEnvironment, parent?: ExecutionReference, discover?: boolean): Promise<CatalogSnapshot>;
@@ -0,0 +1,84 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { AgentError } from '../errors.js';
4
+ import { validateAgent } from '../sdk/definitions.js';
5
+ import { harnessReference } from './definition.js';
6
+ const nativeAgents = [
7
+ { id: 'codex', name: 'codex', description: 'Run the native Codex harness.', scope: 'harness' },
8
+ { id: 'claude', name: 'claude', description: 'Run the native Claude Code harness.', scope: 'harness' },
9
+ { id: 'fx', name: 'fx', description: 'Run the native fx harness through AI Gateway.', scope: 'harness' },
10
+ { id: 'opencode', name: 'opencode', description: 'Run the native OpenCode harness through AI Gateway.', scope: 'harness' },
11
+ { id: 'copilot', name: 'copilot', description: 'Run the native GitHub Copilot harness through AI Gateway.', scope: 'harness' },
12
+ { id: 'cursor', name: 'cursor', description: 'Run the native Cursor harness.', scope: 'harness' },
13
+ ];
14
+ export async function listAgents(input) {
15
+ const snapshot = await loadCatalogSnapshot(input);
16
+ return { items: [...nativeAgents, ...snapshot.entries.map(({ id, name, description, scope }) => ({ id, name, description, scope }))] };
17
+ }
18
+ export async function resolveAgent(agent, input) {
19
+ if (typeof agent !== 'string') {
20
+ validateAgent({ name: 'direct', description: 'Direct native harness.', instructions: 'Run.', harness: agent });
21
+ return { kind: 'harness', harness: agent };
22
+ }
23
+ if (agent === 'codex')
24
+ return harnessReference('codex');
25
+ if (agent === 'claude')
26
+ return harnessReference('claudeCode');
27
+ if (agent === 'fx')
28
+ return harnessReference('fx');
29
+ if (agent === 'opencode' || agent === 'copilot' || agent === 'cursor')
30
+ throw new AgentError('INVALID_CONFIG', `${agent} requires an explicit model configuration.`);
31
+ if (agent.startsWith('subagent:'))
32
+ throw new AgentError('UNKNOWN_AGENT', 'Managed subagents require an active parent context.');
33
+ const { entries } = await loadCatalogSnapshot(input);
34
+ const matches = entries.filter(entry => entry.id === agent || entry.name === agent);
35
+ if (matches.length !== 1)
36
+ throw new AgentError(matches.length ? 'AMBIGUOUS_AGENT' : 'UNKNOWN_AGENT', matches.length ? `Choose ${matches.map(entry => entry.id).join(' or ')}.` : 'Agent not found.');
37
+ return { file: matches[0].file, subagents: [] };
38
+ }
39
+ export async function checkAgent(agent, input) {
40
+ const { captureExecution, checkCapturedExecution } = await import('./capture.js');
41
+ const captured = await captureExecution(agent, input);
42
+ await checkCapturedExecution(captured, input);
43
+ }
44
+ export function loadCatalogSnapshot(input, parent, discover = true) {
45
+ if (parent && 'kind' in parent && parent.kind === 'inline')
46
+ return Promise.reject(new AgentError('INVALID_PARENT', 'Inline SDK definitions are unavailable to the CLI catalog.'));
47
+ return new Promise((resolve, reject) => {
48
+ const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
49
+ const child = fork(fileURLToPath(new URL(`../cli/catalog-worker.${extension}`, import.meta.url)), [], {
50
+ cwd: input.cwd, env: input.env, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
51
+ execArgv: extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : [],
52
+ });
53
+ let reply;
54
+ let settled = false;
55
+ const fail = () => {
56
+ if (settled)
57
+ return;
58
+ settled = true;
59
+ reject(new AgentError('INVALID_DEFINITION', 'The agent catalog worker exited before returning its catalog.'));
60
+ };
61
+ child.once('error', fail);
62
+ child.once('exit', () => {
63
+ if (!reply)
64
+ fail();
65
+ else if (!settled) {
66
+ settled = true;
67
+ if (reply.error)
68
+ reject(new AgentError(reply.error.code, reply.error.message));
69
+ else
70
+ resolve(reply.result);
71
+ }
72
+ });
73
+ child.once('message', (message) => {
74
+ reply = message;
75
+ child.send({ received: true }, error => { if (error)
76
+ child.kill(); });
77
+ });
78
+ child.send({ cwd: input.cwd, parent, discover }, error => { if (error) {
79
+ child.kill();
80
+ fail();
81
+ } });
82
+ });
83
+ }
84
+ //# sourceMappingURL=catalog.js.map