@bastani/atomic 0.9.5-alpha.4 → 0.9.5-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/builtin/cursor/package.json +2 -2
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/CHANGELOG.md +7 -0
  6. package/dist/builtin/subagents/agents/debugger.md +2 -2
  7. package/dist/builtin/subagents/package.json +1 -1
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/builtin/workflows/CHANGELOG.md +17 -0
  10. package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +5 -5
  11. package/dist/builtin/workflows/builtin/goal-runner.ts +5 -5
  12. package/dist/builtin/workflows/builtin/goal-types.ts +1 -0
  13. package/dist/builtin/workflows/builtin/goal.d.ts +2 -0
  14. package/dist/builtin/workflows/builtin/goal.ts +9 -0
  15. package/dist/builtin/workflows/builtin/index.d.ts +2 -0
  16. package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +5 -5
  17. package/dist/builtin/workflows/builtin/ralph-models.ts +25 -25
  18. package/dist/builtin/workflows/package.json +1 -1
  19. package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +8 -0
  20. package/dist/builtin/workflows/src/runs/foreground/stage-control-registry.ts +2 -0
  21. package/dist/builtin/workflows/src/runs/foreground/stage-tool-execution-buffer.ts +47 -0
  22. package/dist/builtin/workflows/src/tui/stage-chat-view-pending-tools.ts +9 -0
  23. package/dist/builtin/workflows/src/tui/stage-chat-view-render-settings.ts +27 -0
  24. package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +5 -6
  25. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  26. package/dist/core/agent-session-auto-compaction.js +3 -2
  27. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  28. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  29. package/dist/core/agent-session-compaction.js +25 -4
  30. package/dist/core/agent-session-compaction.js.map +1 -1
  31. package/dist/core/compaction/context-compaction-critical.d.ts +15 -0
  32. package/dist/core/compaction/context-compaction-critical.d.ts.map +1 -0
  33. package/dist/core/compaction/context-compaction-critical.js +57 -0
  34. package/dist/core/compaction/context-compaction-critical.js.map +1 -0
  35. package/dist/core/compaction/context-compaction-eviction.d.ts +4 -0
  36. package/dist/core/compaction/context-compaction-eviction.d.ts.map +1 -0
  37. package/dist/core/compaction/context-compaction-eviction.js +172 -0
  38. package/dist/core/compaction/context-compaction-eviction.js.map +1 -0
  39. package/dist/core/compaction/context-compaction-runner.d.ts +7 -1
  40. package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
  41. package/dist/core/compaction/context-compaction-runner.js +97 -21
  42. package/dist/core/compaction/context-compaction-runner.js.map +1 -1
  43. package/dist/core/compaction/context-transcript-analysis.d.ts +3 -0
  44. package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
  45. package/dist/core/compaction/context-transcript-analysis.js +3 -3
  46. package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
  47. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  48. package/dist/core/extensions/loader-core.js +6 -0
  49. package/dist/core/extensions/loader-core.js.map +1 -1
  50. package/dist/core/model-resolver-scope.d.ts +9 -0
  51. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  52. package/dist/core/model-resolver-scope.js +12 -4
  53. package/dist/core/model-resolver-scope.js.map +1 -1
  54. package/dist/core/model-resolver.d.ts +3 -2
  55. package/dist/core/model-resolver.d.ts.map +1 -1
  56. package/dist/core/model-resolver.js +1 -1
  57. package/dist/core/model-resolver.js.map +1 -1
  58. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  59. package/dist/core/resource-loader-extensions.js +4 -0
  60. package/dist/core/resource-loader-extensions.js.map +1 -1
  61. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  62. package/dist/core/resource-loader-reload.js +11 -0
  63. package/dist/core/resource-loader-reload.js.map +1 -1
  64. package/dist/core/settings-manager-core.d.ts.map +1 -1
  65. package/dist/core/settings-manager-core.js +3 -2
  66. package/dist/core/settings-manager-core.js.map +1 -1
  67. package/dist/core/settings-storage.d.ts.map +1 -1
  68. package/dist/core/settings-storage.js +2 -1
  69. package/dist/core/settings-storage.js.map +1 -1
  70. package/dist/core/trust-manager.d.ts +9 -0
  71. package/dist/core/trust-manager.d.ts.map +1 -1
  72. package/dist/core/trust-manager.js +44 -2
  73. package/dist/core/trust-manager.js.map +1 -1
  74. package/dist/index.d.ts +1 -1
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +1 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/main-deferred-startup.d.ts +19 -0
  79. package/dist/main-deferred-startup.d.ts.map +1 -0
  80. package/dist/main-deferred-startup.js +21 -0
  81. package/dist/main-deferred-startup.js.map +1 -0
  82. package/dist/main.d.ts.map +1 -1
  83. package/dist/main.js +24 -22
  84. package/dist/main.js.map +1 -1
  85. package/dist/modes/interactive/interactive-deferred-startup.d.ts +2 -1
  86. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  87. package/dist/modes/interactive/interactive-deferred-startup.js +34 -1
  88. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  89. package/dist/modes/interactive/interactive-mode-deps.d.ts +2 -2
  90. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  91. package/dist/modes/interactive/interactive-mode-deps.js +2 -2
  92. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  93. package/dist/modes/interactive/interactive-mode-types.d.ts +5 -1
  94. package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
  95. package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
  96. package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
  97. package/dist/modes/interactive/interactive-session-routing.js +2 -2
  98. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  99. package/dist/utils/child-process.d.ts +8 -1
  100. package/dist/utils/child-process.d.ts.map +1 -1
  101. package/dist/utils/child-process.js +39 -6
  102. package/dist/utils/child-process.js.map +1 -1
  103. package/dist/utils/event-loop.d.ts +7 -0
  104. package/dist/utils/event-loop.d.ts.map +1 -0
  105. package/dist/utils/event-loop.js +14 -0
  106. package/dist/utils/event-loop.js.map +1 -0
  107. package/dist/utils/json.d.ts +4 -0
  108. package/dist/utils/json.d.ts.map +1 -1
  109. package/dist/utils/json.js +8 -0
  110. package/dist/utils/json.js.map +1 -1
  111. package/docs/compaction.md +45 -27
  112. package/docs/settings.md +5 -1
  113. package/docs/workflows.md +6 -2
  114. package/npm-shrinkwrap.json +23 -23
  115. package/package.json +2 -2
@@ -4,6 +4,9 @@ import type { CompactionSettings } from "./compaction.ts";
4
4
  import { type CompactableTranscriptEntry, type ContextCompactionPreparation, type ContextCompactionRunOptions } from "./context-compaction-types.ts";
5
5
  export declare function isExcludedFromLlmContext(message: AgentMessage): boolean;
6
6
  export declare function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean;
7
+ export declare function hasAssistantError(message: AgentMessage): boolean;
8
+ export declare function hasToolResultError(message: AgentMessage): boolean;
9
+ export declare function hasFailedBashExecution(message: AgentMessage): boolean;
7
10
  export declare function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string;
8
11
  export declare function prepareContextCompaction(pathEntries: SessionEntry[], settings: CompactionSettings, options?: ContextCompactionRunOptions): ContextCompactionPreparation | undefined;
9
12
  //# sourceMappingURL=context-transcript-analysis.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-transcript-analysis.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAOlE,OAAO,EAGN,KAAK,YAAY,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAGN,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,MAAM,+BAA+B,CAAC;AA0BvC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CASvE;AA6BD,wBAAgB,qCAAqC,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAMhG;AA+FD,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAU7F;AAiBD,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,2BAAgC,GACvC,4BAA4B,GAAG,SAAS,CA4D1C","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nfunction hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nfunction hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nfunction hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-transcript-analysis.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAOlE,OAAO,EAGN,KAAK,YAAY,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAGN,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,MAAM,+BAA+B,CAAC;AA0BvC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CASvE;AA6BD,wBAAgB,qCAAqC,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAMhG;AAmFD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEhE;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEjE;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAErE;AAED,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAU7F;AAiBD,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,2BAAgC,GACvC,4BAA4B,GAAG,SAAS,CA4D1C","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
@@ -135,13 +135,13 @@ function messageText(message) {
135
135
  }
136
136
  }
137
137
  }
