@ashx-j/lunr 0.2.8 → 0.2.9

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 (127) hide show
  1. package/dist/builtin-extensions/ashxj-spinners.d.ts +7 -0
  2. package/dist/builtin-extensions/ashxj-spinners.d.ts.map +1 -1
  3. package/dist/builtin-extensions/ashxj-spinners.js +40 -3
  4. package/dist/builtin-extensions/ashxj-spinners.js.map +1 -1
  5. package/dist/builtin-extensions/ashxj-tui.d.ts +4 -0
  6. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  7. package/dist/builtin-extensions/ashxj-tui.js +44 -0
  8. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  9. package/dist/builtin-extensions/lunr-behavior.d.ts +2 -1
  10. package/dist/builtin-extensions/lunr-behavior.d.ts.map +1 -1
  11. package/dist/builtin-extensions/lunr-behavior.js +26 -14
  12. package/dist/builtin-extensions/lunr-behavior.js.map +1 -1
  13. package/dist/builtin-extensions/lunr-todos.d.ts +4 -7
  14. package/dist/builtin-extensions/lunr-todos.d.ts.map +1 -1
  15. package/dist/builtin-extensions/lunr-todos.js +18 -10
  16. package/dist/builtin-extensions/lunr-todos.js.map +1 -1
  17. package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.d.ts.map +1 -1
  18. package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.js +3 -3
  19. package/dist/builtin-extensions/pi-subagents/src/agents/agent-management.js.map +1 -1
  20. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  21. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +2 -2
  22. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  23. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +2 -2
  24. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  25. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +3 -4
  26. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  27. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  28. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +6 -18
  29. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  30. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
  31. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +13 -5
  32. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
  33. package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.d.ts +21 -0
  34. package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.d.ts.map +1 -0
  35. package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js +22 -0
  36. package/dist/builtin-extensions/pi-subagents/src/shared/lunr-child-context.js.map +1 -0
  37. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
  38. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +2 -1
  39. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
  40. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  41. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +10 -18
  42. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  43. package/dist/builtin-extensions/pi-web-access/render-search-error.d.ts.map +1 -1
  44. package/dist/builtin-extensions/pi-web-access/render-search-error.js +1 -1
  45. package/dist/builtin-extensions/pi-web-access/render-search-error.js.map +1 -1
  46. package/dist/catalog/models.json +1 -1
  47. package/dist/catalog/providers/openrouter.json +1 -1
  48. package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
  49. package/dist/catalog/publication.json +3 -3
  50. package/dist/cli/update-cli.d.ts +16 -0
  51. package/dist/cli/update-cli.d.ts.map +1 -0
  52. package/dist/cli/update-cli.js +83 -0
  53. package/dist/cli/update-cli.js.map +1 -0
  54. package/dist/cli.d.ts.map +1 -1
  55. package/dist/cli.js +6 -0
  56. package/dist/cli.js.map +1 -1
  57. package/dist/core/behavior-preset.d.ts +60 -0
  58. package/dist/core/behavior-preset.d.ts.map +1 -0
  59. package/dist/core/behavior-preset.js +257 -0
  60. package/dist/core/behavior-preset.js.map +1 -0
  61. package/dist/core/customize.d.ts +3 -0
  62. package/dist/core/customize.d.ts.map +1 -1
  63. package/dist/core/customize.js +9 -0
  64. package/dist/core/customize.js.map +1 -1
  65. package/dist/core/footer-data-provider.d.ts +12 -1
  66. package/dist/core/footer-data-provider.d.ts.map +1 -1
  67. package/dist/core/footer-data-provider.js +70 -5
  68. package/dist/core/footer-data-provider.js.map +1 -1
  69. package/dist/core/keybindings.d.ts +2 -2
  70. package/dist/core/keybindings.d.ts.map +1 -1
  71. package/dist/core/keybindings.js +1 -1
  72. package/dist/core/keybindings.js.map +1 -1
  73. package/dist/core/model-tiers.d.ts +9 -0
  74. package/dist/core/model-tiers.d.ts.map +1 -1
  75. package/dist/core/model-tiers.js +16 -0
  76. package/dist/core/model-tiers.js.map +1 -1
  77. package/dist/core/settings-manager.d.ts +23 -0
  78. package/dist/core/settings-manager.d.ts.map +1 -1
  79. package/dist/core/settings-manager.js +66 -0
  80. package/dist/core/settings-manager.js.map +1 -1
  81. package/dist/core/tools/bash.d.ts.map +1 -1
  82. package/dist/core/tools/bash.js +1 -3
  83. package/dist/core/tools/bash.js.map +1 -1
  84. package/dist/core/update-check.d.ts +32 -0
  85. package/dist/core/update-check.d.ts.map +1 -0
  86. package/dist/core/update-check.js +112 -0
  87. package/dist/core/update-check.js.map +1 -0
  88. package/dist/core/usage-service.d.ts +24 -1
  89. package/dist/core/usage-service.d.ts.map +1 -1
  90. package/dist/core/usage-service.js +91 -14
  91. package/dist/core/usage-service.js.map +1 -1
  92. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  93. package/dist/gateway/agent-bridge.js +5 -1
  94. package/dist/gateway/agent-bridge.js.map +1 -1
  95. package/dist/gateway/cron.d.ts.map +1 -1
  96. package/dist/gateway/cron.js +5 -1
  97. package/dist/gateway/cron.js.map +1 -1
  98. package/dist/main.d.ts.map +1 -1
  99. package/dist/main.js +13 -1
  100. package/dist/main.js.map +1 -1
  101. package/dist/modes/interactive/components/assistant-message.d.ts +4 -0
  102. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/assistant-message.js +68 -10
  104. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  105. package/dist/modes/interactive/components/settings-selector.d.ts +13 -0
  106. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/settings-selector.js +157 -10
  108. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  109. package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
  110. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  111. package/dist/modes/interactive/components/tool-execution.js +9 -0
  112. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  113. package/dist/modes/interactive/interactive-mode.d.ts +4 -1
  114. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  115. package/dist/modes/interactive/interactive-mode.js +82 -3
  116. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  117. package/docs/keybindings.md +1 -1
  118. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  119. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  120. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  121. package/examples/extensions/gondolin/package-lock.json +2 -2
  122. package/examples/extensions/gondolin/package.json +1 -1
  123. package/examples/extensions/sandbox/package-lock.json +2 -2
  124. package/examples/extensions/sandbox/package.json +1 -1
  125. package/examples/extensions/with-deps/package-lock.json +2 -2
  126. package/examples/extensions/with-deps/package.json +1 -1
  127. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"model-fallback.d.ts","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,IAAI,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAmB,KAAK,gBAAgB,EAAE,KAAK,mBAAmB,EAAE,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEtH,YAAY,EAAE,kBAAkB,EAAE,CAAC;AAEnC,UAAU,mBAAmB;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,KAAK,CAAC;CACd;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAOhG;AAED,0FAA0F;AAC1F,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,2EAA2E;AAC3E,MAAM,WAAW,WAAW;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;CACX;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAM7D;AAsCD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAChC,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,kBAAkB,EAAE,EACrC,iBAAiB,CAAC,EAAE,MAAM,GACxB,MAAM,GAAG,SAAS,CAoCpB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACpC,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,eAAe,EAAE,kBAAkB,EAAE,GAAG,SAAS,EACjD,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eAAe,EAAE,kBAAkB,EAAE,GAAG,SAAS,EACjD,iBAAiB,CAAC,EAAE,MAAM,EAC1B,OAAO,CAAC,EAAE,2BAA2B,GACnC,MAAM,EAAE,CAiBV;AAiDD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAI1E;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,mBAAmB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAK/F","sourcesContent":["// @ts-nocheck\nimport type { ModelInfo as AvailableModelInfo } from \"../../shared/model-info.ts\";\nimport type { Usage } from \"../../shared/types.ts\";\nimport { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from \"./model-scope.ts\";\n\nexport type { AvailableModelInfo };\n\ninterface ModelAttemptSummary {\n\tmodel: string;\n\tsuccess: boolean;\n\texitCode?: number | null;\n\terror?: string;\n\tusage?: Usage;\n}\n\nexport function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {\n\tconst colonIdx = model.lastIndexOf(\":\");\n\tif (colonIdx === -1) return { baseModel: model, thinkingSuffix: \"\" };\n\treturn {\n\t\tbaseModel: model.substring(0, colonIdx),\n\t\tthinkingSuffix: model.substring(colonIdx),\n\t};\n}\n\n/** Sentinel model value requesting that a subagent inherit the parent session's model. */\nexport const INHERIT_MODEL = \"inherit\";\n\n/** Minimal shape of the parent session's in-memory model (`ctx.model`). */\nexport interface ParentModel {\n\tprovider: string;\n\tid: string;\n}\n\n/**\n * Normalize a model id or provider segment for fuzzy comparison: case-fold,\n * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse\n * repeated separators. Pure.\n */\nexport function normalizeModelSegment(segment: string): string {\n\treturn segment\n\t\t.toLowerCase()\n\t\t.replace(/[._]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n}\n\nfunction isPlausibleDateStamp(year: string, month: string, day: string): boolean {\n\tconst yyyy = Number(year);\n\tconst mm = Number(month);\n\tconst dd = Number(day);\n\treturn yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;\n}\n\n/** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */\nfunction stripTrailingDateStamp(segment: string): string {\n\tconst dashed = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/.exec(segment);\n\tif (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;\n\tconst compact = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/.exec(segment);\n\tif (compact && isPlausibleDateStamp(compact[2]!, compact[3]!, compact[4]!)) return compact[1]!;\n\treturn segment;\n}\n\nfunction resolveBaseModelCandidate(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (baseModel.includes(\"/\")) {\n\t\tconst exact = availableModels.find((entry) => entry.fullId === baseModel);\n\t\tif (exact) return exact.fullId;\n\t} else {\n\t\tconst exactMatches = availableModels.filter((entry) => entry.id === baseModel);\n\t\tif (preferredProvider) {\n\t\t\tconst preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);\n\t\t\tif (preferredMatch) return preferredMatch.fullId;\n\t\t}\n\t\tif (exactMatches.length === 1) return exactMatches[0]!.fullId;\n\t}\n\n\treturn fuzzyResolveModel(baseModel, availableModels, preferredProvider);\n}\n\n/**\n * Fuzzy-resolve a base model id (thinking suffix already stripped) against the\n * registry, tolerating separator, case, and optional date-stamp differences so\n * users do not have to spell provider/model exactly. A qualified `provider/id`\n * query only matches within the named provider — this never silently switches\n * providers for security/cost-sensitive configs. Returns the matched `fullId`,\n * or `undefined` when there is no match or the match is ambiguous across\n * providers (and no `preferredProvider` disambiguates). Pure.\n */\nexport function fuzzyResolveModel(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tlet queryProvider: string | undefined;\n\tlet queryIdRaw = baseModel;\n\tconst slashIdx = baseModel.indexOf(\"/\");\n\tif (slashIdx !== -1) {\n\t\tqueryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));\n\t\tqueryIdRaw = baseModel.slice(slashIdx + 1);\n\t} else {\n\t\tconst providerSeparators = [\":\", \".\"];\n\t\tfor (const separator of providerSeparators) {\n\t\t\tconst separatorIdx = baseModel.indexOf(separator);\n\t\t\tif (separatorIdx <= 0) continue;\n\t\t\tconst providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));\n\t\t\tif (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;\n\t\t\tqueryProvider = providerPart;\n\t\t\tqueryIdRaw = baseModel.slice(separatorIdx + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst queryId = normalizeModelSegment(queryIdRaw);\n\tconst queryIdNoDate = stripTrailingDateStamp(queryId);\n\n\tconst candidates = availableModels.filter((entry) => {\n\t\tconst entryId = normalizeModelSegment(entry.id);\n\t\tif (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;\n\t\tif (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;\n\t\treturn true;\n\t});\n\tif (candidates.length === 0) return undefined;\n\tif (preferredProvider) {\n\t\tconst preferredProviderNorm = normalizeModelSegment(preferredProvider);\n\t\tconst preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);\n\t\tif (preferred) return preferred.fullId;\n\t}\n\tif (candidates.length === 1) return candidates[0]!.fullId;\n\treturn undefined;\n}\n\n/**\n * Resolve a possibly-loose model id to a canonical `provider/id` (plus any\n * thinking suffix). Exact registry matches win; fuzzy normalization\n * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so\n * spelling differences still resolve. Never switches providers for a qualified\n * query. Pure.\n */\nexport function resolveModelCandidate(\n\tmodel: string | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (!model) return undefined;\n\tif (!availableModels || availableModels.length === 0) return model;\n\n\tconst resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);\n\tif (resolvedWhole) return resolvedWhole;\n\n\tconst { baseModel, thinkingSuffix } = splitThinkingSuffix(model);\n\tif (!thinkingSuffix) return model;\n\tconst resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);\n\tif (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;\n\treturn model;\n}\n\nexport interface ResolveSubagentModelOverrideOptions {\n\t/** When set with `enforce: true`, out-of-scope models are rejected. */\n\tscope?: ModelScopeConfig;\n\t/** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `\"inherited\"`. */\n\tsource?: ModelSource;\n\t/** Called for warn-severity violations instead of `console.warn`. */\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nfunction defaultScopeWarn(violation: ModelScopeViolation): void {\n\tconsole.warn(`[pi-subagents] ${violation.message}`);\n}\n\n/**\n * Resolve the `--model` override passed to a spawned subagent.\n *\n * When no model is requested (`undefined`, `false`, empty, or the `\"inherit\"`\n * sentinel), the child must inherit the parent session's *in-memory* model\n * (`provider/id`) instead of being left to resolve its own model. Without an\n * explicit `provider/id`, the child falls back to the global\n * `~/.pi/agent/settings.json` default, which is shared across every open PI\n * session — so a different session that last changed its model in the TUI would\n * silently contaminate this session's subagents (see issue #266). Passing an\n * explicit `provider/id` keeps each session's children isolated to that\n * session's model.\n *\n * An explicitly requested model string is resolved via {@link resolveModelCandidate}.\n * When `options.scope.enforce` is on, an out-of-scope resolved model throws for\n * an explicit (`source: \"explicit\"`) request and warns for an inherited one.\n */\nexport function resolveSubagentModelOverride(\n\trequestedModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: ResolveSubagentModelOverrideOptions,\n): string | undefined {\n\tconst trimmed = typeof requestedModel === \"string\" ? requestedModel.trim() : \"\";\n\tconst explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;\n\tlet resolved: string | undefined;\n\tif (explicit === undefined) {\n\t\tresolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;\n\t} else {\n\t\tresolved = resolveModelCandidate(explicit, availableModels, preferredProvider);\n\t}\n\tif (resolved && options?.scope?.enforce) {\n\t\tconst source: ModelSource = explicit === undefined ? \"inherited\" : (options.source ?? \"inherited\");\n\t\tconst violation = checkModelScope(resolved, options.scope, source);\n\t\tif (violation) {\n\t\t\tif (violation.severity === \"error\") throw new Error(violation.message);\n\t\t\t(options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t}\n\treturn resolved;\n}\n\nexport function resolveEffectiveSubagentModel(\n\texplicitModel: string | boolean | undefined,\n\tagentModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: Omit<ResolveSubagentModelOverrideOptions, \"source\">,\n): string | undefined {\n\tconst resolved = resolveSubagentModelOverride(\n\t\texplicitModel ?? agentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: explicitModel !== undefined ? \"explicit\" : \"inherited\" },\n\t);\n\tif (resolved || explicitModel === undefined) return resolved;\n\treturn resolveSubagentModelOverride(\n\t\tagentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: \"inherited\" },\n\t);\n}\n\n// lunr: model tier bridge — resolve a subagent `tier` param through lunR core's\n// model-tiers global (Symbol.for(\"@lunr/model-tiers\")). Absent bridge, disabled tier\n// mode, unknown tier, or unconfigured tier all resolve to undefined so callers fall\n// back to normal inherit behavior. Never throws.\nexport function resolveTierModelOverride(tier: unknown): string | undefined {\n\tif (typeof tier !== \"string\" || !tier.trim()) return undefined;\n\tconst tierName = tier.trim();\n\ttry {\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/model-tiers\")] as\n\t\t\t| { getTierModel?: (tier: string) => unknown; isTierModeEnabled?: () => unknown }\n\t\t\t| undefined;\n\t\tif (typeof bridge?.isTierModeEnabled !== \"function\" || typeof bridge?.getTierModel !== \"function\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (bridge.isTierModeEnabled() !== true) return undefined;\n\t\tconst model = bridge.getTierModel(tierName);\n\t\tif (typeof model === \"string\" && model.trim()) return model.trim();\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(\n\t\t\t\t`[pi-subagents] model tier resolution failed for '${tierName}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\nexport interface BuildModelCandidatesOptions {\n\t/** Fallback models are inherited agent config and warn, rather than error, when out of scope. */\n\tscope?: ModelScopeConfig;\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nexport function buildModelCandidates(\n\tprimaryModel: string | undefined,\n\tfallbackModels: string[] | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: BuildModelCandidatesOptions,\n): string[] {\n\tconst seen = new Set<string>();\n\tconst candidates: string[] = [];\n\tconst rawCandidates = [primaryModel, ...(fallbackModels ?? [])];\n\tfor (let index = 0; index < rawCandidates.length; index++) {\n\t\tconst raw = rawCandidates[index];\n\t\tif (!raw) continue;\n\t\tconst normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);\n\t\tif (!normalized || seen.has(normalized)) continue;\n\t\tif (index > 0 && options?.scope?.enforce) {\n\t\t\tconst violation = checkModelScope(normalized, options.scope, \"inherited\");\n\t\t\tif (violation) (options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t\tseen.add(normalized);\n\t\tcandidates.push(normalized);\n\t}\n\treturn candidates;\n}\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS = [\n\t/rate\\s*limit/i,\n\t/too many requests/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication)?/i,\n\t/unauthori[sz]ed/i,\n\t/forbidden/i,\n\t/api key/i,\n\t/token expired/i,\n\t/invalid key/i,\n\t/provider.*unavailable/i,\n\t/model.*unavailable/i,\n\t/model.*disabled/i,\n\t/model.*not found/i,\n\t/unknown model/i,\n\t/overloaded/i,\n\t/service unavailable/i,\n\t/temporar(?:ily)? unavailable/i,\n\t/connection refused/i,\n\t/fetch failed/i,\n\t/network error/i,\n\t/socket hang up/i,\n\t/stream ended without finish_reason/i,\n\t/upstream/i,\n\t/timed? out/i,\n\t/timeout/i,\n\t/\\b502\\b/,\n\t/\\b503\\b/,\n\t/\\b504\\b/,\n\t/cold.?start/i,\n\t/empty response/i,\n\t/no output/i,\n\t/model.*(?:load|fail|error)/i,\n];\n\n/**\n * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with\n * exit code N` come from a tool call inside the child's task, not from the\n * provider/model, however network-flavored their details read. Retrying a\n * different model cannot fix them and would rerun the whole task. Tool names\n * include namespaced forms like `mcp.server/write`.\n */\nconst TOOL_FAILURE_PREFIX = /^[\\w.:@/-]+ failed (?:(?:\\(exit \\d+\\):)|(?:with exit code \\d+))(?:\\s|$)/i;\n\nexport function isRetryableModelFailure(error: string | undefined): boolean {\n\tif (!error) return false;\n\tif (TOOL_FAILURE_PREFIX.test(error.trim())) return false;\n\treturn RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));\n}\n\nexport function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {\n\tconst failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;\n\treturn nextModel\n\t\t? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`\n\t\t: `[fallback] ${attempt.model} failed: ${failure}.`;\n}\n"]}
