open-multi-agent-kit 0.95.2 → 0.96.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +37 -4
  3. package/dist/approvals/approval-receipt-store.d.ts.map +1 -1
  4. package/dist/approvals/approval-receipt-store.js +25 -0
  5. package/dist/approvals/approval-receipt-store.js.map +1 -1
  6. package/dist/commands/doctor-provider.d.ts.map +1 -1
  7. package/dist/commands/doctor-provider.js +15 -20
  8. package/dist/commands/doctor-provider.js.map +1 -1
  9. package/dist/commands/sdk-session-cli.d.ts +24 -0
  10. package/dist/commands/sdk-session-cli.d.ts.map +1 -0
  11. package/dist/commands/sdk-session-cli.js +225 -0
  12. package/dist/commands/sdk-session-cli.js.map +1 -0
  13. package/dist/core/advisory-judge-model.d.ts +18 -0
  14. package/dist/core/advisory-judge-model.d.ts.map +1 -0
  15. package/dist/core/advisory-judge-model.js +168 -0
  16. package/dist/core/advisory-judge-model.js.map +1 -0
  17. package/dist/core/advisory-judge-response.d.ts +8 -0
  18. package/dist/core/advisory-judge-response.d.ts.map +1 -0
  19. package/dist/core/advisory-judge-response.js +61 -0
  20. package/dist/core/advisory-judge-response.js.map +1 -0
  21. package/dist/core/advisory-judge-types.d.ts +53 -0
  22. package/dist/core/advisory-judge-types.d.ts.map +1 -0
  23. package/dist/core/advisory-judge-types.js +2 -0
  24. package/dist/core/advisory-judge-types.js.map +1 -0
  25. package/dist/core/advisory-judge.d.ts +8 -0
  26. package/dist/core/advisory-judge.d.ts.map +1 -0
  27. package/dist/core/advisory-judge.js +178 -0
  28. package/dist/core/advisory-judge.js.map +1 -0
  29. package/dist/core/agent-session-services.d.ts +1 -0
  30. package/dist/core/agent-session-services.d.ts.map +1 -1
  31. package/dist/core/agent-session-services.js +1 -0
  32. package/dist/core/agent-session-services.js.map +1 -1
  33. package/dist/core/agent-session.d.ts +6 -3
  34. package/dist/core/agent-session.d.ts.map +1 -1
  35. package/dist/core/agent-session.js +141 -184
  36. package/dist/core/agent-session.js.map +1 -1
  37. package/dist/core/auth-storage.d.ts.map +1 -1
  38. package/dist/core/auth-storage.js +28 -4
  39. package/dist/core/auth-storage.js.map +1 -1
  40. package/dist/core/compaction-gate.d.ts +28 -0
  41. package/dist/core/compaction-gate.d.ts.map +1 -0
  42. package/dist/core/compaction-gate.js +34 -0
  43. package/dist/core/compaction-gate.js.map +1 -0
  44. package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
  45. package/dist/core/context-budget-system-prompt-items.js +5 -3
  46. package/dist/core/context-budget-system-prompt-items.js.map +1 -1
  47. package/dist/core/domain-loadouts.d.ts.map +1 -1
  48. package/dist/core/domain-loadouts.js +2 -2
  49. package/dist/core/domain-loadouts.js.map +1 -1
  50. package/dist/core/durable-goal-checkpoint.d.ts +6 -0
  51. package/dist/core/durable-goal-checkpoint.d.ts.map +1 -0
  52. package/dist/core/durable-goal-checkpoint.js +195 -0
  53. package/dist/core/durable-goal-checkpoint.js.map +1 -0
  54. package/dist/core/durable-goal-parse.d.ts +3 -0
  55. package/dist/core/durable-goal-parse.d.ts.map +1 -0
  56. package/dist/core/durable-goal-parse.js +86 -0
  57. package/dist/core/durable-goal-parse.js.map +1 -0
  58. package/dist/core/durable-goal-reducer.d.ts +3 -0
  59. package/dist/core/durable-goal-reducer.d.ts.map +1 -0
  60. package/dist/core/durable-goal-reducer.js +175 -0
  61. package/dist/core/durable-goal-reducer.js.map +1 -0
  62. package/dist/core/durable-goal-store.d.ts +19 -0
  63. package/dist/core/durable-goal-store.d.ts.map +1 -0
  64. package/dist/core/durable-goal-store.js +126 -0
  65. package/dist/core/durable-goal-store.js.map +1 -0
  66. package/dist/core/durable-goal.d.ts +92 -0
  67. package/dist/core/durable-goal.d.ts.map +1 -0
  68. package/dist/core/durable-goal.js +62 -0
  69. package/dist/core/durable-goal.js.map +1 -0
  70. package/dist/core/extensions/builtin/goal-controller.d.ts +3 -0
  71. package/dist/core/extensions/builtin/goal-controller.d.ts.map +1 -0
  72. package/dist/core/extensions/builtin/goal-controller.js +125 -0
  73. package/dist/core/extensions/builtin/goal-controller.js.map +1 -0
  74. package/dist/core/extensions/builtin/identical-loop.d.ts +3 -0
  75. package/dist/core/extensions/builtin/identical-loop.d.ts.map +1 -0
  76. package/dist/core/extensions/builtin/identical-loop.js +31 -0
  77. package/dist/core/extensions/builtin/identical-loop.js.map +1 -0
  78. package/dist/core/extensions/builtin/prompt-preset.d.ts +3 -0
  79. package/dist/core/extensions/builtin/prompt-preset.d.ts.map +1 -0
  80. package/dist/core/extensions/builtin/prompt-preset.js +13 -0
  81. package/dist/core/extensions/builtin/prompt-preset.js.map +1 -0
  82. package/dist/core/extensions/builtin/tool-pair-repair.d.ts +3 -0
  83. package/dist/core/extensions/builtin/tool-pair-repair.d.ts.map +1 -0
  84. package/dist/core/extensions/builtin/tool-pair-repair.js +12 -0
  85. package/dist/core/extensions/builtin/tool-pair-repair.js.map +1 -0
  86. package/dist/core/extensions/types.d.ts +6 -2
  87. package/dist/core/extensions/types.d.ts.map +1 -1
  88. package/dist/core/extensions/types.js.map +1 -1
  89. package/dist/core/goal-continuation.d.ts +13 -0
  90. package/dist/core/goal-continuation.d.ts.map +1 -0
  91. package/dist/core/goal-continuation.js +10 -0
  92. package/dist/core/goal-continuation.js.map +1 -0
  93. package/dist/core/grok-harness.d.ts +1 -1
  94. package/dist/core/grok-harness.d.ts.map +1 -1
  95. package/dist/core/grok-harness.js +1 -1
  96. package/dist/core/grok-harness.js.map +1 -1
  97. package/dist/core/grok-playbook.d.ts +1 -1
  98. package/dist/core/grok-playbook.d.ts.map +1 -1
  99. package/dist/core/grok-playbook.js +1 -1
  100. package/dist/core/grok-playbook.js.map +1 -1
  101. package/dist/core/identical-loop.d.ts +15 -0
  102. package/dist/core/identical-loop.d.ts.map +1 -0
  103. package/dist/core/identical-loop.js +34 -0
  104. package/dist/core/identical-loop.js.map +1 -0
  105. package/dist/core/index.d.ts +1 -1
  106. package/dist/core/index.d.ts.map +1 -1
  107. package/dist/core/index.js +1 -1
  108. package/dist/core/index.js.map +1 -1
  109. package/dist/core/model-prompt-policy.d.ts +11 -0
  110. package/dist/core/model-prompt-policy.d.ts.map +1 -0
  111. package/dist/core/model-prompt-policy.js +17 -0
  112. package/dist/core/model-prompt-policy.js.map +1 -0
  113. package/dist/core/model-registry.d.ts.map +1 -1
  114. package/dist/core/model-registry.js +16 -4
  115. package/dist/core/model-registry.js.map +1 -1
  116. package/dist/core/model-resolver.d.ts.map +1 -1
  117. package/dist/core/model-resolver.js +2 -2
  118. package/dist/core/model-resolver.js.map +1 -1
  119. package/dist/core/prompt-budget.d.ts +21 -0
  120. package/dist/core/prompt-budget.d.ts.map +1 -0
  121. package/dist/core/prompt-budget.js +51 -0
  122. package/dist/core/prompt-budget.js.map +1 -0
  123. package/dist/core/prompt-cache.d.ts +14 -0
  124. package/dist/core/prompt-cache.d.ts.map +1 -0
  125. package/dist/core/prompt-cache.js +16 -0
  126. package/dist/core/prompt-cache.js.map +1 -0
  127. package/dist/core/prompt-preset.d.ts +8 -0
  128. package/dist/core/prompt-preset.d.ts.map +1 -0
  129. package/dist/core/prompt-preset.js +56 -0
  130. package/dist/core/prompt-preset.js.map +1 -0
  131. package/dist/core/provider-resilience.d.ts +23 -0
  132. package/dist/core/provider-resilience.d.ts.map +1 -1
  133. package/dist/core/provider-resilience.js +34 -1
  134. package/dist/core/provider-resilience.js.map +1 -1
  135. package/dist/core/provider-retry.d.ts +29 -0
  136. package/dist/core/provider-retry.d.ts.map +1 -0
  137. package/dist/core/provider-retry.js +49 -0
  138. package/dist/core/provider-retry.js.map +1 -0
  139. package/dist/core/provider-usage.d.ts +2 -1
  140. package/dist/core/provider-usage.d.ts.map +1 -1
  141. package/dist/core/provider-usage.js +40 -6
  142. package/dist/core/provider-usage.js.map +1 -1
  143. package/dist/core/resource-loader.d.ts.map +1 -1
  144. package/dist/core/resource-loader.js +32 -0
  145. package/dist/core/resource-loader.js.map +1 -1
  146. package/dist/core/sandbox/backend.d.ts +12 -0
  147. package/dist/core/sandbox/backend.d.ts.map +1 -1
  148. package/dist/core/sandbox/backend.js +52 -42
  149. package/dist/core/sandbox/backend.js.map +1 -1
  150. package/dist/core/sandbox/policy.d.ts +2 -0
  151. package/dist/core/sandbox/policy.d.ts.map +1 -1
  152. package/dist/core/sandbox/policy.js +2 -1
  153. package/dist/core/sandbox/policy.js.map +1 -1
  154. package/dist/core/sdk.d.ts +2 -0
  155. package/dist/core/sdk.d.ts.map +1 -1
  156. package/dist/core/sdk.js +1 -0
  157. package/dist/core/sdk.js.map +1 -1
  158. package/dist/core/session-system-prompt.d.ts +28 -0
  159. package/dist/core/session-system-prompt.d.ts.map +1 -0
  160. package/dist/core/session-system-prompt.js +37 -0
  161. package/dist/core/session-system-prompt.js.map +1 -0
  162. package/dist/core/strict-record.d.ts +2 -0
  163. package/dist/core/strict-record.d.ts.map +1 -0
  164. package/dist/core/strict-record.js +9 -0
  165. package/dist/core/strict-record.js.map +1 -0
  166. package/dist/core/subagent-orchestration.d.ts.map +1 -1
  167. package/dist/core/subagent-orchestration.js +4 -2
  168. package/dist/core/subagent-orchestration.js.map +1 -1
  169. package/dist/core/tool-pair-repair.d.ts +11 -0
  170. package/dist/core/tool-pair-repair.d.ts.map +1 -0
  171. package/dist/core/tool-pair-repair.js +38 -0
  172. package/dist/core/tool-pair-repair.js.map +1 -0
  173. package/dist/core/tools/artifact-spill.d.ts +13 -0
  174. package/dist/core/tools/artifact-spill.d.ts.map +1 -0
  175. package/dist/core/tools/artifact-spill.js +26 -0
  176. package/dist/core/tools/artifact-spill.js.map +1 -0
  177. package/dist/core/tools/bash.d.ts +7 -4
  178. package/dist/core/tools/bash.d.ts.map +1 -1
  179. package/dist/core/tools/bash.js +8 -7
  180. package/dist/core/tools/bash.js.map +1 -1
  181. package/dist/core/tools/diagnostics.d.ts.map +1 -1
  182. package/dist/core/tools/diagnostics.js +8 -2
  183. package/dist/core/tools/diagnostics.js.map +1 -1
  184. package/dist/core/tools/index.d.ts +1 -1
  185. package/dist/core/tools/index.d.ts.map +1 -1
  186. package/dist/core/tools/index.js.map +1 -1
  187. package/dist/core/tools/read.d.ts +1 -0
  188. package/dist/core/tools/read.d.ts.map +1 -1
  189. package/dist/core/tools/read.js +10 -1
  190. package/dist/core/tools/read.js.map +1 -1
  191. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  192. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  193. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  194. package/dist/guardrails/evidence-protocol.d.ts +10 -0
  195. package/dist/guardrails/evidence-protocol.d.ts.map +1 -0
  196. package/dist/guardrails/evidence-protocol.js +34 -0
  197. package/dist/guardrails/evidence-protocol.js.map +1 -0
  198. package/dist/guardrails/evidence-system.d.ts +3 -1
  199. package/dist/guardrails/evidence-system.d.ts.map +1 -1
  200. package/dist/guardrails/evidence-system.js +22 -14
  201. package/dist/guardrails/evidence-system.js.map +1 -1
  202. package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -1
  203. package/dist/guardrails/replay-ledger-lock-owner.js +3 -1
  204. package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -1
  205. package/dist/guardrails/replay-payload-hash.d.ts +6 -0
  206. package/dist/guardrails/replay-payload-hash.d.ts.map +1 -0
  207. package/dist/guardrails/replay-payload-hash.js +24 -0
  208. package/dist/guardrails/replay-payload-hash.js.map +1 -0
  209. package/dist/index.d.ts +20 -2
  210. package/dist/index.d.ts.map +1 -1
  211. package/dist/index.js +19 -0
  212. package/dist/index.js.map +1 -1
  213. package/dist/main.d.ts.map +1 -1
  214. package/dist/main.js +8 -0
  215. package/dist/main.js.map +1 -1
  216. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  217. package/dist/modes/interactive/theme/theme.js +14 -3
  218. package/dist/modes/interactive/theme/theme.js.map +1 -1
  219. package/dist/types/evidence.d.ts +11 -3
  220. package/dist/types/evidence.d.ts.map +1 -1
  221. package/dist/types/evidence.js.map +1 -1
  222. package/docs/adaptorch-preview-spec.md +1 -1
  223. package/docs/adaptorch-preview.md +2 -2
  224. package/docs/book-to-skill.md +79 -0
  225. package/docs/compaction.md +10 -0
  226. package/docs/containerization.md +9 -0
  227. package/docs/docs.json +18 -2
  228. package/docs/environment-variables.md +11 -4
  229. package/docs/extensions.md +14 -1
  230. package/docs/grok-harness.md +35 -12
  231. package/docs/index.md +9 -5
  232. package/docs/loadout-domains/grok-harness.md +2 -2
  233. package/docs/models.md +21 -8
  234. package/docs/provider-resilience.md +42 -55
  235. package/docs/providers.md +13 -4
  236. package/docs/run-protocol.md +104 -0
  237. package/docs/sdk.md +111 -5
  238. package/docs/security.md +22 -32
  239. package/docs/sessions.md +20 -0
  240. package/docs/settings.md +2 -0
  241. package/docs/skills.md +9 -1
  242. package/docs/usage.md +38 -16
  243. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  244. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  245. package/examples/extensions/custom-provider-gitlab-duo/index.ts +6 -1
  246. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  247. package/examples/extensions/gondolin/package-lock.json +2 -2
  248. package/examples/extensions/gondolin/package.json +1 -1
  249. package/examples/extensions/sandbox/package-lock.json +2 -2
  250. package/examples/extensions/sandbox/package.json +1 -1
  251. package/examples/extensions/with-deps/package-lock.json +2 -2
  252. package/examples/extensions/with-deps/package.json +1 -1
  253. package/npm-shrinkwrap.json +37 -15
  254. package/package.json +8 -5
  255. package/dist/core/context-budget-compressors.d.ts +0 -50
  256. package/dist/core/context-budget-compressors.d.ts.map +0 -1
  257. package/dist/core/context-budget-compressors.js +0 -166
  258. package/dist/core/context-budget-compressors.js.map +0 -1
  259. package/dist/core/extensions/loader.js.bak-sharedjiti-20260812-111246 +0 -553
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"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,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,mBAAmB,EAAE,4BAA4B;QACjD,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;QAClD,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,gBAAgB,EAAE,kBAAkB,CAAC,MAAM;QAC3C,YAAY;QACZ,YAAY;QACZ,YAAY,EAAE,OAAO,CAAC,YAAY;KAClC,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\tinspectTranscriptIntegrity,\n\trepairTranscriptIntegrity,\n\ttype ThinkingLevel,\n} from \"omk-agent-core\";\nimport { createNodeResourceKeyResolver } from \"omk-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple, type ToolResultMessage } from \"omk-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { ReplayLedgerManager } from \"../guardrails/evidence-system.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession, type SessionTranscriptRepair } from \"./agent-session.ts\";\nimport { resolveAgentToolSettings } from \"./agent-tool-settings.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { createDomainDispatchRuntimeSession, isDomainRoutingEnabled, tryDomainDispatch } from \"./domain-dispatch.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { tryGrokHarnessDispatch } from \"./grok-harness-dispatch.ts\";\nimport type { LoadoutAccessPolicy } from \"./loadout-access-policy.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { recordClaudePassiveUsage, recordCodexPassiveUsage } from \"./provider-usage.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { classifySessionTermination, SessionTerminationError } from \"./session-termination.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport type { BashSandboxPreflight } from \"./tools/bash.ts\";\nimport {\n\tallToolNames,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.omk/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, OMK enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/**\n\t * Optional prompt hint used only for opt-in domain routing (`OMK_DOMAIN_ROUTING=1`).\n\t * This text only selects a loadout policy and is never sent to the model.\n\t */\n\tdomainRoutingPrompt?: string;\n\t/** Optional loadout enforcement policy for SDK-created sessions. */\n\tloadoutAccessPolicy?: LoadoutAccessPolicy;\n\t/** Trusted sandbox preflight used for built-in local bash execution. */\n\tbashSandboxPreflight?: BashSandboxPreflight;\n\t/** Optional replay ledger shared with VerifiedEvidenceExecutor freshness checks. */\n\treplayLedger?: ReplayLedgerManager;\n\t/** Goal binding for AgentSession replay events; defaults to replayLedger.goalId. */\n\treplayGoalId?: string;\n\t/** Optional lane binding for AgentSession replay events. */\n\treplayLaneId?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\ninterface SessionTranscriptRecovery {\n\tmessages: AgentMessage[];\n\trepair?: SessionTranscriptRepair;\n}\n\n/**\n * ALG001-A: inspect the restored transcript on every live session open/resume.\n *\n * - A clean transcript passes through untouched.\n * - Unambiguous missing-only tail results are auto-repaired: synthetic\n * terminal results (tool-result/v2 envelope) are persisted to the session\n * so the repair is durable and idempotent, together with a durable\n * `transcript_repaired` audit entry.\n * - Any duplicate/orphan/duplicate-call/interleaved corruption marks the\n * session (`session_corrupt` entry, once) and fails closed.\n */\nfunction recoverSessionTranscriptOnOpen(\n\tsessionManager: SessionManager,\n\tmessages: AgentMessage[],\n): SessionTranscriptRecovery {\n\tconst report = inspectTranscriptIntegrity(messages);\n\tif (report.ok) {\n\t\treturn { messages };\n\t}\n\n\tlet repaired: AgentMessage[];\n\ttry {\n\t\trepaired = repairTranscriptIntegrity(messages, \"Tool result missing; synthesized during session resume recovery\");\n\t} catch {\n\t\tconst alreadyMarked = sessionManager\n\t\t\t.getBranch()\n\t\t\t.some((entry) => entry.type === \"custom\" && entry.customType === \"session_corrupt\");\n\t\tif (!alreadyMarked) {\n\t\t\tsessionManager.appendCustomEntry(\"session_corrupt\", {\n\t\t\t\tissues: report.issues.map((issue) => ({\n\t\t\t\t\tkind: issue.kind,\n\t\t\t\t\ttoolCallId: issue.toolCallId,\n\t\t\t\t\t...(issue.toolName === undefined ? {} : { toolName: issue.toolName }),\n\t\t\t\t})),\n\t\t\t});\n\t\t}\n\t\tconst summary = report.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\t\tconst firstIssue = report.issues[0]?.kind ?? \"missing_result\";\n\t\tconst termination = classifySessionTermination({\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\trunId: `resume-${randomUUID()}`,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsource: \"inferred_on_resume\",\n\t\t\tmessage: \"Session transcript has ambiguous tool-result corruption.\",\n\t\t\tcause: { area: \"transcript\", code: firstIssue },\n\t\t\tsideEffects: \"possible\",\n\t\t});\n\t\tthrow new SessionTerminationError(\n\t\t\t`Cannot open session: corrupt tool transcript (${summary}). ` +\n\t\t\t\t\"The session has been marked corrupt; repair it explicitly before resuming.\",\n\t\t\ttermination,\n\t\t);\n\t}\n\n\tconst inserted = repaired.slice(messages.length) as ToolResultMessage[];\n\tif (inserted.length === 0) {\n\t\treturn { messages: repaired };\n\t}\n\tfor (const message of inserted) {\n\t\tsessionManager.appendMessage(message);\n\t}\n\tconst insertedToolCallIds = inserted.map((message) => message.toolCallId);\n\tsessionManager.appendCustomEntry(\"transcript_repaired\", { insertedToolCallIds, reason: \"resume\" });\n\treturn { messages: repaired, repair: { insertedToolCallIds, reason: \"resume\" } };\n}\n\nfunction getDomainDispatchBaseToolNames(options: CreateAgentSessionOptions): string[] {\n\tif (!options.tools && (options.noTools === \"all\" || options.noTools === \"builtin\")) {\n\t\treturn [];\n\t}\n\treturn [...allToolNames];\n}\n\nfunction getAllowedToolNamesForDomainDispatch(options: CreateAgentSessionOptions): string[] | undefined {\n\treturn options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n}\n\nfunction createEffectiveLoadoutAccessPolicy(\n\toptions: CreateAgentSessionOptions,\n\tresourceLoader: ResourceLoader,\n\tcwd: string,\n\tagentDir: string,\n\tprovider?: string,\n): LoadoutAccessPolicy | undefined {\n\tif (options.loadoutAccessPolicy) {\n\t\treturn options.loadoutAccessPolicy;\n\t}\n\n\tconst session = createDomainDispatchRuntimeSession({\n\t\tbaseToolNames: getDomainDispatchBaseToolNames(options),\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tallowedToolNames: getAllowedToolNamesForDomainDispatch(options),\n\t\texcludedToolNames: options.excludeTools,\n\t});\n\n\t// Grok OAuth: apply grok-harness domain loadout without requiring OMK_DOMAIN_ROUTING=1.\n\tif (provider) {\n\t\ttry {\n\t\t\tconst grokDispatch = tryGrokHarnessDispatch({\n\t\t\t\tprovider,\n\t\t\t\tsession,\n\t\t\t\tresourceLoader,\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tenv: process.env,\n\t\t\t});\n\t\t\tif (grokDispatch.loadoutAccessPolicy) {\n\t\t\t\treturn grokDispatch.loadoutAccessPolicy;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to opt-in domain routing.\n\t\t}\n\t}\n\n\tconst domainRoutingPrompt = options.domainRoutingPrompt?.trim();\n\tif (!domainRoutingPrompt || !isDomainRoutingEnabled(process.env)) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst dispatch = tryDomainDispatch({\n\t\t\trole: \"coder\",\n\t\t\tinitialPrompt: domainRoutingPrompt,\n\t\t\tsession,\n\t\t\tresourceLoader,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tenv: process.env,\n\t\t});\n\t\treturn dispatch.loadoutAccessPolicy;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from 'omk-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst agentToolSettings = resolveAgentToolSettings(settingsManager);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\tlet replayLedger = options.replayLedger;\n\tlet replayGoalId = options.replayGoalId;\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!replayLedger && sessionManager.isPersisted() && sessionFile) {\n\t\treplayGoalId ??=\n\t\t\tsessionManager\n\t\t\t\t.getSessionId()\n\t\t\t\t.replace(/[^A-Za-z0-9._-]+/g, \"-\")\n\t\t\t\t.replace(/^[._-]+|[._-]+$/g, \"\") || \"session\";\n\t\treplayLedger = new ReplayLedgerManager(replayGoalId, `${sessionFile}.replay.jsonl`);\n\t}\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore. Live open/resume always\n\t// inspects the transcript and either auto-repairs missing-only tail results\n\t// or fails closed on ambiguous corruption (ALG001-A).\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst transcriptRecovery = recoverSessionTranscriptOnOpen(sessionManager, existingSession.messages);\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// Loadout policy after model resolution so Grok OAuth can auto-apply grok-harness.\n\tconst effectiveLoadoutAccessPolicy = createEffectiveLoadoutAccessPolicy(\n\t\toptions,\n\t\tresourceLoader,\n\t\tcwd,\n\t\tagentDir,\n\t\tmodel?.provider,\n\t);\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"diagnostics\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\tonRateLimit: async (snapshot, responseModel) => {\n\t\t\t\t\tif (auth.apiKey && /^openai-codex(?:-|$)/.test(responseModel.provider)) {\n\t\t\t\t\t\trecordCodexPassiveUsage(auth.apiKey, snapshot);\n\t\t\t\t\t} else if (auth.apiKey && responseModel.provider === \"anthropic\") {\n\t\t\t\t\t\trecordClaudePassiveUsage(auth.apiKey, snapshot);\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onRateLimit?.(snapshot, responseModel);\n\t\t\t\t},\n\t\t\t\theaders: mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\toptions?.sessionId,\n\t\t\t\t\tauth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t),\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\ttoolTimeoutMs: agentToolSettings.toolTimeoutMs,\n\t\ttoolTimeouts: agentToolSettings.toolTimeouts,\n\t\ttoolScheduler: agentToolSettings.toolScheduler,\n\t\tmaxToolConcurrency: agentToolSettings.maxToolConcurrency,\n\t\tstrictExtensionClaims: agentToolSettings.strictExtensionClaims,\n\t\tcwd,\n\t\t// §5.5 Node identity resolver: symlink/hardlink/drive/UNC path aliases\n\t\t// conflict in the dag-v2 scheduler instead of racing (ALG002-A).\n\t\tresourceKeyResolver: createNodeResourceKeyResolver(),\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = transcriptRecovery.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tloadoutAccessPolicy: effectiveLoadoutAccessPolicy,\n\t\tbashSandboxPreflight: options.bashSandboxPreflight,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\ttranscriptRepair: transcriptRecovery.repair,\n\t\treplayLedger,\n\t\treplayGoalId,\n\t\treplayLaneId: options.replayLaneId,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACN,KAAK,EAEL,0BAA0B,EAC1B,yBAAyB,GAEzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAA0B,MAAM,QAAQ,CAAC;AAC5G,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAgC,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAA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import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport {\n\tAgent,\n\ttype AgentMessage,\n\tinspectTranscriptIntegrity,\n\trepairTranscriptIntegrity,\n\ttype ThinkingLevel,\n} from \"omk-agent-core\";\nimport { createNodeResourceKeyResolver } from \"omk-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple, type ToolResultMessage } from \"omk-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { ReplayLedgerManager } from \"../guardrails/evidence-system.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession, type SessionTranscriptRepair } from \"./agent-session.ts\";\nimport { resolveAgentToolSettings } from \"./agent-tool-settings.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { createDomainDispatchRuntimeSession, isDomainRoutingEnabled, tryDomainDispatch } from \"./domain-dispatch.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { tryGrokHarnessDispatch } from \"./grok-harness-dispatch.ts\";\nimport type { LoadoutAccessPolicy } from \"./loadout-access-policy.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport { recordClaudePassiveUsage, recordCodexPassiveUsage } from \"./provider-usage.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { classifySessionTermination, SessionTerminationError } from \"./session-termination.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport type { BashSandboxPreflight } from \"./tools/bash.ts\";\nimport {\n\tallToolNames,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.omk/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/** True when the user pinned `--model` / `--provider` for this process. */\n\tmodelPinned?: boolean;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, OMK enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/**\n\t * Optional prompt hint used only for opt-in domain routing (`OMK_DOMAIN_ROUTING=1`).\n\t * This text only selects a loadout policy and is never sent to the model.\n\t */\n\tdomainRoutingPrompt?: string;\n\t/** Optional loadout enforcement policy for SDK-created sessions. */\n\tloadoutAccessPolicy?: LoadoutAccessPolicy;\n\t/** Trusted sandbox preflight used for built-in local bash execution. */\n\tbashSandboxPreflight?: BashSandboxPreflight;\n\t/** Optional replay ledger shared with VerifiedEvidenceExecutor freshness checks. */\n\treplayLedger?: ReplayLedgerManager;\n\t/** Goal binding for AgentSession replay events; defaults to replayLedger.goalId. */\n\treplayGoalId?: string;\n\t/** Optional lane binding for AgentSession replay events. */\n\treplayLaneId?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\ninterface SessionTranscriptRecovery {\n\tmessages: AgentMessage[];\n\trepair?: SessionTranscriptRepair;\n}\n\n/**\n * ALG001-A: inspect the restored transcript on every live session open/resume.\n *\n * - A clean transcript passes through untouched.\n * - Unambiguous missing-only tail results are auto-repaired: synthetic\n * terminal results (tool-result/v2 envelope) are persisted to the session\n * so the repair is durable and idempotent, together with a durable\n * `transcript_repaired` audit entry.\n * - Any duplicate/orphan/duplicate-call/interleaved corruption marks the\n * session (`session_corrupt` entry, once) and fails closed.\n */\nfunction recoverSessionTranscriptOnOpen(\n\tsessionManager: SessionManager,\n\tmessages: AgentMessage[],\n): SessionTranscriptRecovery {\n\tconst report = inspectTranscriptIntegrity(messages);\n\tif (report.ok) {\n\t\treturn { messages };\n\t}\n\n\tlet repaired: AgentMessage[];\n\ttry {\n\t\trepaired = repairTranscriptIntegrity(messages, \"Tool result missing; synthesized during session resume recovery\");\n\t} catch {\n\t\tconst alreadyMarked = sessionManager\n\t\t\t.getBranch()\n\t\t\t.some((entry) => entry.type === \"custom\" && entry.customType === \"session_corrupt\");\n\t\tif (!alreadyMarked) {\n\t\t\tsessionManager.appendCustomEntry(\"session_corrupt\", {\n\t\t\t\tissues: report.issues.map((issue) => ({\n\t\t\t\t\tkind: issue.kind,\n\t\t\t\t\ttoolCallId: issue.toolCallId,\n\t\t\t\t\t...(issue.toolName === undefined ? {} : { toolName: issue.toolName }),\n\t\t\t\t})),\n\t\t\t});\n\t\t}\n\t\tconst summary = report.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\t\tconst firstIssue = report.issues[0]?.kind ?? \"missing_result\";\n\t\tconst termination = classifySessionTermination({\n\t\t\tsessionId: sessionManager.getSessionId(),\n\t\t\trunId: `resume-${randomUUID()}`,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsource: \"inferred_on_resume\",\n\t\t\tmessage: \"Session transcript has ambiguous tool-result corruption.\",\n\t\t\tcause: { area: \"transcript\", code: firstIssue },\n\t\t\tsideEffects: \"possible\",\n\t\t});\n\t\tthrow new SessionTerminationError(\n\t\t\t`Cannot open session: corrupt tool transcript (${summary}). ` +\n\t\t\t\t\"The session has been marked corrupt; repair it explicitly before resuming.\",\n\t\t\ttermination,\n\t\t);\n\t}\n\n\tconst inserted = repaired.slice(messages.length) as ToolResultMessage[];\n\tif (inserted.length === 0) {\n\t\treturn { messages: repaired };\n\t}\n\tfor (const message of inserted) {\n\t\tsessionManager.appendMessage(message);\n\t}\n\tconst insertedToolCallIds = inserted.map((message) => message.toolCallId);\n\tsessionManager.appendCustomEntry(\"transcript_repaired\", { insertedToolCallIds, reason: \"resume\" });\n\treturn { messages: repaired, repair: { insertedToolCallIds, reason: \"resume\" } };\n}\n\nfunction getDomainDispatchBaseToolNames(options: CreateAgentSessionOptions): string[] {\n\tif (!options.tools && (options.noTools === \"all\" || options.noTools === \"builtin\")) {\n\t\treturn [];\n\t}\n\treturn [...allToolNames];\n}\n\nfunction getAllowedToolNamesForDomainDispatch(options: CreateAgentSessionOptions): string[] | undefined {\n\treturn options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n}\n\nfunction createEffectiveLoadoutAccessPolicy(\n\toptions: CreateAgentSessionOptions,\n\tresourceLoader: ResourceLoader,\n\tcwd: string,\n\tagentDir: string,\n\tprovider?: string,\n): LoadoutAccessPolicy | undefined {\n\tif (options.loadoutAccessPolicy) {\n\t\treturn options.loadoutAccessPolicy;\n\t}\n\n\tconst session = createDomainDispatchRuntimeSession({\n\t\tbaseToolNames: getDomainDispatchBaseToolNames(options),\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tallowedToolNames: getAllowedToolNamesForDomainDispatch(options),\n\t\texcludedToolNames: options.excludeTools,\n\t});\n\n\t// Grok OAuth: apply grok-harness domain loadout without requiring OMK_DOMAIN_ROUTING=1.\n\tif (provider) {\n\t\ttry {\n\t\t\tconst grokDispatch = tryGrokHarnessDispatch({\n\t\t\t\tprovider,\n\t\t\t\tsession,\n\t\t\t\tresourceLoader,\n\t\t\t\tcwd,\n\t\t\t\tagentDir,\n\t\t\t\tenv: process.env,\n\t\t\t});\n\t\t\tif (grokDispatch.loadoutAccessPolicy) {\n\t\t\t\treturn grokDispatch.loadoutAccessPolicy;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to opt-in domain routing.\n\t\t}\n\t}\n\n\tconst domainRoutingPrompt = options.domainRoutingPrompt?.trim();\n\tif (!domainRoutingPrompt || !isDomainRoutingEnabled(process.env)) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst dispatch = tryDomainDispatch({\n\t\t\trole: \"coder\",\n\t\t\tinitialPrompt: domainRoutingPrompt,\n\t\t\tsession,\n\t\t\tresourceLoader,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tenv: process.env,\n\t\t});\n\t\treturn dispatch.loadoutAccessPolicy;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from 'omk-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst agentToolSettings = resolveAgentToolSettings(settingsManager);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\tlet replayLedger = options.replayLedger;\n\tlet replayGoalId = options.replayGoalId;\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!replayLedger && sessionManager.isPersisted() && sessionFile) {\n\t\treplayGoalId ??=\n\t\t\tsessionManager\n\t\t\t\t.getSessionId()\n\t\t\t\t.replace(/[^A-Za-z0-9._-]+/g, \"-\")\n\t\t\t\t.replace(/^[._-]+|[._-]+$/g, \"\") || \"session\";\n\t\treplayLedger = new ReplayLedgerManager(replayGoalId, `${sessionFile}.replay.jsonl`);\n\t}\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore. Live open/resume always\n\t// inspects the transcript and either auto-repairs missing-only tail results\n\t// or fails closed on ambiguous corruption (ALG001-A).\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst transcriptRecovery = recoverSessionTranscriptOnOpen(sessionManager, existingSession.messages);\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// Loadout policy after model resolution so Grok OAuth can auto-apply grok-harness.\n\tconst effectiveLoadoutAccessPolicy = createEffectiveLoadoutAccessPolicy(\n\t\toptions,\n\t\tresourceLoader,\n\t\tcwd,\n\t\tagentDir,\n\t\tmodel?.provider,\n\t);\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\", \"diagnostics\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\tonRateLimit: async (snapshot, responseModel) => {\n\t\t\t\t\tif (auth.apiKey && /^openai-codex(?:-|$)/.test(responseModel.provider)) {\n\t\t\t\t\t\trecordCodexPassiveUsage(auth.apiKey, snapshot);\n\t\t\t\t\t} else if (auth.apiKey && responseModel.provider === \"anthropic\") {\n\t\t\t\t\t\trecordClaudePassiveUsage(auth.apiKey, snapshot);\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onRateLimit?.(snapshot, responseModel);\n\t\t\t\t},\n\t\t\t\theaders: mergeProviderAttributionHeaders(\n\t\t\t\t\tmodel,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\toptions?.sessionId,\n\t\t\t\t\tauth.headers,\n\t\t\t\t\toptions?.headers,\n\t\t\t\t),\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\ttoolTimeoutMs: agentToolSettings.toolTimeoutMs,\n\t\ttoolTimeouts: agentToolSettings.toolTimeouts,\n\t\ttoolScheduler: agentToolSettings.toolScheduler,\n\t\tmaxToolConcurrency: agentToolSettings.maxToolConcurrency,\n\t\tstrictExtensionClaims: agentToolSettings.strictExtensionClaims,\n\t\tcwd,\n\t\t// §5.5 Node identity resolver: symlink/hardlink/drive/UNC path aliases\n\t\t// conflict in the dag-v2 scheduler instead of racing (ALG002-A).\n\t\tresourceKeyResolver: createNodeResourceKeyResolver(),\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = transcriptRecovery.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tloadoutAccessPolicy: effectiveLoadoutAccessPolicy,\n\t\tbashSandboxPreflight: options.bashSandboxPreflight,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tmodelPinned: options.modelPinned,\n\t\ttranscriptRepair: transcriptRecovery.repair,\n\t\treplayLedger,\n\t\treplayGoalId,\n\t\treplayLaneId: options.replayLaneId,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import type { ContextFile } from "./resource-loader.ts";
2
+ import type { Skill } from "./skills.ts";
3
+ import { type BuildSystemPromptOptions } from "./system-prompt.ts";
4
+ export interface SessionSystemPromptInput {
5
+ readonly cwd: string;
6
+ readonly toolNames: readonly string[];
7
+ readonly hasTool: (name: string) => boolean;
8
+ readonly toolPromptSnippets: ReadonlyMap<string, string>;
9
+ readonly toolPromptGuidelines: ReadonlyMap<string, readonly string[]>;
10
+ readonly customPrompt?: string;
11
+ readonly appendSystemPrompt?: readonly string[];
12
+ readonly providerAppend?: string;
13
+ readonly skills: readonly Skill[];
14
+ readonly contextFiles: readonly ContextFile[];
15
+ readonly contextBudget?: BuildSystemPromptOptions["contextBudget"];
16
+ }
17
+ export interface SessionSystemPromptAssembly {
18
+ readonly options: BuildSystemPromptOptions;
19
+ readonly prompt: string;
20
+ readonly cacheBoundary: number;
21
+ }
22
+ /**
23
+ * Pure assembly of the session system-prompt plan: tool filtering, snippet and
24
+ * guideline collection, and append-section joining. Callers resolve side effects
25
+ * (resource loader reads, provider playbook files) and pass them in.
26
+ */
27
+ export declare function assembleSessionSystemPrompt(input: SessionSystemPromptInput): SessionSystemPromptAssembly;
28
+ //# sourceMappingURL=session-system-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/session-system-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,wBAAwB,EAAiD,MAAM,oBAAoB,CAAC;AAElH,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IAC5C,QAAQ,CAAC,kBAAkB,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzD,QAAQ,CAAC,oBAAoB,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IACtE,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,CAAC;IAClC,QAAQ,CAAC,YAAY,EAAE,SAAS,WAAW,EAAE,CAAC;IAC9C,QAAQ,CAAC,aAAa,CAAC,EAAE,wBAAwB,CAAC,eAAe,CAAC,CAAC;CACnE;AAED,MAAM,WAAW,2BAA2B;IAC3C,QAAQ,CAAC,OAAO,EAAE,wBAAwB,CAAC;IAC3C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAC/B;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,wBAAwB,GAAG,2BAA2B,CA4BxG","sourcesContent":["import type { ContextFile } from \"./resource-loader.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { type BuildSystemPromptOptions, type BuiltSystemPrompt, buildSystemPromptPlan } from \"./system-prompt.ts\";\n\nexport interface SessionSystemPromptInput {\n\treadonly cwd: string;\n\treadonly toolNames: readonly string[];\n\treadonly hasTool: (name: string) => boolean;\n\treadonly toolPromptSnippets: ReadonlyMap<string, string>;\n\treadonly toolPromptGuidelines: ReadonlyMap<string, readonly string[]>;\n\treadonly customPrompt?: string;\n\treadonly appendSystemPrompt?: readonly string[];\n\treadonly providerAppend?: string;\n\treadonly skills: readonly Skill[];\n\treadonly contextFiles: readonly ContextFile[];\n\treadonly contextBudget?: BuildSystemPromptOptions[\"contextBudget\"];\n}\n\nexport interface SessionSystemPromptAssembly {\n\treadonly options: BuildSystemPromptOptions;\n\treadonly prompt: string;\n\treadonly cacheBoundary: number;\n}\n\n/**\n * Pure assembly of the session system-prompt plan: tool filtering, snippet and\n * guideline collection, and append-section joining. Callers resolve side effects\n * (resource loader reads, provider playbook files) and pass them in.\n */\nexport function assembleSessionSystemPrompt(input: SessionSystemPromptInput): SessionSystemPromptAssembly {\n\tconst validToolNames = input.toolNames.filter((name) => input.hasTool(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = input.toolPromptSnippets.get(name);\n\t\tif (snippet) toolSnippets[name] = snippet;\n\t\tconst toolGuidelines = input.toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) promptGuidelines.push(...toolGuidelines);\n\t}\n\n\tconst appendParts = [...(input.appendSystemPrompt ?? [])];\n\tif (input.providerAppend) appendParts.push(input.providerAppend);\n\tconst appendSystemPrompt = appendParts.length > 0 ? appendParts.join(\"\\n\\n\") : undefined;\n\n\tconst options: BuildSystemPromptOptions = {\n\t\tcwd: input.cwd,\n\t\tskills: [...input.skills],\n\t\tcontextFiles: [...input.contextFiles],\n\t\tcustomPrompt: input.customPrompt,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tcontextBudget: input.contextBudget,\n\t};\n\tconst built: BuiltSystemPrompt = buildSystemPromptPlan(options);\n\treturn { options, prompt: built.prompt, cacheBoundary: built.cacheBoundary };\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import { buildSystemPromptPlan } from "./system-prompt.js";
2
+ /**
3
+ * Pure assembly of the session system-prompt plan: tool filtering, snippet and
4
+ * guideline collection, and append-section joining. Callers resolve side effects
5
+ * (resource loader reads, provider playbook files) and pass them in.
6
+ */
7
+ export function assembleSessionSystemPrompt(input) {
8
+ const validToolNames = input.toolNames.filter((name) => input.hasTool(name));
9
+ const toolSnippets = {};
10
+ const promptGuidelines = [];
11
+ for (const name of validToolNames) {
12
+ const snippet = input.toolPromptSnippets.get(name);
13
+ if (snippet)
14
+ toolSnippets[name] = snippet;
15
+ const toolGuidelines = input.toolPromptGuidelines.get(name);
16
+ if (toolGuidelines)
17
+ promptGuidelines.push(...toolGuidelines);
18
+ }
19
+ const appendParts = [...(input.appendSystemPrompt ?? [])];
20
+ if (input.providerAppend)
21
+ appendParts.push(input.providerAppend);
22
+ const appendSystemPrompt = appendParts.length > 0 ? appendParts.join("\n\n") : undefined;
23
+ const options = {
24
+ cwd: input.cwd,
25
+ skills: [...input.skills],
26
+ contextFiles: [...input.contextFiles],
27
+ customPrompt: input.customPrompt,
28
+ appendSystemPrompt,
29
+ selectedTools: validToolNames,
30
+ toolSnippets,
31
+ promptGuidelines,
32
+ contextBudget: input.contextBudget,
33
+ };
34
+ const built = buildSystemPromptPlan(options);
35
+ return { options, prompt: built.prompt, cacheBoundary: built.cacheBoundary };
36
+ }
37
+ //# sourceMappingURL=session-system-prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-system-prompt.js","sourceRoot":"","sources":["../../src/core/session-system-prompt.ts"],"names":[],"mappings":"AAEA,OAAO,EAAyD,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAsBlH;;;;GAIG;AACH,MAAM,UAAU,2BAA2B,CAAC,KAA+B,EAA+B;IACzG,MAAM,cAAc,GAAG,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7E,MAAM,YAAY,GAA2B,EAAE,CAAC;IAChD,MAAM,gBAAgB,GAAa,EAAE,CAAC;IACtC,KAAK,MAAM,IAAI,IAAI,cAAc,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,KAAK,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACnD,IAAI,OAAO;YAAE,YAAY,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC;QAC1C,MAAM,cAAc,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5D,IAAI,cAAc;YAAE,gBAAgB,CAAC,IAAI,CAAC,GAAG,cAAc,CAAC,CAAC;IAC9D,CAAC;IAED,MAAM,WAAW,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1D,IAAI,KAAK,CAAC,cAAc;QAAE,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IACjE,MAAM,kBAAkB,GAAG,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAEzF,MAAM,OAAO,GAA6B;QACzC,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,MAAM,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC;QACzB,YAAY,EAAE,CAAC,GAAG,KAAK,CAAC,YAAY,CAAC;QACrC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB;QAClB,aAAa,EAAE,cAAc;QAC7B,YAAY;QACZ,gBAAgB;QAChB,aAAa,EAAE,KAAK,CAAC,aAAa;KAClC,CAAC;IACF,MAAM,KAAK,GAAsB,qBAAqB,CAAC,OAAO,CAAC,CAAC;IAChE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC;AAAA,CAC7E","sourcesContent":["import type { ContextFile } from \"./resource-loader.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { type BuildSystemPromptOptions, type BuiltSystemPrompt, buildSystemPromptPlan } from \"./system-prompt.ts\";\n\nexport interface SessionSystemPromptInput {\n\treadonly cwd: string;\n\treadonly toolNames: readonly string[];\n\treadonly hasTool: (name: string) => boolean;\n\treadonly toolPromptSnippets: ReadonlyMap<string, string>;\n\treadonly toolPromptGuidelines: ReadonlyMap<string, readonly string[]>;\n\treadonly customPrompt?: string;\n\treadonly appendSystemPrompt?: readonly string[];\n\treadonly providerAppend?: string;\n\treadonly skills: readonly Skill[];\n\treadonly contextFiles: readonly ContextFile[];\n\treadonly contextBudget?: BuildSystemPromptOptions[\"contextBudget\"];\n}\n\nexport interface SessionSystemPromptAssembly {\n\treadonly options: BuildSystemPromptOptions;\n\treadonly prompt: string;\n\treadonly cacheBoundary: number;\n}\n\n/**\n * Pure assembly of the session system-prompt plan: tool filtering, snippet and\n * guideline collection, and append-section joining. Callers resolve side effects\n * (resource loader reads, provider playbook files) and pass them in.\n */\nexport function assembleSessionSystemPrompt(input: SessionSystemPromptInput): SessionSystemPromptAssembly {\n\tconst validToolNames = input.toolNames.filter((name) => input.hasTool(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = input.toolPromptSnippets.get(name);\n\t\tif (snippet) toolSnippets[name] = snippet;\n\t\tconst toolGuidelines = input.toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) promptGuidelines.push(...toolGuidelines);\n\t}\n\n\tconst appendParts = [...(input.appendSystemPrompt ?? [])];\n\tif (input.providerAppend) appendParts.push(input.providerAppend);\n\tconst appendSystemPrompt = appendParts.length > 0 ? appendParts.join(\"\\n\\n\") : undefined;\n\n\tconst options: BuildSystemPromptOptions = {\n\t\tcwd: input.cwd,\n\t\tskills: [...input.skills],\n\t\tcontextFiles: [...input.contextFiles],\n\t\tcustomPrompt: input.customPrompt,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tcontextBudget: input.contextBudget,\n\t};\n\tconst built: BuiltSystemPrompt = buildSystemPromptPlan(options);\n\treturn { options, prompt: built.prompt, cacheBoundary: built.cacheBoundary };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function isExactRecord(value: unknown, keys: readonly string[]): value is Record<string, unknown>;
2
+ //# sourceMappingURL=strict-record.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strict-record.d.ts","sourceRoot":"","sources":["../../src/core/strict-record.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMvG","sourcesContent":["export function isExactRecord(value: unknown, keys: readonly string[]): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst compare = (left: string, right: string): number => left.localeCompare(right);\n\tconst actual = Object.keys(value).sort(compare);\n\tconst expected = [...keys].sort(compare);\n\treturn actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\n"]}
@@ -0,0 +1,9 @@
1
+ export function isExactRecord(value, keys) {
2
+ if (typeof value !== "object" || value === null || Array.isArray(value))
3
+ return false;
4
+ const compare = (left, right) => left.localeCompare(right);
5
+ const actual = Object.keys(value).sort(compare);
6
+ const expected = [...keys].sort(compare);
7
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
8
+ }
9
+ //# sourceMappingURL=strict-record.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strict-record.js","sourceRoot":"","sources":["../../src/core/strict-record.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,aAAa,CAAC,KAAc,EAAE,IAAuB,EAAoC;IACxG,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtF,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,KAAa,EAAU,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACnF,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;AAAA,CAClG","sourcesContent":["export function isExactRecord(value: unknown, keys: readonly string[]): value is Record<string, unknown> {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst compare = (left: string, right: string): number => left.localeCompare(right);\n\tconst actual = Object.keys(value).sort(compare);\n\tconst expected = [...keys].sort(compare);\n\treturn actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-orchestration.d.ts","sourceRoot":"","sources":["../../src/core/subagent-orchestration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGN,KAAK,mBAAmB,EAExB,KAAK,gBAAgB,EAErB,KAAK,WAAW,EAChB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,yBAAyB,GAClC,SAAS,GACT,WAAW,GACX,UAAU,GACV,QAAQ,GACR,WAAW,GACX,UAAU,GACV,UAAU,GACV,oBAAoB,CAAC;AAExB,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG,UAAU,GAAG,YAAY,GAAG,QAAQ,CAAC;AAExF,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,IAAI,EAAE,yBAAyB,CAAC;IACzC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC,QAAQ,CAAC,WAAW,EAAE,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,sBAAsB,CAErG;AAED,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,mCAAmC,GAAG,yBAAyB,CAmCpH;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC5B,GAAG,iBAAiB,CAqCpB;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,GAAG,MAAM,EAAE,CAWvF","sourcesContent":["import {\n\tbuildSubagentLaneGrant,\n\ttype LaneContextInheritanceMode,\n\ttype LaneEvidenceGate,\n\ttype LaneSpawnReceipt,\n\ttype SubagentLaneGrant,\n} from \"./loadout-runtime.ts\";\nimport {\n\tapplyLoadoutProfile,\n\tBUILTIN_LOADOUTS,\n\ttype CapabilityInventory,\n\tderiveSchedulerFields,\n\ttype LoadoutAuthority,\n\ttype LoadoutProfile,\n\ttype LoadoutRole,\n} from \"./loadouts.ts\";\n\nexport type SubagentOrchestrationRole =\n\t| \"planner\"\n\t| \"architect\"\n\t| \"executor\"\n\t| \"critic\"\n\t| \"visual-qa\"\n\t| \"rhwp-doc\"\n\t| \"security\"\n\t| \"package-maintainer\";\n\nexport type SubagentSchedulerTopology = \"serial\" | \"parallel\" | \"map-reduce\" | \"hybrid\";\n\nexport interface SubagentRoleAssignment {\n\treadonly role: SubagentOrchestrationRole;\n\treadonly loadoutRole: LoadoutRole;\n\treadonly loadoutName: string;\n\treadonly agentName: string;\n\treadonly contextInheritance: LaneContextInheritanceMode;\n\treadonly evidenceGates: readonly LaneEvidenceGate[];\n\treadonly writesProductFiles: boolean;\n}\n\nexport interface SubagentLaneSpec {\n\treadonly id: string;\n\treadonly role: SubagentOrchestrationRole;\n\treadonly task: string;\n\treadonly dependsOn?: readonly string[];\n\treadonly readScope?: readonly string[];\n\treadonly writeScope?: readonly string[];\n\treadonly acceptance?: readonly string[];\n\treadonly evidenceOutput?: string;\n\treadonly blockedPaths?: readonly string[];\n\treadonly contextInheritance?: LaneContextInheritanceMode;\n\treadonly grantAuthority?: LoadoutAuthority;\n\treadonly loadoutName?: string;\n\treadonly agentName?: string;\n}\n\nexport interface SpawnGateDecision {\n\treadonly outcome: \"allowed\" | \"rejected\";\n\treadonly reason: string;\n\treadonly planRequired: boolean;\n\treadonly missingFields: readonly string[];\n}\n\nexport interface SubagentScheduleBatch {\n\treadonly index: number;\n\treadonly laneIds: readonly string[];\n\treadonly reason: \"ready-parallel\" | \"serialized-writer\" | \"parallel-limit\";\n}\n\nexport interface SubagentRouteFeatures {\n\treadonly topology: SubagentSchedulerTopology;\n\treadonly width: number;\n\treadonly criticalDepth: number;\n\treadonly couplingDensity: number;\n\treadonly parallelRatio: number;\n\treadonly nodeCount: number;\n\treadonly edgeCount: number;\n}\n\nexport interface BuildSubagentOrchestrationPlanInput {\n\treadonly runId: string;\n\treadonly lanes: readonly SubagentLaneSpec[];\n\treadonly inventory: CapabilityInventory;\n\treadonly spawnPlan?: LaneSpawnReceipt;\n\treadonly spawnThreshold?: number;\n\treadonly maxParallelLanes?: number;\n}\n\nexport interface SubagentOrchestrationPlan {\n\treadonly laneGrants: readonly SubagentLaneGrant[];\n\treadonly batches: readonly SubagentScheduleBatch[];\n\treadonly route: SubagentRouteFeatures;\n\treadonly spawnGate: SpawnGateDecision;\n\treadonly blockers: readonly string[];\n\treadonly warnings: readonly string[];\n}\n\nconst DEFAULT_SPAWN_THRESHOLD = 4;\n\nconst ROLE_ASSIGNMENTS: Readonly<Record<SubagentOrchestrationRole, SubagentRoleAssignment>> = {\n\tplanner: {\n\t\trole: \"planner\",\n\t\tloadoutRole: \"planner\",\n\t\tloadoutName: \"plan\",\n\t\tagentName: \"omk-planner\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\tarchitect: {\n\t\trole: \"architect\",\n\t\tloadoutRole: \"architect\",\n\t\tloadoutName: \"architect\",\n\t\tagentName: \"omk-architect\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\texecutor: {\n\t\trole: \"executor\",\n\t\tloadoutRole: \"executor\",\n\t\tloadoutName: \"executor\",\n\t\tagentName: \"omk-executor\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n\tcritic: {\n\t\trole: \"critic\",\n\t\tloadoutRole: \"critic\",\n\t\tloadoutName: \"critic\",\n\t\tagentName: \"omk-critic\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"visual-qa\": {\n\t\trole: \"visual-qa\",\n\t\tloadoutRole: \"visual-qa\",\n\t\tloadoutName: \"visual-qa\",\n\t\tagentName: \"omk-visual-qa\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"rhwp-doc\": {\n\t\trole: \"rhwp-doc\",\n\t\tloadoutRole: \"rhwp-doc\",\n\t\tloadoutName: \"rhwp-doc\",\n\t\tagentName: \"omk-rhwp-doc\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n\tsecurity: {\n\t\trole: \"security\",\n\t\tloadoutRole: \"security\",\n\t\tloadoutName: \"security\",\n\t\tagentName: \"omk-security\",\n\t\tcontextInheritance: \"none\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"package-maintainer\": {\n\t\trole: \"package-maintainer\",\n\t\tloadoutRole: \"package-maintainer\",\n\t\tloadoutName: \"package-maintainer\",\n\t\tagentName: \"omk-package-maintainer\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n};\n\nconst REQUIRED_SPAWN_PLAN_STRING_FIELDS = [\n\t\"whyParallel\",\n\t\"whyNotLocal\",\n\t\"independence\",\n\t\"expectedReceiptShape\",\n] as const;\n\ninterface PreparedLane {\n\treadonly index: number;\n\treadonly spec: SubagentLaneSpec;\n\treadonly grant: SubagentLaneGrant;\n\treadonly dependsOn: readonly string[];\n}\n\nexport function resolveSubagentRoleAssignment(role: SubagentOrchestrationRole): SubagentRoleAssignment {\n\treturn ROLE_ASSIGNMENTS[role];\n}\n\nexport function buildSubagentOrchestrationPlan(input: BuildSubagentOrchestrationPlanInput): SubagentOrchestrationPlan {\n\tif (\n\t\tinput.maxParallelLanes !== undefined &&\n\t\t(!Number.isInteger(input.maxParallelLanes) || input.maxParallelLanes < 1)\n\t) {\n\t\tthrow new RangeError(\"maxParallelLanes must be a positive integer\");\n\t}\n\n\tconst blockers: string[] = [];\n\tconst warnings: string[] = [];\n\tblockers.push(...validateLaneIntake(input.lanes));\n\tconst spawnGate = evaluateSpawnGate({\n\t\tchildCount: input.lanes.length,\n\t\tplan: input.spawnPlan,\n\t\tthreshold: input.spawnThreshold ?? DEFAULT_SPAWN_THRESHOLD,\n\t});\n\tif (spawnGate.outcome === \"rejected\") blockers.push(spawnGate.reason);\n\n\tconst prepared = input.lanes.map((lane, index) =>\n\t\tprepareLane(lane, index, input.runId, input.inventory, input.spawnPlan, blockers, warnings),\n\t);\n\tblockers.push(...findDependencyBlockers(prepared));\n\n\tconst scheduledLanes = applyReceiptConsumerDependencies(prepared);\n\tconst batches = schedulePreparedLanes(scheduledLanes, input.maxParallelLanes, blockers);\n\tconst route = buildRouteFeatures(scheduledLanes, batches);\n\n\treturn {\n\t\tlaneGrants: scheduledLanes.map((lane) => lane.grant),\n\t\tbatches,\n\t\troute,\n\t\tspawnGate,\n\t\tblockers: uniqueSorted(blockers),\n\t\twarnings: uniqueSorted(warnings),\n\t};\n}\n\nexport function evaluateSpawnGate(request: {\n\treadonly childCount: number;\n\treadonly plan?: LaneSpawnReceipt;\n\treadonly threshold?: number;\n}): SpawnGateDecision {\n\tconst threshold = request.threshold ?? DEFAULT_SPAWN_THRESHOLD;\n\tif (!Number.isInteger(request.childCount) || request.childCount < 0) {\n\t\tthrow new RangeError(\"childCount must be a non-negative integer\");\n\t}\n\tif (!Number.isInteger(threshold) || threshold < 1) {\n\t\tthrow new RangeError(\"threshold must be a positive integer\");\n\t}\n\n\tconst planRequired = request.childCount > threshold;\n\tif (!planRequired) {\n\t\treturn {\n\t\t\toutcome: \"allowed\",\n\t\t\treason: `batch of ${request.childCount} is at or below threshold ${threshold}`,\n\t\t\tplanRequired: false,\n\t\t\tmissingFields: [],\n\t\t};\n\t}\n\n\tconst missingFields = findMissingSpawnPlanFields(request.plan);\n\tif (missingFields.length > 0) {\n\t\treturn {\n\t\t\toutcome: \"rejected\",\n\t\t\treason: `batch of ${request.childCount} exceeds threshold ${threshold} and the spawn-plan receipt is ${\n\t\t\t\trequest.plan ? `incomplete (${missingFields.join(\", \")})` : \"missing\"\n\t\t\t}`,\n\t\t\tplanRequired: true,\n\t\t\tmissingFields,\n\t\t};\n\t}\n\n\treturn {\n\t\toutcome: \"allowed\",\n\t\treason: `batch of ${request.childCount} exceeds threshold ${threshold} and a complete spawn-plan receipt was provided`,\n\t\tplanRequired: true,\n\t\tmissingFields: [],\n\t};\n}\n\nexport function findMissingSpawnPlanFields(plan: LaneSpawnReceipt | undefined): string[] {\n\tif (!plan) return [...REQUIRED_SPAWN_PLAN_STRING_FIELDS, \"maxInlineTokens\"];\n\tconst missing: string[] = [];\n\tfor (const field of REQUIRED_SPAWN_PLAN_STRING_FIELDS) {\n\t\tconst value = plan[field];\n\t\tif (value.trim().length === 0) missing.push(field);\n\t}\n\tif (!Number.isFinite(plan.maxInlineTokens) || plan.maxInlineTokens <= 0) {\n\t\tmissing.push(\"maxInlineTokens\");\n\t}\n\treturn missing;\n}\n\nfunction validateLaneIntake(lanes: readonly SubagentLaneSpec[]): string[] {\n\tconst blockers: string[] = [];\n\tconst seenIds = new Map<string, number>();\n\n\tfor (const [index, lane] of lanes.entries()) {\n\t\tconst id = lane.id.trim();\n\t\tconst label = id === \"\" ? `lane at index ${index}` : `lane ${id}`;\n\t\tif (id === \"\") {\n\t\t\tblockers.push(`lane at index ${index} has empty id`);\n\t\t} else {\n\t\t\tconst firstIndex = seenIds.get(id);\n\t\t\tif (firstIndex === undefined) {\n\t\t\t\tseenIds.set(id, index);\n\t\t\t} else {\n\t\t\t\tblockers.push(`duplicate lane id ${id} at indexes ${firstIndex} and ${index}`);\n\t\t\t}\n\t\t}\n\n\t\tif (lane.task.trim() === \"\") {\n\t\t\tblockers.push(`${label} has empty task`);\n\t\t}\n\n\t\tconst seenDependencies = new Set<string>();\n\t\tfor (const dependency of lane.dependsOn ?? []) {\n\t\t\tconst dependencyId = dependency.trim();\n\t\t\tif (dependencyId === \"\") {\n\t\t\t\tblockers.push(`${label} has empty dependency id`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dependencyId === id) {\n\t\t\t\tblockers.push(`${label} depends on itself`);\n\t\t\t}\n\t\t\tif (seenDependencies.has(dependencyId)) {\n\t\t\t\tblockers.push(`${label} repeats dependency ${dependencyId}`);\n\t\t\t}\n\t\t\tseenDependencies.add(dependencyId);\n\t\t}\n\t}\n\n\treturn blockers;\n}\n\nfunction prepareLane(\n\tspec: SubagentLaneSpec,\n\tindex: number,\n\trunId: string,\n\tinventory: CapabilityInventory,\n\tspawnReceipt: LaneSpawnReceipt | undefined,\n\tblockers: string[],\n\twarnings: string[],\n): PreparedLane {\n\tconst assignment = resolveSubagentRoleAssignment(spec.role);\n\tif ((spec.writeScope?.length ?? 0) > 0 && !assignment.writesProductFiles) {\n\t\tblockers.push(`lane ${spec.id} role ${spec.role} cannot write product files`);\n\t}\n\tconst dependsOn = uniqueSorted(spec.dependsOn ?? []);\n\n\tconst profile = resolveLoadoutProfile(spec, assignment, blockers);\n\tconst applied = applyLoadoutProfile(profile, inventory, { grantAuthority: spec.grantAuthority });\n\tblockers.push(...applied.blockers.map((blocker) => `lane ${spec.id}: ${blocker}`));\n\twarnings.push(...applied.warnings.map((warning) => `lane ${spec.id}: ${warning}`));\n\n\tconst schedulerFields = deriveSchedulerFields({\n\t\trole: assignment.loadoutRole,\n\t\tassignedReadPaths: spec.readScope,\n\t\tassignedWritePaths: spec.writeScope,\n\t});\n\n\tconst grant = buildSubagentLaneGrant(spec.id, assignment.loadoutRole, spec.task, applied, schedulerFields, {\n\t\tallowedReadPaths: spec.readScope,\n\t\tallowedWritePaths: spec.writeScope,\n\t\tblockedPaths: spec.blockedPaths,\n\t\tevidenceOutputPattern: spec.evidenceOutput ?? profile.evidence?.outputPattern,\n\t\trunId,\n\t\tprofile,\n\t\tagentName: spec.agentName ?? assignment.agentName,\n\t\tcontextInheritance: spec.contextInheritance ?? assignment.contextInheritance,\n\t\tspawnReceipt,\n\t\tevidenceGates: assignment.evidenceGates,\n\t\tdependsOn,\n\t\tacceptance: spec.acceptance,\n\t});\n\n\treturn { index, spec, grant, dependsOn };\n}\n\nfunction resolveLoadoutProfile(\n\tspec: SubagentLaneSpec,\n\tassignment: SubagentRoleAssignment,\n\tblockers: string[],\n): LoadoutProfile {\n\tconst loadoutName = spec.loadoutName ?? assignment.loadoutName;\n\tconst profile = BUILTIN_LOADOUTS[loadoutName];\n\tif (profile) return profile;\n\tblockers.push(`lane ${spec.id}: unknown loadout ${loadoutName}`);\n\treturn BUILTIN_LOADOUTS.none;\n}\n\nfunction findDependencyBlockers(lanes: readonly PreparedLane[]): string[] {\n\tconst ids = new Set(lanes.map((lane) => lane.spec.id));\n\tconst blockers: string[] = [];\n\tfor (const lane of lanes) {\n\t\tfor (const dependency of lane.dependsOn) {\n\t\t\tif (!ids.has(dependency)) {\n\t\t\t\tblockers.push(`lane ${lane.spec.id} depends on missing lane ${dependency}`);\n\t\t\t}\n\t\t}\n\t}\n\treturn blockers;\n}\n\nfunction applyReceiptConsumerDependencies(lanes: readonly PreparedLane[]): PreparedLane[] {\n\tconst receiptProducerIds = lanes\n\t\t.filter((lane) => lane.grant.evidenceOutput !== undefined && !isReceiptConsumerRole(lane.spec.role))\n\t\t.map((lane) => lane.spec.id);\n\n\treturn lanes.map((lane) => {\n\t\tif (!isReceiptReadingConsumer(lane) || receiptProducerIds.length === 0) return lane;\n\t\tconst dependsOn = uniqueSorted([\n\t\t\t...lane.dependsOn,\n\t\t\t...receiptProducerIds.filter((producerId) => producerId !== lane.spec.id),\n\t\t]);\n\t\tif (arrayEquals(dependsOn, lane.dependsOn)) return lane;\n\t\treturn {\n\t\t\t...lane,\n\t\t\tdependsOn,\n\t\t\tgrant: {\n\t\t\t\t...lane.grant,\n\t\t\t\tdependsOn,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction isReceiptReadingConsumer(lane: PreparedLane): boolean {\n\tif (!isReceiptConsumerRole(lane.spec.role)) return false;\n\treturn (lane.spec.readScope ?? []).some(isReceiptPath);\n}\n\nfunction isReceiptConsumerRole(role: SubagentOrchestrationRole): boolean {\n\treturn role === \"critic\" || role === \"visual-qa\" || role === \"rhwp-doc\";\n}\n\nfunction isReceiptPath(path: string): boolean {\n\tconst normalized = normalizePath(path);\n\treturn normalized === \".omk/runs\" || normalized.startsWith(\".omk/runs/\") || normalized.includes(\"/.omk/runs/\");\n}\n\nfunction schedulePreparedLanes(\n\tlanes: readonly PreparedLane[],\n\tmaxParallelLanes: number | undefined,\n\tblockers: string[],\n): SubagentScheduleBatch[] {\n\tconst scheduled = new Set<string>();\n\tconst batches: SubagentScheduleBatch[] = [];\n\n\twhile (scheduled.size < lanes.length) {\n\t\tconst ready = lanes.filter(\n\t\t\t(lane) => !scheduled.has(lane.spec.id) && lane.dependsOn.every((dependency) => scheduled.has(dependency)),\n\t\t);\n\t\tif (ready.length === 0) {\n\t\t\tconst remaining = lanes.filter((lane) => !scheduled.has(lane.spec.id)).map((lane) => lane.spec.id);\n\t\t\tblockers.push(`lane dependency cycle or unsatisfied dependency among: ${remaining.join(\", \")}`);\n\t\t\tbreak;\n\t\t}\n\n\t\tconst serialized = ready.find((lane) => !lane.grant.scheduler.parallelizable);\n\t\tif (serialized) {\n\t\t\tbatches.push({\n\t\t\t\tindex: batches.length,\n\t\t\t\tlaneIds: [serialized.spec.id],\n\t\t\t\treason: \"serialized-writer\",\n\t\t\t});\n\t\t\tscheduled.add(serialized.spec.id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst selected: PreparedLane[] = [];\n\t\tfor (const lane of ready) {\n\t\t\tif (maxParallelLanes !== undefined && selected.length >= maxParallelLanes) break;\n\t\t\tif (!selected.some((selectedLane) => lanesConflict(selectedLane, lane))) {\n\t\t\t\tselected.push(lane);\n\t\t\t}\n\t\t}\n\t\tconst batchLanes = selected.length > 0 ? selected : [ready[0]];\n\t\tfor (const lane of batchLanes) scheduled.add(lane.spec.id);\n\t\tbatches.push({\n\t\t\tindex: batches.length,\n\t\t\tlaneIds: batchLanes.map((lane) => lane.spec.id),\n\t\t\treason:\n\t\t\t\tmaxParallelLanes !== undefined && ready.length > batchLanes.length ? \"parallel-limit\" : \"ready-parallel\",\n\t\t});\n\t}\n\n\treturn batches;\n}\n\nfunction lanesConflict(left: PreparedLane, right: PreparedLane): boolean {\n\treturn (\n\t\tpathsConflict(\n\t\t\tleft.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t[\n\t\t\t\t...right.grant.scheduler.readSet.map((entry) => entry.path),\n\t\t\t\t...right.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t],\n\t\t) ||\n\t\tpathsConflict(\n\t\t\tright.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t[\n\t\t\t\t...left.grant.scheduler.readSet.map((entry) => entry.path),\n\t\t\t\t...left.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t],\n\t\t)\n\t);\n}\n\nfunction pathsConflict(writers: readonly string[], candidates: readonly string[]): boolean {\n\tfor (const writer of writers) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (pathIntersects(writer, candidate)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction pathIntersects(left: string, right: string): boolean {\n\tconst normalizedLeft = normalizePath(left);\n\tconst normalizedRight = normalizePath(right);\n\treturn (\n\t\tnormalizedLeft === normalizedRight ||\n\t\tnormalizedLeft.startsWith(`${normalizedRight}/`) ||\n\t\tnormalizedRight.startsWith(`${normalizedLeft}/`)\n\t);\n}\n\nfunction buildRouteFeatures(\n\tlanes: readonly PreparedLane[],\n\tbatches: readonly SubagentScheduleBatch[],\n): SubagentRouteFeatures {\n\tconst nodeCount = lanes.length;\n\tconst edgeCount = lanes.reduce((sum, lane) => sum + lane.dependsOn.length, 0);\n\tconst width = batches.reduce((max, batch) => Math.max(max, batch.laneIds.length), 0);\n\tconst criticalDepth = batches.length;\n\tconst parallelizable = lanes.filter((lane) => lane.grant.scheduler.parallelizable).length;\n\tconst parallelRatio = nodeCount === 0 ? 1 : parallelizable / nodeCount;\n\tconst couplingDensity = nodeCount <= 1 ? 0 : edgeCount / (nodeCount * (nodeCount - 1));\n\tconst topology = selectTopology(lanes, batches, width, criticalDepth, edgeCount);\n\n\treturn {\n\t\ttopology,\n\t\twidth,\n\t\tcriticalDepth,\n\t\tcouplingDensity: round(couplingDensity),\n\t\tparallelRatio: round(parallelRatio),\n\t\tnodeCount,\n\t\tedgeCount,\n\t};\n}\n\nfunction selectTopology(\n\tlanes: readonly PreparedLane[],\n\tbatches: readonly SubagentScheduleBatch[],\n\twidth: number,\n\tcriticalDepth: number,\n\tedgeCount: number,\n): SubagentSchedulerTopology {\n\tif (lanes.length <= 1 || width <= 1) return \"serial\";\n\tif (edgeCount === 0 && criticalDepth === 1) return \"parallel\";\n\tif (isMapReduceShape(lanes, batches)) return \"map-reduce\";\n\treturn \"hybrid\";\n}\n\nfunction isMapReduceShape(lanes: readonly PreparedLane[], batches: readonly SubagentScheduleBatch[]): boolean {\n\tif (batches.length < 2) return false;\n\tconst firstBatch = batches[0];\n\tconst finalBatch = batches[batches.length - 1];\n\tif (firstBatch.laneIds.length < 2 || finalBatch.laneIds.length !== 1) return false;\n\tconst finalLane = lanes.find((lane) => lane.spec.id === finalBatch.laneIds[0]);\n\tif (!finalLane) return false;\n\treturn firstBatch.laneIds.every((laneId) => finalLane.dependsOn.includes(laneId));\n}\n\nfunction normalizePath(path: string): string {\n\treturn path.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/g, \"\");\n}\n\nfunction round(value: number): number {\n\treturn Math.round(value * 1000) / 1000;\n}\n\nfunction uniqueSorted(values: readonly string[]): string[] {\n\treturn [...new Set(values)]\n\t\t.map((value) => value.trim())\n\t\t.filter((value) => value !== \"\")\n\t\t.sort();\n}\n\nfunction arrayEquals(left: readonly string[], right: readonly string[]): boolean {\n\treturn left.length === right.length && left.every((value, index) => value === right[index]);\n}\n"]}
1
+ {"version":3,"file":"subagent-orchestration.d.ts","sourceRoot":"","sources":["../../src/core/subagent-orchestration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGN,KAAK,mBAAmB,EAExB,KAAK,gBAAgB,EAErB,KAAK,WAAW,EAChB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,yBAAyB,GAClC,SAAS,GACT,WAAW,GACX,UAAU,GACV,QAAQ,GACR,WAA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,CAAC;IACnD,QAAQ,CAAC,KAAK,EAAE,qBAAqB,CAAC;IACtC,QAAQ,CAAC,SAAS,EAAE,iBAAiB,CAAC;IACtC,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC;AA6FD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,yBAAyB,GAAG,sBAAsB,CAErG;AAED,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,mCAAmC,GAAG,yBAAyB,CAmCpH;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC5B,GAAG,iBAAiB,CAqCpB;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,GAAG,MAAM,EAAE,CAWvF","sourcesContent":["import {\n\tbuildSubagentLaneGrant,\n\ttype LaneContextInheritanceMode,\n\ttype LaneEvidenceGate,\n\ttype LaneSpawnReceipt,\n\ttype SubagentLaneGrant,\n} from \"./loadout-runtime.ts\";\nimport {\n\tapplyLoadoutProfile,\n\tBUILTIN_LOADOUTS,\n\ttype CapabilityInventory,\n\tderiveSchedulerFields,\n\ttype LoadoutAuthority,\n\ttype LoadoutProfile,\n\ttype LoadoutRole,\n} from \"./loadouts.ts\";\n\nexport type SubagentOrchestrationRole =\n\t| \"planner\"\n\t| \"architect\"\n\t| \"executor\"\n\t| \"critic\"\n\t| \"visual-qa\"\n\t| \"rhwp-doc\"\n\t| \"security\"\n\t| \"package-maintainer\";\n\nexport type SubagentSchedulerTopology = \"serial\" | \"parallel\" | \"map-reduce\" | \"hybrid\";\n\nexport interface SubagentRoleAssignment {\n\treadonly role: SubagentOrchestrationRole;\n\treadonly loadoutRole: LoadoutRole;\n\treadonly loadoutName: string;\n\treadonly agentName: string;\n\treadonly contextInheritance: LaneContextInheritanceMode;\n\treadonly evidenceGates: readonly LaneEvidenceGate[];\n\treadonly writesProductFiles: boolean;\n}\n\nexport interface SubagentLaneSpec {\n\treadonly id: string;\n\treadonly role: SubagentOrchestrationRole;\n\treadonly task: string;\n\treadonly dependsOn?: readonly string[];\n\treadonly readScope?: readonly string[];\n\treadonly writeScope?: readonly string[];\n\treadonly acceptance?: readonly string[];\n\treadonly evidenceOutput?: string;\n\treadonly blockedPaths?: readonly string[];\n\treadonly contextInheritance?: LaneContextInheritanceMode;\n\treadonly grantAuthority?: LoadoutAuthority;\n\treadonly loadoutName?: string;\n\treadonly agentName?: string;\n}\n\nexport interface SpawnGateDecision {\n\treadonly outcome: \"allowed\" | \"rejected\";\n\treadonly reason: string;\n\treadonly planRequired: boolean;\n\treadonly missingFields: readonly string[];\n}\n\nexport interface SubagentScheduleBatch {\n\treadonly index: number;\n\treadonly laneIds: readonly string[];\n\treadonly reason: \"ready-parallel\" | \"serialized-writer\" | \"parallel-limit\";\n}\n\nexport interface SubagentRouteFeatures {\n\treadonly topology: SubagentSchedulerTopology;\n\treadonly width: number;\n\treadonly criticalDepth: number;\n\treadonly couplingDensity: number;\n\treadonly parallelRatio: number;\n\treadonly nodeCount: number;\n\treadonly edgeCount: number;\n}\n\nexport interface BuildSubagentOrchestrationPlanInput {\n\treadonly runId: string;\n\treadonly lanes: readonly SubagentLaneSpec[];\n\treadonly inventory: CapabilityInventory;\n\treadonly spawnPlan?: LaneSpawnReceipt;\n\treadonly spawnThreshold?: number;\n\treadonly maxParallelLanes?: number;\n}\n\nexport interface SubagentOrchestrationPlan {\n\treadonly laneGrants: readonly SubagentLaneGrant[];\n\treadonly batches: readonly SubagentScheduleBatch[];\n\treadonly route: SubagentRouteFeatures;\n\treadonly spawnGate: SpawnGateDecision;\n\treadonly blockers: readonly string[];\n\treadonly warnings: readonly string[];\n}\n\nconst DEFAULT_SPAWN_THRESHOLD = 4;\n\nconst ROLE_ASSIGNMENTS: Readonly<Record<SubagentOrchestrationRole, SubagentRoleAssignment>> = {\n\tplanner: {\n\t\trole: \"planner\",\n\t\tloadoutRole: \"planner\",\n\t\tloadoutName: \"plan\",\n\t\tagentName: \"omk-planner\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\tarchitect: {\n\t\trole: \"architect\",\n\t\tloadoutRole: \"architect\",\n\t\tloadoutName: \"architect\",\n\t\tagentName: \"omk-architect\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\texecutor: {\n\t\trole: \"executor\",\n\t\tloadoutRole: \"executor\",\n\t\tloadoutName: \"executor\",\n\t\tagentName: \"omk-executor\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n\tcritic: {\n\t\trole: \"critic\",\n\t\tloadoutRole: \"critic\",\n\t\tloadoutName: \"critic\",\n\t\tagentName: \"omk-critic\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"visual-qa\": {\n\t\trole: \"visual-qa\",\n\t\tloadoutRole: \"visual-qa\",\n\t\tloadoutName: \"visual-qa\",\n\t\tagentName: \"omk-visual-qa\",\n\t\tcontextInheritance: \"receipt\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"rhwp-doc\": {\n\t\trole: \"rhwp-doc\",\n\t\tloadoutRole: \"rhwp-doc\",\n\t\tloadoutName: \"rhwp-doc\",\n\t\tagentName: \"omk-rhwp-doc\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n\tsecurity: {\n\t\trole: \"security\",\n\t\tloadoutRole: \"security\",\n\t\tloadoutName: \"security\",\n\t\tagentName: \"omk-security\",\n\t\tcontextInheritance: \"none\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: false,\n\t},\n\t\"package-maintainer\": {\n\t\trole: \"package-maintainer\",\n\t\tloadoutRole: \"package-maintainer\",\n\t\tloadoutName: \"package-maintainer\",\n\t\tagentName: \"omk-package-maintainer\",\n\t\tcontextInheritance: \"bounded\",\n\t\tevidenceGates: [\"plan-reread\", \"automated-verification\", \"manual-qa\", \"adversarial-qa\", \"cleanup\"],\n\t\twritesProductFiles: true,\n\t},\n};\n\nconst REQUIRED_SPAWN_PLAN_STRING_FIELDS = [\n\t\"whyParallel\",\n\t\"whyNotLocal\",\n\t\"independence\",\n\t\"expectedReceiptShape\",\n] as const;\n\ninterface PreparedLane {\n\treadonly index: number;\n\treadonly spec: SubagentLaneSpec;\n\treadonly grant: SubagentLaneGrant;\n\treadonly dependsOn: readonly string[];\n}\n\nexport function resolveSubagentRoleAssignment(role: SubagentOrchestrationRole): SubagentRoleAssignment {\n\treturn ROLE_ASSIGNMENTS[role];\n}\n\nexport function buildSubagentOrchestrationPlan(input: BuildSubagentOrchestrationPlanInput): SubagentOrchestrationPlan {\n\tif (\n\t\tinput.maxParallelLanes !== undefined &&\n\t\t(!Number.isInteger(input.maxParallelLanes) || input.maxParallelLanes < 1)\n\t) {\n\t\tthrow new RangeError(\"maxParallelLanes must be a positive integer\");\n\t}\n\n\tconst blockers: string[] = [];\n\tconst warnings: string[] = [];\n\tblockers.push(...validateLaneIntake(input.lanes));\n\tconst spawnGate = evaluateSpawnGate({\n\t\tchildCount: input.lanes.length,\n\t\tplan: input.spawnPlan,\n\t\tthreshold: input.spawnThreshold ?? DEFAULT_SPAWN_THRESHOLD,\n\t});\n\tif (spawnGate.outcome === \"rejected\") blockers.push(spawnGate.reason);\n\n\tconst prepared = input.lanes.map((lane, index) =>\n\t\tprepareLane(lane, index, input.runId, input.inventory, input.spawnPlan, blockers, warnings),\n\t);\n\tblockers.push(...findDependencyBlockers(prepared));\n\n\tconst scheduledLanes = applyReceiptConsumerDependencies(prepared);\n\tconst batches = schedulePreparedLanes(scheduledLanes, input.maxParallelLanes, blockers);\n\tconst route = buildRouteFeatures(scheduledLanes, batches);\n\n\treturn {\n\t\tlaneGrants: scheduledLanes.map((lane) => lane.grant),\n\t\tbatches,\n\t\troute,\n\t\tspawnGate,\n\t\tblockers: uniqueSorted(blockers),\n\t\twarnings: uniqueSorted(warnings),\n\t};\n}\n\nexport function evaluateSpawnGate(request: {\n\treadonly childCount: number;\n\treadonly plan?: LaneSpawnReceipt;\n\treadonly threshold?: number;\n}): SpawnGateDecision {\n\tconst threshold = request.threshold ?? DEFAULT_SPAWN_THRESHOLD;\n\tif (!Number.isInteger(request.childCount) || request.childCount < 0) {\n\t\tthrow new RangeError(\"childCount must be a non-negative integer\");\n\t}\n\tif (!Number.isInteger(threshold) || threshold < 1) {\n\t\tthrow new RangeError(\"threshold must be a positive integer\");\n\t}\n\n\tconst planRequired = request.childCount > threshold;\n\tif (!planRequired) {\n\t\treturn {\n\t\t\toutcome: \"allowed\",\n\t\t\treason: `batch of ${request.childCount} is at or below threshold ${threshold}`,\n\t\t\tplanRequired: false,\n\t\t\tmissingFields: [],\n\t\t};\n\t}\n\n\tconst missingFields = findMissingSpawnPlanFields(request.plan);\n\tif (missingFields.length > 0) {\n\t\treturn {\n\t\t\toutcome: \"rejected\",\n\t\t\treason: `batch of ${request.childCount} exceeds threshold ${threshold} and the spawn-plan receipt is ${\n\t\t\t\trequest.plan ? `incomplete (${missingFields.join(\", \")})` : \"missing\"\n\t\t\t}`,\n\t\t\tplanRequired: true,\n\t\t\tmissingFields,\n\t\t};\n\t}\n\n\treturn {\n\t\toutcome: \"allowed\",\n\t\treason: `batch of ${request.childCount} exceeds threshold ${threshold} and a complete spawn-plan receipt was provided`,\n\t\tplanRequired: true,\n\t\tmissingFields: [],\n\t};\n}\n\nexport function findMissingSpawnPlanFields(plan: LaneSpawnReceipt | undefined): string[] {\n\tif (!plan) return [...REQUIRED_SPAWN_PLAN_STRING_FIELDS, \"maxInlineTokens\"];\n\tconst missing: string[] = [];\n\tfor (const field of REQUIRED_SPAWN_PLAN_STRING_FIELDS) {\n\t\tconst value = plan[field];\n\t\tif (value.trim().length === 0) missing.push(field);\n\t}\n\tif (!Number.isFinite(plan.maxInlineTokens) || plan.maxInlineTokens <= 0) {\n\t\tmissing.push(\"maxInlineTokens\");\n\t}\n\treturn missing;\n}\n\nfunction validateLaneIntake(lanes: readonly SubagentLaneSpec[]): string[] {\n\tconst blockers: string[] = [];\n\tconst seenIds = new Map<string, number>();\n\n\tfor (const [index, lane] of lanes.entries()) {\n\t\tconst id = lane.id.trim();\n\t\tconst label = id === \"\" ? `lane at index ${index}` : `lane ${id}`;\n\t\tif (id === \"\") {\n\t\t\tblockers.push(`lane at index ${index} has empty id`);\n\t\t} else {\n\t\t\tconst firstIndex = seenIds.get(id);\n\t\t\tif (firstIndex === undefined) {\n\t\t\t\tseenIds.set(id, index);\n\t\t\t} else {\n\t\t\t\tblockers.push(`duplicate lane id ${id} at indexes ${firstIndex} and ${index}`);\n\t\t\t}\n\t\t}\n\n\t\tif (lane.task.trim() === \"\") {\n\t\t\tblockers.push(`${label} has empty task`);\n\t\t}\n\n\t\tconst seenDependencies = new Set<string>();\n\t\tfor (const dependency of lane.dependsOn ?? []) {\n\t\t\tconst dependencyId = dependency.trim();\n\t\t\tif (dependencyId === \"\") {\n\t\t\t\tblockers.push(`${label} has empty dependency id`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dependencyId === id) {\n\t\t\t\tblockers.push(`${label} depends on itself`);\n\t\t\t}\n\t\t\tif (seenDependencies.has(dependencyId)) {\n\t\t\t\tblockers.push(`${label} repeats dependency ${dependencyId}`);\n\t\t\t}\n\t\t\tseenDependencies.add(dependencyId);\n\t\t}\n\t}\n\n\treturn blockers;\n}\n\nfunction prepareLane(\n\tspec: SubagentLaneSpec,\n\tindex: number,\n\trunId: string,\n\tinventory: CapabilityInventory,\n\tspawnReceipt: LaneSpawnReceipt | undefined,\n\tblockers: string[],\n\twarnings: string[],\n): PreparedLane {\n\tconst assignment = resolveSubagentRoleAssignment(spec.role);\n\tif ((spec.writeScope?.length ?? 0) > 0 && !assignment.writesProductFiles) {\n\t\tblockers.push(`lane ${spec.id} role ${spec.role} cannot write product files`);\n\t}\n\tconst dependsOn = uniqueSorted(spec.dependsOn ?? []);\n\n\tconst profile = resolveLoadoutProfile(spec, assignment, blockers);\n\tconst applied = applyLoadoutProfile(profile, inventory, { grantAuthority: spec.grantAuthority });\n\tblockers.push(...applied.blockers.map((blocker) => `lane ${spec.id}: ${blocker}`));\n\twarnings.push(...applied.warnings.map((warning) => `lane ${spec.id}: ${warning}`));\n\n\tconst schedulerFields = deriveSchedulerFields({\n\t\trole: assignment.loadoutRole,\n\t\tassignedReadPaths: spec.readScope,\n\t\tassignedWritePaths: spec.writeScope,\n\t});\n\n\tconst grant = buildSubagentLaneGrant(spec.id, assignment.loadoutRole, spec.task, applied, schedulerFields, {\n\t\tallowedReadPaths: spec.readScope,\n\t\tallowedWritePaths: spec.writeScope,\n\t\tblockedPaths: spec.blockedPaths,\n\t\tevidenceOutputPattern: spec.evidenceOutput ?? profile.evidence?.outputPattern,\n\t\trunId,\n\t\tprofile,\n\t\tagentName: spec.agentName ?? assignment.agentName,\n\t\tcontextInheritance: spec.contextInheritance ?? assignment.contextInheritance,\n\t\tspawnReceipt,\n\t\tevidenceGates: assignment.evidenceGates,\n\t\tdependsOn,\n\t\tacceptance: spec.acceptance,\n\t});\n\n\treturn { index, spec, grant, dependsOn };\n}\n\nfunction resolveLoadoutProfile(\n\tspec: SubagentLaneSpec,\n\tassignment: SubagentRoleAssignment,\n\tblockers: string[],\n): LoadoutProfile {\n\tconst loadoutName = spec.loadoutName ?? assignment.loadoutName;\n\tconst profile = BUILTIN_LOADOUTS[loadoutName];\n\tif (profile) return profile;\n\tblockers.push(`lane ${spec.id}: unknown loadout ${loadoutName}`);\n\treturn BUILTIN_LOADOUTS.none;\n}\n\nfunction findDependencyBlockers(lanes: readonly PreparedLane[]): string[] {\n\tconst ids = new Set(lanes.map((lane) => lane.spec.id));\n\tconst blockers: string[] = [];\n\tfor (const lane of lanes) {\n\t\tfor (const dependency of lane.dependsOn) {\n\t\t\tif (!ids.has(dependency)) {\n\t\t\t\tblockers.push(`lane ${lane.spec.id} depends on missing lane ${dependency}`);\n\t\t\t}\n\t\t}\n\t}\n\treturn blockers;\n}\n\nfunction applyReceiptConsumerDependencies(lanes: readonly PreparedLane[]): PreparedLane[] {\n\tconst receiptProducerIds = lanes\n\t\t.filter((lane) => lane.grant.evidenceOutput !== undefined && !isReceiptConsumerRole(lane.spec.role))\n\t\t.map((lane) => lane.spec.id);\n\n\treturn lanes.map((lane) => {\n\t\tif (!isReceiptReadingConsumer(lane) || receiptProducerIds.length === 0) return lane;\n\t\tconst dependsOn = uniqueSorted([\n\t\t\t...lane.dependsOn,\n\t\t\t...receiptProducerIds.filter((producerId) => producerId !== lane.spec.id),\n\t\t]);\n\t\tif (arrayEquals(dependsOn, lane.dependsOn)) return lane;\n\t\treturn {\n\t\t\t...lane,\n\t\t\tdependsOn,\n\t\t\tgrant: {\n\t\t\t\t...lane.grant,\n\t\t\t\tdependsOn,\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction isReceiptReadingConsumer(lane: PreparedLane): boolean {\n\tif (!isReceiptConsumerRole(lane.spec.role)) return false;\n\treturn (lane.spec.readScope ?? []).some(isReceiptPath);\n}\n\nfunction isReceiptConsumerRole(role: SubagentOrchestrationRole): boolean {\n\treturn role === \"critic\" || role === \"visual-qa\" || role === \"rhwp-doc\";\n}\n\nfunction isReceiptPath(path: string): boolean {\n\tconst normalized = normalizePath(path);\n\treturn normalized === \".omk/runs\" || normalized.startsWith(\".omk/runs/\") || normalized.includes(\"/.omk/runs/\");\n}\n\nfunction schedulePreparedLanes(\n\tlanes: readonly PreparedLane[],\n\tmaxParallelLanes: number | undefined,\n\tblockers: string[],\n): SubagentScheduleBatch[] {\n\tconst scheduled = new Set<string>();\n\tconst batches: SubagentScheduleBatch[] = [];\n\n\twhile (scheduled.size < lanes.length) {\n\t\tconst ready = lanes\n\t\t\t.filter(\n\t\t\t\t(lane) => !scheduled.has(lane.spec.id) && lane.dependsOn.every((dependency) => scheduled.has(dependency)),\n\t\t\t)\n\t\t\t.sort((left, right) => (left.spec.id < right.spec.id ? -1 : left.spec.id > right.spec.id ? 1 : 0));\n\t\tif (ready.length === 0) {\n\t\t\tconst remaining = lanes.filter((lane) => !scheduled.has(lane.spec.id)).map((lane) => lane.spec.id);\n\t\t\tblockers.push(`lane dependency cycle or unsatisfied dependency among: ${remaining.join(\", \")}`);\n\t\t\tbreak;\n\t\t}\n\n\t\tconst serialized = ready.find((lane) => !lane.grant.scheduler.parallelizable);\n\t\tif (serialized) {\n\t\t\tbatches.push({\n\t\t\t\tindex: batches.length,\n\t\t\t\tlaneIds: [serialized.spec.id],\n\t\t\t\treason: \"serialized-writer\",\n\t\t\t});\n\t\t\tscheduled.add(serialized.spec.id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst selected: PreparedLane[] = [];\n\t\tfor (const lane of ready) {\n\t\t\tif (maxParallelLanes !== undefined && selected.length >= maxParallelLanes) break;\n\t\t\tif (!selected.some((selectedLane) => lanesConflict(selectedLane, lane))) {\n\t\t\t\tselected.push(lane);\n\t\t\t}\n\t\t}\n\t\tconst batchLanes = selected.length > 0 ? selected : [ready[0]];\n\t\tfor (const lane of batchLanes) scheduled.add(lane.spec.id);\n\t\tbatches.push({\n\t\t\tindex: batches.length,\n\t\t\tlaneIds: batchLanes.map((lane) => lane.spec.id),\n\t\t\treason:\n\t\t\t\tmaxParallelLanes !== undefined && ready.length > batchLanes.length ? \"parallel-limit\" : \"ready-parallel\",\n\t\t});\n\t}\n\n\treturn batches;\n}\n\nfunction lanesConflict(left: PreparedLane, right: PreparedLane): boolean {\n\treturn (\n\t\tpathsConflict(\n\t\t\tleft.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t[\n\t\t\t\t...right.grant.scheduler.readSet.map((entry) => entry.path),\n\t\t\t\t...right.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t],\n\t\t) ||\n\t\tpathsConflict(\n\t\t\tright.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t[\n\t\t\t\t...left.grant.scheduler.readSet.map((entry) => entry.path),\n\t\t\t\t...left.grant.scheduler.writeSet.map((entry) => entry.path),\n\t\t\t],\n\t\t)\n\t);\n}\n\nfunction pathsConflict(writers: readonly string[], candidates: readonly string[]): boolean {\n\tfor (const writer of writers) {\n\t\tfor (const candidate of candidates) {\n\t\t\tif (pathIntersects(writer, candidate)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction pathIntersects(left: string, right: string): boolean {\n\tconst normalizedLeft = normalizePath(left);\n\tconst normalizedRight = normalizePath(right);\n\treturn (\n\t\tnormalizedLeft === normalizedRight ||\n\t\tnormalizedLeft.startsWith(`${normalizedRight}/`) ||\n\t\tnormalizedRight.startsWith(`${normalizedLeft}/`)\n\t);\n}\n\nfunction buildRouteFeatures(\n\tlanes: readonly PreparedLane[],\n\tbatches: readonly SubagentScheduleBatch[],\n): SubagentRouteFeatures {\n\tconst nodeCount = lanes.length;\n\tconst edgeCount = lanes.reduce((sum, lane) => sum + lane.dependsOn.length, 0);\n\tconst width = batches.reduce((max, batch) => Math.max(max, batch.laneIds.length), 0);\n\tconst criticalDepth = batches.length;\n\tconst parallelizable = lanes.filter((lane) => lane.grant.scheduler.parallelizable).length;\n\tconst parallelRatio = nodeCount === 0 ? 1 : parallelizable / nodeCount;\n\tconst couplingDensity = nodeCount <= 1 ? 0 : edgeCount / (nodeCount * (nodeCount - 1));\n\tconst topology = selectTopology(lanes, batches, width, criticalDepth, edgeCount);\n\n\treturn {\n\t\ttopology,\n\t\twidth,\n\t\tcriticalDepth,\n\t\tcouplingDensity: round(couplingDensity),\n\t\tparallelRatio: round(parallelRatio),\n\t\tnodeCount,\n\t\tedgeCount,\n\t};\n}\n\nfunction selectTopology(\n\tlanes: readonly PreparedLane[],\n\tbatches: readonly SubagentScheduleBatch[],\n\twidth: number,\n\tcriticalDepth: number,\n\tedgeCount: number,\n): SubagentSchedulerTopology {\n\tif (lanes.length <= 1 || width <= 1) return \"serial\";\n\tif (edgeCount === 0 && criticalDepth === 1) return \"parallel\";\n\tif (isMapReduceShape(lanes, batches)) return \"map-reduce\";\n\treturn \"hybrid\";\n}\n\nfunction isMapReduceShape(lanes: readonly PreparedLane[], batches: readonly SubagentScheduleBatch[]): boolean {\n\tif (batches.length < 2) return false;\n\tconst firstBatch = batches[0];\n\tconst finalBatch = batches[batches.length - 1];\n\tif (firstBatch.laneIds.length < 2 || finalBatch.laneIds.length !== 1) return false;\n\tconst finalLane = lanes.find((lane) => lane.spec.id === finalBatch.laneIds[0]);\n\tif (!finalLane) return false;\n\treturn firstBatch.laneIds.every((laneId) => finalLane.dependsOn.includes(laneId));\n}\n\nfunction normalizePath(path: string): string {\n\treturn path.replace(/\\\\/g, \"/\").replace(/\\/+$/g, \"\");\n}\n\nfunction round(value: number): number {\n\treturn Math.round(value * 1000) / 1000;\n}\n\nfunction uniqueSorted(values: readonly string[]): string[] {\n\treturn [...new Set(values)]\n\t\t.map((value) => value.trim())\n\t\t.filter((value) => value !== \"\")\n\t\t.sort();\n}\n\nfunction arrayEquals(left: readonly string[], right: readonly string[]): boolean {\n\treturn left.length === right.length && left.every((value, index) => value === right[index]);\n}\n"]}
@@ -289,7 +289,9 @@ function schedulePreparedLanes(lanes, maxParallelLanes, blockers) {
289
289
  const scheduled = new Set();
290
290
  const batches = [];
291
291
  while (scheduled.size < lanes.length) {
292
- const ready = lanes.filter((lane) => !scheduled.has(lane.spec.id) && lane.dependsOn.every((dependency) => scheduled.has(dependency)));
292
+ const ready = lanes
293
+ .filter((lane) => !scheduled.has(lane.spec.id) && lane.dependsOn.every((dependency) => scheduled.has(dependency)))
294
+ .sort((left, right) => (left.spec.id < right.spec.id ? -1 : left.spec.id > right.spec.id ? 1 : 0));
293
295
  if (ready.length === 0) {
294
296
  const remaining = lanes.filter((lane) => !scheduled.has(lane.spec.id)).map((lane) => lane.spec.id);
295
297
  blockers.push(`lane dependency cycle or unsatisfied dependency among: ${remaining.join(", ")}`);
@@ -391,7 +393,7 @@ function isMapReduceShape(lanes, batches) {
391
393
  return firstBatch.laneIds.every((laneId) => finalLane.dependsOn.includes(laneId));
392
394
  }
393
395
  function normalizePath(path) {
394
- return path.replaceAll("\\", "/").replace(/\/+$/g, "");
396
+ return path.replace(/\\/g, "/").replace(/\/+$/g, "");
395
397
  }
396
398
  function round(value) {
397
399
  return Math.round(value * 1000) / 1000;