138
- function hasAssistantError(message) {
138
+ export function hasAssistantError(message) {
139
139
  return message.role === "assistant" && message.stopReason === "error";
140
140
  }
141
- function hasToolResultError(message) {
141
+ export function hasToolResultError(message) {
142
142
  return message.role === "toolResult" && message.isError === true;
143
143
  }
144
- function hasFailedBashExecution(message) {
144
+ export function hasFailedBashExecution(message) {
145
145
  return message.role === "bashExecution" && typeof message.exitCode === "number" && message.exitCode !== 0;
146
146
  }
147
147
  export function autoDetectContextCompactionQuery(pathEntries) {
@@ -1 +1 @@
1
- {"version":3,"file":"context-transcript-analysis.js","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EACN,4BAA4B,EAC5B,uCAAuC,GACvC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gCAAgC,EAChC,oCAAoC,GAEpC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,sBAAsB,EAAE,cAAc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EAAE,CAAC,GAAG,iBAAiB,CAAC;YACzC,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC;YAC9E,QAAQ;YACR,UAAU;SACV;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nfunction hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nfunction hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nfunction hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-transcript-analysis.js","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EACN,4BAA4B,EAC5B,uCAAuC,GACvC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gCAAgC,EAChC,oCAAoC,GAEpC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EACN,6BAA6B,GAK7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,oCAAoC,EACpC,+BAA+B,GAC/B,MAAM,kCAAkC,CAAC;AAE1C,SAAS,mBAAmB,CAAC,KAAmB;IAC/C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC,OAAO,CAAC;IACtB,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;QACrC,OAAO,mBAAmB,CACzB,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,kBAAkB,CACxB,CAA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E,KAAK,SAAS,CAAC,CAAC;QAClH,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACnH,OAAO,CAAC,IAAI,CAAC;YACZ,OAAO,EAAE,KAAK,CAAC,EAAE;YACjB,SAAS,EAAE,KAAK,CAAC,IAAI;YACrB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,IAAI;YACJ,aAAa,EAAE,cAAc,CAAC,OAAO,CAAC;YACtC,SAAS,EAAE,cAAc;YACzB,aAAa;YACb,OAAO;YACP,WAAW;YACX,aAAa,EAAE,mBAAmB,CAAC,OAAO,CAAC;SAC3C,CAAC,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzC,OAAO;QACN,aAAa,EAAE,WAAW;QAC1B,UAAU;QACV,UAAU,EAAE;YACX,OAAO;YACP,iBAAiB,EAAE,CAAC,GAAG,iBAAiB,CAAC;YACzC,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC;YAC9E,QAAQ;YACR,UAAU;SACV;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"loader-core.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-core.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAIhE,OAAO,EAEL,KAAK,yCAAyC,EAC9C,KAAK,6BAA6B,EACnC,MAAM,uBAAuB,CAAC;AAO/B,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAkEtG;;GAEG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,gBAAgB,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,gBAAgB,EACzB,aAAa,SAAa,EAC1B,wBAAwB,GAAE,6BAA6D,EACvF,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,SAAS,CAAC,CAapB;AAmDD,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,wBAAwB,GAAE,6BAA6D,EACvF,OAAO,CAAC,EAAE,gBAAgB,EAC1B,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,oBAAoB,CAAC,CAS/B;AAED,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,wBAAwB,GAAE,6BAA6D,EACvF,OAAO,CAAC,EAAE,gBAAgB,EAC1B,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,oBAAoB,CAAC,CAU/B","sourcesContent":["import * as path from \"node:path\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { endTimingSpan, startTimingSpan } from \"../timings.ts\";\nimport { createExtensionAPI } from \"./loader-api.ts\";\nimport {\n emptyWorkflowResourceProvider,\n type ResourceLoaderInheritanceSnapshotProvider,\n type WorkflowResourceProviderInput,\n} from \"./loader-resources.ts\";\nimport { createExtensionRuntime } from \"./loader-runtime.ts\";\nimport {\n loadExtensionModule,\n type ExtensionCacheToken,\n useExtensionCacheCwd,\n} from \"./loader-virtual-modules.ts\";\nimport type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from \"./types.ts\";\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n const source = extensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n ? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n : \"local\";\n const baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n return {\n path: extensionPath,\n resolvedPath,\n sourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n handlers: new Map(),\n tools: new Map(),\n messageRenderers: new Map(),\n commands: new Map(),\n flags: new Map(),\n shortcuts: new Map(),\n };\n}\n\nasync function loadExtension(\n extensionPath: string,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n cacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n try {\n const moduleSpan = startTimingSpan(`loadExtensions.${extensionPath}.module`, \"extensions\");\n const factory = await loadExtensionModule(resolvedPath, cacheToken);\n endTimingSpan(moduleSpan);\n if (!factory) {\n return {\n extension: null,\n error: `Extension does not export a valid factory function: ${extensionPath}`,\n };\n }\n\n const extension = createExtension(extensionPath, resolvedPath);\n const api = createExtensionAPI(\n extension,\n runtime,\n cwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n const factorySpan = startTimingSpan(`loadExtensions.${extensionPath}.factory`, \"extensions\");\n await factory(api);\n endTimingSpan(factorySpan);\n\n return { extension, error: null };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { extension: null, error: `Failed to load extension: ${message}` };\n }\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n factory: ExtensionFactory,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n extensionPath = \"<inline>\",\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<Extension> {\n const extension = createExtension(extensionPath, extensionPath);\n const resolvedCwd = resolvePath(cwd);\n const api = createExtensionAPI(\n extension,\n runtime,\n resolvedCwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n await factory(api);\n return extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n useCache = false,\n): Promise<LoadExtensionsResult> {\n const extensions: Extension[] = [];\n const errors: Array<{ path: string; error: string }> = [];\n const cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n const resolvedEventBus = eventBus ?? createEventBus();\n const resolvedRuntime = runtime ?? createExtensionRuntime();\n\n for (const extPath of paths) {\n const extensionSpan = startTimingSpan(`loadExtensions.${extPath}.total`, \"extensions\");\n const { extension, error } = await loadExtension(\n extPath,\n resolvedCwd,\n resolvedEventBus,\n resolvedRuntime,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n cacheToken,\n );\n endTimingSpan(extensionSpan);\n\n if (error) {\n errors.push({ path: extPath, error });\n continue;\n }\n\n if (extension) {\n extensions.push(extension);\n }\n }\n\n return {\n extensions,\n errors,\n runtime: resolvedRuntime,\n };\n}\n\nexport async function loadExtensions(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n );\n}\n\nexport async function loadExtensionsCached(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n true,\n );\n}\n"]}
1
+ {"version":3,"file":"loader-core.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-core.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAKhE,OAAO,EAEL,KAAK,yCAAyC,EAC9C,KAAK,6BAA6B,EACnC,MAAM,uBAAuB,CAAC;AAO/B,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAkEtG;;GAEG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,gBAAgB,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,gBAAgB,EACzB,aAAa,SAAa,EAC1B,wBAAwB,GAAE,6BAA6D,EACvF,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,SAAS,CAAC,CAapB;AAuDD,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,wBAAwB,GAAE,6BAA6D,EACvF,OAAO,CAAC,EAAE,gBAAgB,EAC1B,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,oBAAoB,CAAC,CAS/B;AAED,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,wBAAwB,GAAE,6BAA6D,EACvF,OAAO,CAAC,EAAE,gBAAgB,EAC1B,yCAAyC,CAAC,EAAE,yCAAyC,GACpF,OAAO,CAAC,oBAAoB,CAAC,CAU/B","sourcesContent":["import * as path from \"node:path\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { endTimingSpan, startTimingSpan } from \"../timings.ts\";\nimport { yieldToEventLoop } from \"../../utils/event-loop.ts\";\nimport { createExtensionAPI } from \"./loader-api.ts\";\nimport {\n emptyWorkflowResourceProvider,\n type ResourceLoaderInheritanceSnapshotProvider,\n type WorkflowResourceProviderInput,\n} from \"./loader-resources.ts\";\nimport { createExtensionRuntime } from \"./loader-runtime.ts\";\nimport {\n loadExtensionModule,\n type ExtensionCacheToken,\n useExtensionCacheCwd,\n} from \"./loader-virtual-modules.ts\";\nimport type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from \"./types.ts\";\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n const source = extensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n ? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n : \"local\";\n const baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n return {\n path: extensionPath,\n resolvedPath,\n sourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n handlers: new Map(),\n tools: new Map(),\n messageRenderers: new Map(),\n commands: new Map(),\n flags: new Map(),\n shortcuts: new Map(),\n };\n}\n\nasync function loadExtension(\n extensionPath: string,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n cacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n try {\n const moduleSpan = startTimingSpan(`loadExtensions.${extensionPath}.module`, \"extensions\");\n const factory = await loadExtensionModule(resolvedPath, cacheToken);\n endTimingSpan(moduleSpan);\n if (!factory) {\n return {\n extension: null,\n error: `Extension does not export a valid factory function: ${extensionPath}`,\n };\n }\n\n const extension = createExtension(extensionPath, resolvedPath);\n const api = createExtensionAPI(\n extension,\n runtime,\n cwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n const factorySpan = startTimingSpan(`loadExtensions.${extensionPath}.factory`, \"extensions\");\n await factory(api);\n endTimingSpan(factorySpan);\n\n return { extension, error: null };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { extension: null, error: `Failed to load extension: ${message}` };\n }\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n factory: ExtensionFactory,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n extensionPath = \"<inline>\",\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<Extension> {\n const extension = createExtension(extensionPath, extensionPath);\n const resolvedCwd = resolvePath(cwd);\n const api = createExtensionAPI(\n extension,\n runtime,\n resolvedCwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n await factory(api);\n return extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n useCache = false,\n): Promise<LoadExtensionsResult> {\n const extensions: Extension[] = [];\n const errors: Array<{ path: string; error: string }> = [];\n const cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n const resolvedEventBus = eventBus ?? createEventBus();\n const resolvedRuntime = runtime ?? createExtensionRuntime();\n\n let processedExtensionCount = 0;\n for (const extPath of paths) {\n if (processedExtensionCount > 0) {\n await yieldToEventLoop();\n }\n const extensionSpan = startTimingSpan(`loadExtensions.${extPath}.total`, \"extensions\");\n const { extension, error } = await loadExtension(\n extPath,\n resolvedCwd,\n resolvedEventBus,\n resolvedRuntime,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n cacheToken,\n );\n endTimingSpan(extensionSpan);\n processedExtensionCount += 1;\n if (error) {\n errors.push({ path: extPath, error });\n continue;\n }\n\n if (extension) {\n extensions.push(extension);\n }\n }\n\n return {\n extensions,\n errors,\n runtime: resolvedRuntime,\n };\n}\n\nexport async function loadExtensions(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n );\n}\n\nexport async function loadExtensionsCached(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n true,\n );\n}\n"]}
@@ -3,6 +3,7 @@ import { resolvePath } from "../../utils/paths.js";
3
3
  import { createEventBus } from "../event-bus.js";
4
4
  import { createSyntheticSourceInfo } from "../source-info.js";
5
5
  import { endTimingSpan, startTimingSpan } from "../timings.js";
6
+ import { yieldToEventLoop } from "../../utils/event-loop.js";
6
7
  import { createExtensionAPI } from "./loader-api.js";
7
8
  import { emptyWorkflowResourceProvider, } from "./loader-resources.js";
8
9
  import { createExtensionRuntime } from "./loader-runtime.js";
@@ -71,10 +72,15 @@ async function loadExtensionsInternal(paths, cwd, eventBus, workflowResourceProv
71
72
  const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);
72
73
  const resolvedEventBus = eventBus ?? createEventBus();
73
74
  const resolvedRuntime = runtime ?? createExtensionRuntime();
75
+ let processedExtensionCount = 0;
74
76
  for (const extPath of paths) {
77
+ if (processedExtensionCount > 0) {
78
+ await yieldToEventLoop();
79
+ }
75
80
  const extensionSpan = startTimingSpan(`loadExtensions.${extPath}.total`, "extensions");
76
81
  const { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, resolvedRuntime, workflowResourceProvider, resourceLoaderInheritanceSnapshotProvider, cacheToken);
77
82
  endTimingSpan(extensionSpan);
83
+ processedExtensionCount += 1;
78
84
  if (error) {
79
85
  errors.push({ path: extPath, error });
80
86
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"loader-core.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-core.ts"],"names":[],"mappings":"AAAA,O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AAC,kBAAkB,OAAO,QAAQ,EAAE,YAAY,CAAC,CAAC;QACvF,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,MAAM,aAAa,CAC9C,OAAO,EACP,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,wBAAwB,EACxB,yCAAyC,EACzC,UAAU,CACX,CAAC;QACF,aAAa,CAAC,aAAa,CAAC,CAAC;QAE7B,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACtC,SAAS;QACX,CAAC;QAED,IAAI,SAAS,EAAE,CAAC;YACd,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,OAAO;QACL,UAAU;QACV,MAAM;QACN,OAAO,EAAE,eAAe;KACzB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,KAAe,EACf,GAAW,EACX,QAAmB,EACnB,wBAAwB,GAAkC,6BAA6B,EACvF,OAA0B,EAC1B,yCAAqF;IAErF,OAAO,sBAAsB,CAC3B,KAAK,EACL,GAAG,EACH,QAAQ,EACR,wBAAwB,EACxB,OAAO,EACP,yCAAyC,CAC1C,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAe,EACf,GAAW,EACX,QAAmB,EACnB,wBAAwB,GAAkC,6BAA6B,EACvF,OAA0B,EAC1B,yCAAqF;IAErF,OAAO,sBAAsB,CAC3B,KAAK,EACL,GAAG,EACH,QAAQ,EACR,wBAAwB,EACxB,OAAO,EACP,yCAAyC,EACzC,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { endTimingSpan, startTimingSpan } from \"../timings.ts\";\nimport { createExtensionAPI } from \"./loader-api.ts\";\nimport {\n emptyWorkflowResourceProvider,\n type ResourceLoaderInheritanceSnapshotProvider,\n type WorkflowResourceProviderInput,\n} from \"./loader-resources.ts\";\nimport { createExtensionRuntime } from \"./loader-runtime.ts\";\nimport {\n loadExtensionModule,\n type ExtensionCacheToken,\n useExtensionCacheCwd,\n} from \"./loader-virtual-modules.ts\";\nimport type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from \"./types.ts\";\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n const source = extensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n ? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n : \"local\";\n const baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n return {\n path: extensionPath,\n resolvedPath,\n sourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n handlers: new Map(),\n tools: new Map(),\n messageRenderers: new Map(),\n commands: new Map(),\n flags: new Map(),\n shortcuts: new Map(),\n };\n}\n\nasync function loadExtension(\n extensionPath: string,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n cacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n try {\n const moduleSpan = startTimingSpan(`loadExtensions.${extensionPath}.module`, \"extensions\");\n const factory = await loadExtensionModule(resolvedPath, cacheToken);\n endTimingSpan(moduleSpan);\n if (!factory) {\n return {\n extension: null,\n error: `Extension does not export a valid factory function: ${extensionPath}`,\n };\n }\n\n const extension = createExtension(extensionPath, resolvedPath);\n const api = createExtensionAPI(\n extension,\n runtime,\n cwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n const factorySpan = startTimingSpan(`loadExtensions.${extensionPath}.factory`, \"extensions\");\n await factory(api);\n endTimingSpan(factorySpan);\n\n return { extension, error: null };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { extension: null, error: `Failed to load extension: ${message}` };\n }\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n factory: ExtensionFactory,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n extensionPath = \"<inline>\",\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<Extension> {\n const extension = createExtension(extensionPath, extensionPath);\n const resolvedCwd = resolvePath(cwd);\n const api = createExtensionAPI(\n extension,\n runtime,\n resolvedCwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n await factory(api);\n return extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n useCache = false,\n): Promise<LoadExtensionsResult> {\n const extensions: Extension[] = [];\n const errors: Array<{ path: string; error: string }> = [];\n const cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n const resolvedEventBus = eventBus ?? createEventBus();\n const resolvedRuntime = runtime ?? createExtensionRuntime();\n\n for (const extPath of paths) {\n const extensionSpan = startTimingSpan(`loadExtensions.${extPath}.total`, \"extensions\");\n const { extension, error } = await loadExtension(\n extPath,\n resolvedCwd,\n resolvedEventBus,\n resolvedRuntime,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n cacheToken,\n );\n endTimingSpan(extensionSpan);\n\n if (error) {\n errors.push({ path: extPath, error });\n continue;\n }\n\n if (extension) {\n extensions.push(extension);\n }\n }\n\n return {\n extensions,\n errors,\n runtime: resolvedRuntime,\n };\n}\n\nexport async function loadExtensions(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n );\n}\n\nexport async function loadExtensionsCached(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n true,\n );\n}\n"]}
1
+ {"version":3,"file":"loader-core.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-core.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAiB,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EACL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UAAU,CACX,CAAC;QACF,aAAa,CAAC,aAAa,CAAC,CAAC;QAC7B,uBAAuB,IAAI,CAAC,CAAC;QAC7B,IAAI,KAAK,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YACtC,SAAS;QACX,CAAC;QAED,IAAI,SAAS,EAAE,CAAC;YACd,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,OAAO;QACL,UAAU;QACV,MAAM;QACN,OAAO,EAAE,eAAe;KACzB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,KAAe,EACf,GAAW,EACX,QAAmB,EACnB,wBAAwB,GAAkC,6BAA6B,EACvF,OAA0B,EAC1B,yCAAqF;IAErF,OAAO,sBAAsB,CAC3B,KAAK,EACL,GAAG,EACH,QAAQ,EACR,wBAAwB,EACxB,OAAO,EACP,yCAAyC,CAC1C,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAe,EACf,GAAW,EACX,QAAmB,EACnB,wBAAwB,GAAkC,6BAA6B,EACvF,OAA0B,EAC1B,yCAAqF;IAErF,OAAO,sBAAsB,CAC3B,KAAK,EACL,GAAG,EACH,QAAQ,EACR,wBAAwB,EACxB,OAAO,EACP,yCAAyC,EACzC,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { endTimingSpan, startTimingSpan } from \"../timings.ts\";\nimport { yieldToEventLoop } from \"../../utils/event-loop.ts\";\nimport { createExtensionAPI } from \"./loader-api.ts\";\nimport {\n emptyWorkflowResourceProvider,\n type ResourceLoaderInheritanceSnapshotProvider,\n type WorkflowResourceProviderInput,\n} from \"./loader-resources.ts\";\nimport { createExtensionRuntime } from \"./loader-runtime.ts\";\nimport {\n loadExtensionModule,\n type ExtensionCacheToken,\n useExtensionCacheCwd,\n} from \"./loader-virtual-modules.ts\";\nimport type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from \"./types.ts\";\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n const source = extensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n ? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n : \"local\";\n const baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n return {\n path: extensionPath,\n resolvedPath,\n sourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n handlers: new Map(),\n tools: new Map(),\n messageRenderers: new Map(),\n commands: new Map(),\n flags: new Map(),\n shortcuts: new Map(),\n };\n}\n\nasync function loadExtension(\n extensionPath: string,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n cacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n try {\n const moduleSpan = startTimingSpan(`loadExtensions.${extensionPath}.module`, \"extensions\");\n const factory = await loadExtensionModule(resolvedPath, cacheToken);\n endTimingSpan(moduleSpan);\n if (!factory) {\n return {\n extension: null,\n error: `Extension does not export a valid factory function: ${extensionPath}`,\n };\n }\n\n const extension = createExtension(extensionPath, resolvedPath);\n const api = createExtensionAPI(\n extension,\n runtime,\n cwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n const factorySpan = startTimingSpan(`loadExtensions.${extensionPath}.factory`, \"extensions\");\n await factory(api);\n endTimingSpan(factorySpan);\n\n return { extension, error: null };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { extension: null, error: `Failed to load extension: ${message}` };\n }\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n factory: ExtensionFactory,\n cwd: string,\n eventBus: EventBus,\n runtime: ExtensionRuntime,\n extensionPath = \"<inline>\",\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<Extension> {\n const extension = createExtension(extensionPath, extensionPath);\n const resolvedCwd = resolvePath(cwd);\n const api = createExtensionAPI(\n extension,\n runtime,\n resolvedCwd,\n eventBus,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n );\n await factory(api);\n return extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n useCache = false,\n): Promise<LoadExtensionsResult> {\n const extensions: Extension[] = [];\n const errors: Array<{ path: string; error: string }> = [];\n const cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n const resolvedEventBus = eventBus ?? createEventBus();\n const resolvedRuntime = runtime ?? createExtensionRuntime();\n\n let processedExtensionCount = 0;\n for (const extPath of paths) {\n if (processedExtensionCount > 0) {\n await yieldToEventLoop();\n }\n const extensionSpan = startTimingSpan(`loadExtensions.${extPath}.total`, \"extensions\");\n const { extension, error } = await loadExtension(\n extPath,\n resolvedCwd,\n resolvedEventBus,\n resolvedRuntime,\n workflowResourceProvider,\n resourceLoaderInheritanceSnapshotProvider,\n cacheToken,\n );\n endTimingSpan(extensionSpan);\n processedExtensionCount += 1;\n if (error) {\n errors.push({ path: extPath, error });\n continue;\n }\n\n if (extension) {\n extensions.push(extension);\n }\n }\n\n return {\n extensions,\n errors,\n runtime: resolvedRuntime,\n };\n}\n\nexport async function loadExtensions(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n );\n}\n\nexport async function loadExtensionsCached(\n paths: string[],\n cwd: string,\n eventBus?: EventBus,\n workflowResourceProvider: WorkflowResourceProviderInput = emptyWorkflowResourceProvider,\n runtime?: ExtensionRuntime,\n resourceLoaderInheritanceSnapshotProvider?: ResourceLoaderInheritanceSnapshotProvider,\n): Promise<LoadExtensionsResult> {\n return loadExtensionsInternal(\n paths,\n cwd,\n eventBus,\n workflowResourceProvider,\n runtime,\n resourceLoaderInheritanceSnapshotProvider,\n true,\n );\n}\n"]}
@@ -1,5 +1,13 @@
1
1
  import type { ModelRegistry } from "./model-registry.ts";
2
2
  import type { ScopedModel } from "./model-resolver-types.ts";
3
+ export interface ModelScopeDiagnostic {
4
+ type: "warning";
5
+ message: string;
6
+ }
7
+ export interface ResolveModelScopeResult {
8
+ scopedModels: ScopedModel[];
9
+ diagnostics: ModelScopeDiagnostic[];
10
+ }
3
11
  /**
4
12
  * Resolve model patterns to actual Model objects with optional thinking levels
5
13
  * Format: "pattern:level" where :level is optional
@@ -11,5 +19,6 @@ import type { ScopedModel } from "./model-resolver-types.ts";
11
19
  * The algorithm tries to match the full pattern first, then progressively
12
20
  * strips colon-suffixes to find a match.
13
21
  */
22
+ export declare function resolveModelScopeWithDiagnostics(patterns: string[], modelRegistry: ModelRegistry): Promise<ResolveModelScopeResult>;
14
23
  export declare function resolveModelScope(patterns: string[], modelRegistry: ModelRegistry): Promise<ScopedModel[]>;
15
24
  //# sourceMappingURL=model-resolver-scope.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-resolver-scope.d.ts","sourceRoot":"","sources":["../../src/core/model-resolver-scope.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAoB7D;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CA0ChH","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { parseModelPattern } from \"./model-resolver-patterns.ts\";\nimport type { ScopedModel } from \"./model-resolver-types.ts\";\n\nfunction hasGlobCharacters(pattern: string): boolean {\n return pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\");\n}\n\nfunction parseGlobThinkingLevel(pattern: string): { globPattern: string; thinkingLevel?: ThinkingLevel } {\n const colonIdx = pattern.lastIndexOf(\":\");\n if (colonIdx === -1) {\n return { globPattern: pattern };\n }\n\n const suffix = pattern.substring(colonIdx + 1);\n if (!isValidThinkingLevel(suffix)) {\n return { globPattern: pattern };\n }\n\n return { globPattern: pattern.substring(0, colonIdx), thinkingLevel: suffix };\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport async function resolveModelScope(patterns: string[], modelRegistry: ModelRegistry): Promise<ScopedModel[]> {\n const availableModels = await modelRegistry.getAvailable();\n const scopedModels: ScopedModel[] = [];\n\n for (const pattern of patterns) {\n if (hasGlobCharacters(pattern)) {\n const { globPattern, thinkingLevel } = parseGlobThinkingLevel(pattern);\n const matchingModels = availableModels.filter((m) => {\n const fullId = `${m.provider}/${m.id}`;\n return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n });\n\n if (matchingModels.length === 0) {\n console.warn(chalk.yellow(`Warning: No models match pattern \"${pattern}\"`));\n continue;\n }\n\n for (const model of matchingModels) {\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n continue;\n }\n\n const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n if (warning) {\n console.warn(chalk.yellow(`Warning: ${warning}`));\n }\n\n if (!model) {\n console.warn(chalk.yellow(`Warning: No models match pattern \"${pattern}\"`));\n continue;\n }\n\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n\n return scopedModels;\n}\n"]}
1
+ {"version":3,"file":"model-resolver-scope.d.ts","sourceRoot":"","sources":["../../src/core/model-resolver-scope.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAE7D,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B,WAAW,EAAE,oBAAoB,EAAE,CAAC;CACrC;AAoBD;;;;;;;;;;GAUG;AACH,wBAAsB,gCAAgC,CACpD,QAAQ,EAAE,MAAM,EAAE,EAClB,aAAa,EAAE,aAAa,GAC3B,OAAO,CAAC,uBAAuB,CAAC,CA0ClC;AAED,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAMhH","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { parseModelPattern } from \"./model-resolver-patterns.ts\";\nimport type { ScopedModel } from \"./model-resolver-types.ts\";\n\nexport interface ModelScopeDiagnostic {\n type: \"warning\";\n message: string;\n}\n\nexport interface ResolveModelScopeResult {\n scopedModels: ScopedModel[];\n diagnostics: ModelScopeDiagnostic[];\n}\n\nfunction hasGlobCharacters(pattern: string): boolean {\n return pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\");\n}\n\nfunction parseGlobThinkingLevel(pattern: string): { globPattern: string; thinkingLevel?: ThinkingLevel } {\n const colonIdx = pattern.lastIndexOf(\":\");\n if (colonIdx === -1) {\n return { globPattern: pattern };\n }\n\n const suffix = pattern.substring(colonIdx + 1);\n if (!isValidThinkingLevel(suffix)) {\n return { globPattern: pattern };\n }\n\n return { globPattern: pattern.substring(0, colonIdx), thinkingLevel: suffix };\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport async function resolveModelScopeWithDiagnostics(\n patterns: string[],\n modelRegistry: ModelRegistry,\n): Promise<ResolveModelScopeResult> {\n const availableModels = await modelRegistry.getAvailable();\n const scopedModels: ScopedModel[] = [];\n const diagnostics: ModelScopeDiagnostic[] = [];\n for (const pattern of patterns) {\n if (hasGlobCharacters(pattern)) {\n const { globPattern, thinkingLevel } = parseGlobThinkingLevel(pattern);\n const matchingModels = availableModels.filter((m) => {\n const fullId = `${m.provider}/${m.id}`;\n return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n });\n\n if (matchingModels.length === 0) {\n diagnostics.push({ type: \"warning\", message: `No models match pattern \"${pattern}\"` });\n continue;\n }\n\n for (const model of matchingModels) {\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n continue;\n }\n\n const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n if (warning) {\n diagnostics.push({ type: \"warning\", message: warning });\n }\n\n if (!model) {\n diagnostics.push({ type: \"warning\", message: `No models match pattern \"${pattern}\"` });\n continue;\n }\n\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n\n return { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScope(patterns: string[], modelRegistry: ModelRegistry): Promise<ScopedModel[]> {\n const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRegistry);\n for (const diagnostic of diagnostics) {\n console.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n }\n return scopedModels;\n}\n"]}
@@ -28,9 +28,10 @@ function parseGlobThinkingLevel(pattern) {
28
28
  * The algorithm tries to match the full pattern first, then progressively
29
29
  * strips colon-suffixes to find a match.
30
30
  */
31
- export async function resolveModelScope(patterns, modelRegistry) {
31
+ export async function resolveModelScopeWithDiagnostics(patterns, modelRegistry) {
32
32
  const availableModels = await modelRegistry.getAvailable();
33
33
  const scopedModels = [];
34
+ const diagnostics = [];
34
35
  for (const pattern of patterns) {
35
36
  if (hasGlobCharacters(pattern)) {
36
37
  const { globPattern, thinkingLevel } = parseGlobThinkingLevel(pattern);
@@ -39,7 +40,7 @@ export async function resolveModelScope(patterns, modelRegistry) {
39
40
  return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });
40
41
  });
41
42
  if (matchingModels.length === 0) {
42
- console.warn(chalk.yellow(`Warning: No models match pattern "${pattern}"`));
43
+ diagnostics.push({ type: "warning", message: `No models match pattern "${pattern}"` });
43
44
  continue;
44
45
  }
45
46
  for (const model of matchingModels) {
@@ -51,16 +52,23 @@ export async function resolveModelScope(patterns, modelRegistry) {
51
52
  }
52
53
  const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);
53
54
  if (warning) {
54
- console.warn(chalk.yellow(`Warning: ${warning}`));
55
+ diagnostics.push({ type: "warning", message: warning });
55
56
  }
56
57
  if (!model) {
57
- console.warn(chalk.yellow(`Warning: No models match pattern "${pattern}"`));
58
+ diagnostics.push({ type: "warning", message: `No models match pattern "${pattern}"` });
58
59
  continue;
59
60
  }
60
61
  if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {
61
62
  scopedModels.push({ model, thinkingLevel });
62
63
  }
63
64
  }
65
+ return { scopedModels, diagnostics };
66
+ }
67
+ export async function resolveModelScope(patterns, modelRegistry) {
68
+ const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRegistry);
69
+ for (const diagnostic of diagnostics) {
70
+ console.warn(chalk.yellow(`Warning: ${diagnostic.message}`));
71
+ }
64
72
  return scopedModels;
65
73
  }