1
+ {"version":3,"file":"model-fallback.d.ts","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,IAAI,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAmB,KAAK,gBAAgB,EAAE,KAAK,mBAAmB,EAAE,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGtH,YAAY,EAAE,kBAAkB,EAAE,CAAC;AAEnC,UAAU,mBAAmB;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,KAAK,CAAC;CACd;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAOhG;AAED,0FAA0F;AAC1F,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC,2EAA2E;AAC3E,MAAM,WAAW,WAAW;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;CACX;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAM7D;AAsCD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAChC,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,kBAAkB,EAAE,EACrC,iBAAiB,CAAC,EAAE,MAAM,GACxB,MAAM,GAAG,SAAS,CAoCpB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACpC,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C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,cAAc,EAAE,MAAM,EAAE,GAAG,SAAS,EACpC,eAAe,EAAE,kBAAkB,EAAE,GAAG,SAAS,EACjD,iBAAiB,CAAC,EAAE,MAAM,EAC1B,OAAO,CAAC,EAAE,2BAA2B,GACnC,MAAM,EAAE,CAiBV;AAiDD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAI1E;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,mBAAmB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAK/F","sourcesContent":["// @ts-nocheck\nimport type { ModelInfo as AvailableModelInfo } from \"../../shared/model-info.ts\";\nimport type { Usage } from \"../../shared/types.ts\";\nimport { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from \"./model-scope.ts\";\nimport { applyThinkingSuffix } from \"./pi-args.ts\";\n\nexport type { AvailableModelInfo };\n\ninterface ModelAttemptSummary {\n\tmodel: string;\n\tsuccess: boolean;\n\texitCode?: number | null;\n\terror?: string;\n\tusage?: Usage;\n}\n\nexport function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {\n\tconst colonIdx = model.lastIndexOf(\":\");\n\tif (colonIdx === -1) return { baseModel: model, thinkingSuffix: \"\" };\n\treturn {\n\t\tbaseModel: model.substring(0, colonIdx),\n\t\tthinkingSuffix: model.substring(colonIdx),\n\t};\n}\n\n/** Sentinel model value requesting that a subagent inherit the parent session's model. */\nexport const INHERIT_MODEL = \"inherit\";\n\n/** Minimal shape of the parent session's in-memory model (`ctx.model`). */\nexport interface ParentModel {\n\tprovider: string;\n\tid: string;\n}\n\n/**\n * Normalize a model id or provider segment for fuzzy comparison: case-fold,\n * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse\n * repeated separators. Pure.\n */\nexport function normalizeModelSegment(segment: string): string {\n\treturn segment\n\t\t.toLowerCase()\n\t\t.replace(/[._]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n}\n\nfunction isPlausibleDateStamp(year: string, month: string, day: string): boolean {\n\tconst yyyy = Number(year);\n\tconst mm = Number(month);\n\tconst dd = Number(day);\n\treturn yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;\n}\n\n/** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */\nfunction stripTrailingDateStamp(segment: string): string {\n\tconst dashed = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/.exec(segment);\n\tif (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;\n\tconst compact = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/.exec(segment);\n\tif (compact && isPlausibleDateStamp(compact[2]!, compact[3]!, compact[4]!)) return compact[1]!;\n\treturn segment;\n}\n\nfunction resolveBaseModelCandidate(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (baseModel.includes(\"/\")) {\n\t\tconst exact = availableModels.find((entry) => entry.fullId === baseModel);\n\t\tif (exact) return exact.fullId;\n\t} else {\n\t\tconst exactMatches = availableModels.filter((entry) => entry.id === baseModel);\n\t\tif (preferredProvider) {\n\t\t\tconst preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);\n\t\t\tif (preferredMatch) return preferredMatch.fullId;\n\t\t}\n\t\tif (exactMatches.length === 1) return exactMatches[0]!.fullId;\n\t}\n\n\treturn fuzzyResolveModel(baseModel, availableModels, preferredProvider);\n}\n\n/**\n * Fuzzy-resolve a base model id (thinking suffix already stripped) against the\n * registry, tolerating separator, case, and optional date-stamp differences so\n * users do not have to spell provider/model exactly. A qualified `provider/id`\n * query only matches within the named provider — this never silently switches\n * providers for security/cost-sensitive configs. Returns the matched `fullId`,\n * or `undefined` when there is no match or the match is ambiguous across\n * providers (and no `preferredProvider` disambiguates). Pure.\n */\nexport function fuzzyResolveModel(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tlet queryProvider: string | undefined;\n\tlet queryIdRaw = baseModel;\n\tconst slashIdx = baseModel.indexOf(\"/\");\n\tif (slashIdx !== -1) {\n\t\tqueryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));\n\t\tqueryIdRaw = baseModel.slice(slashIdx + 1);\n\t} else {\n\t\tconst providerSeparators = [\":\", \".\"];\n\t\tfor (const separator of providerSeparators) {\n\t\t\tconst separatorIdx = baseModel.indexOf(separator);\n\t\t\tif (separatorIdx <= 0) continue;\n\t\t\tconst providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));\n\t\t\tif (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;\n\t\t\tqueryProvider = providerPart;\n\t\t\tqueryIdRaw = baseModel.slice(separatorIdx + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst queryId = normalizeModelSegment(queryIdRaw);\n\tconst queryIdNoDate = stripTrailingDateStamp(queryId);\n\n\tconst candidates = availableModels.filter((entry) => {\n\t\tconst entryId = normalizeModelSegment(entry.id);\n\t\tif (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;\n\t\tif (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;\n\t\treturn true;\n\t});\n\tif (candidates.length === 0) return undefined;\n\tif (preferredProvider) {\n\t\tconst preferredProviderNorm = normalizeModelSegment(preferredProvider);\n\t\tconst preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);\n\t\tif (preferred) return preferred.fullId;\n\t}\n\tif (candidates.length === 1) return candidates[0]!.fullId;\n\treturn undefined;\n}\n\n/**\n * Resolve a possibly-loose model id to a canonical `provider/id` (plus any\n * thinking suffix). Exact registry matches win; fuzzy normalization\n * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so\n * spelling differences still resolve. Never switches providers for a qualified\n * query. Pure.\n */\nexport function resolveModelCandidate(\n\tmodel: string | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (!model) return undefined;\n\tif (!availableModels || availableModels.length === 0) return model;\n\n\tconst resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);\n\tif (resolvedWhole) return resolvedWhole;\n\n\tconst { baseModel, thinkingSuffix } = splitThinkingSuffix(model);\n\tif (!thinkingSuffix) return model;\n\tconst resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);\n\tif (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;\n\treturn model;\n}\n\nexport interface ResolveSubagentModelOverrideOptions {\n\t/** When set with `enforce: true`, out-of-scope models are rejected. */\n\tscope?: ModelScopeConfig;\n\t/** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `\"inherited\"`. */\n\tsource?: ModelSource;\n\t/** Called for warn-severity violations instead of `console.warn`. */\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nfunction defaultScopeWarn(violation: ModelScopeViolation): void {\n\tconsole.warn(`[pi-subagents] ${violation.message}`);\n}\n\n/**\n * Resolve the `--model` override passed to a spawned subagent.\n *\n * When no model is requested (`undefined`, `false`, empty, or the `\"inherit\"`\n * sentinel), the child must inherit the parent session's *in-memory* model\n * (`provider/id`) instead of being left to resolve its own model. Without an\n * explicit `provider/id`, the child falls back to the global\n * `~/.pi/agent/settings.json` default, which is shared across every open PI\n * session — so a different session that last changed its model in the TUI would\n * silently contaminate this session's subagents (see issue #266). Passing an\n * explicit `provider/id` keeps each session's children isolated to that\n * session's model.\n *\n * An explicitly requested model string is resolved via {@link resolveModelCandidate}.\n * When `options.scope.enforce` is on, an out-of-scope resolved model throws for\n * an explicit (`source: \"explicit\"`) request and warns for an inherited one.\n */\nexport function resolveSubagentModelOverride(\n\trequestedModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: ResolveSubagentModelOverrideOptions,\n): string | undefined {\n\tconst trimmed = typeof requestedModel === \"string\" ? requestedModel.trim() : \"\";\n\tconst explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;\n\tlet resolved: string | undefined;\n\tif (explicit === undefined) {\n\t\tresolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;\n\t} else {\n\t\tresolved = resolveModelCandidate(explicit, availableModels, preferredProvider);\n\t}\n\tif (resolved && options?.scope?.enforce) {\n\t\tconst source: ModelSource = explicit === undefined ? \"inherited\" : (options.source ?? \"inherited\");\n\t\tconst violation = checkModelScope(resolved, options.scope, source);\n\t\tif (violation) {\n\t\t\tif (violation.severity === \"error\") throw new Error(violation.message);\n\t\t\t(options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t}\n\treturn resolved;\n}\n\nexport function resolveEffectiveSubagentModel(\n\texplicitModel: string | boolean | undefined,\n\tagentModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: Omit<ResolveSubagentModelOverrideOptions, \"source\">,\n): string | undefined {\n\tconst resolved = resolveSubagentModelOverride(\n\t\texplicitModel ?? agentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: explicitModel !== undefined ? \"explicit\" : \"inherited\" },\n\t);\n\tif (resolved || explicitModel === undefined) return resolved;\n\treturn resolveSubagentModelOverride(\n\t\tagentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: \"inherited\" },\n\t);\n}\n\n// lunr: model tier bridge — resolve a subagent `tier` param through lunR core's\n// model-tiers global (Symbol.for(\"@lunr/model-tiers\")). Absent bridge, disabled tier\n// mode, unknown tier, or unconfigured tier all resolve to undefined so callers fall\n// back to normal inherit behavior. Never throws.\nexport function resolveTierModelOverride(tier: unknown): string | undefined {\n\tif (typeof tier !== \"string\" || !tier.trim()) return undefined;\n\tconst tierName = tier.trim();\n\ttry {\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/model-tiers\")] as\n\t\t\t| { getTierModel?: (tier: string) => unknown; isTierModeEnabled?: () => unknown }\n\t\t\t| undefined;\n\t\tif (typeof bridge?.isTierModeEnabled !== \"function\" || typeof bridge?.getTierModel !== \"function\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (bridge.isTierModeEnabled() !== true) return undefined;\n\t\tconst model = bridge.getTierModel(tierName);\n\t\tif (typeof model !== \"string\" || !model.trim()) {\n\t\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\t\tconsole.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tconst trimmed = model.trim();\n\t\tconst thinking =\n\t\t\ttypeof bridge.getTierThinking === \"function\" ? bridge.getTierThinking(tierName) : undefined;\n\t\tconst parent = typeof bridge.getParentThinking === \"function\" ? bridge.getParentThinking() : undefined;\n\t\tconst level = (typeof thinking === \"string\" && thinking ? thinking : undefined) ?? (typeof parent === \"string\" && parent ? parent : undefined);\n\t\tif (!level) return trimmed;\n\t\treturn applyThinkingSuffix(trimmed, level, true) ?? trimmed;\n\t} catch (error) {\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(\n\t\t\t\t`[pi-subagents] model tier resolution failed for '${tierName}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\nexport interface BuildModelCandidatesOptions {\n\t/** Fallback models are inherited agent config and warn, rather than error, when out of scope. */\n\tscope?: ModelScopeConfig;\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nexport function buildModelCandidates(\n\tprimaryModel: string | undefined,\n\tfallbackModels: string[] | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: BuildModelCandidatesOptions,\n): string[] {\n\tconst seen = new Set<string>();\n\tconst candidates: string[] = [];\n\tconst rawCandidates = [primaryModel, ...(fallbackModels ?? [])];\n\tfor (let index = 0; index < rawCandidates.length; index++) {\n\t\tconst raw = rawCandidates[index];\n\t\tif (!raw) continue;\n\t\tconst normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);\n\t\tif (!normalized || seen.has(normalized)) continue;\n\t\tif (index > 0 && options?.scope?.enforce) {\n\t\t\tconst violation = checkModelScope(normalized, options.scope, \"inherited\");\n\t\t\tif (violation) (options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t\tseen.add(normalized);\n\t\tcandidates.push(normalized);\n\t}\n\treturn candidates;\n}\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS = [\n\t/rate\\s*limit/i,\n\t/too many requests/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication)?/i,\n\t/unauthori[sz]ed/i,\n\t/forbidden/i,\n\t/api key/i,\n\t/token expired/i,\n\t/invalid key/i,\n\t/provider.*unavailable/i,\n\t/model.*unavailable/i,\n\t/model.*disabled/i,\n\t/model.*not found/i,\n\t/unknown model/i,\n\t/overloaded/i,\n\t/service unavailable/i,\n\t/temporar(?:ily)? unavailable/i,\n\t/connection refused/i,\n\t/fetch failed/i,\n\t/network error/i,\n\t/socket hang up/i,\n\t/stream ended without finish_reason/i,\n\t/upstream/i,\n\t/timed? out/i,\n\t/timeout/i,\n\t/\\b502\\b/,\n\t/\\b503\\b/,\n\t/\\b504\\b/,\n\t/cold.?start/i,\n\t/empty response/i,\n\t/no output/i,\n\t/model.*(?:load|fail|error)/i,\n];\n\n/**\n * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with\n * exit code N` come from a tool call inside the child's task, not from the\n * provider/model, however network-flavored their details read. Retrying a\n * different model cannot fix them and would rerun the whole task. Tool names\n * include namespaced forms like `mcp.server/write`.\n */\nconst TOOL_FAILURE_PREFIX = /^[\\w.:@/-]+ failed (?:(?:\\(exit \\d+\\):)|(?:with exit code \\d+))(?:\\s|$)/i;\n\nexport function isRetryableModelFailure(error: string | undefined): boolean {\n\tif (!error) return false;\n\tif (TOOL_FAILURE_PREFIX.test(error.trim())) return false;\n\treturn RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));\n}\n\nexport function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {\n\tconst failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;\n\treturn nextModel\n\t\t? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`\n\t\t: `[fallback] ${attempt.model} failed: ${failure}.`;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { checkModelScope } from "./model-scope.js";
2
+ import { applyThinkingSuffix } from "./pi-args.js";
2
3
  export function splitThinkingSuffix(model) {
3
4
  const colonIdx = model.lastIndexOf(":");
4
5
  if (colonIdx === -1)
@@ -195,12 +196,19 @@ export function resolveTierModelOverride(tier) {
195
196
  if (bridge.isTierModeEnabled() !== true)
196
197
  return undefined;
197
198
  const model = bridge.getTierModel(tierName);
198
- if (typeof model === "string" && model.trim())
199
- return model.trim();
200
- if (process.env.PI_SUBAGENTS_DEBUG) {
201
- console.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);
199
+ if (typeof model !== "string" || !model.trim()) {
200
+ if (process.env.PI_SUBAGENTS_DEBUG) {
201
+ console.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);
202
+ }
203
+ return undefined;
202
204
  }
203
- return undefined;
205
+ const trimmed = model.trim();
206
+ const thinking = typeof bridge.getTierThinking === "function" ? bridge.getTierThinking(tierName) : undefined;
207
+ const parent = typeof bridge.getParentThinking === "function" ? bridge.getParentThinking() : undefined;
208
+ const level = (typeof thinking === "string" && thinking ? thinking : undefined) ?? (typeof parent === "string" && parent ? parent : undefined);
209
+ if (!level)
210
+ return trimmed;
211
+ return applyThinkingSuffix(trimmed, level, true) ?? trimmed;
204
212
  }
205
213
  catch (error) {
206
214
  if (process.env.PI_SUBAGENTS_DEBUG) {
@@ -1 +1 @@
1
- {"version":3,"file":"model-fallback.js","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAqE,MAAM,kBAAkB,CAAC;AAYtH,MAAM,UAAU,mBAAmB,CAAC,KAAa,EAAiD;IACjG,MAAM,QAAQ,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACxC,IAAI,QAAQ,KAAK,CAAC,CAAC;QAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;IACrE,OAAO;QACN,SAAS,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,CAAC;QACvC,cAAc,EAAE,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC;KACzC,CAAC;AAAA,CACF;AAED,0FAA0F;AAC1F,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAQvC;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAAe,EAAU;IAC9D,OAAO,OAAO;SACZ,WAAW,EAAE;SACb,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC;SACtB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAAA,CACxB;AAED,SAAS,oBAAoB,CAAC,IAAY,EAAE,KAAa,EAAE,GAAW,EAAW;IAChF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,MAAM,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACzB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,CA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";\nimport type { Usage } from \"../../shared/types.ts\";\nimport { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from \"./model-scope.ts\";\n\nexport type { AvailableModelInfo };\n\ninterface ModelAttemptSummary {\n\tmodel: string;\n\tsuccess: boolean;\n\texitCode?: number | null;\n\terror?: string;\n\tusage?: Usage;\n}\n\nexport function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {\n\tconst colonIdx = model.lastIndexOf(\":\");\n\tif (colonIdx === -1) return { baseModel: model, thinkingSuffix: \"\" };\n\treturn {\n\t\tbaseModel: model.substring(0, colonIdx),\n\t\tthinkingSuffix: model.substring(colonIdx),\n\t};\n}\n\n/** Sentinel model value requesting that a subagent inherit the parent session's model. */\nexport const INHERIT_MODEL = \"inherit\";\n\n/** Minimal shape of the parent session's in-memory model (`ctx.model`). */\nexport interface ParentModel {\n\tprovider: string;\n\tid: string;\n}\n\n/**\n * Normalize a model id or provider segment for fuzzy comparison: case-fold,\n * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse\n * repeated separators. Pure.\n */\nexport function normalizeModelSegment(segment: string): string {\n\treturn segment\n\t\t.toLowerCase()\n\t\t.replace(/[._]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n}\n\nfunction isPlausibleDateStamp(year: string, month: string, day: string): boolean {\n\tconst yyyy = Number(year);\n\tconst mm = Number(month);\n\tconst dd = Number(day);\n\treturn yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;\n}\n\n/** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */\nfunction stripTrailingDateStamp(segment: string): string {\n\tconst dashed = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/.exec(segment);\n\tif (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;\n\tconst compact = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/.exec(segment);\n\tif (compact && isPlausibleDateStamp(compact[2]!, compact[3]!, compact[4]!)) return compact[1]!;\n\treturn segment;\n}\n\nfunction resolveBaseModelCandidate(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (baseModel.includes(\"/\")) {\n\t\tconst exact = availableModels.find((entry) => entry.fullId === baseModel);\n\t\tif (exact) return exact.fullId;\n\t} else {\n\t\tconst exactMatches = availableModels.filter((entry) => entry.id === baseModel);\n\t\tif (preferredProvider) {\n\t\t\tconst preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);\n\t\t\tif (preferredMatch) return preferredMatch.fullId;\n\t\t}\n\t\tif (exactMatches.length === 1) return exactMatches[0]!.fullId;\n\t}\n\n\treturn fuzzyResolveModel(baseModel, availableModels, preferredProvider);\n}\n\n/**\n * Fuzzy-resolve a base model id (thinking suffix already stripped) against the\n * registry, tolerating separator, case, and optional date-stamp differences so\n * users do not have to spell provider/model exactly. A qualified `provider/id`\n * query only matches within the named provider — this never silently switches\n * providers for security/cost-sensitive configs. Returns the matched `fullId`,\n * or `undefined` when there is no match or the match is ambiguous across\n * providers (and no `preferredProvider` disambiguates). Pure.\n */\nexport function fuzzyResolveModel(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tlet queryProvider: string | undefined;\n\tlet queryIdRaw = baseModel;\n\tconst slashIdx = baseModel.indexOf(\"/\");\n\tif (slashIdx !== -1) {\n\t\tqueryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));\n\t\tqueryIdRaw = baseModel.slice(slashIdx + 1);\n\t} else {\n\t\tconst providerSeparators = [\":\", \".\"];\n\t\tfor (const separator of providerSeparators) {\n\t\t\tconst separatorIdx = baseModel.indexOf(separator);\n\t\t\tif (separatorIdx <= 0) continue;\n\t\t\tconst providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));\n\t\t\tif (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;\n\t\t\tqueryProvider = providerPart;\n\t\t\tqueryIdRaw = baseModel.slice(separatorIdx + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst queryId = normalizeModelSegment(queryIdRaw);\n\tconst queryIdNoDate = stripTrailingDateStamp(queryId);\n\n\tconst candidates = availableModels.filter((entry) => {\n\t\tconst entryId = normalizeModelSegment(entry.id);\n\t\tif (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;\n\t\tif (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;\n\t\treturn true;\n\t});\n\tif (candidates.length === 0) return undefined;\n\tif (preferredProvider) {\n\t\tconst preferredProviderNorm = normalizeModelSegment(preferredProvider);\n\t\tconst preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);\n\t\tif (preferred) return preferred.fullId;\n\t}\n\tif (candidates.length === 1) return candidates[0]!.fullId;\n\treturn undefined;\n}\n\n/**\n * Resolve a possibly-loose model id to a canonical `provider/id` (plus any\n * thinking suffix). Exact registry matches win; fuzzy normalization\n * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so\n * spelling differences still resolve. Never switches providers for a qualified\n * query. Pure.\n */\nexport function resolveModelCandidate(\n\tmodel: string | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (!model) return undefined;\n\tif (!availableModels || availableModels.length === 0) return model;\n\n\tconst resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);\n\tif (resolvedWhole) return resolvedWhole;\n\n\tconst { baseModel, thinkingSuffix } = splitThinkingSuffix(model);\n\tif (!thinkingSuffix) return model;\n\tconst resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);\n\tif (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;\n\treturn model;\n}\n\nexport interface ResolveSubagentModelOverrideOptions {\n\t/** When set with `enforce: true`, out-of-scope models are rejected. */\n\tscope?: ModelScopeConfig;\n\t/** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `\"inherited\"`. */\n\tsource?: ModelSource;\n\t/** Called for warn-severity violations instead of `console.warn`. */\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nfunction defaultScopeWarn(violation: ModelScopeViolation): void {\n\tconsole.warn(`[pi-subagents] ${violation.message}`);\n}\n\n/**\n * Resolve the `--model` override passed to a spawned subagent.\n *\n * When no model is requested (`undefined`, `false`, empty, or the `\"inherit\"`\n * sentinel), the child must inherit the parent session's *in-memory* model\n * (`provider/id`) instead of being left to resolve its own model. Without an\n * explicit `provider/id`, the child falls back to the global\n * `~/.pi/agent/settings.json` default, which is shared across every open PI\n * session — so a different session that last changed its model in the TUI would\n * silently contaminate this session's subagents (see issue #266). Passing an\n * explicit `provider/id` keeps each session's children isolated to that\n * session's model.\n *\n * An explicitly requested model string is resolved via {@link resolveModelCandidate}.\n * When `options.scope.enforce` is on, an out-of-scope resolved model throws for\n * an explicit (`source: \"explicit\"`) request and warns for an inherited one.\n */\nexport function resolveSubagentModelOverride(\n\trequestedModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: ResolveSubagentModelOverrideOptions,\n): string | undefined {\n\tconst trimmed = typeof requestedModel === \"string\" ? requestedModel.trim() : \"\";\n\tconst explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;\n\tlet resolved: string | undefined;\n\tif (explicit === undefined) {\n\t\tresolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;\n\t} else {\n\t\tresolved = resolveModelCandidate(explicit, availableModels, preferredProvider);\n\t}\n\tif (resolved && options?.scope?.enforce) {\n\t\tconst source: ModelSource = explicit === undefined ? \"inherited\" : (options.source ?? \"inherited\");\n\t\tconst violation = checkModelScope(resolved, options.scope, source);\n\t\tif (violation) {\n\t\t\tif (violation.severity === \"error\") throw new Error(violation.message);\n\t\t\t(options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t}\n\treturn resolved;\n}\n\nexport function resolveEffectiveSubagentModel(\n\texplicitModel: string | boolean | undefined,\n\tagentModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: Omit<ResolveSubagentModelOverrideOptions, \"source\">,\n): string | undefined {\n\tconst resolved = resolveSubagentModelOverride(\n\t\texplicitModel ?? agentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: explicitModel !== undefined ? \"explicit\" : \"inherited\" },\n\t);\n\tif (resolved || explicitModel === undefined) return resolved;\n\treturn resolveSubagentModelOverride(\n\t\tagentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: \"inherited\" },\n\t);\n}\n\n// lunr: model tier bridge — resolve a subagent `tier` param through lunR core's\n// model-tiers global (Symbol.for(\"@lunr/model-tiers\")). Absent bridge, disabled tier\n// mode, unknown tier, or unconfigured tier all resolve to undefined so callers fall\n// back to normal inherit behavior. Never throws.\nexport function resolveTierModelOverride(tier: unknown): string | undefined {\n\tif (typeof tier !== \"string\" || !tier.trim()) return undefined;\n\tconst tierName = tier.trim();\n\ttry {\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/model-tiers\")] as\n\t\t\t| { getTierModel?: (tier: string) => unknown; isTierModeEnabled?: () => unknown }\n\t\t\t| undefined;\n\t\tif (typeof bridge?.isTierModeEnabled !== \"function\" || typeof bridge?.getTierModel !== \"function\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (bridge.isTierModeEnabled() !== true) return undefined;\n\t\tconst model = bridge.getTierModel(tierName);\n\t\tif (typeof model === \"string\" && model.trim()) return model.trim();\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(\n\t\t\t\t`[pi-subagents] model tier resolution failed for '${tierName}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\nexport interface BuildModelCandidatesOptions {\n\t/** Fallback models are inherited agent config and warn, rather than error, when out of scope. */\n\tscope?: ModelScopeConfig;\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nexport function buildModelCandidates(\n\tprimaryModel: string | undefined,\n\tfallbackModels: string[] | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: BuildModelCandidatesOptions,\n): string[] {\n\tconst seen = new Set<string>();\n\tconst candidates: string[] = [];\n\tconst rawCandidates = [primaryModel, ...(fallbackModels ?? [])];\n\tfor (let index = 0; index < rawCandidates.length; index++) {\n\t\tconst raw = rawCandidates[index];\n\t\tif (!raw) continue;\n\t\tconst normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);\n\t\tif (!normalized || seen.has(normalized)) continue;\n\t\tif (index > 0 && options?.scope?.enforce) {\n\t\t\tconst violation = checkModelScope(normalized, options.scope, \"inherited\");\n\t\t\tif (violation) (options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t\tseen.add(normalized);\n\t\tcandidates.push(normalized);\n\t}\n\treturn candidates;\n}\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS = [\n\t/rate\\s*limit/i,\n\t/too many requests/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication)?/i,\n\t/unauthori[sz]ed/i,\n\t/forbidden/i,\n\t/api key/i,\n\t/token expired/i,\n\t/invalid key/i,\n\t/provider.*unavailable/i,\n\t/model.*unavailable/i,\n\t/model.*disabled/i,\n\t/model.*not found/i,\n\t/unknown model/i,\n\t/overloaded/i,\n\t/service unavailable/i,\n\t/temporar(?:ily)? unavailable/i,\n\t/connection refused/i,\n\t/fetch failed/i,\n\t/network error/i,\n\t/socket hang up/i,\n\t/stream ended without finish_reason/i,\n\t/upstream/i,\n\t/timed? out/i,\n\t/timeout/i,\n\t/\\b502\\b/,\n\t/\\b503\\b/,\n\t/\\b504\\b/,\n\t/cold.?start/i,\n\t/empty response/i,\n\t/no output/i,\n\t/model.*(?:load|fail|error)/i,\n];\n\n/**\n * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with\n * exit code N` come from a tool call inside the child's task, not from the\n * provider/model, however network-flavored their details read. Retrying a\n * different model cannot fix them and would rerun the whole task. Tool names\n * include namespaced forms like `mcp.server/write`.\n */\nconst TOOL_FAILURE_PREFIX = /^[\\w.:@/-]+ failed (?:(?:\\(exit \\d+\\):)|(?:with exit code \\d+))(?:\\s|$)/i;\n\nexport function isRetryableModelFailure(error: string | undefined): boolean {\n\tif (!error) return false;\n\tif (TOOL_FAILURE_PREFIX.test(error.trim())) return false;\n\treturn RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));\n}\n\nexport function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {\n\tconst failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;\n\treturn nextModel\n\t\t? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`\n\t\t: `[fallback] ${attempt.model} failed: ${failure}.`;\n}\n"]}
1
+ {"version":3,"file":"model-fallback.js","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAqE,MAAM,kBAAkB,CAAC;AACtH,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAYnD,MAAM,UAAU,mBAAmB,CAAC,KAAa,EAAiD;IACjG,MAAM,QAAQ,GAAG,KAAK,CAAC,WA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,OAAO,CAAC,QAAQ,IAAI,CAAC,EAAE,CAAC;IACzE,OAAO,SAAS;QACf,CAAC,CAAC,cAAc,OAAO,CAAC,KAAK,YAAY,OAAO,mBAAmB,SAAS,GAAG;QAC/E,CAAC,CAAC,cAAc,OAAO,CAAC,KAAK,YAAY,OAAO,GAAG,CAAC;AAAA,CACrD","sourcesContent":["// @ts-nocheck\nimport type { ModelInfo as AvailableModelInfo } from \"../../shared/model-info.ts\";\nimport type { Usage } from \"../../shared/types.ts\";\nimport { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from \"./model-scope.ts\";\nimport { applyThinkingSuffix } from \"./pi-args.ts\";\n\nexport type { AvailableModelInfo };\n\ninterface ModelAttemptSummary {\n\tmodel: string;\n\tsuccess: boolean;\n\texitCode?: number | null;\n\terror?: string;\n\tusage?: Usage;\n}\n\nexport function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {\n\tconst colonIdx = model.lastIndexOf(\":\");\n\tif (colonIdx === -1) return { baseModel: model, thinkingSuffix: \"\" };\n\treturn {\n\t\tbaseModel: model.substring(0, colonIdx),\n\t\tthinkingSuffix: model.substring(colonIdx),\n\t};\n}\n\n/** Sentinel model value requesting that a subagent inherit the parent session's model. */\nexport const INHERIT_MODEL = \"inherit\";\n\n/** Minimal shape of the parent session's in-memory model (`ctx.model`). */\nexport interface ParentModel {\n\tprovider: string;\n\tid: string;\n}\n\n/**\n * Normalize a model id or provider segment for fuzzy comparison: case-fold,\n * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse\n * repeated separators. Pure.\n */\nexport function normalizeModelSegment(segment: string): string {\n\treturn segment\n\t\t.toLowerCase()\n\t\t.replace(/[._]+/g, \"-\")\n\t\t.replace(/-+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\");\n}\n\nfunction isPlausibleDateStamp(year: string, month: string, day: string): boolean {\n\tconst yyyy = Number(year);\n\tconst mm = Number(month);\n\tconst dd = Number(day);\n\treturn yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;\n}\n\n/** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */\nfunction stripTrailingDateStamp(segment: string): string {\n\tconst dashed = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/.exec(segment);\n\tif (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;\n\tconst compact = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/.exec(segment);\n\tif (compact && isPlausibleDateStamp(compact[2]!, compact[3]!, compact[4]!)) return compact[1]!;\n\treturn segment;\n}\n\nfunction resolveBaseModelCandidate(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (baseModel.includes(\"/\")) {\n\t\tconst exact = availableModels.find((entry) => entry.fullId === baseModel);\n\t\tif (exact) return exact.fullId;\n\t} else {\n\t\tconst exactMatches = availableModels.filter((entry) => entry.id === baseModel);\n\t\tif (preferredProvider) {\n\t\t\tconst preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);\n\t\t\tif (preferredMatch) return preferredMatch.fullId;\n\t\t}\n\t\tif (exactMatches.length === 1) return exactMatches[0]!.fullId;\n\t}\n\n\treturn fuzzyResolveModel(baseModel, availableModels, preferredProvider);\n}\n\n/**\n * Fuzzy-resolve a base model id (thinking suffix already stripped) against the\n * registry, tolerating separator, case, and optional date-stamp differences so\n * users do not have to spell provider/model exactly. A qualified `provider/id`\n * query only matches within the named provider — this never silently switches\n * providers for security/cost-sensitive configs. Returns the matched `fullId`,\n * or `undefined` when there is no match or the match is ambiguous across\n * providers (and no `preferredProvider` disambiguates). Pure.\n */\nexport function fuzzyResolveModel(\n\tbaseModel: string,\n\tavailableModels: AvailableModelInfo[],\n\tpreferredProvider?: string,\n): string | undefined {\n\tlet queryProvider: string | undefined;\n\tlet queryIdRaw = baseModel;\n\tconst slashIdx = baseModel.indexOf(\"/\");\n\tif (slashIdx !== -1) {\n\t\tqueryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));\n\t\tqueryIdRaw = baseModel.slice(slashIdx + 1);\n\t} else {\n\t\tconst providerSeparators = [\":\", \".\"];\n\t\tfor (const separator of providerSeparators) {\n\t\t\tconst separatorIdx = baseModel.indexOf(separator);\n\t\t\tif (separatorIdx <= 0) continue;\n\t\t\tconst providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));\n\t\t\tif (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;\n\t\t\tqueryProvider = providerPart;\n\t\t\tqueryIdRaw = baseModel.slice(separatorIdx + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst queryId = normalizeModelSegment(queryIdRaw);\n\tconst queryIdNoDate = stripTrailingDateStamp(queryId);\n\n\tconst candidates = availableModels.filter((entry) => {\n\t\tconst entryId = normalizeModelSegment(entry.id);\n\t\tif (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;\n\t\tif (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;\n\t\treturn true;\n\t});\n\tif (candidates.length === 0) return undefined;\n\tif (preferredProvider) {\n\t\tconst preferredProviderNorm = normalizeModelSegment(preferredProvider);\n\t\tconst preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);\n\t\tif (preferred) return preferred.fullId;\n\t}\n\tif (candidates.length === 1) return candidates[0]!.fullId;\n\treturn undefined;\n}\n\n/**\n * Resolve a possibly-loose model id to a canonical `provider/id` (plus any\n * thinking suffix). Exact registry matches win; fuzzy normalization\n * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so\n * spelling differences still resolve. Never switches providers for a qualified\n * query. Pure.\n */\nexport function resolveModelCandidate(\n\tmodel: string | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n): string | undefined {\n\tif (!model) return undefined;\n\tif (!availableModels || availableModels.length === 0) return model;\n\n\tconst resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);\n\tif (resolvedWhole) return resolvedWhole;\n\n\tconst { baseModel, thinkingSuffix } = splitThinkingSuffix(model);\n\tif (!thinkingSuffix) return model;\n\tconst resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);\n\tif (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;\n\treturn model;\n}\n\nexport interface ResolveSubagentModelOverrideOptions {\n\t/** When set with `enforce: true`, out-of-scope models are rejected. */\n\tscope?: ModelScopeConfig;\n\t/** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `\"inherited\"`. */\n\tsource?: ModelSource;\n\t/** Called for warn-severity violations instead of `console.warn`. */\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nfunction defaultScopeWarn(violation: ModelScopeViolation): void {\n\tconsole.warn(`[pi-subagents] ${violation.message}`);\n}\n\n/**\n * Resolve the `--model` override passed to a spawned subagent.\n *\n * When no model is requested (`undefined`, `false`, empty, or the `\"inherit\"`\n * sentinel), the child must inherit the parent session's *in-memory* model\n * (`provider/id`) instead of being left to resolve its own model. Without an\n * explicit `provider/id`, the child falls back to the global\n * `~/.pi/agent/settings.json` default, which is shared across every open PI\n * session — so a different session that last changed its model in the TUI would\n * silently contaminate this session's subagents (see issue #266). Passing an\n * explicit `provider/id` keeps each session's children isolated to that\n * session's model.\n *\n * An explicitly requested model string is resolved via {@link resolveModelCandidate}.\n * When `options.scope.enforce` is on, an out-of-scope resolved model throws for\n * an explicit (`source: \"explicit\"`) request and warns for an inherited one.\n */\nexport function resolveSubagentModelOverride(\n\trequestedModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: ResolveSubagentModelOverrideOptions,\n): string | undefined {\n\tconst trimmed = typeof requestedModel === \"string\" ? requestedModel.trim() : \"\";\n\tconst explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;\n\tlet resolved: string | undefined;\n\tif (explicit === undefined) {\n\t\tresolved = parentModel ? `${parentModel.provider}/${parentModel.id}` : undefined;\n\t} else {\n\t\tresolved = resolveModelCandidate(explicit, availableModels, preferredProvider);\n\t}\n\tif (resolved && options?.scope?.enforce) {\n\t\tconst source: ModelSource = explicit === undefined ? \"inherited\" : (options.source ?? \"inherited\");\n\t\tconst violation = checkModelScope(resolved, options.scope, source);\n\t\tif (violation) {\n\t\t\tif (violation.severity === \"error\") throw new Error(violation.message);\n\t\t\t(options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t}\n\treturn resolved;\n}\n\nexport function resolveEffectiveSubagentModel(\n\texplicitModel: string | boolean | undefined,\n\tagentModel: string | boolean | undefined,\n\tparentModel: ParentModel | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: Omit<ResolveSubagentModelOverrideOptions, \"source\">,\n): string | undefined {\n\tconst resolved = resolveSubagentModelOverride(\n\t\texplicitModel ?? agentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: explicitModel !== undefined ? \"explicit\" : \"inherited\" },\n\t);\n\tif (resolved || explicitModel === undefined) return resolved;\n\treturn resolveSubagentModelOverride(\n\t\tagentModel,\n\t\tparentModel,\n\t\tavailableModels,\n\t\tpreferredProvider,\n\t\t{ ...options, source: \"inherited\" },\n\t);\n}\n\n// lunr: model tier bridge — resolve a subagent `tier` param through lunR core's\n// model-tiers global (Symbol.for(\"@lunr/model-tiers\")). Absent bridge, disabled tier\n// mode, unknown tier, or unconfigured tier all resolve to undefined so callers fall\n// back to normal inherit behavior. Never throws.\nexport function resolveTierModelOverride(tier: unknown): string | undefined {\n\tif (typeof tier !== \"string\" || !tier.trim()) return undefined;\n\tconst tierName = tier.trim();\n\ttry {\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/model-tiers\")] as\n\t\t\t| { getTierModel?: (tier: string) => unknown; isTierModeEnabled?: () => unknown }\n\t\t\t| undefined;\n\t\tif (typeof bridge?.isTierModeEnabled !== \"function\" || typeof bridge?.getTierModel !== \"function\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (bridge.isTierModeEnabled() !== true) return undefined;\n\t\tconst model = bridge.getTierModel(tierName);\n\t\tif (typeof model !== \"string\" || !model.trim()) {\n\t\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\t\tconsole.warn(`[pi-subagents] model tier '${tierName}' has no configured model; inheriting parent model.`);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tconst trimmed = model.trim();\n\t\tconst thinking =\n\t\t\ttypeof bridge.getTierThinking === \"function\" ? bridge.getTierThinking(tierName) : undefined;\n\t\tconst parent = typeof bridge.getParentThinking === \"function\" ? bridge.getParentThinking() : undefined;\n\t\tconst level = (typeof thinking === \"string\" && thinking ? thinking : undefined) ?? (typeof parent === \"string\" && parent ? parent : undefined);\n\t\tif (!level) return trimmed;\n\t\treturn applyThinkingSuffix(trimmed, level, true) ?? trimmed;\n\t} catch (error) {\n\t\tif (process.env.PI_SUBAGENTS_DEBUG) {\n\t\t\tconsole.warn(\n\t\t\t\t`[pi-subagents] model tier resolution failed for '${tierName}': ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n}\n\nexport interface BuildModelCandidatesOptions {\n\t/** Fallback models are inherited agent config and warn, rather than error, when out of scope. */\n\tscope?: ModelScopeConfig;\n\tonWarn?: (violation: ModelScopeViolation) => void;\n}\n\nexport function buildModelCandidates(\n\tprimaryModel: string | undefined,\n\tfallbackModels: string[] | undefined,\n\tavailableModels: AvailableModelInfo[] | undefined,\n\tpreferredProvider?: string,\n\toptions?: BuildModelCandidatesOptions,\n): string[] {\n\tconst seen = new Set<string>();\n\tconst candidates: string[] = [];\n\tconst rawCandidates = [primaryModel, ...(fallbackModels ?? [])];\n\tfor (let index = 0; index < rawCandidates.length; index++) {\n\t\tconst raw = rawCandidates[index];\n\t\tif (!raw) continue;\n\t\tconst normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);\n\t\tif (!normalized || seen.has(normalized)) continue;\n\t\tif (index > 0 && options?.scope?.enforce) {\n\t\t\tconst violation = checkModelScope(normalized, options.scope, \"inherited\");\n\t\t\tif (violation) (options.onWarn ?? defaultScopeWarn)(violation);\n\t\t}\n\t\tseen.add(normalized);\n\t\tcandidates.push(normalized);\n\t}\n\treturn candidates;\n}\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS = [\n\t/rate\\s*limit/i,\n\t/too many requests/i,\n\t/\\b429\\b/,\n\t/quota/i,\n\t/billing/i,\n\t/credit/i,\n\t/auth(?:entication)?/i,\n\t/unauthori[sz]ed/i,\n\t/forbidden/i,\n\t/api key/i,\n\t/token expired/i,\n\t/invalid key/i,\n\t/provider.*unavailable/i,\n\t/model.*unavailable/i,\n\t/model.*disabled/i,\n\t/model.*not found/i,\n\t/unknown model/i,\n\t/overloaded/i,\n\t/service unavailable/i,\n\t/temporar(?:ily)? unavailable/i,\n\t/connection refused/i,\n\t/fetch failed/i,\n\t/network error/i,\n\t/socket hang up/i,\n\t/stream ended without finish_reason/i,\n\t/upstream/i,\n\t/timed? out/i,\n\t/timeout/i,\n\t/\\b502\\b/,\n\t/\\b503\\b/,\n\t/\\b504\\b/,\n\t/cold.?start/i,\n\t/empty response/i,\n\t/no output/i,\n\t/model.*(?:load|fail|error)/i,\n];\n\n/**\n * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with\n * exit code N` come from a tool call inside the child's task, not from the\n * provider/model, however network-flavored their details read. Retrying a\n * different model cannot fix them and would rerun the whole task. Tool names\n * include namespaced forms like `mcp.server/write`.\n */\nconst TOOL_FAILURE_PREFIX = /^[\\w.:@/-]+ failed (?:(?:\\(exit \\d+\\):)|(?:with exit code \\d+))(?:\\s|$)/i;\n\nexport function isRetryableModelFailure(error: string | undefined): boolean {\n\tif (!error) return false;\n\tif (TOOL_FAILURE_PREFIX.test(error.trim())) return false;\n\treturn RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));\n}\n\nexport function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {\n\tconst failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;\n\treturn nextModel\n\t\t? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`\n\t\t: `[fallback] ${attempt.model} failed: ${failure}.`;\n}\n"]}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * lunr: advertised subagents always start with a fresh session.
3
+ * Fork-context internals (`fork-context.ts`, executor usesFork path) stay in
4
+ * the tree for upstream sync; they are not reachable from the model, slash
5
+ * `--fork`, or agent `defaultContext: fork` frontmatter.
6
+ */
7
+ export type LunrChildContext = "fresh";
8
+ /** Coerce any requested/defaulted context to fresh. */
9
+ export declare function lunrChildContext(_requested?: string): LunrChildContext;
10
+ /** List/get view: never advertise fork, even when on-disk frontmatter says fork. */
11
+ export declare function advertisedDefaultContext(_stored?: string): LunrChildContext;
12
+ export declare function lunrContextPolicy<T extends {
13
+ context?: string;
14
+ }>(params: T): {
15
+ params: T & {
16
+ context: LunrChildContext;
17
+ };
18
+ contextForAgent: (agentName: string) => LunrChildContext;
19
+ usesFork: false;
20
+ };
21
+ //# sourceMappingURL=lunr-child-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lunr-child-context.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/shared/lunr-child-context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAEvC,uDAAuD;AACvD,wBAAgB,gBAAgB,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAEtE;AAED,oFAAoF;AACpF,wBAAgB,wBAAwB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAE3E;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,EAAE,CAAC,GAAG;IAC7E,MAAM,EAAE,CAAC,GAAG;QAAE,OAAO,EAAE,gBAAgB,CAAA;KAAE,CAAC;IAC1C,eAAe,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,gBAAgB,CAAC;IACzD,QAAQ,EAAE,KAAK,CAAC;CAChB,CAMA","sourcesContent":["/**\n * lunr: advertised subagents always start with a fresh session.\n * Fork-context internals (`fork-context.ts`, executor usesFork path) stay in\n * the tree for upstream sync; they are not reachable from the model, slash\n * `--fork`, or agent `defaultContext: fork` frontmatter.\n */\n\nexport type LunrChildContext = \"fresh\";\n\n/** Coerce any requested/defaulted context to fresh. */\nexport function lunrChildContext(_requested?: string): LunrChildContext {\n\treturn \"fresh\";\n}\n\n/** List/get view: never advertise fork, even when on-disk frontmatter says fork. */\nexport function advertisedDefaultContext(_stored?: string): LunrChildContext {\n\treturn \"fresh\";\n}\n\nexport function lunrContextPolicy<T extends { context?: string }>(params: T): {\n\tparams: T & { context: LunrChildContext };\n\tcontextForAgent: (agentName: string) => LunrChildContext;\n\tusesFork: false;\n} {\n\treturn {\n\t\tparams: { ...params, context: \"fresh\" },\n\t\tcontextForAgent: () => \"fresh\",\n\t\tusesFork: false,\n\t};\n}\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * lunr: advertised subagents always start with a fresh session.
3
+ * Fork-context internals (`fork-context.ts`, executor usesFork path) stay in
4
+ * the tree for upstream sync; they are not reachable from the model, slash
5
+ * `--fork`, or agent `defaultContext: fork` frontmatter.
6
+ */
7
+ /** Coerce any requested/defaulted context to fresh. */
8
+ export function lunrChildContext(_requested) {
9
+ return "fresh";
10
+ }
11
+ /** List/get view: never advertise fork, even when on-disk frontmatter says fork. */
12
+ export function advertisedDefaultContext(_stored) {
13
+ return "fresh";
14
+ }
15
+ export function lunrContextPolicy(params) {
16
+ return {
17
+ params: { ...params, context: "fresh" },
18
+ contextForAgent: () => "fresh",
19
+ usesFork: false,
20
+ };
21
+ }
22
+ //# sourceMappingURL=lunr-child-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lunr-child-context.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/shared/lunr-child-context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,uDAAuD;AACvD,MAAM,UAAU,gBAAgB,CAAC,UAAmB,EAAoB;IACvE,OAAO,OAAO,CAAC;AAAA,CACf;AAED,oFAAoF;AACpF,MAAM,UAAU,wBAAwB,CAAC,OAAgB,EAAoB;IAC5E,OAAO,OAAO,CAAC;AAAA,CACf;AAED,MAAM,UAAU,iBAAiB,CAAiC,MAAS,EAIzE;IACD,OAAO;QACN,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE;QACvC,eAAe,EAAE,GAAG,EAAE,CAAC,OAAO;QAC9B,QAAQ,EAAE,KAAK;KACf,CAAC;AAAA,CACF","sourcesContent":["/**\n * lunr: advertised subagents always start with a fresh session.\n * Fork-context internals (`fork-context.ts`, executor usesFork path) stay in\n * the tree for upstream sync; they are not reachable from the model, slash\n * `--fork`, or agent `defaultContext: fork` frontmatter.\n */\n\nexport type LunrChildContext = \"fresh\";\n\n/** Coerce any requested/defaulted context to fresh. */\nexport function lunrChildContext(_requested?: string): LunrChildContext {\n\treturn \"fresh\";\n}\n\n/** List/get view: never advertise fork, even when on-disk frontmatter says fork. */\nexport function advertisedDefaultContext(_stored?: string): LunrChildContext {\n\treturn \"fresh\";\n}\n\nexport function lunrContextPolicy<T extends { context?: string }>(params: T): {\n\tparams: T & { context: LunrChildContext };\n\tcontextForAgent: (agentName: string) => LunrChildContext;\n\tusesFork: false;\n} {\n\treturn {\n\t\tparams: { ...params, context: \"fresh\" },\n\t\tcontextForAgent: () => \"fresh\",\n\t\tusesFork: false,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-workflows.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/slash/prompt-workflows.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAIlF,UAAU,cAAc;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,KAAK,oBAAoB,GAAG,CAAC,MAAM,EAAE,kBAAkB,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AA+FjG,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,EAAE,CAOrE;AAyID,wBAAgB,8BAA8B,CAAC,KAAK,EAAE;IACrD,EAAE,EAAE,YAAY,CAAC;IACjB,GAAG,EAAE,oBAAoB,CAAC;CAC1B,GAAG,IAAI,CAgEP","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ExtensionAPI, ExtensionContext } from \"@ashx-j/lunr\";\nimport { parseFrontmatter } from \"../agents/frontmatter.ts\";\nimport type { SubagentParamsLike } from \"../runs/foreground/subagent-executor.ts\";\nimport type { ChainStep } from \"../shared/settings.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\ninterface PromptWorkflow {\n\tname: string;\n\tdescription: string;\n\tbody: string;\n\tfilePath: string;\n\tagent: string;\n\tcontext?: \"fresh\" | \"fork\";\n\tmodel?: string;\n\tskill?: string | string[] | false;\n\tcwd?: string;\n\tworktree?: boolean;\n\tchain?: string;\n}\n\ntype PromptWorkflowRunner = (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<void>;\n\nconst RESERVED_COMMAND_NAMES = new Set([\n\t\"chain-prompts\",\n\t\"prompt-workflow\",\n\t\"run\",\n\t\"chain\",\n\t\"parallel\",\n\t\"run-chain\",\n\t\"subagents-doctor\",\n\t\"subagents-models\",\n]);\n\nfunction packagePromptsDir(): string {\n\treturn path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"prompts\");\n}\n\nfunction promptDirs(cwd: string): string[] {\n\treturn [\n\t\tpackagePromptsDir(),\n\t\tpath.join(getAgentDir(), \"prompts\"),\n\t\tpath.join(getProjectConfigDir(cwd), \"prompts\"),\n\t];\n}\n\nfunction readPromptFiles(cwd: string): string[] {\n\tconst files: string[] = [];\n\tfor (const dir of promptDirs(cwd)) {\n\t\tlet entries: fs.Dirent[];\n\t\ttry {\n\t\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".md\")) files.push(path.join(dir, entry.name));\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction firstNonEmptyLine(value: string): string {\n\treturn value.split(/\\r?\\n/).map((line) => line.trim()).find(Boolean) ?? \"Prompt workflow\";\n}\n\nfunction stringField(frontmatter: Record<string, string>, key: string): string | undefined {\n\tconst value = frontmatter[key]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction booleanField(frontmatter: Record<string, string>, key: string): boolean | undefined {\n\tconst value = frontmatter[key]?.trim().toLowerCase();\n\tif (value === \"true\" || value === \"yes\" || value === \"1\") return true;\n\tif (value === \"false\" || value === \"no\" || value === \"0\") return false;\n\treturn undefined;\n}\n\nfunction parseSkill(value: string | undefined): string | string[] | false | undefined {\n\tif (!value) return undefined;\n\tif (value === \"false\") return false;\n\tconst parts = value.split(\",\").map((part) => part.trim()).filter(Boolean);\n\treturn parts.length > 1 ? parts : parts[0];\n}\n\nfunction parseAgent(frontmatter: Record<string, string>): string {\n\tconst subagent = stringField(frontmatter, \"subagent\");\n\tif (!subagent || subagent === \"true\") return \"delegate\";\n\treturn subagent;\n}\n\nfunction loadPromptWorkflow(filePath: string): PromptWorkflow | undefined {\n\tconst content = fs.readFileSync(filePath, \"utf-8\");\n\tconst { frontmatter, body } = parseFrontmatter(content);\n\tconst name = path.basename(filePath, \".md\");\n\tif (!name || RESERVED_COMMAND_NAMES.has(name)) return undefined;\n\tconst model = stringField(frontmatter, \"model\");\n\tconst skill = parseSkill(stringField(frontmatter, \"skill\"));\n\tconst cwd = stringField(frontmatter, \"cwd\");\n\tconst chain = stringField(frontmatter, \"chain\");\n\treturn {\n\t\tname,\n\t\tdescription: stringField(frontmatter, \"description\") ?? firstNonEmptyLine(body),\n\t\tbody,\n\t\tfilePath,\n\t\tagent: parseAgent(frontmatter),\n\t\t...(booleanField(frontmatter, \"inheritContext\") === true || booleanField(frontmatter, \"fork\") === true ? { context: \"fork\" as const } : {}),\n\t\t...(booleanField(frontmatter, \"fresh\") === true ? { context: \"fresh\" as const } : {}),\n\t\t...(model ? { model } : {}),\n\t\t...(skill !== undefined ? { skill } : {}),\n\t\t...(cwd ? { cwd } : {}),\n\t\t...(booleanField(frontmatter, \"worktree\") === true ? { worktree: true } : {}),\n\t\t...(chain ? { chain } : {}),\n\t};\n}\n\nexport function discoverPromptWorkflows(cwd: string): PromptWorkflow[] {\n\tconst workflows = new Map<string, PromptWorkflow>();\n\tfor (const file of readPromptFiles(cwd)) {\n\t\tconst workflow = loadPromptWorkflow(file);\n\t\tif (workflow) workflows.set(workflow.name, workflow);\n\t}\n\treturn [...workflows.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction shellWords(input: string): string[] {\n\tconst words: string[] = [];\n\tlet current = \"\";\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const ch of input) {\n\t\tif (escaped) {\n\t\t\tcurrent += ch;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\telse current += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (current) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t}\n\tif (current) words.push(current);\n\treturn words;\n}\n\nfunction substituteArgs(template: string, args: string[]): string {\n\tconst all = args.join(\" \");\n\treturn template\n\t\t.replace(/\\$ARGUMENTS/g, all)\n\t\t.replace(/\\$@/g, all)\n\t\t.replace(/\\$\\{(\\d+):-([^}]*)\\}/g, (_match, index: string, fallback: string) => args[Number(index) - 1] || fallback)\n\t\t.replace(/\\$(\\d+)/g, (_match, index: string) => args[Number(index) - 1] ?? \"\");\n}\n\nfunction parseRuntimeOptions(words: string[]): { args: string[]; agentOverride?: string; fork?: boolean; fresh?: boolean; worktree?: boolean; bg?: boolean } {\n\tconst args: string[] = [];\n\tlet agentOverride: string | undefined;\n\tlet fork = false;\n\tlet fresh = false;\n\tlet worktree = false;\n\tlet bg = false;\n\tfor (let i = 0; i < words.length; i++) {\n\t\tconst word = words[i]!;\n\t\tif (word === \"--fork\") {\n\t\t\tfork = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--fresh\") {\n\t\t\tfresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--worktree\") {\n\t\t\tworktree = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--bg\" || word === \"--async\") {\n\t\t\tbg = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--subagent\") {\n\t\t\tagentOverride = words[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst eq = word.match(/^--subagent(?:=|:)(.+)$/);\n\t\tif (eq) {\n\t\t\tagentOverride = eq[1];\n\t\t\tcontinue;\n\t\t}\n\t\targs.push(word);\n\t}\n\treturn { args, agentOverride, fork, fresh, worktree, bg };\n}\n\nfunction splitChainDeclaration(input: string): { declaration: string; argsText: string } {\n\tconst delimiter = input.indexOf(\" -- \");\n\tif (delimiter === -1) return { declaration: input.trim(), argsText: \"\" };\n\treturn { declaration: input.slice(0, delimiter).trim(), argsText: input.slice(delimiter + 4).trim() };\n}\n\nfunction splitPromptChain(input: string): string[] {\n\treturn input.split(\" -> \").map((part) => part.trim()).filter(Boolean);\n}\n\nfunction workflowParams(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): SubagentParamsLike {\n\tconst task = substituteArgs(workflow.body, args).trim();\n\tconst context = runtime.fork ? \"fork\" : runtime.fresh ? \"fresh\" : workflow.context;\n\treturn {\n\t\tagent: runtime.agentOverride ?? workflow.agent,\n\t\ttask,\n\t\tclarify: false,\n\t\tagentScope: \"both\",\n\t\t...(context ? { context } : {}),\n\t\t...(workflow.model ? { model: workflow.model } : {}),\n\t\t...(workflow.skill !== undefined ? { skill: workflow.skill } : {}),\n\t\t...(workflow.cwd ? { cwd: workflow.cwd } : {}),\n\t\t...(runtime.worktree || workflow.worktree ? { worktree: true } : {}),\n\t\t...(runtime.bg ? { async: true } : {}),\n\t};\n}\n\nfunction workflowChainStep(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): ChainStep {\n\tconst params = workflowParams(workflow, args, runtime);\n\treturn {\n\t\tagent: params.agent ?? \"delegate\",\n\t\ttask: params.task,\n\t\t...(params.model ? { model: params.model } : {}),\n\t\t...(params.skill !== undefined ? { skill: params.skill } : {}),\n\t\t...(params.cwd ? { cwd: params.cwd } : {}),\n\t};\n}\n\nfunction findWorkflow(workflows: PromptWorkflow[], name: string): PromptWorkflow | undefined {\n\treturn workflows.find((workflow) => workflow.name === name);\n}\n\nfunction formatWorkflowList(workflows: PromptWorkflow[]): string {\n\tif (workflows.length === 0) return \"No prompt workflows found in package, user, or project prompts.\";\n\treturn [\n\t\t\"Prompt workflows:\",\n\t\t...workflows.map((workflow) => `- ${workflow.name}: ${workflow.description} (${workflow.filePath})`),\n\t].join(\"\\n\");\n}\n\nexport function registerPromptWorkflowCommands(input: {\n\tpi: ExtensionAPI;\n\trun: PromptWorkflowRunner;\n}): void {\n\tconst { pi, run } = input;\n\n\tpi.registerCommand(\"prompt-workflow\", {\n\t\tdescription: \"Run a prompt template through native pi-subagents: /prompt-workflow <name> [args]\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst words = shellWords(rawArgs);\n\t\t\tconst name = words.shift();\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!name || name === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\tif (!workflow) {\n\t\t\t\tctx.ui.notify(`Unknown prompt workflow: ${name}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(words);\n\t\t\ttry {\n\t\t\t\tif (workflow.chain) {\n\t\t\t\t\tconst chainNames = splitPromptChain(workflow.chain);\n\t\t\t\t\tconst chain = chainNames.map((stepName) => {\n\t\t\t\t\t\tconst step = findWorkflow(workflows, stepName);\n\t\t\t\t\t\tif (!step) throw new Error(`Unknown prompt workflow in chain '${workflow.name}': ${stepName}`);\n\t\t\t\t\t\treturn workflowChainStep(step, runtime.args, runtime);\n\t\t\t\t\t});\n\t\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait run(workflowParams(workflow, runtime.args, runtime), ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.registerCommand(\"chain-prompts\", {\n\t\tdescription: \"Run prompt templates as a native subagent chain: /chain-prompts analyze -> fix -- args\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst { declaration, argsText } = splitChainDeclaration(rawArgs);\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!declaration || declaration === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(shellWords(argsText));\n\t\t\tconst names = splitPromptChain(declaration);\n\t\t\tif (names.length === 0) {\n\t\t\t\tctx.ui.notify(\"Usage: /chain-prompts prompt-a -> prompt-b -- args\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst chain = names.map((name) => {\n\t\t\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\t\t\tif (!workflow) throw new Error(`Unknown prompt workflow: ${name}`);\n\t\t\t\t\treturn workflowChainStep(workflow, runtime.args, runtime);\n\t\t\t\t});\n\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"prompt-workflows.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/slash/prompt-workflows.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAIlF,UAAU,cAAc;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC;IAClC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,KAAK,oBAAoB,GAAG,CAAC,MAAM,EAAE,kBAAkB,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AA+FjG,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,EAAE,CAOrE;AA0ID,wBAAgB,8BAA8B,CAAC,KAAK,EAAE;IACrD,EAAE,EAAE,YAAY,CAAC;IACjB,GAAG,EAAE,oBAAoB,CAAC;CAC1B,GAAG,IAAI,CAgEP","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ExtensionAPI, ExtensionContext } from \"@ashx-j/lunr\";\nimport { parseFrontmatter } from \"../agents/frontmatter.ts\";\nimport type { SubagentParamsLike } from \"../runs/foreground/subagent-executor.ts\";\nimport type { ChainStep } from \"../shared/settings.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\ninterface PromptWorkflow {\n\tname: string;\n\tdescription: string;\n\tbody: string;\n\tfilePath: string;\n\tagent: string;\n\tcontext?: \"fresh\" | \"fork\";\n\tmodel?: string;\n\tskill?: string | string[] | false;\n\tcwd?: string;\n\tworktree?: boolean;\n\tchain?: string;\n}\n\ntype PromptWorkflowRunner = (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<void>;\n\nconst RESERVED_COMMAND_NAMES = new Set([\n\t\"chain-prompts\",\n\t\"prompt-workflow\",\n\t\"run\",\n\t\"chain\",\n\t\"parallel\",\n\t\"run-chain\",\n\t\"subagents-doctor\",\n\t\"subagents-models\",\n]);\n\nfunction packagePromptsDir(): string {\n\treturn path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"prompts\");\n}\n\nfunction promptDirs(cwd: string): string[] {\n\treturn [\n\t\tpackagePromptsDir(),\n\t\tpath.join(getAgentDir(), \"prompts\"),\n\t\tpath.join(getProjectConfigDir(cwd), \"prompts\"),\n\t];\n}\n\nfunction readPromptFiles(cwd: string): string[] {\n\tconst files: string[] = [];\n\tfor (const dir of promptDirs(cwd)) {\n\t\tlet entries: fs.Dirent[];\n\t\ttry {\n\t\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".md\")) files.push(path.join(dir, entry.name));\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction firstNonEmptyLine(value: string): string {\n\treturn value.split(/\\r?\\n/).map((line) => line.trim()).find(Boolean) ?? \"Prompt workflow\";\n}\n\nfunction stringField(frontmatter: Record<string, string>, key: string): string | undefined {\n\tconst value = frontmatter[key]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction booleanField(frontmatter: Record<string, string>, key: string): boolean | undefined {\n\tconst value = frontmatter[key]?.trim().toLowerCase();\n\tif (value === \"true\" || value === \"yes\" || value === \"1\") return true;\n\tif (value === \"false\" || value === \"no\" || value === \"0\") return false;\n\treturn undefined;\n}\n\nfunction parseSkill(value: string | undefined): string | string[] | false | undefined {\n\tif (!value) return undefined;\n\tif (value === \"false\") return false;\n\tconst parts = value.split(\",\").map((part) => part.trim()).filter(Boolean);\n\treturn parts.length > 1 ? parts : parts[0];\n}\n\nfunction parseAgent(frontmatter: Record<string, string>): string {\n\tconst subagent = stringField(frontmatter, \"subagent\");\n\tif (!subagent || subagent === \"true\") return \"delegate\";\n\treturn subagent;\n}\n\nfunction loadPromptWorkflow(filePath: string): PromptWorkflow | undefined {\n\tconst content = fs.readFileSync(filePath, \"utf-8\");\n\tconst { frontmatter, body } = parseFrontmatter(content);\n\tconst name = path.basename(filePath, \".md\");\n\tif (!name || RESERVED_COMMAND_NAMES.has(name)) return undefined;\n\tconst model = stringField(frontmatter, \"model\");\n\tconst skill = parseSkill(stringField(frontmatter, \"skill\"));\n\tconst cwd = stringField(frontmatter, \"cwd\");\n\tconst chain = stringField(frontmatter, \"chain\");\n\treturn {\n\t\tname,\n\t\tdescription: stringField(frontmatter, \"description\") ?? firstNonEmptyLine(body),\n\t\tbody,\n\t\tfilePath,\n\t\tagent: parseAgent(frontmatter),\n\t\t...(booleanField(frontmatter, \"inheritContext\") === true || booleanField(frontmatter, \"fork\") === true ? { context: \"fork\" as const } : {}),\n\t\t...(booleanField(frontmatter, \"fresh\") === true ? { context: \"fresh\" as const } : {}),\n\t\t...(model ? { model } : {}),\n\t\t...(skill !== undefined ? { skill } : {}),\n\t\t...(cwd ? { cwd } : {}),\n\t\t...(booleanField(frontmatter, \"worktree\") === true ? { worktree: true } : {}),\n\t\t...(chain ? { chain } : {}),\n\t};\n}\n\nexport function discoverPromptWorkflows(cwd: string): PromptWorkflow[] {\n\tconst workflows = new Map<string, PromptWorkflow>();\n\tfor (const file of readPromptFiles(cwd)) {\n\t\tconst workflow = loadPromptWorkflow(file);\n\t\tif (workflow) workflows.set(workflow.name, workflow);\n\t}\n\treturn [...workflows.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction shellWords(input: string): string[] {\n\tconst words: string[] = [];\n\tlet current = \"\";\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const ch of input) {\n\t\tif (escaped) {\n\t\t\tcurrent += ch;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\telse current += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (current) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t}\n\tif (current) words.push(current);\n\treturn words;\n}\n\nfunction substituteArgs(template: string, args: string[]): string {\n\tconst all = args.join(\" \");\n\treturn template\n\t\t.replace(/\\$ARGUMENTS/g, all)\n\t\t.replace(/\\$@/g, all)\n\t\t.replace(/\\$\\{(\\d+):-([^}]*)\\}/g, (_match, index: string, fallback: string) => args[Number(index) - 1] || fallback)\n\t\t.replace(/\\$(\\d+)/g, (_match, index: string) => args[Number(index) - 1] ?? \"\");\n}\n\nfunction parseRuntimeOptions(words: string[]): { args: string[]; agentOverride?: string; fork?: boolean; fresh?: boolean; worktree?: boolean; bg?: boolean } {\n\tconst args: string[] = [];\n\tlet agentOverride: string | undefined;\n\tlet fork = false;\n\tlet fresh = false;\n\tlet worktree = false;\n\tlet bg = false;\n\tfor (let i = 0; i < words.length; i++) {\n\t\tconst word = words[i]!;\n\t\tif (word === \"--fork\") {\n\t\t\tfork = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--fresh\") {\n\t\t\tfresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--worktree\") {\n\t\t\tworktree = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--bg\" || word === \"--async\") {\n\t\t\tbg = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--subagent\") {\n\t\t\tagentOverride = words[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst eq = word.match(/^--subagent(?:=|:)(.+)$/);\n\t\tif (eq) {\n\t\t\tagentOverride = eq[1];\n\t\t\tcontinue;\n\t\t}\n\t\targs.push(word);\n\t}\n\treturn { args, agentOverride, fork, fresh, worktree, bg };\n}\n\nfunction splitChainDeclaration(input: string): { declaration: string; argsText: string } {\n\tconst delimiter = input.indexOf(\" -- \");\n\tif (delimiter === -1) return { declaration: input.trim(), argsText: \"\" };\n\treturn { declaration: input.slice(0, delimiter).trim(), argsText: input.slice(delimiter + 4).trim() };\n}\n\nfunction splitPromptChain(input: string): string[] {\n\treturn input.split(\" -> \").map((part) => part.trim()).filter(Boolean);\n}\n\nfunction workflowParams(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): SubagentParamsLike {\n\tconst task = substituteArgs(workflow.body, args).trim();\n\t// lunr: --fork is parsed so it is not a task word; children always start fresh.\n\tconst context = \"fresh\";\n\treturn {\n\t\tagent: runtime.agentOverride ?? workflow.agent,\n\t\ttask,\n\t\tclarify: false,\n\t\tagentScope: \"both\",\n\t\t...(context ? { context } : {}),\n\t\t...(workflow.model ? { model: workflow.model } : {}),\n\t\t...(workflow.skill !== undefined ? { skill: workflow.skill } : {}),\n\t\t...(workflow.cwd ? { cwd: workflow.cwd } : {}),\n\t\t...(runtime.worktree || workflow.worktree ? { worktree: true } : {}),\n\t\t...(runtime.bg ? { async: true } : {}),\n\t};\n}\n\nfunction workflowChainStep(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): ChainStep {\n\tconst params = workflowParams(workflow, args, runtime);\n\treturn {\n\t\tagent: params.agent ?? \"delegate\",\n\t\ttask: params.task,\n\t\t...(params.model ? { model: params.model } : {}),\n\t\t...(params.skill !== undefined ? { skill: params.skill } : {}),\n\t\t...(params.cwd ? { cwd: params.cwd } : {}),\n\t};\n}\n\nfunction findWorkflow(workflows: PromptWorkflow[], name: string): PromptWorkflow | undefined {\n\treturn workflows.find((workflow) => workflow.name === name);\n}\n\nfunction formatWorkflowList(workflows: PromptWorkflow[]): string {\n\tif (workflows.length === 0) return \"No prompt workflows found in package, user, or project prompts.\";\n\treturn [\n\t\t\"Prompt workflows:\",\n\t\t...workflows.map((workflow) => `- ${workflow.name}: ${workflow.description} (${workflow.filePath})`),\n\t].join(\"\\n\");\n}\n\nexport function registerPromptWorkflowCommands(input: {\n\tpi: ExtensionAPI;\n\trun: PromptWorkflowRunner;\n}): void {\n\tconst { pi, run } = input;\n\n\tpi.registerCommand(\"prompt-workflow\", {\n\t\tdescription: \"Run a prompt template through native pi-subagents: /prompt-workflow <name> [args]\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst words = shellWords(rawArgs);\n\t\t\tconst name = words.shift();\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!name || name === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\tif (!workflow) {\n\t\t\t\tctx.ui.notify(`Unknown prompt workflow: ${name}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(words);\n\t\t\ttry {\n\t\t\t\tif (workflow.chain) {\n\t\t\t\t\tconst chainNames = splitPromptChain(workflow.chain);\n\t\t\t\t\tconst chain = chainNames.map((stepName) => {\n\t\t\t\t\t\tconst step = findWorkflow(workflows, stepName);\n\t\t\t\t\t\tif (!step) throw new Error(`Unknown prompt workflow in chain '${workflow.name}': ${stepName}`);\n\t\t\t\t\t\treturn workflowChainStep(step, runtime.args, runtime);\n\t\t\t\t\t});\n\t\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait run(workflowParams(workflow, runtime.args, runtime), ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.registerCommand(\"chain-prompts\", {\n\t\tdescription: \"Run prompt templates as a native subagent chain: /chain-prompts analyze -> fix -- args\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst { declaration, argsText } = splitChainDeclaration(rawArgs);\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!declaration || declaration === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(shellWords(argsText));\n\t\t\tconst names = splitPromptChain(declaration);\n\t\t\tif (names.length === 0) {\n\t\t\t\tctx.ui.notify(\"Usage: /chain-prompts prompt-a -> prompt-b -- args\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst chain = names.map((name) => {\n\t\t\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\t\t\tif (!workflow) throw new Error(`Unknown prompt workflow: ${name}`);\n\t\t\t\t\treturn workflowChainStep(workflow, runtime.args, runtime);\n\t\t\t\t});\n\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
@@ -200,7 +200,8 @@ function splitPromptChain(input) {
200
200
  }
201
201
  function workflowParams(workflow, args, runtime) {
202
202
  const task = substituteArgs(workflow.body, args).trim();
203
- const context = runtime.fork ? "fork" : runtime.fresh ? "fresh" : workflow.context;
203
+ // lunr: --fork is parsed so it is not a task word; children always start fresh.
204
+ const context = "fresh";
204
205
  return {
205
206
  agent: runtime.agentOverride ?? workflow.agent,
206
207
  task,
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-workflows.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/slash/prompt-workflows.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG5D,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAkBtE,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACtC,eAAe;IACf,iBAAiB;IACjB,KAAK;IACL,OAAO;IACP,UAAU;IACV,WAAW;IACX,kBAAkB;IAClB,kBAAkB;CAClB,CAAC,CAAC;AAEH,SAAS,iBAAiB,GAAW;IACpC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;AAAA,CACzF;AAED,SAAS,UAAU,CAAC,GAAW,EAAY;IAC1C,OAAO;QACN,iBAAiB,EAAE;QACnB,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,CAAC;QACnC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,SAAS,CAAC;KAC9C,CAAC;AAAA,CACF;AAED,SAAS,eAAe,CAAC,GAAW,EAAY;IAC/C,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,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O,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;YACrI,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;YAChF,CAAC;QAAA,CACD;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ExtensionAPI, ExtensionContext } from \"@ashx-j/lunr\";\nimport { parseFrontmatter } from \"../agents/frontmatter.ts\";\nimport type { SubagentParamsLike } from \"../runs/foreground/subagent-executor.ts\";\nimport type { ChainStep } from \"../shared/settings.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\ninterface PromptWorkflow {\n\tname: string;\n\tdescription: string;\n\tbody: string;\n\tfilePath: string;\n\tagent: string;\n\tcontext?: \"fresh\" | \"fork\";\n\tmodel?: string;\n\tskill?: string | string[] | false;\n\tcwd?: string;\n\tworktree?: boolean;\n\tchain?: string;\n}\n\ntype PromptWorkflowRunner = (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<void>;\n\nconst RESERVED_COMMAND_NAMES = new Set([\n\t\"chain-prompts\",\n\t\"prompt-workflow\",\n\t\"run\",\n\t\"chain\",\n\t\"parallel\",\n\t\"run-chain\",\n\t\"subagents-doctor\",\n\t\"subagents-models\",\n]);\n\nfunction packagePromptsDir(): string {\n\treturn path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"prompts\");\n}\n\nfunction promptDirs(cwd: string): string[] {\n\treturn [\n\t\tpackagePromptsDir(),\n\t\tpath.join(getAgentDir(), \"prompts\"),\n\t\tpath.join(getProjectConfigDir(cwd), \"prompts\"),\n\t];\n}\n\nfunction readPromptFiles(cwd: string): string[] {\n\tconst files: string[] = [];\n\tfor (const dir of promptDirs(cwd)) {\n\t\tlet entries: fs.Dirent[];\n\t\ttry {\n\t\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".md\")) files.push(path.join(dir, entry.name));\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction firstNonEmptyLine(value: string): string {\n\treturn value.split(/\\r?\\n/).map((line) => line.trim()).find(Boolean) ?? \"Prompt workflow\";\n}\n\nfunction stringField(frontmatter: Record<string, string>, key: string): string | undefined {\n\tconst value = frontmatter[key]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction booleanField(frontmatter: Record<string, string>, key: string): boolean | undefined {\n\tconst value = frontmatter[key]?.trim().toLowerCase();\n\tif (value === \"true\" || value === \"yes\" || value === \"1\") return true;\n\tif (value === \"false\" || value === \"no\" || value === \"0\") return false;\n\treturn undefined;\n}\n\nfunction parseSkill(value: string | undefined): string | string[] | false | undefined {\n\tif (!value) return undefined;\n\tif (value === \"false\") return false;\n\tconst parts = value.split(\",\").map((part) => part.trim()).filter(Boolean);\n\treturn parts.length > 1 ? parts : parts[0];\n}\n\nfunction parseAgent(frontmatter: Record<string, string>): string {\n\tconst subagent = stringField(frontmatter, \"subagent\");\n\tif (!subagent || subagent === \"true\") return \"delegate\";\n\treturn subagent;\n}\n\nfunction loadPromptWorkflow(filePath: string): PromptWorkflow | undefined {\n\tconst content = fs.readFileSync(filePath, \"utf-8\");\n\tconst { frontmatter, body } = parseFrontmatter(content);\n\tconst name = path.basename(filePath, \".md\");\n\tif (!name || RESERVED_COMMAND_NAMES.has(name)) return undefined;\n\tconst model = stringField(frontmatter, \"model\");\n\tconst skill = parseSkill(stringField(frontmatter, \"skill\"));\n\tconst cwd = stringField(frontmatter, \"cwd\");\n\tconst chain = stringField(frontmatter, \"chain\");\n\treturn {\n\t\tname,\n\t\tdescription: stringField(frontmatter, \"description\") ?? firstNonEmptyLine(body),\n\t\tbody,\n\t\tfilePath,\n\t\tagent: parseAgent(frontmatter),\n\t\t...(booleanField(frontmatter, \"inheritContext\") === true || booleanField(frontmatter, \"fork\") === true ? { context: \"fork\" as const } : {}),\n\t\t...(booleanField(frontmatter, \"fresh\") === true ? { context: \"fresh\" as const } : {}),\n\t\t...(model ? { model } : {}),\n\t\t...(skill !== undefined ? { skill } : {}),\n\t\t...(cwd ? { cwd } : {}),\n\t\t...(booleanField(frontmatter, \"worktree\") === true ? { worktree: true } : {}),\n\t\t...(chain ? { chain } : {}),\n\t};\n}\n\nexport function discoverPromptWorkflows(cwd: string): PromptWorkflow[] {\n\tconst workflows = new Map<string, PromptWorkflow>();\n\tfor (const file of readPromptFiles(cwd)) {\n\t\tconst workflow = loadPromptWorkflow(file);\n\t\tif (workflow) workflows.set(workflow.name, workflow);\n\t}\n\treturn [...workflows.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction shellWords(input: string): string[] {\n\tconst words: string[] = [];\n\tlet current = \"\";\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const ch of input) {\n\t\tif (escaped) {\n\t\t\tcurrent += ch;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\telse current += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (current) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t}\n\tif (current) words.push(current);\n\treturn words;\n}\n\nfunction substituteArgs(template: string, args: string[]): string {\n\tconst all = args.join(\" \");\n\treturn template\n\t\t.replace(/\\$ARGUMENTS/g, all)\n\t\t.replace(/\\$@/g, all)\n\t\t.replace(/\\$\\{(\\d+):-([^}]*)\\}/g, (_match, index: string, fallback: string) => args[Number(index) - 1] || fallback)\n\t\t.replace(/\\$(\\d+)/g, (_match, index: string) => args[Number(index) - 1] ?? \"\");\n}\n\nfunction parseRuntimeOptions(words: string[]): { args: string[]; agentOverride?: string; fork?: boolean; fresh?: boolean; worktree?: boolean; bg?: boolean } {\n\tconst args: string[] = [];\n\tlet agentOverride: string | undefined;\n\tlet fork = false;\n\tlet fresh = false;\n\tlet worktree = false;\n\tlet bg = false;\n\tfor (let i = 0; i < words.length; i++) {\n\t\tconst word = words[i]!;\n\t\tif (word === \"--fork\") {\n\t\t\tfork = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--fresh\") {\n\t\t\tfresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--worktree\") {\n\t\t\tworktree = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--bg\" || word === \"--async\") {\n\t\t\tbg = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--subagent\") {\n\t\t\tagentOverride = words[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst eq = word.match(/^--subagent(?:=|:)(.+)$/);\n\t\tif (eq) {\n\t\t\tagentOverride = eq[1];\n\t\t\tcontinue;\n\t\t}\n\t\targs.push(word);\n\t}\n\treturn { args, agentOverride, fork, fresh, worktree, bg };\n}\n\nfunction splitChainDeclaration(input: string): { declaration: string; argsText: string } {\n\tconst delimiter = input.indexOf(\" -- \");\n\tif (delimiter === -1) return { declaration: input.trim(), argsText: \"\" };\n\treturn { declaration: input.slice(0, delimiter).trim(), argsText: input.slice(delimiter + 4).trim() };\n}\n\nfunction splitPromptChain(input: string): string[] {\n\treturn input.split(\" -> \").map((part) => part.trim()).filter(Boolean);\n}\n\nfunction workflowParams(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): SubagentParamsLike {\n\tconst task = substituteArgs(workflow.body, args).trim();\n\tconst context = runtime.fork ? \"fork\" : runtime.fresh ? \"fresh\" : workflow.context;\n\treturn {\n\t\tagent: runtime.agentOverride ?? workflow.agent,\n\t\ttask,\n\t\tclarify: false,\n\t\tagentScope: \"both\",\n\t\t...(context ? { context } : {}),\n\t\t...(workflow.model ? { model: workflow.model } : {}),\n\t\t...(workflow.skill !== undefined ? { skill: workflow.skill } : {}),\n\t\t...(workflow.cwd ? { cwd: workflow.cwd } : {}),\n\t\t...(runtime.worktree || workflow.worktree ? { worktree: true } : {}),\n\t\t...(runtime.bg ? { async: true } : {}),\n\t};\n}\n\nfunction workflowChainStep(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): ChainStep {\n\tconst params = workflowParams(workflow, args, runtime);\n\treturn {\n\t\tagent: params.agent ?? \"delegate\",\n\t\ttask: params.task,\n\t\t...(params.model ? { model: params.model } : {}),\n\t\t...(params.skill !== undefined ? { skill: params.skill } : {}),\n\t\t...(params.cwd ? { cwd: params.cwd } : {}),\n\t};\n}\n\nfunction findWorkflow(workflows: PromptWorkflow[], name: string): PromptWorkflow | undefined {\n\treturn workflows.find((workflow) => workflow.name === name);\n}\n\nfunction formatWorkflowList(workflows: PromptWorkflow[]): string {\n\tif (workflows.length === 0) return \"No prompt workflows found in package, user, or project prompts.\";\n\treturn [\n\t\t\"Prompt workflows:\",\n\t\t...workflows.map((workflow) => `- ${workflow.name}: ${workflow.description} (${workflow.filePath})`),\n\t].join(\"\\n\");\n}\n\nexport function registerPromptWorkflowCommands(input: {\n\tpi: ExtensionAPI;\n\trun: PromptWorkflowRunner;\n}): void {\n\tconst { pi, run } = input;\n\n\tpi.registerCommand(\"prompt-workflow\", {\n\t\tdescription: \"Run a prompt template through native pi-subagents: /prompt-workflow <name> [args]\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst words = shellWords(rawArgs);\n\t\t\tconst name = words.shift();\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!name || name === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\tif (!workflow) {\n\t\t\t\tctx.ui.notify(`Unknown prompt workflow: ${name}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(words);\n\t\t\ttry {\n\t\t\t\tif (workflow.chain) {\n\t\t\t\t\tconst chainNames = splitPromptChain(workflow.chain);\n\t\t\t\t\tconst chain = chainNames.map((stepName) => {\n\t\t\t\t\t\tconst step = findWorkflow(workflows, stepName);\n\t\t\t\t\t\tif (!step) throw new Error(`Unknown prompt workflow in chain '${workflow.name}': ${stepName}`);\n\t\t\t\t\t\treturn workflowChainStep(step, runtime.args, runtime);\n\t\t\t\t\t});\n\t\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait run(workflowParams(workflow, runtime.args, runtime), ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.registerCommand(\"chain-prompts\", {\n\t\tdescription: \"Run prompt templates as a native subagent chain: /chain-prompts analyze -> fix -- args\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst { declaration, argsText } = splitChainDeclaration(rawArgs);\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!declaration || declaration === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(shellWords(argsText));\n\t\t\tconst names = splitPromptChain(declaration);\n\t\t\tif (names.length === 0) {\n\t\t\t\tctx.ui.notify(\"Usage: /chain-prompts prompt-a -> prompt-b -- args\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst chain = names.map((name) => {\n\t\t\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\t\t\tif (!workflow) throw new Error(`Unknown prompt workflow: ${name}`);\n\t\t\t\t\treturn workflowChainStep(workflow, runtime.args, runtime);\n\t\t\t\t});\n\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n}\n"]}
1
+ {"version":3,"file":"prompt-workflows.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/slash/prompt-workflows.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG5D,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAkBtE,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACtC,eAAe;IACf,iBAAiB;IACjB,KAAK;IACL,OAAO;IACP,UAAU;IACV,WAAW;IACX,kBAAkB;IAClB,kBAAkB;CAClB,CAAC,CAAC;AAEH,SAAS,iBAAiB,GAAW;IACpC,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CA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iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;gBAAA,CAC1D,CAAC,CAAC;gBACH,MAAM,GAAG,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;YACrI,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;YAChF,CAAC;QAAA,CACD;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ExtensionAPI, ExtensionContext } from \"@ashx-j/lunr\";\nimport { parseFrontmatter } from \"../agents/frontmatter.ts\";\nimport type { SubagentParamsLike } from \"../runs/foreground/subagent-executor.ts\";\nimport type { ChainStep } from \"../shared/settings.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\ninterface PromptWorkflow {\n\tname: string;\n\tdescription: string;\n\tbody: string;\n\tfilePath: string;\n\tagent: string;\n\tcontext?: \"fresh\" | \"fork\";\n\tmodel?: string;\n\tskill?: string | string[] | false;\n\tcwd?: string;\n\tworktree?: boolean;\n\tchain?: string;\n}\n\ntype PromptWorkflowRunner = (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<void>;\n\nconst RESERVED_COMMAND_NAMES = new Set([\n\t\"chain-prompts\",\n\t\"prompt-workflow\",\n\t\"run\",\n\t\"chain\",\n\t\"parallel\",\n\t\"run-chain\",\n\t\"subagents-doctor\",\n\t\"subagents-models\",\n]);\n\nfunction packagePromptsDir(): string {\n\treturn path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"prompts\");\n}\n\nfunction promptDirs(cwd: string): string[] {\n\treturn [\n\t\tpackagePromptsDir(),\n\t\tpath.join(getAgentDir(), \"prompts\"),\n\t\tpath.join(getProjectConfigDir(cwd), \"prompts\"),\n\t];\n}\n\nfunction readPromptFiles(cwd: string): string[] {\n\tconst files: string[] = [];\n\tfor (const dir of promptDirs(cwd)) {\n\t\tlet entries: fs.Dirent[];\n\t\ttry {\n\t\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".md\")) files.push(path.join(dir, entry.name));\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction firstNonEmptyLine(value: string): string {\n\treturn value.split(/\\r?\\n/).map((line) => line.trim()).find(Boolean) ?? \"Prompt workflow\";\n}\n\nfunction stringField(frontmatter: Record<string, string>, key: string): string | undefined {\n\tconst value = frontmatter[key]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction booleanField(frontmatter: Record<string, string>, key: string): boolean | undefined {\n\tconst value = frontmatter[key]?.trim().toLowerCase();\n\tif (value === \"true\" || value === \"yes\" || value === \"1\") return true;\n\tif (value === \"false\" || value === \"no\" || value === \"0\") return false;\n\treturn undefined;\n}\n\nfunction parseSkill(value: string | undefined): string | string[] | false | undefined {\n\tif (!value) return undefined;\n\tif (value === \"false\") return false;\n\tconst parts = value.split(\",\").map((part) => part.trim()).filter(Boolean);\n\treturn parts.length > 1 ? parts : parts[0];\n}\n\nfunction parseAgent(frontmatter: Record<string, string>): string {\n\tconst subagent = stringField(frontmatter, \"subagent\");\n\tif (!subagent || subagent === \"true\") return \"delegate\";\n\treturn subagent;\n}\n\nfunction loadPromptWorkflow(filePath: string): PromptWorkflow | undefined {\n\tconst content = fs.readFileSync(filePath, \"utf-8\");\n\tconst { frontmatter, body } = parseFrontmatter(content);\n\tconst name = path.basename(filePath, \".md\");\n\tif (!name || RESERVED_COMMAND_NAMES.has(name)) return undefined;\n\tconst model = stringField(frontmatter, \"model\");\n\tconst skill = parseSkill(stringField(frontmatter, \"skill\"));\n\tconst cwd = stringField(frontmatter, \"cwd\");\n\tconst chain = stringField(frontmatter, \"chain\");\n\treturn {\n\t\tname,\n\t\tdescription: stringField(frontmatter, \"description\") ?? firstNonEmptyLine(body),\n\t\tbody,\n\t\tfilePath,\n\t\tagent: parseAgent(frontmatter),\n\t\t...(booleanField(frontmatter, \"inheritContext\") === true || booleanField(frontmatter, \"fork\") === true ? { context: \"fork\" as const } : {}),\n\t\t...(booleanField(frontmatter, \"fresh\") === true ? { context: \"fresh\" as const } : {}),\n\t\t...(model ? { model } : {}),\n\t\t...(skill !== undefined ? { skill } : {}),\n\t\t...(cwd ? { cwd } : {}),\n\t\t...(booleanField(frontmatter, \"worktree\") === true ? { worktree: true } : {}),\n\t\t...(chain ? { chain } : {}),\n\t};\n}\n\nexport function discoverPromptWorkflows(cwd: string): PromptWorkflow[] {\n\tconst workflows = new Map<string, PromptWorkflow>();\n\tfor (const file of readPromptFiles(cwd)) {\n\t\tconst workflow = loadPromptWorkflow(file);\n\t\tif (workflow) workflows.set(workflow.name, workflow);\n\t}\n\treturn [...workflows.values()].sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction shellWords(input: string): string[] {\n\tconst words: string[] = [];\n\tlet current = \"\";\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const ch of input) {\n\t\tif (escaped) {\n\t\t\tcurrent += ch;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\telse current += ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"'\" || ch === '\"') {\n\t\t\tquote = ch;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(ch)) {\n\t\t\tif (current) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t}\n\tif (current) words.push(current);\n\treturn words;\n}\n\nfunction substituteArgs(template: string, args: string[]): string {\n\tconst all = args.join(\" \");\n\treturn template\n\t\t.replace(/\\$ARGUMENTS/g, all)\n\t\t.replace(/\\$@/g, all)\n\t\t.replace(/\\$\\{(\\d+):-([^}]*)\\}/g, (_match, index: string, fallback: string) => args[Number(index) - 1] || fallback)\n\t\t.replace(/\\$(\\d+)/g, (_match, index: string) => args[Number(index) - 1] ?? \"\");\n}\n\nfunction parseRuntimeOptions(words: string[]): { args: string[]; agentOverride?: string; fork?: boolean; fresh?: boolean; worktree?: boolean; bg?: boolean } {\n\tconst args: string[] = [];\n\tlet agentOverride: string | undefined;\n\tlet fork = false;\n\tlet fresh = false;\n\tlet worktree = false;\n\tlet bg = false;\n\tfor (let i = 0; i < words.length; i++) {\n\t\tconst word = words[i]!;\n\t\tif (word === \"--fork\") {\n\t\t\tfork = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--fresh\") {\n\t\t\tfresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--worktree\") {\n\t\t\tworktree = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--bg\" || word === \"--async\") {\n\t\t\tbg = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (word === \"--subagent\") {\n\t\t\tagentOverride = words[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tconst eq = word.match(/^--subagent(?:=|:)(.+)$/);\n\t\tif (eq) {\n\t\t\tagentOverride = eq[1];\n\t\t\tcontinue;\n\t\t}\n\t\targs.push(word);\n\t}\n\treturn { args, agentOverride, fork, fresh, worktree, bg };\n}\n\nfunction splitChainDeclaration(input: string): { declaration: string; argsText: string } {\n\tconst delimiter = input.indexOf(\" -- \");\n\tif (delimiter === -1) return { declaration: input.trim(), argsText: \"\" };\n\treturn { declaration: input.slice(0, delimiter).trim(), argsText: input.slice(delimiter + 4).trim() };\n}\n\nfunction splitPromptChain(input: string): string[] {\n\treturn input.split(\" -> \").map((part) => part.trim()).filter(Boolean);\n}\n\nfunction workflowParams(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): SubagentParamsLike {\n\tconst task = substituteArgs(workflow.body, args).trim();\n\t// lunr: --fork is parsed so it is not a task word; children always start fresh.\n\tconst context = \"fresh\";\n\treturn {\n\t\tagent: runtime.agentOverride ?? workflow.agent,\n\t\ttask,\n\t\tclarify: false,\n\t\tagentScope: \"both\",\n\t\t...(context ? { context } : {}),\n\t\t...(workflow.model ? { model: workflow.model } : {}),\n\t\t...(workflow.skill !== undefined ? { skill: workflow.skill } : {}),\n\t\t...(workflow.cwd ? { cwd: workflow.cwd } : {}),\n\t\t...(runtime.worktree || workflow.worktree ? { worktree: true } : {}),\n\t\t...(runtime.bg ? { async: true } : {}),\n\t};\n}\n\nfunction workflowChainStep(workflow: PromptWorkflow, args: string[], runtime: ReturnType<typeof parseRuntimeOptions>): ChainStep {\n\tconst params = workflowParams(workflow, args, runtime);\n\treturn {\n\t\tagent: params.agent ?? \"delegate\",\n\t\ttask: params.task,\n\t\t...(params.model ? { model: params.model } : {}),\n\t\t...(params.skill !== undefined ? { skill: params.skill } : {}),\n\t\t...(params.cwd ? { cwd: params.cwd } : {}),\n\t};\n}\n\nfunction findWorkflow(workflows: PromptWorkflow[], name: string): PromptWorkflow | undefined {\n\treturn workflows.find((workflow) => workflow.name === name);\n}\n\nfunction formatWorkflowList(workflows: PromptWorkflow[]): string {\n\tif (workflows.length === 0) return \"No prompt workflows found in package, user, or project prompts.\";\n\treturn [\n\t\t\"Prompt workflows:\",\n\t\t...workflows.map((workflow) => `- ${workflow.name}: ${workflow.description} (${workflow.filePath})`),\n\t].join(\"\\n\");\n}\n\nexport function registerPromptWorkflowCommands(input: {\n\tpi: ExtensionAPI;\n\trun: PromptWorkflowRunner;\n}): void {\n\tconst { pi, run } = input;\n\n\tpi.registerCommand(\"prompt-workflow\", {\n\t\tdescription: \"Run a prompt template through native pi-subagents: /prompt-workflow <name> [args]\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst words = shellWords(rawArgs);\n\t\t\tconst name = words.shift();\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!name || name === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\tif (!workflow) {\n\t\t\t\tctx.ui.notify(`Unknown prompt workflow: ${name}`, \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(words);\n\t\t\ttry {\n\t\t\t\tif (workflow.chain) {\n\t\t\t\t\tconst chainNames = splitPromptChain(workflow.chain);\n\t\t\t\t\tconst chain = chainNames.map((stepName) => {\n\t\t\t\t\t\tconst step = findWorkflow(workflows, stepName);\n\t\t\t\t\t\tif (!step) throw new Error(`Unknown prompt workflow in chain '${workflow.name}': ${stepName}`);\n\t\t\t\t\t\treturn workflowChainStep(step, runtime.args, runtime);\n\t\t\t\t\t});\n\t\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait run(workflowParams(workflow, runtime.args, runtime), ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.registerCommand(\"chain-prompts\", {\n\t\tdescription: \"Run prompt templates as a native subagent chain: /chain-prompts analyze -> fix -- args\",\n\t\thandler: async (rawArgs, ctx) => {\n\t\t\tconst { declaration, argsText } = splitChainDeclaration(rawArgs);\n\t\t\tconst workflows = discoverPromptWorkflows(ctx.cwd);\n\t\t\tif (!declaration || declaration === \"list\") {\n\t\t\t\tpi.sendMessage({ content: formatWorkflowList(workflows), display: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst runtime = parseRuntimeOptions(shellWords(argsText));\n\t\t\tconst names = splitPromptChain(declaration);\n\t\t\tif (names.length === 0) {\n\t\t\t\tctx.ui.notify(\"Usage: /chain-prompts prompt-a -> prompt-b -- args\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst chain = names.map((name) => {\n\t\t\t\t\tconst workflow = findWorkflow(workflows, name);\n\t\t\t\t\tif (!workflow) throw new Error(`Unknown prompt workflow: ${name}`);\n\t\t\t\t\treturn workflowChainStep(workflow, runtime.args, runtime);\n\t\t\t\t});\n\t\t\t\tawait run({ chain, task: runtime.args.join(\" \"), clarify: false, agentScope: \"both\", ...(runtime.bg ? { async: true } : {}) }, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t}\n\t\t},\n\t});\n}\n"]}