open-multi-agent-kit 0.95.2 → 0.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +15 -0
- package/dist/approvals/approval-receipt-store.d.ts.map +1 -1
- package/dist/approvals/approval-receipt-store.js +25 -0
- package/dist/approvals/approval-receipt-store.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +41 -17
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/provider-resilience.d.ts +7 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +11 -0
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/subagent-orchestration.d.ts.map +1 -1
- package/dist/core/subagent-orchestration.js +4 -2
- package/dist/core/subagent-orchestration.js.map +1 -1
- package/dist/core/tools/diagnostics.d.ts.map +1 -1
- package/dist/core/tools/diagnostics.js +8 -2
- package/dist/core/tools/diagnostics.js.map +1 -1
- package/dist/guardrails/evidence-protocol.d.ts +10 -0
- package/dist/guardrails/evidence-protocol.d.ts.map +1 -0
- package/dist/guardrails/evidence-protocol.js +34 -0
- package/dist/guardrails/evidence-protocol.js.map +1 -0
- package/dist/guardrails/evidence-system.d.ts +3 -1
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +22 -14
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -1
- package/dist/guardrails/replay-ledger-lock-owner.js +3 -1
- package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -1
- package/dist/guardrails/replay-payload-hash.d.ts +6 -0
- package/dist/guardrails/replay-payload-hash.d.ts.map +1 -0
- package/dist/guardrails/replay-payload-hash.js +24 -0
- package/dist/guardrails/replay-payload-hash.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/evidence.d.ts +11 -3
- package/dist/types/evidence.d.ts.map +1 -1
- package/dist/types/evidence.js.map +1 -1
- package/docs/book-to-skill.md +79 -0
- package/docs/compaction.md +10 -0
- package/docs/docs.json +8 -0
- package/docs/index.md +3 -0
- package/docs/models.md +12 -0
- package/docs/provider-resilience.md +37 -56
- package/docs/providers.md +4 -0
- package/docs/run-protocol.md +72 -0
- package/docs/sdk.md +15 -2
- package/docs/sessions.md +6 -0
- package/docs/settings.md +2 -0
- package/docs/skills.md +9 -1
- package/docs/usage.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +37 -15
- package/package.json +8 -5
- package/dist/core/context-budget-compressors.d.ts +0 -50
- package/dist/core/context-budget-compressors.d.ts.map +0 -1
- package/dist/core/context-budget-compressors.js +0 -166
- package/dist/core/context-budget-compressors.js.map +0 -1
- package/dist/core/extensions/loader.js.bak-sharedjiti-20260812-111246 +0 -553
|
@@ -26,6 +26,13 @@ export declare const DEFAULT_PROVIDER_RESILIENCE: Required<Pick<ProviderResilien
|
|
|
26
26
|
};
|
|
27
27
|
export declare function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean;
|
|
28
28
|
export declare function isContentSafetyStopMessage(text: string | undefined): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Billing/quota exhaustion ("usage limit for this billing cycle",
|
|
31
|
+
* "insufficient_quota", zero balance, ...). Same-model retry is useless until
|
|
32
|
+
* the cycle resets, but the turn can still be saved by failing over to another
|
|
33
|
+
* candidate — so these classify as retryable-with-failover, not auth-fatal.
|
|
34
|
+
*/
|
|
35
|
+
export declare function isQuotaExhaustionMessage(text: string | undefined): boolean;
|
|
29
36
|
/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */
|
|
30
37
|
export declare function isOrphanToolCallIdError(text: string | undefined): boolean;
|
|
31
38
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-resilience.d.ts","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACpB,CAAC,CAAC;AAEH,oFAAoF;AACpF,eAAO,MAAM,sBAAsB,QAAW,CAAC;AAE/C,wEAAwE;AACxE,eAAO,MAAM,kCAAkC,EAAE,SAAS,iBAAiB,EAQjE,CAAC;AAEX,MAAM,MAAM,0BAA0B,GAAG,QAAQ,CAAC;IACjD,wFAAwF;IACxF,QAAQ,CAAC,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAC3C,kFAAkF;IAClF,QAAQ,CAAC,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAC5C,kFAAkF;IAClF,QAAQ,CAAC,kBAAkB,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;CAC3D,CAAC,CAAC;AAEH,eAAO,MAAM,2BAA2B,EAAE,QAAQ,CACjD,IAAI,CAAC,0BAA0B,EAAE,yBAAyB,GAAG,0BAA0B,CAAC,CACxF,GAAG;IACH,QAAQ,CAAC,kBAAkB,EAAE,SAAS,iBAAiB,EAAE,CAAC;CAK1D,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAMvG;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAK5E;AAED,0FAA0F;AAC1F,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAGzE;AAED;;;GAGG;AACH,wBAAgB,+BAA+B,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAKjF;AAED,wBAAgB,yBAAyB,CACxC,QAAQ,EAAE,0BAA0B,GAAG,SAAS,GAC9C,SAAS,iBAAiB,EAAE,CAI9B;AAED,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,0BAA0B,GAAG,SAAS,GAAG;IAC5F,QAAQ,CAAC,uBAAuB,EAAE,OAAO,CAAC;IAC1C,QAAQ,CAAC,wBAAwB,EAAE,OAAO,CAAC;IAC3C,QAAQ,CAAC,kBAAkB,EAAE,SAAS,iBAAiB,EAAE,CAAC;CAC1D,CAOA;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACpC,UAAU,EAAE,SAAS,iBAAiB,EAAE,EACxC,OAAO,EAAE;IAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,EACzE,SAAS,EAAE,CAAC,SAAS,EAAE,iBAAiB,KAAK,OAAO,GAClD,iBAAiB,GAAG,SAAS,CAQ/B;AAED,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMlF","sourcesContent":["/**\n * Provider resilience — root-level recovery for sticky safety models and\n * sanitize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"grok-oauth-proxy\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider-resilience.d.ts","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACpB,CAAC,CAAC;AAEH,oFAAoF;AACpF,eAAO,MAAM,sBAAsB,QAAW,CAAC;AAE/C,wEAAwE;AACxE,eAAO,MAAM,kCAAkC,EAAE,SAAS,iBAAiB,EAQjE,CAAC;AAEX,MAAM,MAAM,0BAA0B,GAAG,QAAQ,CAAC;IACjD,wFAAwF;IACxF,QAAQ,CAAC,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAC3C,kFAAkF;IAClF,QAAQ,CAAC,wBAAwB,CAAC,EAAE,OAAO,CAAC;IAC5C,kFAA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Q,CAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,EACzE,SAAS,EAAE,CAAC,SAAS,EAAE,iBAAiB,KAAK,OAAO,GAClD,iBAAiB,GAAG,SAAS,CAQ/B;AAED,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAMlF","sourcesContent":["/**\n * Provider resilience — root-level recovery for sticky safety models and\n * sanitize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"grok-oauth-proxy\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Billing/quota exhaustion (\"usage limit for this billing cycle\",\n * \"insufficient_quota\", zero balance, ...). Same-model retry is useless until\n * the cycle resets, but the turn can still be saved by failing over to another\n * candidate — so these classify as retryable-with-failover, not auth-fatal.\n */\nexport function isQuotaExhaustionMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /usage limit|GoUsageLimitError|FreeUsageLimitError|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
|
|
@@ -36,6 +36,17 @@ export function isContentSafetyStopMessage(text) {
|
|
|
36
36
|
return false;
|
|
37
37
|
return /content\/safety stop|stop_reason\s*=\s*(refusal|sensitive)|safety stop|provider\.refusal|kind=provider_refusal/i.test(text);
|
|
38
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Billing/quota exhaustion ("usage limit for this billing cycle",
|
|
41
|
+
* "insufficient_quota", zero balance, ...). Same-model retry is useless until
|
|
42
|
+
* the cycle resets, but the turn can still be saved by failing over to another
|
|
43
|
+
* candidate — so these classify as retryable-with-failover, not auth-fatal.
|
|
44
|
+
*/
|
|
45
|
+
export function isQuotaExhaustionMessage(text) {
|
|
46
|
+
if (!text)
|
|
47
|
+
return false;
|
|
48
|
+
return /usage limit|GoUsageLimitError|FreeUsageLimitError|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(text);
|
|
49
|
+
}
|
|
39
50
|
/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */
|
|
40
51
|
export function isOrphanToolCallIdError(text) {
|
|
41
52
|
if (!text)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-resilience.js","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,oFAAoF;AACpF,MAAM,CAAC,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AAE/C,wEAAwE;AACxE,MAAM,CAAC,MAAM,kCAAkC,GAAiC;IAC/E,EAAE,QAAQ,EAAE,aAAa,EAAE,EAAE,EAAE,IAAI,EAAE;IACrC,EAAE,QAAQ,EAAE,kBAAkB,EAAE,EAAE,EAAE,qBAAqB,EAAE;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AAO,CACN,+BAA+B,QAAQ,IAAI,OAAO,iDAAiD;QACnG,mFAAmF;QACnF,0DAA0D,CAC1D,CAAC;AAAA,CACF","sourcesContent":["/**\n * Provider resilience — root-level recovery for sticky safety models and\n * sanitize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"grok-oauth-proxy\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider-resilience.js","sourceRoot":"","sources":["../../src/core/provider-resilience.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,oFAAoF;AACpF,MAAM,CAAC,MAAM,sBAAsB,GAAG,QAAQ,CAAC;AAE/C,wEAAwE;AACxE,MAAM,CAAC,MAAM,kCAAkC,GAAiC;IAC/E,EAAE,QAAQ,EA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SAAS;QAChF,IAAI,mBAAmB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC;YAAE,SAAS;QACpD,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;YAAE,SAAS;QAC5B,OAAO,CAAC,CAAC;IACV,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,MAAM,UAAU,wBAAwB,CAAC,OAAe,EAAE,QAAgB,EAAU;IACnF,OAAO,CACN,+BAA+B,QAAQ,IAAI,OAAO,iDAAiD;QACnG,mFAAmF;QACnF,0DAA0D,CAC1D,CAAC;AAAA,CACF","sourcesContent":["/**\n * Provider resilience — root-level recovery for sticky safety models and\n * sanitize-and-retry protocol failures (orphan tool_call_id, terminated streams).\n *\n * This is not a jailbreak layer. It keeps sessions alive when a provider\n * false-positives or returns a sticky transcript-shape error.\n */\n\nexport type FailoverCandidate = Readonly<{\n\treadonly provider: string;\n\treadonly id: string;\n}>;\n\n/** Models known to emit high false-positive content/safety stops on coding work. */\nexport const STICKY_SAFETY_MODEL_RE = /fable/i;\n\n/** Default failover chain when a sticky safety model refuses a turn. */\nexport const DEFAULT_SAFETY_FAILOVER_CANDIDATES: readonly FailoverCandidate[] = [\n\t{ provider: \"kimi-coding\", id: \"k3\" },\n\t{ provider: \"modelstudio-maas\", id: \"qwen3.8-max-preview\" },\n\t{ provider: \"grok-oauth-proxy\", id: \"grok-4.5\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"deepseek\", id: \"deepseek-v4-flash\" },\n\t{ provider: \"modelstudio-maas\", id: \"deepseek-v4-pro\" },\n\t{ provider: \"kimi-coding\", id: \"kimi-for-coding\" },\n] as const;\n\nexport type ProviderResilienceSettings = Readonly<{\n\t/** When true (default), refuse selecting sticky safety models (e.g. claude-fable-5). */\n\treadonly blockStickySafetyModels?: boolean;\n\t/** When true (default), auto-switch model on content/safety stop before retry. */\n\treadonly autoFailoverOnSafetyStop?: boolean;\n\t/** Ordered failover targets. Falls back to DEFAULT_SAFETY_FAILOVER_CANDIDATES. */\n\treadonly failoverCandidates?: readonly FailoverCandidate[];\n}>;\n\nexport const DEFAULT_PROVIDER_RESILIENCE: Required<\n\tPick<ProviderResilienceSettings, \"blockStickySafetyModels\" | \"autoFailoverOnSafetyStop\">\n> & {\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} = {\n\tblockStickySafetyModels: true,\n\tautoFailoverOnSafetyStop: true,\n\tfailoverCandidates: DEFAULT_SAFETY_FAILOVER_CANDIDATES,\n};\n\nexport function isStickySafetyModel(modelId: string | undefined, provider?: string | undefined): boolean {\n\tconst id = (modelId ?? \"\").trim();\n\tif (!id) return false;\n\tif (STICKY_SAFETY_MODEL_RE.test(id)) return true;\n\tconst p = (provider ?? \"\").toLowerCase();\n\treturn p.includes(\"anthropic\") && STICKY_SAFETY_MODEL_RE.test(id);\n}\n\nexport function isContentSafetyStopMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|provider\\.refusal|kind=provider_refusal/i.test(\n\t\ttext,\n\t);\n}\n\n/**\n * Billing/quota exhaustion (\"usage limit for this billing cycle\",\n * \"insufficient_quota\", zero balance, ...). Same-model retry is useless until\n * the cycle resets, but the turn can still be saved by failing over to another\n * candidate — so these classify as retryable-with-failover, not auth-fatal.\n */\nexport function isQuotaExhaustionMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /usage limit|GoUsageLimitError|FreeUsageLimitError|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\ttext,\n\t);\n}\n\n/** Orphan tool results / Kimi-K3 protocol shape errors that heal after sanitize+retry. */\nexport function isOrphanToolCallIdError(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|unknown\\s+tool_call_id/i.test(text);\n}\n\n/**\n * Errors the agent loop may auto-retry (after optional failover / message sanitize).\n * Kept in one place so agent-session and tests share the same contract.\n */\nexport function isTransientProviderErrorMessage(text: string | undefined): boolean {\n\tif (!text) return false;\n\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|\\bterminated\\b|retry delay|content\\/safety stop|stop_reason\\s*=\\s*(refusal|sensitive)|safety stop|tool_call_id\\s+is\\s+not\\s+found|tool_call_id\\s+not\\s+found|invalid_request_error/i.test(\n\t\ttext,\n\t);\n}\n\nexport function resolveFailoverCandidates(\n\tsettings: ProviderResilienceSettings | undefined,\n): readonly FailoverCandidate[] {\n\tconst custom = settings?.failoverCandidates;\n\tif (custom && custom.length > 0) return custom;\n\treturn DEFAULT_SAFETY_FAILOVER_CANDIDATES;\n}\n\nexport function resolveProviderResilience(settings: ProviderResilienceSettings | undefined): {\n\treadonly blockStickySafetyModels: boolean;\n\treadonly autoFailoverOnSafetyStop: boolean;\n\treadonly failoverCandidates: readonly FailoverCandidate[];\n} {\n\treturn {\n\t\tblockStickySafetyModels: settings?.blockStickySafetyModels ?? DEFAULT_PROVIDER_RESILIENCE.blockStickySafetyModels,\n\t\tautoFailoverOnSafetyStop:\n\t\t\tsettings?.autoFailoverOnSafetyStop ?? DEFAULT_PROVIDER_RESILIENCE.autoFailoverOnSafetyStop,\n\t\tfailoverCandidates: resolveFailoverCandidates(settings),\n\t};\n}\n\n/**\n * Pick first failover candidate that is not the current model and passes `isAllowed`.\n * Pure — caller performs auth checks and setModel.\n */\nexport function pickFailoverCandidate(\n\tcandidates: readonly FailoverCandidate[],\n\tcurrent: { readonly provider?: string; readonly id?: string } | undefined,\n\tisAllowed: (candidate: FailoverCandidate) => boolean,\n): FailoverCandidate | undefined {\n\tfor (const c of candidates) {\n\t\tif (current && c.provider === current.provider && c.id === current.id) continue;\n\t\tif (isStickySafetyModel(c.id, c.provider)) continue;\n\t\tif (!isAllowed(c)) continue;\n\t\treturn c;\n\t}\n\treturn undefined;\n}\n\nexport function stickySafetyBlockMessage(modelId: string, provider: string): string {\n\treturn (\n\t\t`Blocked sticky safety model ${provider}/${modelId} (providerResilience.blockStickySafetyModels). ` +\n\t\t`Use kimi-coding/k3, modelstudio-maas/qwen3.8-max-preview, grok-4.5, or deepseek; ` +\n\t\t`or set providerResilience.blockStickySafetyModels=false.`\n\t);\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,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,kBAAkB,EAAE,0BAA0B,CAAC;IACxD,QAAQ,CAAC,aAAa,EAAE,SAAS,gBAAgB,EAAE,CAAC;IACpD,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAC;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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,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;IACz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AE,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
|
|
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.
|
|
396
|
+
return path.replace(/\\/g, "/").replace(/\/+$/g, "");
|
|
395
397
|
}
|
|
396
398
|
function round(value) {
|
|
397
399
|
return Math.round(value * 1000) / 1000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-orchestration.js","sourceRoot":"","sources":["../../src/core/subagent-orchestration.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,sBAAsB,GAKtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,mBAAmB,EACnB,gBAAgB,EAEhB,qBAAqB,GAIrB,MAAM,eAAe,CAAC;AAiFvB,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAElC,MAAM,gBAAgB,GAAwE;IAC7F,OAAO,EAAE;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;QACtB,WAAW,EAAE,MAAM;QACnB,SAAS,EAAE,aAAa;QACxB,kBAAkB,EAAE,SAAS;QAC7B,aAAa,EAAE,CAAC,aAAa,EAAE,SAAS,CAAC;QACzC,kBAAkB,EAAE,KAAK;KACzB;IACD,SAAS,EAAE;QACV,IAAI,EAAE,WAAW;QACjB,WAAW,EAAE,WAAW;QACxB,WAAW,EAAE,WAAW;QACxB,SAAS,EAAE,eAAe;QAC1B,kBAAkB,EAAE,SAAS;QAC7B,aAAa,E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,IAAI,CAAC,SAAS;QAAE,OAAO,KAAK,CAAC;IAC7B,OAAO,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AAAA,CAClF;AAED,SAAS,aAAa,CAAC,IAAY,EAAU;IAC5C,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAAA,CACvD;AAED,SAAS,KAAK,CAAC,KAAa,EAAU;IACrC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AAAA,CACvC;AAED,SAAS,YAAY,CAAC,MAAyB,EAAY;IAC1D,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;SACzB,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC;SAC/B,IAAI,EAAE,CAAC;AAAA,CACT;AAED,SAAS,WAAW,CAAC,IAAuB,EAAE,KAAwB,EAAW;IAChF,OAAO,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AAAA,CAC5F","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.js","sourceRoot":"","sources":["../../src/core/subagent-orchestration.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,sBAAsB,GAKtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,mBAAmB,EACnB,gBAAgB,EAEhB,qBAAqB,GAIrB,MAAM,eAAe,CAAC;AAiFvB,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAElC,MAAM,gBAAgB,GAAwE;IAC7F,OAAO,EAAE;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;QACtB,WAAW,EAAE,MAAM;QACnB,SAAS,EAAE,aAAa;QACxB,kBAAkB,EAAE,SAAS;QAC7B,aAAa,EAAE,CAAC,aAAa,EAAE,SAAS,CAAC;QACzC,kBAAkB,EAAE,KAAK;KACzB;IACD,SAAS,EAAE;QACV,IAAI,EAAE,WAAW;QACjB,WAAW,EAAE,WAAW;QACxB,WAAW,EAAE,WAAW;QACxB,SAAS,EAAE,eAAe;QAC1B,kBAAkB,EAAE,SAAS;QAC7B,aAAa,EAAE,CAAC,aAAa,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,SAAS,CAAC;QACrF,kBAAkB,EAAE,KAAK;KACzB;IACD,QAAQ,EAAE;QACT,IAAI,EAAE,UAAU;QAChB,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU;QACvB,SAAS,EAAE,cAAc;QACzB,kBAAkB,EAAE,SAAS;QAC7B,aAAa,EAAE,CAAC,aAAa,EAAE,wBAAwB,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,CAAC;QAClG,kBAAk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AAK,CAAC;IAC7B,OAAO,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AAAA,CAClF;AAED,SAAS,aAAa,CAAC,IAAY,EAAU;IAC5C,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAAA,CACrD;AAED,SAAS,KAAK,CAAC,KAAa,EAAU;IACrC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AAAA,CACvC;AAED,SAAS,YAAY,CAAC,MAAyB,EAAY;IAC1D,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;SACzB,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC;SAC/B,IAAI,EAAE,CAAC;AAAA,CACT;AAED,SAAS,WAAW,CAAC,IAAuB,EAAE,KAAwB,EAAW;IAChF,OAAO,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AAAA,CAC5F","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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../../src/core/tools/diagnostics.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,QAAA,MAAM,iBAAiB;;;;EAiBrB,CAAC;AAEH,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEpE,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;IAChD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,CAAC;IAChD,QAAQ,CAAC,OAAO,EAAE,SAAS;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAClE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACxC;AAoRD,wBAAgB,+BAA+B,CAC9C,GAAG,EAAE,MAAM,GACT,cAAc,CAAC,OAAO,iBAAiB,EAAE,sBAAsB,CAAC,CAoClE;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,OAAO,iBAAiB,CAAC,CAEtF","sourcesContent":["/**\n * Compiler-backed diagnostics tool (LSP-class value via project-native checkers).\n *\n * Routes per language to the checker the project already uses and normalizes\n * output to `SEVERITY path:line:col message`. Fail-soft by construction: a\n * missing checker, missing project marker, or checker crash reports `skipped`\n * for that language instead of throwing. Results are TTL-cached (5 s) since\n * project-wide checks are expensive.\n *\n * | language | checker (first found) | scope |\n * |------------|------------------------------------------|-------------------|\n * | typescript | `tsc --noEmit -p <nearest tsconfig>` | project |\n * | python | `pyright --outputjson` / `ruff check` | file or project |\n * | go | `go vet ./...` | module |\n * | rust | `cargo check --message-format short` | workspace |\n */\nimport { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"omk-agent-core\";\nimport { type Static, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst diagnosticsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Restrict diagnostics to this file (relative to cwd)\" })),\n\tlanguage: Type.Optional(\n\t\tType.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"auto\"),\n\t\t\t\tType.Literal(\"typescript\"),\n\t\t\t\tType.Literal(\"python\"),\n\t\t\t\tType.Literal(\"go\"),\n\t\t\t\tType.Literal(\"rust\"),\n\t\t\t],\n\t\t\t{\n\t\t\t\tdescription: \"Language to check; auto detects from path extension and project markers\",\n\t\t\t},\n\t\t),\n\t),\n\ttimeout: Type.Optional(Type.Number({ description: \"Per-language timeout in seconds (default 90)\" })),\n});\n\nexport type DiagnosticsToolInput = Static<typeof diagnosticsSchema>;\n\nexport interface DiagnosticLine {\n\treadonly language: string;\n\treadonly severity: \"error\" | \"warning\" | \"info\";\n\treadonly path: string;\n\treadonly line: number;\n\treadonly column: number;\n\treadonly message: string;\n}\n\nexport interface DiagnosticsToolDetails {\n\treadonly diagnostics: readonly DiagnosticLine[];\n\treadonly skipped: readonly { language: string; reason: string }[];\n\treadonly counts: Record<string, number>;\n}\n\nconst CACHE_TTL_MS = 5_000;\nconst MAX_DIAGNOSTICS = 50;\nconst DEFAULT_TIMEOUT_MS = 90_000;\n\nconst cache = new Map<string, { at: number; result: LanguageResult }>();\n\ninterface LanguageResult {\n\treadonly lines: readonly DiagnosticLine[];\n\treadonly skippedReason?: string;\n}\n\nfunction commandExists(command: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst probe = spawn(\"sh\", [\"-c\", `command -v ${command}`], { stdio: \"ignore\" });\n\t\tprobe.on(\"close\", (code) => resolve(code === 0));\n\t\tprobe.on(\"error\", () => resolve(false));\n\t});\n}\n\nfunction run(\n\tcommand: string,\n\targs: readonly string[],\n\tcwd: string,\n\ttimeoutMs: number,\n): Promise<{ code: number | null; out: string }> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(command, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"], windowsHide: true });\n\t\tlet out = \"\";\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t}, timeoutMs);\n\t\tchild.stdout.on(\"data\", (d: Buffer) => {\n\t\t\tif (out.length < 4 * 1024 * 1024) out += d.toString(\"utf8\");\n\t\t});\n\t\tchild.stderr.on(\"data\", (d: Buffer) => {\n\t\t\tif (out.length < 4 * 1024 * 1024) out += d.toString(\"utf8\");\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ code, out });\n\t\t});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ code: null, out });\n\t\t});\n\t});\n}\n\nfunction nearestMarker(cwd: string, names: readonly string[]): string | undefined {\n\t// ponytail: project markers live at the session root in this harness; walk up\n\t// at most 4 levels for nested worktrees.\n\tlet dir = cwd;\n\tfor (let level = 0; level <= 4; level++) {\n\t\tfor (const name of names) {\n\t\t\tif (existsSync(join(dir, name))) return dir;\n\t\t}\n\t\tconst parent = join(dir, \"..\");\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n\treturn undefined;\n}\n\nconst TS_ERROR = /^(?<path>.+?)\\((?<line>\\d+),(?<col>\\d+)\\): error TS\\d+: (?<msg>.+)$/;\n\nfunction parseTsc(out: string, language: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = TS_ERROR.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage,\n\t\t\t\tseverity: \"error\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst PYRIGHT_ISSUE = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+) - (?<sev>error|warning|information): (?<msg>.+)$/;\n\nfunction parsePyright(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\t// pyright --outputjson wraps issues in JSON; fall back to the text form when absent.\n\ttry {\n\t\tconst parsed = JSON.parse(out) as {\n\t\t\tgeneralDiagnostics?: {\n\t\t\t\tfile: string;\n\t\t\t\tseverity: string;\n\t\t\t\trange: { start: { line: number; character: number } };\n\t\t\t\tmessage: string;\n\t\t\t}[];\n\t\t};\n\t\tfor (const issue of parsed.generalDiagnostics ?? []) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"python\",\n\t\t\t\tseverity: issue.severity === \"error\" ? \"error\" : issue.severity === \"warning\" ? \"warning\" : \"info\",\n\t\t\t\tpath: issue.file,\n\t\t\t\tline: issue.range.start.line + 1,\n\t\t\t\tcolumn: issue.range.start.character + 1,\n\t\t\t\tmessage: issue.message,\n\t\t\t});\n\t\t}\n\t\treturn lines;\n\t} catch {\n\t\tfor (const raw of out.split(\"\\n\")) {\n\t\t\tconst match = PYRIGHT_ISSUE.exec(raw.trim());\n\t\t\tif (match?.groups) {\n\t\t\t\tlines.push({\n\t\t\t\t\tlanguage: \"python\",\n\t\t\t\t\tseverity: match.groups.sev === \"error\" ? \"error\" : match.groups.sev === \"warning\" ? \"warning\" : \"info\",\n\t\t\t\t\tpath: match.groups.path,\n\t\t\t\t\tline: Number(match.groups.line),\n\t\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n}\n\nconst RUFF_ISSUE = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseRuff(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = RUFF_ISSUE.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"python\",\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst GO_VET = /^(?:#\\s+\\S+\\s+)?(?<path>.+?\\.go):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseGoVet(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = GO_VET.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"go\",\n\t\t\t\tseverity: \"error\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst CARGO_SHORT = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseCargo(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = CARGO_SHORT.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tconst sev = match.groups.msg.startsWith(\"warning\") ? \"warning\" : \"error\";\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"rust\",\n\t\t\t\tseverity: sev,\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nasync function checkTypeScript(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"tsconfig.json\", \"tsconfig.build.json\"]);\n\tif (!root) return { lines: [], skippedReason: \"no tsconfig found\" };\n\tconst tsc = join(cwd, \"node_modules\", \".bin\", \"tsc\");\n\tconst localBin = existsSync(tsc) ? tsc : join(root, \"node_modules\", \".bin\", \"tsc\");\n\tconst bin = existsSync(localBin) ? localBin : \"tsc\";\n\tconst config = existsSync(join(root, \"tsconfig.json\")) ? \"tsconfig.json\" : \"tsconfig.build.json\";\n\tconst { code, out } = await run(bin, [\"--noEmit\", \"-p\", config, \"--pretty\", \"false\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"tsc spawn failed\" };\n\treturn { lines: parseTsc(out, \"typescript\").filter((d) => !path || d.path.includes(path)) };\n}\n\nasync function checkPython(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst target = path ?? \".\";\n\tif (await commandExists(\"pyright\")) {\n\t\tconst { code, out } = await run(\"pyright\", [\"--outputjson\", target], cwd, timeoutMs);\n\t\tif (code === null) return { lines: [], skippedReason: \"pyright spawn failed\" };\n\t\treturn { lines: parsePyright(out) };\n\t}\n\tif (await commandExists(\"ruff\")) {\n\t\tconst { code, out } = await run(\"ruff\", [\"check\", \"--no-cache\", target], cwd, timeoutMs);\n\t\tif (code === null) return { lines: [], skippedReason: \"ruff spawn failed\" };\n\t\treturn { lines: parseRuff(out) };\n\t}\n\treturn { lines: [], skippedReason: \"pyright/ruff not installed\" };\n}\n\nasync function checkGo(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"go.mod\"]);\n\tif (!root) return { lines: [], skippedReason: \"no go.mod found\" };\n\tif (!(await commandExists(\"go\"))) return { lines: [], skippedReason: \"go not installed\" };\n\tconst { code, out } = await run(\"go\", [\"vet\", \"./...\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"go vet spawn failed\" };\n\treturn { lines: parseGoVet(out).filter((d) => !path || d.path.includes(path)) };\n}\n\nasync function checkRust(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"Cargo.toml\"]);\n\tif (!root) return { lines: [], skippedReason: \"no Cargo.toml found\" };\n\tif (!(await commandExists(\"cargo\"))) return { lines: [], skippedReason: \"cargo not installed\" };\n\tconst { code, out } = await run(\"cargo\", [\"check\", \"--quiet\", \"--message-format\", \"short\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"cargo spawn failed\" };\n\treturn { lines: parseCargo(out).filter((d) => !path || d.path.includes(path)) };\n}\n\nconst CHECKERS = {\n\ttypescript: checkTypeScript,\n\tpython: checkPython,\n\tgo: checkGo,\n\trust: checkRust,\n} as const;\n\ntype Language = keyof typeof CHECKERS;\n\nfunction detectLanguages(cwd: string, path: string | undefined): Language[] {\n\tif (path) {\n\t\tif (/\\.tsx?$/.test(path)) return [\"typescript\"];\n\t\tif (/\\.py$/.test(path)) return [\"python\"];\n\t\tif (/\\.go$/.test(path)) return [\"go\"];\n\t\tif (/\\.rs$/.test(path)) return [\"rust\"];\n\t}\n\tconst detected: Language[] = [];\n\tif (nearestMarker(cwd, [\"tsconfig.json\", \"tsconfig.build.json\"])) detected.push(\"typescript\");\n\tif (nearestMarker(cwd, [\"pyproject.toml\", \"setup.py\", \"setup.cfg\", \"requirements.txt\"])) detected.push(\"python\");\n\tif (nearestMarker(cwd, [\"go.mod\"])) detected.push(\"go\");\n\tif (nearestMarker(cwd, [\"Cargo.toml\"])) detected.push(\"rust\");\n\treturn detected.length > 0 ? detected : [\"typescript\", \"python\", \"go\", \"rust\"];\n}\n\nasync function checkLanguage(\n\tlanguage: Language,\n\tcwd: string,\n\tpath: string | undefined,\n\ttimeoutMs: number,\n): Promise<LanguageResult> {\n\tconst key = `${language}${cwd}${path ?? \"\"}`;\n\tconst cached = cache.get(key);\n\tif (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;\n\tconst result = await CHECKERS[language](cwd, path, timeoutMs);\n\tif (cache.size >= 16) {\n\t\tconst oldest = cache.keys().next().value;\n\t\tif (oldest !== undefined) cache.delete(oldest);\n\t}\n\tcache.set(key, { at: Date.now(), result });\n\treturn result;\n}\n\nexport function createDiagnosticsToolDefinition(\n\tcwd: string,\n): ToolDefinition<typeof diagnosticsSchema, DiagnosticsToolDetails> {\n\treturn {\n\t\tname: \"diagnostics\",\n\t\tlabel: \"diagnostics\",\n\t\tdescription:\n\t\t\t\"Run the project's own type/lint checkers (tsc, pyright/ruff, go vet, cargo check) and return normalized diagnostics. Missing checkers or missing project markers are reported as skipped, never as tool errors.\",\n\t\tpromptSnippet: \"Get compiler/lint diagnostics for the workspace or a file\",\n\t\tparameters: diagnosticsSchema,\n\t\tasync execute(_toolCallId, { path, language, timeout }: DiagnosticsToolInput) {\n\t\t\tconst timeoutMs = timeout !== undefined && timeout > 0 ? timeout * 1000 : DEFAULT_TIMEOUT_MS;\n\t\t\tconst languages = language && language !== \"auto\" ? [language] : detectLanguages(cwd, path);\n\t\t\tconst settled = await Promise.all(languages.map((lang) => checkLanguage(lang, cwd, path, timeoutMs)));\n\t\t\tconst diagnostics: DiagnosticLine[] = [];\n\t\t\tconst skipped: { language: string; reason: string }[] = [];\n\t\t\tfor (let index = 0; index < languages.length; index++) {\n\t\t\t\tconst result = settled[index];\n\t\t\t\tif (result.skippedReason) skipped.push({ language: languages[index], reason: result.skippedReason });\n\t\t\t\tdiagnostics.push(...result.lines);\n\t\t\t}\n\t\t\tconst capped = diagnostics.slice(0, MAX_DIAGNOSTICS);\n\t\t\tconst counts: Record<string, number> = {};\n\t\t\tfor (const d of diagnostics) counts[d.language] = (counts[d.language] ?? 0) + 1;\n\t\t\tconst text =\n\t\t\t\tcapped.length === 0 && skipped.length === 0\n\t\t\t\t\t? \"No diagnostics.\"\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t...capped.map(\n\t\t\t\t\t\t\t\t(d) =>\n\t\t\t\t\t\t\t\t\t`${d.severity.toUpperCase()} ${d.path}:${d.line}:${d.column} ${d.message} (${d.language})`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...(diagnostics.length > capped.length ? [`... ${diagnostics.length - capped.length} more`] : []),\n\t\t\t\t\t\t\t...skipped.map((s) => `${s.language}: skipped (${s.reason})`),\n\t\t\t\t\t\t].join(\"\\n\");\n\t\t\treturn { content: [{ type: \"text\", text }], details: { diagnostics: capped, skipped, counts } };\n\t\t},\n\t};\n}\n\nexport function createDiagnosticsTool(cwd: string): AgentTool<typeof diagnosticsSchema> {\n\treturn wrapToolDefinition(createDiagnosticsToolDefinition(cwd));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../../src/core/tools/diagnostics.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAG7D,QAAA,MAAM,iBAAiB;;;;EAiBrB,CAAC;AAEH,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEpE,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;IAChD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,CAAC;IAChD,QAAQ,CAAC,OAAO,EAAE,SAAS;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAClE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACxC;AA8RD,wBAAgB,+BAA+B,CAC9C,GAAG,EAAE,MAAM,GACT,cAAc,CAAC,OAAO,iBAAiB,EAAE,sBAAsB,CAAC,CAoClE;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,OAAO,iBAAiB,CAAC,CAEtF","sourcesContent":["/**\n * Compiler-backed diagnostics tool (LSP-class value via project-native checkers).\n *\n * Routes per language to the checker the project already uses and normalizes\n * output to `SEVERITY path:line:col message`. Fail-soft by construction: a\n * missing checker, missing project marker, or checker crash reports `skipped`\n * for that language instead of throwing. Results are TTL-cached (5 s) since\n * project-wide checks are expensive.\n *\n * | language | checker (first found) | scope |\n * |------------|------------------------------------------|-------------------|\n * | typescript | `tsc --noEmit -p <nearest tsconfig>` | project |\n * | python | `pyright --outputjson` / `ruff check` | file or project |\n * | go | `go vet ./...` | module |\n * | rust | `cargo check --message-format short` | workspace |\n */\nimport { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"omk-agent-core\";\nimport { type Static, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst diagnosticsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Restrict diagnostics to this file (relative to cwd)\" })),\n\tlanguage: Type.Optional(\n\t\tType.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"auto\"),\n\t\t\t\tType.Literal(\"typescript\"),\n\t\t\t\tType.Literal(\"python\"),\n\t\t\t\tType.Literal(\"go\"),\n\t\t\t\tType.Literal(\"rust\"),\n\t\t\t],\n\t\t\t{\n\t\t\t\tdescription: \"Language to check; auto detects from path extension and project markers\",\n\t\t\t},\n\t\t),\n\t),\n\ttimeout: Type.Optional(Type.Number({ description: \"Per-language timeout in seconds (default 90)\" })),\n});\n\nexport type DiagnosticsToolInput = Static<typeof diagnosticsSchema>;\n\nexport interface DiagnosticLine {\n\treadonly language: string;\n\treadonly severity: \"error\" | \"warning\" | \"info\";\n\treadonly path: string;\n\treadonly line: number;\n\treadonly column: number;\n\treadonly message: string;\n}\n\nexport interface DiagnosticsToolDetails {\n\treadonly diagnostics: readonly DiagnosticLine[];\n\treadonly skipped: readonly { language: string; reason: string }[];\n\treadonly counts: Record<string, number>;\n}\n\nconst CACHE_TTL_MS = 5_000;\nconst MAX_DIAGNOSTICS = 50;\nconst DEFAULT_TIMEOUT_MS = 90_000;\n\nconst cache = new Map<string, { at: number; result: LanguageResult }>();\n\ninterface LanguageResult {\n\treadonly lines: readonly DiagnosticLine[];\n\treadonly skippedReason?: string;\n}\n\nfunction commandExists(command: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst probe = spawn(\"sh\", [\"-c\", `command -v ${command}`], { stdio: \"ignore\" });\n\t\tprobe.on(\"close\", (code) => resolve(code === 0));\n\t\tprobe.on(\"error\", () => resolve(false));\n\t});\n}\n\nfunction run(\n\tcommand: string,\n\targs: readonly string[],\n\tcwd: string,\n\ttimeoutMs: number,\n): Promise<{ code: number | null; out: string }> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(command, args, { cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"], windowsHide: true });\n\t\tlet out = \"\";\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t}, timeoutMs);\n\t\tchild.stdout.on(\"data\", (d: Buffer) => {\n\t\t\tif (out.length < 4 * 1024 * 1024) out += d.toString(\"utf8\");\n\t\t});\n\t\tchild.stderr.on(\"data\", (d: Buffer) => {\n\t\t\tif (out.length < 4 * 1024 * 1024) out += d.toString(\"utf8\");\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ code, out });\n\t\t});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ code: null, out });\n\t\t});\n\t});\n}\n\nfunction nearestMarker(cwd: string, names: readonly string[]): string | undefined {\n\t// ponytail: project markers live at the session root in this harness; walk up\n\t// at most 4 levels for nested worktrees.\n\tlet dir = cwd;\n\tfor (let level = 0; level <= 4; level++) {\n\t\tfor (const name of names) {\n\t\t\tif (existsSync(join(dir, name))) return dir;\n\t\t}\n\t\tconst parent = join(dir, \"..\");\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n\treturn undefined;\n}\n\nconst TS_ERROR = /^(?<path>.+?)\\((?<line>\\d+),(?<col>\\d+)\\): error TS\\d+: (?<msg>.+)$/;\n\nfunction parseTsc(out: string, language: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = TS_ERROR.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage,\n\t\t\t\tseverity: \"error\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst PYRIGHT_ISSUE = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+) - (?<sev>error|warning|information): (?<msg>.+)$/;\n\nfunction parsePyright(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\t// pyright --outputjson wraps issues in JSON; fall back to the text form when absent.\n\ttry {\n\t\tconst parsed = JSON.parse(out) as {\n\t\t\tgeneralDiagnostics?: {\n\t\t\t\tfile: string;\n\t\t\t\tseverity: string;\n\t\t\t\trange: { start: { line: number; character: number } };\n\t\t\t\tmessage: string;\n\t\t\t}[];\n\t\t};\n\t\tfor (const issue of parsed.generalDiagnostics ?? []) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"python\",\n\t\t\t\tseverity: issue.severity === \"error\" ? \"error\" : issue.severity === \"warning\" ? \"warning\" : \"info\",\n\t\t\t\tpath: issue.file,\n\t\t\t\tline: issue.range.start.line + 1,\n\t\t\t\tcolumn: issue.range.start.character + 1,\n\t\t\t\tmessage: issue.message,\n\t\t\t});\n\t\t}\n\t\treturn lines;\n\t} catch {\n\t\tfor (const raw of out.split(\"\\n\")) {\n\t\t\tconst match = PYRIGHT_ISSUE.exec(raw.trim());\n\t\t\tif (match?.groups) {\n\t\t\t\tlines.push({\n\t\t\t\t\tlanguage: \"python\",\n\t\t\t\t\tseverity: match.groups.sev === \"error\" ? \"error\" : match.groups.sev === \"warning\" ? \"warning\" : \"info\",\n\t\t\t\t\tpath: match.groups.path,\n\t\t\t\t\tline: Number(match.groups.line),\n\t\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n}\n\nconst RUFF_ISSUE = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseRuff(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = RUFF_ISSUE.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"python\",\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst GO_VET = /^(?:#\\s+\\S+\\s+)?(?<path>.+?\\.go):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseGoVet(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = GO_VET.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"go\",\n\t\t\t\tseverity: \"error\",\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst CARGO_SHORT = /^(?<path>.+?):(?<line>\\d+):(?<col>\\d+): (?<msg>.+)$/;\n\nfunction parseCargo(out: string): DiagnosticLine[] {\n\tconst lines: DiagnosticLine[] = [];\n\tfor (const raw of out.split(\"\\n\")) {\n\t\tconst match = CARGO_SHORT.exec(raw.trim());\n\t\tif (match?.groups) {\n\t\t\tconst sev = match.groups.msg.startsWith(\"warning\") ? \"warning\" : \"error\";\n\t\t\tlines.push({\n\t\t\t\tlanguage: \"rust\",\n\t\t\t\tseverity: sev,\n\t\t\t\tpath: match.groups.path,\n\t\t\t\tline: Number(match.groups.line),\n\t\t\t\tcolumn: Number(match.groups.col),\n\t\t\t\tmessage: match.groups.msg.trim(),\n\t\t\t});\n\t\t}\n\t}\n\treturn lines;\n}\n\nasync function checkTypeScript(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"tsconfig.json\", \"tsconfig.build.json\"]);\n\tif (!root) return { lines: [], skippedReason: \"no tsconfig found\" };\n\tconst tsc = join(cwd, \"node_modules\", \".bin\", \"tsc\");\n\tconst localBin = existsSync(tsc) ? tsc : join(root, \"node_modules\", \".bin\", \"tsc\");\n\tconst bin = existsSync(localBin) ? localBin : \"tsc\";\n\tconst config = existsSync(join(root, \"tsconfig.json\")) ? \"tsconfig.json\" : \"tsconfig.build.json\";\n\tconst { code, out } = await run(bin, [\"--noEmit\", \"-p\", config, \"--pretty\", \"false\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"tsc spawn failed\" };\n\treturn { lines: parseTsc(out, \"typescript\").filter((d) => !path || d.path.includes(path)) };\n}\n\nasync function checkPython(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst target = path ?? \".\";\n\tif (await commandExists(\"pyright\")) {\n\t\tconst { code, out } = await run(\"pyright\", [\"--outputjson\", target], cwd, timeoutMs);\n\t\tif (code === null) return { lines: [], skippedReason: \"pyright spawn failed\" };\n\t\tconst lines = parsePyright(out);\n\t\t// pyright가 사용 가능한 출력을 내지 못했으면(깨진 설치·실행 오류) 조용히 0건으로\n\t\t// 보고하지 말고 ruff로 폴�백한다. `--outputjson`은 정상 실행 시 항상\n\t\t// generalDiagnostics JSON을 낸다 — 마커가 없으면 실행 실패로 간주한다.\n\t\tif (lines.length > 0 || out.includes('\"generalDiagnostics\"')) return { lines };\n\t}\n\tif (await commandExists(\"ruff\")) {\n\t\t// ruff의 기본 full 출력은 parseRuff가 읽지 못하므로 concise(path:line:col: msg)를 강제한다.\n\t\tconst { code, out } = await run(\n\t\t\t\"ruff\",\n\t\t\t[\"check\", \"--no-cache\", \"--output-format\", \"concise\", target],\n\t\t\tcwd,\n\t\t\ttimeoutMs,\n\t\t);\n\t\tif (code === null) return { lines: [], skippedReason: \"ruff spawn failed\" };\n\t\treturn { lines: parseRuff(out) };\n\t}\n\treturn { lines: [], skippedReason: \"pyright/ruff not installed\" };\n}\n\nasync function checkGo(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"go.mod\"]);\n\tif (!root) return { lines: [], skippedReason: \"no go.mod found\" };\n\tif (!(await commandExists(\"go\"))) return { lines: [], skippedReason: \"go not installed\" };\n\tconst { code, out } = await run(\"go\", [\"vet\", \"./...\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"go vet spawn failed\" };\n\treturn { lines: parseGoVet(out).filter((d) => !path || d.path.includes(path)) };\n}\n\nasync function checkRust(cwd: string, path: string | undefined, timeoutMs: number): Promise<LanguageResult> {\n\tconst root = nearestMarker(cwd, [\"Cargo.toml\"]);\n\tif (!root) return { lines: [], skippedReason: \"no Cargo.toml found\" };\n\tif (!(await commandExists(\"cargo\"))) return { lines: [], skippedReason: \"cargo not installed\" };\n\tconst { code, out } = await run(\"cargo\", [\"check\", \"--quiet\", \"--message-format\", \"short\"], root, timeoutMs);\n\tif (code === null) return { lines: [], skippedReason: \"cargo spawn failed\" };\n\treturn { lines: parseCargo(out).filter((d) => !path || d.path.includes(path)) };\n}\n\nconst CHECKERS = {\n\ttypescript: checkTypeScript,\n\tpython: checkPython,\n\tgo: checkGo,\n\trust: checkRust,\n} as const;\n\ntype Language = keyof typeof CHECKERS;\n\nfunction detectLanguages(cwd: string, path: string | undefined): Language[] {\n\tif (path) {\n\t\tif (/\\.tsx?$/.test(path)) return [\"typescript\"];\n\t\tif (/\\.py$/.test(path)) return [\"python\"];\n\t\tif (/\\.go$/.test(path)) return [\"go\"];\n\t\tif (/\\.rs$/.test(path)) return [\"rust\"];\n\t}\n\tconst detected: Language[] = [];\n\tif (nearestMarker(cwd, [\"tsconfig.json\", \"tsconfig.build.json\"])) detected.push(\"typescript\");\n\tif (nearestMarker(cwd, [\"pyproject.toml\", \"setup.py\", \"setup.cfg\", \"requirements.txt\"])) detected.push(\"python\");\n\tif (nearestMarker(cwd, [\"go.mod\"])) detected.push(\"go\");\n\tif (nearestMarker(cwd, [\"Cargo.toml\"])) detected.push(\"rust\");\n\treturn detected.length > 0 ? detected : [\"typescript\", \"python\", \"go\", \"rust\"];\n}\n\nasync function checkLanguage(\n\tlanguage: Language,\n\tcwd: string,\n\tpath: string | undefined,\n\ttimeoutMs: number,\n): Promise<LanguageResult> {\n\tconst key = `${language}${cwd}${path ?? \"\"}`;\n\tconst cached = cache.get(key);\n\tif (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;\n\tconst result = await CHECKERS[language](cwd, path, timeoutMs);\n\tif (cache.size >= 16) {\n\t\tconst oldest = cache.keys().next().value;\n\t\tif (oldest !== undefined) cache.delete(oldest);\n\t}\n\tcache.set(key, { at: Date.now(), result });\n\treturn result;\n}\n\nexport function createDiagnosticsToolDefinition(\n\tcwd: string,\n): ToolDefinition<typeof diagnosticsSchema, DiagnosticsToolDetails> {\n\treturn {\n\t\tname: \"diagnostics\",\n\t\tlabel: \"diagnostics\",\n\t\tdescription:\n\t\t\t\"Run the project's own type/lint checkers (tsc, pyright/ruff, go vet, cargo check) and return normalized diagnostics. Missing checkers or missing project markers are reported as skipped, never as tool errors.\",\n\t\tpromptSnippet: \"Get compiler/lint diagnostics for the workspace or a file\",\n\t\tparameters: diagnosticsSchema,\n\t\tasync execute(_toolCallId, { path, language, timeout }: DiagnosticsToolInput) {\n\t\t\tconst timeoutMs = timeout !== undefined && timeout > 0 ? timeout * 1000 : DEFAULT_TIMEOUT_MS;\n\t\t\tconst languages = language && language !== \"auto\" ? [language] : detectLanguages(cwd, path);\n\t\t\tconst settled = await Promise.all(languages.map((lang) => checkLanguage(lang, cwd, path, timeoutMs)));\n\t\t\tconst diagnostics: DiagnosticLine[] = [];\n\t\t\tconst skipped: { language: string; reason: string }[] = [];\n\t\t\tfor (let index = 0; index < languages.length; index++) {\n\t\t\t\tconst result = settled[index];\n\t\t\t\tif (result.skippedReason) skipped.push({ language: languages[index], reason: result.skippedReason });\n\t\t\t\tdiagnostics.push(...result.lines);\n\t\t\t}\n\t\t\tconst capped = diagnostics.slice(0, MAX_DIAGNOSTICS);\n\t\t\tconst counts: Record<string, number> = {};\n\t\t\tfor (const d of diagnostics) counts[d.language] = (counts[d.language] ?? 0) + 1;\n\t\t\tconst text =\n\t\t\t\tcapped.length === 0 && skipped.length === 0\n\t\t\t\t\t? \"No diagnostics.\"\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t...capped.map(\n\t\t\t\t\t\t\t\t(d) =>\n\t\t\t\t\t\t\t\t\t`${d.severity.toUpperCase()} ${d.path}:${d.line}:${d.column} ${d.message} (${d.language})`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...(diagnostics.length > capped.length ? [`... ${diagnostics.length - capped.length} more`] : []),\n\t\t\t\t\t\t\t...skipped.map((s) => `${s.language}: skipped (${s.reason})`),\n\t\t\t\t\t\t].join(\"\\n\");\n\t\t\treturn { content: [{ type: \"text\", text }], details: { diagnostics: capped, skipped, counts } };\n\t\t},\n\t};\n}\n\nexport function createDiagnosticsTool(cwd: string): AgentTool<typeof diagnosticsSchema> {\n\treturn wrapToolDefinition(createDiagnosticsToolDefinition(cwd));\n}\n"]}
|
|
@@ -211,10 +211,16 @@ async function checkPython(cwd, path, timeoutMs) {
|
|
|
211
211
|
const { code, out } = await run("pyright", ["--outputjson", target], cwd, timeoutMs);
|
|
212
212
|
if (code === null)
|
|
213
213
|
return { lines: [], skippedReason: "pyright spawn failed" };
|
|
214
|
-
|
|
214
|
+
const lines = parsePyright(out);
|
|
215
|
+
// pyright가 사용 가능한 출력을 내지 못했으면(깨진 설치·실행 오류) 조용히 0건으로
|
|
216
|
+
// 보고하지 말고 ruff로 폴�백한다. `--outputjson`은 정상 실행 시 항상
|
|
217
|
+
// generalDiagnostics JSON을 낸다 — 마커가 없으면 실행 실패로 간주한다.
|
|
218
|
+
if (lines.length > 0 || out.includes('"generalDiagnostics"'))
|
|
219
|
+
return { lines };
|
|
215
220
|
}
|
|
216
221
|
if (await commandExists("ruff")) {
|
|
217
|
-
|
|
222
|
+
// ruff의 기본 full 출력은 parseRuff가 읽지 못하므로 concise(path:line:col: msg)를 강제한다.
|
|
223
|
+
const { code, out } = await run("ruff", ["check", "--no-cache", "--output-format", "concise", target], cwd, timeoutMs);
|
|
218
224
|
if (code === null)
|
|
219
225
|
return { lines: [], skippedReason: "ruff spawn failed" };
|
|
220
226
|
return { lines: parseRuff(out) };
|