66
74
  //# sourceMappingURL=model-resolver-scope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-resolver-scope.js","sourceRoot":"","sources":["../../src/core/model-resolver-scope.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAA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CAAC,qCAAqC,OAAO,GAAG,CAAC,CAAC,CAAC;YAC5E,SAAS;QACX,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;YAChE,YAAY,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IAED,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { parseModelPattern } from \"./model-resolver-patterns.ts\";\nimport type { ScopedModel } from \"./model-resolver-types.ts\";\n\nfunction hasGlobCharacters(pattern: string): boolean {\n return pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\");\n}\n\nfunction parseGlobThinkingLevel(pattern: string): { globPattern: string; thinkingLevel?: ThinkingLevel } {\n const colonIdx = pattern.lastIndexOf(\":\");\n if (colonIdx === -1) {\n return { globPattern: pattern };\n }\n\n const suffix = pattern.substring(colonIdx + 1);\n if (!isValidThinkingLevel(suffix)) {\n return { globPattern: pattern };\n }\n\n return { globPattern: pattern.substring(0, colonIdx), thinkingLevel: suffix };\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport async function resolveModelScope(patterns: string[], modelRegistry: ModelRegistry): Promise<ScopedModel[]> {\n const availableModels = await modelRegistry.getAvailable();\n const scopedModels: ScopedModel[] = [];\n\n for (const pattern of patterns) {\n if (hasGlobCharacters(pattern)) {\n const { globPattern, thinkingLevel } = parseGlobThinkingLevel(pattern);\n const matchingModels = availableModels.filter((m) => {\n const fullId = `${m.provider}/${m.id}`;\n return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n });\n\n if (matchingModels.length === 0) {\n console.warn(chalk.yellow(`Warning: No models match pattern \"${pattern}\"`));\n continue;\n }\n\n for (const model of matchingModels) {\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n continue;\n }\n\n const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n if (warning) {\n console.warn(chalk.yellow(`Warning: ${warning}`));\n }\n\n if (!model) {\n console.warn(chalk.yellow(`Warning: No models match pattern \"${pattern}\"`));\n continue;\n }\n\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n\n return scopedModels;\n}\n"]}
1
+ {"version":3,"file":"model-resolver-scope.js","sourceRoot":"","sources":["../../src/core/model-resolver-scope.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAajE,SAAS,iBAAiB,CAAC,OAAe;IACxC,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC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AO,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC;AACvC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,QAAkB,EAAE,aAA4B;IACtF,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,MAAM,gCAAgC,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC;IACtG,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;QACrC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { parseModelPattern } from \"./model-resolver-patterns.ts\";\nimport type { ScopedModel } from \"./model-resolver-types.ts\";\n\nexport interface ModelScopeDiagnostic {\n type: \"warning\";\n message: string;\n}\n\nexport interface ResolveModelScopeResult {\n scopedModels: ScopedModel[];\n diagnostics: ModelScopeDiagnostic[];\n}\n\nfunction hasGlobCharacters(pattern: string): boolean {\n return pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\");\n}\n\nfunction parseGlobThinkingLevel(pattern: string): { globPattern: string; thinkingLevel?: ThinkingLevel } {\n const colonIdx = pattern.lastIndexOf(\":\");\n if (colonIdx === -1) {\n return { globPattern: pattern };\n }\n\n const suffix = pattern.substring(colonIdx + 1);\n if (!isValidThinkingLevel(suffix)) {\n return { globPattern: pattern };\n }\n\n return { globPattern: pattern.substring(0, colonIdx), thinkingLevel: suffix };\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport async function resolveModelScopeWithDiagnostics(\n patterns: string[],\n modelRegistry: ModelRegistry,\n): Promise<ResolveModelScopeResult> {\n const availableModels = await modelRegistry.getAvailable();\n const scopedModels: ScopedModel[] = [];\n const diagnostics: ModelScopeDiagnostic[] = [];\n for (const pattern of patterns) {\n if (hasGlobCharacters(pattern)) {\n const { globPattern, thinkingLevel } = parseGlobThinkingLevel(pattern);\n const matchingModels = availableModels.filter((m) => {\n const fullId = `${m.provider}/${m.id}`;\n return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n });\n\n if (matchingModels.length === 0) {\n diagnostics.push({ type: \"warning\", message: `No models match pattern \"${pattern}\"` });\n continue;\n }\n\n for (const model of matchingModels) {\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n continue;\n }\n\n const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n if (warning) {\n diagnostics.push({ type: \"warning\", message: warning });\n }\n\n if (!model) {\n diagnostics.push({ type: \"warning\", message: `No models match pattern \"${pattern}\"` });\n continue;\n }\n\n if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n scopedModels.push({ model, thinkingLevel });\n }\n }\n\n return { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScope(patterns: string[], modelRegistry: ModelRegistry): Promise<ScopedModel[]> {\n const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRegistry);\n for (const diagnostic of diagnostics) {\n console.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n }\n return scopedModels;\n}\n"]}
@@ -5,6 +5,7 @@ export { defaultModelPerProvider } from "./model-resolver-defaults.ts";
5
5
  export { resolveCliModel } from "./model-resolver-cli.ts";
6
6
  export { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from "./model-resolver-initial.ts";
7
7
  export { findExactModelReferenceMatch, parseModelPattern } from "./model-resolver-patterns.ts";
8
- export { resolveModelScope } from "./model-resolver-scope.ts";
9
- export type { InitialModelResult, ParsedModelResult, ResolveCliModelResult, ScopedModel, } from "./model-resolver-types.ts";
8
+ export { resolveModelScope, resolveModelScopeWithDiagnostics } from "./model-resolver-scope.ts";
9
+ export type { ModelScopeDiagnostic, ResolveModelScopeResult } from "./model-resolver-scope.ts";
10
+ export type { InitialModelResult, ParsedModelResult, ResolveCliModelResult, ScopedModel } from "./model-resolver-types.ts";
10
11
  //# sourceMappingURL=model-resolver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-resolver.d.ts","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,qBAAqB,EACrB,WAAW,GACZ,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nexport { defaultModelPerProvider } from \"./model-resolver-defaults.ts\";\nexport { resolveCliModel } from \"./model-resolver-cli.ts\";\nexport { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from \"./model-resolver-initial.ts\";\nexport { findExactModelReferenceMatch, parseModelPattern } from \"./model-resolver-patterns.ts\";\nexport { resolveModelScope } from \"./model-resolver-scope.ts\";\nexport type {\n InitialModelResult,\n ParsedModelResult,\n ResolveCliModelResult,\n ScopedModel,\n} from \"./model-resolver-types.ts\";\n"]}
1
+ {"version":3,"file":"model-resolver.d.ts","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAChG,YAAY,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAC/F,YAAY,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nexport { defaultModelPerProvider } from \"./model-resolver-defaults.ts\";\nexport { resolveCliModel } from \"./model-resolver-cli.ts\";\nexport { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from \"./model-resolver-initial.ts\";\nexport { findExactModelReferenceMatch, parseModelPattern } from \"./model-resolver-patterns.ts\";\nexport { resolveModelScope, resolveModelScopeWithDiagnostics } from \"./model-resolver-scope.ts\";\nexport type { ModelScopeDiagnostic, ResolveModelScopeResult } from \"./model-resolver-scope.ts\";\nexport type { InitialModelResult, ParsedModelResult, ResolveCliModelResult, ScopedModel } from \"./model-resolver-types.ts\";\n"]}
@@ -5,5 +5,5 @@ export { defaultModelPerProvider } from "./model-resolver-defaults.js";
5
5
  export { resolveCliModel } from "./model-resolver-cli.js";
6
6
  export { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from "./model-resolver-initial.js";
7
7
  export { findExactModelReferenceMatch, parseModelPattern } from "./model-resolver-patterns.js";
8
- export { resolveModelScope } from "./model-resolver-scope.js";
8
+ export { resolveModelScope, resolveModelScopeWithDiagnostics } from "./model-resolver-scope.js";
9
9
  //# sourceMappingURL=model-resolver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nexport { defaultModelPerProvider } from \"./model-resolver-defaults.ts\";\nexport { resolveCliModel } from \"./model-resolver-cli.ts\";\nexport { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from \"./model-resolver-initial.ts\";\nexport { findExactModelReferenceMatch, parseModelPattern } from \"./model-resolver-patterns.ts\";\nexport { resolveModelScope } from \"./model-resolver-scope.ts\";\nexport type {\n InitialModelResult,\n ParsedModelResult,\n ResolveCliModelResult,\n ScopedModel,\n} from \"./model-resolver-types.ts\";\n"]}
1
+ {"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nexport { defaultModelPerProvider } from \"./model-resolver-defaults.ts\";\nexport { resolveCliModel } from \"./model-resolver-cli.ts\";\nexport { findInitialModel, resolveSavedModelReference, restoreModelFromSession } from \"./model-resolver-initial.ts\";\nexport { findExactModelReferenceMatch, parseModelPattern } from \"./model-resolver-patterns.ts\";\nexport { resolveModelScope, resolveModelScopeWithDiagnostics } from \"./model-resolver-scope.ts\";\nexport type { ModelScopeDiagnostic, ResolveModelScopeResult } from \"./model-resolver-scope.ts\";\nexport type { InitialModelResult, ParsedModelResult, ResolveCliModelResult, ScopedModel } from \"./model-resolver-types.ts\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"resource-loader-extensions.d.ts","sourceRoot":"","sources":["../../src/core/resource-loader-extensions.ts"],"names":[],"mappings":"AAEA,OAAO,EAGN,KAAK,wBAAwB,EAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAE/F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AAM3F,wBAAsB,qBAAqB,CAC1C,MAAM,EAAE,qBAAqB,EAC7B,cAAc,EAAE,MAAM,EAAE,EACxB,kBAAkB,EAAE,oBAAoB,GAAG,SAAS,EACpD,wBAAwB,EAAE,wBAAwB,EAClD,2BAA2B,EAAE,MAAM,wCAAwC,GACzE,OAAO,CAAC,oBAAoB,CAAC,CAmE/B;AAED,wBAAsB,sBAAsB,CAC3C,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,wBAAwB,EAAE,wBAAwB,EAClD,2BAA2B,EAAE,MAAM,wCAAwC,GACzE,OAAO,CAAC;IACV,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/C,CAAC,CAyBD","sourcesContent":["import { resolvePath } from \"../utils/paths.ts\";\nimport { startTimingSpan, endTimingSpan } from \"./timings.ts\";\nimport {\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n\ttype WorkflowResourceProvider,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { resourceInternals } from \"./resource-loader-internals.ts\";\nimport type { DefaultResourceLoader } from \"./resource-loader-core.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"./resource-loader-types.ts\";\n\nfunction resolveExtensionLoadPath(loader: DefaultResourceLoader, path: string): string {\n\treturn resolvePath(path, resourceInternals(loader).cwd, { normalizeUnicodeSpaces: true });\n}\n\nexport async function loadFinalExtensionSet(\n\tloader: DefaultResourceLoader,\n\textensionPaths: string[],\n\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<LoadExtensionsResult> {\n\tconst state = resourceInternals(loader);\n\tif (!preTrustExtensions) {\n\t\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\t\tconst extensionsResult = await loadExtensionsCached(\n\t\t\textensionPaths,\n\t\t\tstate.cwd,\n\t\t\tstate.eventBus,\n\t\t\tworkflowResourceProvider,\n\t\t\tundefined,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(loadExtensionsSpan);\n\t\tconst inlineExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadInlineExtensionFactories\");\n\t\tconst inlineExtensions = await loadExtensionFactories(\n\t\t\tloader,\n\t\t\textensionsResult.runtime,\n\t\t\tworkflowResourceProvider,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(inlineExtensionsSpan);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\taddExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tconst preloadedByPath = new Map(\n\t\tpreTrustExtensions.extensions\n\t\t\t.filter((extension) => !extension.path.startsWith(\"<inline:\"))\n\t\t\t.map((extension) => [extension.resolvedPath, extension]),\n\t);\n\tconst failedPreloadPaths = new Set(\n\t\tpreTrustExtensions.errors.map((error) => resolveExtensionLoadPath(loader, error.path)),\n\t);\n\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\tconst resolvedPath = resolveExtensionLoadPath(loader, path);\n\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t});\n\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\tconst remainingExtensions = await loadExtensionsCached(\n\t\tremainingPaths,\n\t\tstate.cwd,\n\t\tstate.eventBus,\n\t\tworkflowResourceProvider,\n\t\tpreTrustExtensions.runtime,\n\t\tinheritanceSnapshotProvider,\n\t);\n\tendTimingSpan(loadExtensionsSpan);\n\tconst loadedByPath = new Map(preloadedByPath);\n\tfor (const extension of remainingExtensions.extensions) {\n\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t}\n\n\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith(\"<inline:\"));\n\tconst orderedExtensions = extensionPaths\n\t\t.map((path) => loadedByPath.get(resolveExtensionLoadPath(loader, path)))\n\t\t.filter((extension): extension is Extension => extension !== undefined);\n\torderedExtensions.push(...inlineExtensions);\n\n\tconst extensionsResult: LoadExtensionsResult = {\n\t\textensions: orderedExtensions,\n\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\truntime: preTrustExtensions.runtime,\n\t};\n\taddExtensionConflictDiagnostics(extensionsResult);\n\treturn extensionsResult;\n}\n\nexport async function loadExtensionFactories(\n\tloader: DefaultResourceLoader,\n\truntime: ExtensionRuntime,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<{\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n}> {\n\tconst state = resourceInternals(loader);\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const [index, factory] of state.extensionFactories.entries()) {\n\t\tconst extensionPath = `<inline:${index + 1}>`;\n\t\ttry {\n\t\t\tconst extension = await loadExtensionFromFactory(\n\t\t\t\tfactory,\n\t\t\t\tstate.cwd,\n\t\t\t\tstate.eventBus,\n\t\t\t\truntime,\n\t\t\t\textensionPath,\n\t\t\t\tworkflowResourceProvider,\n\t\t\t\tinheritanceSnapshotProvider,\n\t\t\t);\n\t\t\textensions.push(extension);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t}\n\t}\n\n\treturn { extensions, errors };\n}\n\nfunction addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\tconst conflicts = detectExtensionConflicts(extensionsResult.extensions);\n\tfor (const conflict of conflicts) {\n\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t}\n}\n\nfunction detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t// Track which extension registered each tool and flag\n\tconst toolOwners = new Map<string, string>();\n\tconst flagOwners = new Map<string, string>();\n\n\tfor (const ext of extensions) {\n\t\t// Check tools\n\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t}\n\t\t}\n\n\t\t// Check flags\n\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn conflicts;\n}\n"]}
1
+ {"version":3,"file":"resource-loader-extensions.d.ts","sourceRoot":"","sources":["../../src/core/resource-loader-extensions.ts"],"names":[],"mappings":"AAGA,OAAO,EAGN,KAAK,wBAAwB,EAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAE/F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AAM3F,wBAAsB,qBAAqB,CAC1C,MAAM,EAAE,qBAAqB,EAC7B,cAAc,EAAE,MAAM,EAAE,EACxB,kBAAkB,EAAE,oBAAoB,GAAG,SAAS,EACpD,wBAAwB,EAAE,wBAAwB,EAClD,2BAA2B,EAAE,MAAM,wCAAwC,GACzE,OAAO,CAAC,oBAAoB,CAAC,CAmE/B;AAED,wBAAsB,sBAAsB,CAC3C,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,wBAAwB,EAAE,wBAAwB,EAClD,2BAA2B,EAAE,MAAM,wCAAwC,GACzE,OAAO,CAAC;IACV,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/C,CAAC,CA4BD","sourcesContent":["import { resolvePath } from \"../utils/paths.ts\";\nimport { yieldToEventLoop } from \"../utils/event-loop.ts\";\nimport { startTimingSpan, endTimingSpan } from \"./timings.ts\";\nimport {\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n\ttype WorkflowResourceProvider,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { resourceInternals } from \"./resource-loader-internals.ts\";\nimport type { DefaultResourceLoader } from \"./resource-loader-core.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"./resource-loader-types.ts\";\n\nfunction resolveExtensionLoadPath(loader: DefaultResourceLoader, path: string): string {\n\treturn resolvePath(path, resourceInternals(loader).cwd, { normalizeUnicodeSpaces: true });\n}\n\nexport async function loadFinalExtensionSet(\n\tloader: DefaultResourceLoader,\n\textensionPaths: string[],\n\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<LoadExtensionsResult> {\n\tconst state = resourceInternals(loader);\n\tif (!preTrustExtensions) {\n\t\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\t\tconst extensionsResult = await loadExtensionsCached(\n\t\t\textensionPaths,\n\t\t\tstate.cwd,\n\t\t\tstate.eventBus,\n\t\t\tworkflowResourceProvider,\n\t\t\tundefined,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(loadExtensionsSpan);\n\t\tconst inlineExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadInlineExtensionFactories\");\n\t\tconst inlineExtensions = await loadExtensionFactories(\n\t\t\tloader,\n\t\t\textensionsResult.runtime,\n\t\t\tworkflowResourceProvider,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(inlineExtensionsSpan);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\taddExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tconst preloadedByPath = new Map(\n\t\tpreTrustExtensions.extensions\n\t\t\t.filter((extension) => !extension.path.startsWith(\"<inline:\"))\n\t\t\t.map((extension) => [extension.resolvedPath, extension]),\n\t);\n\tconst failedPreloadPaths = new Set(\n\t\tpreTrustExtensions.errors.map((error) => resolveExtensionLoadPath(loader, error.path)),\n\t);\n\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\tconst resolvedPath = resolveExtensionLoadPath(loader, path);\n\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t});\n\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\tconst remainingExtensions = await loadExtensionsCached(\n\t\tremainingPaths,\n\t\tstate.cwd,\n\t\tstate.eventBus,\n\t\tworkflowResourceProvider,\n\t\tpreTrustExtensions.runtime,\n\t\tinheritanceSnapshotProvider,\n\t);\n\tendTimingSpan(loadExtensionsSpan);\n\tconst loadedByPath = new Map(preloadedByPath);\n\tfor (const extension of remainingExtensions.extensions) {\n\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t}\n\n\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith(\"<inline:\"));\n\tconst orderedExtensions = extensionPaths\n\t\t.map((path) => loadedByPath.get(resolveExtensionLoadPath(loader, path)))\n\t\t.filter((extension): extension is Extension => extension !== undefined);\n\torderedExtensions.push(...inlineExtensions);\n\n\tconst extensionsResult: LoadExtensionsResult = {\n\t\textensions: orderedExtensions,\n\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\truntime: preTrustExtensions.runtime,\n\t};\n\taddExtensionConflictDiagnostics(extensionsResult);\n\treturn extensionsResult;\n}\n\nexport async function loadExtensionFactories(\n\tloader: DefaultResourceLoader,\n\truntime: ExtensionRuntime,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<{\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n}> {\n\tconst state = resourceInternals(loader);\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const [index, factory] of state.extensionFactories.entries()) {\n\t\tif (index > 0) {\n\t\t\tawait yieldToEventLoop();\n\t\t}\n\t\tconst extensionPath = `<inline:${index + 1}>`;\n\t\ttry {\n\t\t\tconst extension = await loadExtensionFromFactory(\n\t\t\t\tfactory,\n\t\t\t\tstate.cwd,\n\t\t\t\tstate.eventBus,\n\t\t\t\truntime,\n\t\t\t\textensionPath,\n\t\t\t\tworkflowResourceProvider,\n\t\t\t\tinheritanceSnapshotProvider,\n\t\t\t);\n\t\t\textensions.push(extension);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t}\n\t}\n\n\treturn { extensions, errors };\n}\n\nfunction addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\tconst conflicts = detectExtensionConflicts(extensionsResult.extensions);\n\tfor (const conflict of conflicts) {\n\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t}\n}\n\nfunction detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t// Track which extension registered each tool and flag\n\tconst toolOwners = new Map<string, string>();\n\tconst flagOwners = new Map<string, string>();\n\n\tfor (const ext of extensions) {\n\t\t// Check tools\n\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t}\n\t\t}\n\n\t\t// Check flags\n\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn conflicts;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { resolvePath } from "../utils/paths.js";
2
+ import { yieldToEventLoop } from "../utils/event-loop.js";
2
3
  import { startTimingSpan, endTimingSpan } from "./timings.js";
3
4
  import { loadExtensionFromFactory, loadExtensionsCached, } from "./extensions/loader.js";
4
5
  import { resourceInternals } from "./resource-loader-internals.js";
@@ -52,6 +53,9 @@ export async function loadExtensionFactories(loader, runtime, workflowResourcePr
52
53
  const extensions = [];
53
54
  const errors = [];
54
55
  for (const [index, factory] of state.extensionFactories.entries()) {
56
+ if (index > 0) {
57
+ await yieldToEventLoop();
58
+ }
55
59
  const extensionPath = `<inline:${index + 1}>`;
56
60
  try {
57
61
  const extension = await loadExtensionFromFactory(factory, state.cwd, state.eventBus, runtime, extensionPath, workflowResourceProvider, inheritanceSnapshotProvider);
@@ -1 +1 @@
1
- {"version":3,"file":"resource-loader-extensions.js","sourceRoot":"","sources":["../../src/core/resource-loader-extensions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EACN,wBAAwB,EACxB,oBAAoB,GAEpB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAInE,SAAS,wBAAwB,CAAC,MAA6B,EAAE,IAAY;IAC5E,OAAO,WAAW,CAAC,IAAI,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,CAAC,CAAC;AAC3F,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAC1C,MAA6B,EAC7B,cAAwB,EACxB,kBAAoD,EACpD,wBAAkD,EAClD,2BAA2E;IAE3E,MAAM,KAAK,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACzB,MAAM,kBAAkB,GAAG,eAAe,CAAC,6CAA6C,CAAC,CAAC;QAC1F,MAAM,gBAAgB,GAAG,MAAM,oBAAoB,CAClD,cAAc,EACd,KAAK,CAAC,GAAG,EACT,KAAK,CAAC,QAAQ,EACd,wBAAwB,EACxB,SAAS,EACT,2BAA2B,CAC3B,CAAC;QACF,aAAa,CAAC,kBAAkB,CAAC,CAAC;QAClC,MAAM,oBAAoB,GAAG,eAAe,CAAC,2DAA2D,CAAC,CAAC;QAC1G,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CACpD,MAAM,EACN,gBAAgB,CAAC,OAAO,EACxB,wBAAwB,EACxB,2BAA2B,C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AG,EAAkB,CAAC;IAE7C,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAC9B,cAAc;QACd,KAAK,MAAM,QAAQ,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;YACzC,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAC/C,IAAI,aAAa,IAAI,aAAa,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;gBACjD,SAAS,CAAC,IAAI,CAAC;oBACd,IAAI,EAAE,GAAG,CAAC,IAAI;oBACd,OAAO,EAAE,SAAS,QAAQ,oBAAoB,aAAa,EAAE;iBAC7D,CAAC,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACP,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;YACpC,CAAC;QACF,CAAC;QAED,cAAc;QACd,KAAK,MAAM,QAAQ,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;YACzC,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAC/C,IAAI,aAAa,IAAI,aAAa,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;gBACjD,SAAS,CAAC,IAAI,CAAC;oBACd,IAAI,EAAE,GAAG,CAAC,IAAI;oBACd,OAAO,EAAE,WAAW,QAAQ,oBAAoB,aAAa,EAAE;iBAC/D,CAAC,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACP,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;YACpC,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { resolvePath } from \"../utils/paths.ts\";\nimport { startTimingSpan, endTimingSpan } from \"./timings.ts\";\nimport {\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n\ttype WorkflowResourceProvider,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { resourceInternals } from \"./resource-loader-internals.ts\";\nimport type { DefaultResourceLoader } from \"./resource-loader-core.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"./resource-loader-types.ts\";\n\nfunction resolveExtensionLoadPath(loader: DefaultResourceLoader, path: string): string {\n\treturn resolvePath(path, resourceInternals(loader).cwd, { normalizeUnicodeSpaces: true });\n}\n\nexport async function loadFinalExtensionSet(\n\tloader: DefaultResourceLoader,\n\textensionPaths: string[],\n\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<LoadExtensionsResult> {\n\tconst state = resourceInternals(loader);\n\tif (!preTrustExtensions) {\n\t\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\t\tconst extensionsResult = await loadExtensionsCached(\n\t\t\textensionPaths,\n\t\t\tstate.cwd,\n\t\t\tstate.eventBus,\n\t\t\tworkflowResourceProvider,\n\t\t\tundefined,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(loadExtensionsSpan);\n\t\tconst inlineExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadInlineExtensionFactories\");\n\t\tconst inlineExtensions = await loadExtensionFactories(\n\t\t\tloader,\n\t\t\textensionsResult.runtime,\n\t\t\tworkflowResourceProvider,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(inlineExtensionsSpan);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\taddExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tconst preloadedByPath = new Map(\n\t\tpreTrustExtensions.extensions\n\t\t\t.filter((extension) => !extension.path.startsWith(\"<inline:\"))\n\t\t\t.map((extension) => [extension.resolvedPath, extension]),\n\t);\n\tconst failedPreloadPaths = new Set(\n\t\tpreTrustExtensions.errors.map((error) => resolveExtensionLoadPath(loader, error.path)),\n\t);\n\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\tconst resolvedPath = resolveExtensionLoadPath(loader, path);\n\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t});\n\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\tconst remainingExtensions = await loadExtensionsCached(\n\t\tremainingPaths,\n\t\tstate.cwd,\n\t\tstate.eventBus,\n\t\tworkflowResourceProvider,\n\t\tpreTrustExtensions.runtime,\n\t\tinheritanceSnapshotProvider,\n\t);\n\tendTimingSpan(loadExtensionsSpan);\n\tconst loadedByPath = new Map(preloadedByPath);\n\tfor (const extension of remainingExtensions.extensions) {\n\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t}\n\n\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith(\"<inline:\"));\n\tconst orderedExtensions = extensionPaths\n\t\t.map((path) => loadedByPath.get(resolveExtensionLoadPath(loader, path)))\n\t\t.filter((extension): extension is Extension => extension !== undefined);\n\torderedExtensions.push(...inlineExtensions);\n\n\tconst extensionsResult: LoadExtensionsResult = {\n\t\textensions: orderedExtensions,\n\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\truntime: preTrustExtensions.runtime,\n\t};\n\taddExtensionConflictDiagnostics(extensionsResult);\n\treturn extensionsResult;\n}\n\nexport async function loadExtensionFactories(\n\tloader: DefaultResourceLoader,\n\truntime: ExtensionRuntime,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<{\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n}> {\n\tconst state = resourceInternals(loader);\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const [index, factory] of state.extensionFactories.entries()) {\n\t\tconst extensionPath = `<inline:${index + 1}>`;\n\t\ttry {\n\t\t\tconst extension = await loadExtensionFromFactory(\n\t\t\t\tfactory,\n\t\t\t\tstate.cwd,\n\t\t\t\tstate.eventBus,\n\t\t\t\truntime,\n\t\t\t\textensionPath,\n\t\t\t\tworkflowResourceProvider,\n\t\t\t\tinheritanceSnapshotProvider,\n\t\t\t);\n\t\t\textensions.push(extension);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t}\n\t}\n\n\treturn { extensions, errors };\n}\n\nfunction addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\tconst conflicts = detectExtensionConflicts(extensionsResult.extensions);\n\tfor (const conflict of conflicts) {\n\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t}\n}\n\nfunction detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t// Track which extension registered each tool and flag\n\tconst toolOwners = new Map<string, string>();\n\tconst flagOwners = new Map<string, string>();\n\n\tfor (const ext of extensions) {\n\t\t// Check tools\n\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t}\n\t\t}\n\n\t\t// Check flags\n\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn conflicts;\n}\n"]}
1
+ {"version":3,"file":"resource-loader-extensions.js","sourceRoot":"","sources":["../../src/core/resource-loader-extensions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EACN,wBAAwB,EACxB,oBAAoB,GAEpB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAInE,SAAS,wBAAwB,CAAC,MAA6B,EAAE,IAAY;IAC5E,OAAO,WAAW,CAAC,IAAI,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,CAAC,CAAC;AAC3F,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAC1C,MAA6B,EAC7B,cAAwB,EACxB,kBAAoD,EACpD,wBAAkD,EAClD,2BAA2E;IAE3E,MAAM,KAAK,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,CAAC,kBAAkB,EAAE,CAAC;QACzB,MAAM,kBAAkB,GAAG,eAAe,CAAC,6CAA6C,CAAC,CAAC;QAC1F,MAAM,gBAAgB,GAAG,MAAM,oBAAoB,CAClD,cAAc,EACd,KAAK,CAAC,GAAG,EACT,KAAK,CAAC,QAAQ,EACd,wBAAwB,EACxB,SAAS,EACT,2BAA2B,CAC3B,CAA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AC;gBACP,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;YACpC,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { resolvePath } from \"../utils/paths.ts\";\nimport { yieldToEventLoop } from \"../utils/event-loop.ts\";\nimport { startTimingSpan, endTimingSpan } from \"./timings.ts\";\nimport {\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n\ttype WorkflowResourceProvider,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { resourceInternals } from \"./resource-loader-internals.ts\";\nimport type { DefaultResourceLoader } from \"./resource-loader-core.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"./resource-loader-types.ts\";\n\nfunction resolveExtensionLoadPath(loader: DefaultResourceLoader, path: string): string {\n\treturn resolvePath(path, resourceInternals(loader).cwd, { normalizeUnicodeSpaces: true });\n}\n\nexport async function loadFinalExtensionSet(\n\tloader: DefaultResourceLoader,\n\textensionPaths: string[],\n\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<LoadExtensionsResult> {\n\tconst state = resourceInternals(loader);\n\tif (!preTrustExtensions) {\n\t\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\t\tconst extensionsResult = await loadExtensionsCached(\n\t\t\textensionPaths,\n\t\t\tstate.cwd,\n\t\t\tstate.eventBus,\n\t\t\tworkflowResourceProvider,\n\t\t\tundefined,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(loadExtensionsSpan);\n\t\tconst inlineExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadInlineExtensionFactories\");\n\t\tconst inlineExtensions = await loadExtensionFactories(\n\t\t\tloader,\n\t\t\textensionsResult.runtime,\n\t\t\tworkflowResourceProvider,\n\t\t\tinheritanceSnapshotProvider,\n\t\t);\n\t\tendTimingSpan(inlineExtensionsSpan);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\taddExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tconst preloadedByPath = new Map(\n\t\tpreTrustExtensions.extensions\n\t\t\t.filter((extension) => !extension.path.startsWith(\"<inline:\"))\n\t\t\t.map((extension) => [extension.resolvedPath, extension]),\n\t);\n\tconst failedPreloadPaths = new Set(\n\t\tpreTrustExtensions.errors.map((error) => resolveExtensionLoadPath(loader, error.path)),\n\t);\n\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\tconst resolvedPath = resolveExtensionLoadPath(loader, path);\n\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t});\n\tconst loadExtensionsSpan = startTimingSpan(\"DefaultResourceLoader.reload.loadExtensions\");\n\tconst remainingExtensions = await loadExtensionsCached(\n\t\tremainingPaths,\n\t\tstate.cwd,\n\t\tstate.eventBus,\n\t\tworkflowResourceProvider,\n\t\tpreTrustExtensions.runtime,\n\t\tinheritanceSnapshotProvider,\n\t);\n\tendTimingSpan(loadExtensionsSpan);\n\tconst loadedByPath = new Map(preloadedByPath);\n\tfor (const extension of remainingExtensions.extensions) {\n\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t}\n\n\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith(\"<inline:\"));\n\tconst orderedExtensions = extensionPaths\n\t\t.map((path) => loadedByPath.get(resolveExtensionLoadPath(loader, path)))\n\t\t.filter((extension): extension is Extension => extension !== undefined);\n\torderedExtensions.push(...inlineExtensions);\n\n\tconst extensionsResult: LoadExtensionsResult = {\n\t\textensions: orderedExtensions,\n\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\truntime: preTrustExtensions.runtime,\n\t};\n\taddExtensionConflictDiagnostics(extensionsResult);\n\treturn extensionsResult;\n}\n\nexport async function loadExtensionFactories(\n\tloader: DefaultResourceLoader,\n\truntime: ExtensionRuntime,\n\tworkflowResourceProvider: WorkflowResourceProvider,\n\tinheritanceSnapshotProvider: () => DefaultResourceLoaderInheritanceSnapshot,\n): Promise<{\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n}> {\n\tconst state = resourceInternals(loader);\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const [index, factory] of state.extensionFactories.entries()) {\n\t\tif (index > 0) {\n\t\t\tawait yieldToEventLoop();\n\t\t}\n\t\tconst extensionPath = `<inline:${index + 1}>`;\n\t\ttry {\n\t\t\tconst extension = await loadExtensionFromFactory(\n\t\t\t\tfactory,\n\t\t\t\tstate.cwd,\n\t\t\t\tstate.eventBus,\n\t\t\t\truntime,\n\t\t\t\textensionPath,\n\t\t\t\tworkflowResourceProvider,\n\t\t\t\tinheritanceSnapshotProvider,\n\t\t\t);\n\t\t\textensions.push(extension);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t}\n\t}\n\n\treturn { extensions, errors };\n}\n\nfunction addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\tconst conflicts = detectExtensionConflicts(extensionsResult.extensions);\n\tfor (const conflict of conflicts) {\n\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t}\n}\n\nfunction detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t// Track which extension registered each tool and flag\n\tconst toolOwners = new Map<string, string>();\n\tconst flagOwners = new Map<string, string>();\n\n\tfor (const ext of extensions) {\n\t\t// Check tools\n\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t}\n\t\t}\n\n\t\t// Check flags\n\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\tconflicts.push({\n\t\t\t\t\tpath: ext.path,\n\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn conflicts;\n}\n"]}