@bastani/atomic 0.9.15 → 0.9.16-alpha.2

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 (151) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/README.md +8 -8
  4. package/dist/builtin/intercom/contact-supervisor-tool.ts +68 -32
  5. package/dist/builtin/intercom/index-heavy.ts +1 -0
  6. package/dist/builtin/intercom/index.ts +21 -15
  7. package/dist/builtin/intercom/intercom-tool.ts +66 -10
  8. package/dist/builtin/intercom/package.json +1 -1
  9. package/dist/builtin/intercom/parent-ask-handoff.ts +72 -0
  10. package/dist/builtin/mcp/package.json +1 -1
  11. package/dist/builtin/subagents/CHANGELOG.md +26 -0
  12. package/dist/builtin/subagents/README.md +37 -114
  13. package/dist/builtin/subagents/agents/worker.md +2 -2
  14. package/dist/builtin/subagents/package.json +1 -5
  15. package/dist/builtin/subagents/skills/subagent/SKILL.md +26 -103
  16. package/dist/builtin/subagents/src/extension/index.ts +5 -30
  17. package/dist/builtin/subagents/src/extension/notification-content.ts +1 -1
  18. package/dist/builtin/subagents/src/extension/schemas.ts +2 -14
  19. package/dist/builtin/subagents/src/extension/tool-description.ts +1 -4
  20. package/dist/builtin/subagents/src/extension/tool-rendering.ts +53 -0
  21. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +1 -54
  22. package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
  23. package/dist/builtin/subagents/src/runs/foreground/execution-parent-ask-handoff.ts +78 -0
  24. package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +7 -5
  25. package/dist/builtin/subagents/src/runs/foreground/notify.ts +5 -6
  26. package/dist/builtin/subagents/src/runs/foreground/parent-ask-output.ts +48 -0
  27. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst-display.ts +46 -0
  28. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-burst.ts +403 -0
  29. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +48 -9
  30. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +3 -1
  31. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-live-update.ts +11 -0
  32. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +164 -93
  33. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +36 -29
  34. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parent-ask-projection.ts +11 -0
  35. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +42 -17
  36. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +3 -121
  37. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +7 -2
  38. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +30 -257
  39. package/dist/builtin/subagents/src/runs/inprocess/control-status.ts +0 -34
  40. package/dist/builtin/subagents/src/runs/inprocess/index.ts +0 -12
  41. package/dist/builtin/subagents/src/runs/inprocess/prompt-behavior.ts +1 -1
  42. package/dist/builtin/subagents/src/runs/inprocess/runner.ts +2 -141
  43. package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +8 -0
  44. package/dist/builtin/subagents/src/shared/status-format.ts +3 -3
  45. package/dist/builtin/subagents/src/shared/types-config.ts +41 -0
  46. package/dist/builtin/subagents/src/shared/types-foreground-state.ts +7 -15
  47. package/dist/builtin/subagents/src/shared/types-results.ts +3 -1
  48. package/dist/builtin/subagents/src/shared/types-runtime.ts +1 -11
  49. package/dist/builtin/subagents/src/slash/slash-commands.ts +4 -468
  50. package/dist/builtin/subagents/src/tui/render-progress.ts +2 -2
  51. package/dist/builtin/subagents/src/tui/render-result-compact.ts +2 -2
  52. package/dist/builtin/subagents/src/tui/render-result.ts +38 -14
  53. package/dist/builtin/subagents/src/tui/render-status-progress.ts +1 -1
  54. package/dist/builtin/web-access/package.json +1 -1
  55. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  56. package/dist/builtin/workflows/README.md +1 -1
  57. package/dist/builtin/workflows/package.json +1 -1
  58. package/dist/builtin/workflows/skills/bro/LICENSE.txt +21 -0
  59. package/dist/builtin/workflows/skills/bro/SKILL.md +14 -0
  60. package/dist/builtin/workflows/skills/how/LICENSE.txt +21 -0
  61. package/dist/builtin/workflows/skills/how/SKILL.md +162 -0
  62. package/dist/builtin/workflows/skills/how/references/critic-prompt.md +59 -0
  63. package/dist/builtin/workflows/skills/how/references/critique-rubric.md +58 -0
  64. package/dist/builtin/workflows/skills/how/references/explainer-prompt.md +55 -0
  65. package/dist/builtin/workflows/skills/how/references/explorer-prompt.md +52 -0
  66. package/dist/builtin/workflows/skills/teach/LICENSE.txt +21 -0
  67. package/dist/builtin/workflows/skills/teach/SKILL.md +28 -0
  68. package/dist/builtin/workflows/skills/unslop/LICENSE.txt +21 -0
  69. package/dist/builtin/workflows/skills/unslop/SKILL.md +87 -0
  70. package/dist/builtin/workflows/skills/why/LICENSE.txt +21 -0
  71. package/dist/builtin/workflows/skills/why/SKILL.md +267 -0
  72. package/dist/builtin/workflows/skills/why/references/epistemics.md +144 -0
  73. package/dist/builtin/workflows/skills/why/references/investigator-prompt.md +103 -0
  74. package/dist/builtin/workflows/skills/why/references/source-playbook.md +17 -0
  75. package/dist/builtin/workflows/skills/why/references/sources/code-archaeology.md +88 -0
  76. package/dist/builtin/workflows/skills/why/references/sources/databricks.md +70 -0
  77. package/dist/builtin/workflows/skills/why/references/sources/datadog.md +99 -0
  78. package/dist/builtin/workflows/skills/why/references/sources/incident-postmortem.md +15 -0
  79. package/dist/builtin/workflows/skills/why/references/sources/linear.md +48 -0
  80. package/dist/builtin/workflows/skills/why/references/sources/notion.md +55 -0
  81. package/dist/builtin/workflows/skills/why/references/sources/sentry.md +100 -0
  82. package/dist/builtin/workflows/skills/why/references/sources/slack.md +54 -0
  83. package/dist/builtin/workflows/skills/why/references/synthesizer-prompt.md +135 -0
  84. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +548 -39
  85. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +529 -65
  86. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +30 -8
  87. package/dist/builtin/workflows/src/durable/dbos-local-postgres.ts +36 -3
  88. package/dist/builtin/workflows/src/durable/local-command.ts +68 -10
  89. package/dist/builtin/workflows/src/extension/companions.ts +1 -1
  90. package/dist/builtin/workflows/src/extension/dispatcher.ts +7 -1
  91. package/dist/builtin/workflows/src/extension/extension-factory.ts +2 -2
  92. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1094 -298
  93. package/dist/builtin/workflows/src/extension/public-types.ts +2 -2
  94. package/dist/builtin/workflows/src/extension/render-result.ts +16 -2
  95. package/dist/builtin/workflows/src/extension/runtime.ts +8 -1
  96. package/dist/builtin/workflows/src/extension/workflow-request-abort.ts +15 -0
  97. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +4 -3
  98. package/dist/builtin/workflows/src/extension/workflow-tool-registration.ts +107 -13
  99. package/dist/builtin/workflows/src/extension/workflow-tool.ts +22 -12
  100. package/dist/builtin/workflows/src/tui/widget.ts +25 -6
  101. package/dist/core/agent-session-auto-compaction.js +10 -10
  102. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  103. package/dist/core/agent-session-events.d.ts.map +1 -1
  104. package/dist/core/agent-session-events.js +11 -13
  105. package/dist/core/agent-session-events.js.map +1 -1
  106. package/dist/core/agent-session-methods.d.ts +1 -1
  107. package/dist/core/agent-session-methods.d.ts.map +1 -1
  108. package/dist/core/agent-session-methods.js.map +1 -1
  109. package/dist/core/agent-session-models.d.ts.map +1 -1
  110. package/dist/core/agent-session-models.js +5 -7
  111. package/dist/core/agent-session-models.js.map +1 -1
  112. package/dist/core/agent-session-prompt.js +4 -4
  113. package/dist/core/agent-session-prompt.js.map +1 -1
  114. package/dist/core/agent-session-retry.d.ts +4 -4
  115. package/dist/core/agent-session-retry.d.ts.map +1 -1
  116. package/dist/core/agent-session-retry.js +8 -34
  117. package/dist/core/agent-session-retry.js.map +1 -1
  118. package/dist/core/agent-session-tool-hooks.js +4 -4
  119. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  120. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  121. package/dist/core/atomic-guide-command.js +3 -10
  122. package/dist/core/atomic-guide-command.js.map +1 -1
  123. package/dist/core/event-bus.d.ts.map +1 -1
  124. package/dist/core/event-bus.js +19 -3
  125. package/dist/core/event-bus.js.map +1 -1
  126. package/dist/core/slash-commands.d.ts.map +1 -1
  127. package/dist/core/slash-commands.js +0 -3
  128. package/dist/core/slash-commands.js.map +1 -1
  129. package/dist/core/system-prompt.d.ts.map +1 -1
  130. package/dist/core/system-prompt.js +0 -12
  131. package/dist/core/system-prompt.js.map +1 -1
  132. package/dist/modes/interactive-engine/remote-command-catalog.d.ts +1 -1
  133. package/dist/modes/interactive-engine/remote-command-catalog.js +1 -1
  134. package/dist/modes/interactive-engine/remote-command-catalog.js.map +1 -1
  135. package/docs/intercom.md +29 -27
  136. package/docs/settings.md +2 -2
  137. package/docs/subagents.md +18 -15
  138. package/docs/usage.md +0 -9
  139. package/docs/workflows.md +27 -10
  140. package/npm-shrinkwrap.json +32 -32
  141. package/package.json +3 -3
  142. package/dist/builtin/subagents/prompts/gather-context-and-clarify.md +0 -27
  143. package/dist/builtin/subagents/prompts/parallel-cleanup.md +0 -61
  144. package/dist/builtin/subagents/prompts/parallel-context-build.md +0 -43
  145. package/dist/builtin/subagents/prompts/parallel-handoff-plan.md +0 -47
  146. package/dist/builtin/subagents/prompts/parallel-research.md +0 -34
  147. package/dist/builtin/subagents/prompts/parallel-review.md +0 -47
  148. package/dist/builtin/subagents/prompts/review-loop.md +0 -39
  149. package/dist/builtin/subagents/src/extension/doctor.ts +0 -188
  150. package/dist/builtin/subagents/src/runs/inprocess/attempt-handles.ts +0 -104
  151. /package/dist/builtin/subagents/src/runs/foreground/{subagent-executor-resume.ts → subagent-executor-cwd.ts} +0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CAAC,aAAa,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACd,CAAC;IACD,IAAI,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAEvC,4EAA4E;IAC5E,UAAU,CAAC,GAAG,EAAE;QACf,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE;YAChC,kDAAkD;QACnD,CAAC,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,CAAC,CAAC;IAEN,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;GAEG;AAEH,MAAM,UAAU,UAAU;IACzB,IAAI,CAAC,qBAAqB,EAAE,KAAK,EAAE,CAAC;IACpC,gEAAgE;IAChE,IAAI,CAAC,aAAa,EAAE,CAAC;AACtB,CAAC;AAED;;;GAGG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY;IACjC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,CAAC,aAAa,CAAC;IACzB,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,mBAAmB,CAAqB,OAAgB;IACvE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,oBAAoB;IACpB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,wBAAwB;IACxB,wBAAwB;IACxB,qBAAqB;IACrB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// Safety/refusal errors remain bounded same-model retries, but do not spend\n\t// another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nfunction applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): boolean {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis.agent.state.thinkingLevel = level;\n\tif (previousLevel === level) return false;\n\tthis.sessionManager.appendThinkingLevelChange(level);\n\tthis._emit({ type: \"thinking_level_changed\", level });\n\tvoid this._extensionRunner?.emit({\n\t\ttype: \"thinking_level_select\",\n\t\tlevel,\n\t\tpreviousLevel,\n\t});\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Cancel a pending fallback restore after an explicit model/effort choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Restore the model that was active before this turn spent a fallback. */\nexport async function _restoreFallbackModel(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\n\tconst previousModel = this.agent.state.model ?? this.model;\n\tconst previousThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst originThinkingLevel = clampThinkingLevel(\n\t\toriginModel,\n\t\tthis._fallbackOriginThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t) as ThinkingLevel;\n\tconst modelChanged = !modelsAreEqual(previousModel, originModel);\n\tconst thinkingChanged = previousThinkingLevel !== originThinkingLevel;\n\tif (!modelChanged && !thinkingChanged) {\n\t\treturn finishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(previousModel),\n\t\t\tto: modelLabel(originModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t}\n\n\tconst stillOwnsRestore = (): boolean =>\n\t\tthis._fallbackOriginGeneration === originGeneration &&\n\t\tthis._fallbackOriginModel === originModel &&\n\t\tmodelsAreEqual(this.agent.state.model ?? this.model, originModel) &&\n\t\t(this.agent.state.thinkingLevel ?? this.thinkingLevel) === originThinkingLevel;\n\n\tthis.agent.state.model = originModel;\n\tif (modelChanged) this.sessionManager.appendModelChange(originModel.provider, originModel.id);\n\tapplyFallbackThinkingLevel.call(this, originThinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\tthis._emitModelChanged(originModel, previousModel, \"restore\");\n\tif (!stillOwnsRestore()) return false;\n\tawait this._emitModelSelect(originModel, previousModel, \"restore\");\n\tif (!stillOwnsRestore()) return false;\n\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(previousModel),\n\t\tto: modelLabel(originModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1]?.role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tapplyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._restoreFallbackModel();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Remove error message from agent state (keep in session for history)\n\tconst messages = this.agent.state.messages;\n\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n\n\t// Wait with exponential backoff (abortable)\n\tthis._retryAbortController = new AbortController();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tconst attempt = this._retryAttempt;\n\t\tthis._retryAttempt = 0;\n\t\tthis._retryAbortController = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt,\n\t\t\tfinalError: \"Retry cancelled\",\n\t\t});\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\t// Note: _retryAttempt is reset in the catch block of _autoRetry\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setRetryEnabled(enabled);\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_restoreFallbackModel,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
1
+ {"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;A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AAa,EAAE,CAAC;AACtB,CAAC;AAED;;;GAGG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY;IACjC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,CAAC,aAAa,CAAC;IACzB,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,mBAAmB,CAAqB,OAAgB;IACvE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,oBAAoB;IACpB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// Safety/refusal errors remain bounded same-model retries, but do not spend\n\t// another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nfunction applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): boolean {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis.agent.state.thinkingLevel = level;\n\tif (previousLevel === level) return false;\n\tthis.sessionManager.appendThinkingLevelChange(level);\n\tthis._emit({ type: \"thinking_level_changed\", level });\n\tvoid this._extensionRunner?.emit({\n\t\ttype: \"thinking_level_select\",\n\t\tlevel,\n\t\tpreviousLevel,\n\t});\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Finish an active fallback lifecycle before an explicit model choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Finish an active fallback lifecycle without changing the selected fallback model. */\nexport async function _settleFallbackModelScope(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\tif (this._fallbackOriginGeneration !== originGeneration || this._fallbackOriginModel !== originModel) return false;\n\n\tconst currentModel = this.agent.state.model ?? this.model;\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(currentModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1]?.role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tapplyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Remove error message from agent state (keep in session for history)\n\tconst messages = this.agent.state.messages;\n\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n\n\t// Wait with exponential backoff (abortable)\n\tthis._retryAbortController = new AbortController();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tconst attempt = this._retryAttempt;\n\t\tthis._retryAttempt = 0;\n\t\tthis._retryAbortController = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt,\n\t\t\tfinalError: \"Retry cancelled\",\n\t\t});\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\t// Note: _retryAttempt is reset in the catch block of _autoRetry\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setRetryEnabled(enabled);\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_settleFallbackModelScope,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
@@ -107,9 +107,9 @@ export function _installAgentNextTurnRefresh() {
107
107
  const messages = turn.toolResults.length > 0 && !terminatingBatch
108
108
  ? await this._preflightPostToolContext(previousContext.messages, signal)
109
109
  : previousContext.messages;
110
- // Restore before queued follow-up messages are polled, but keep the
111
- // fallback for deceptive completions that event processing must retry on
112
- // the same model (safety refusal, empty completion, or length truncation).
110
+ // Settle before queued follow-up messages are polled, but keep the fallback
111
+ // lifecycle open for deceptive completions that event processing must retry
112
+ // on the same model (safety refusal, empty completion, or length truncation).
113
113
  const preserveFallbackForFailure = turn.message.role === "assistant" &&
114
114
  !this.agent.hasQueuedMessages() &&
115
115
  (turn.message.stopReason === "length" ||
@@ -117,7 +117,7 @@ export function _installAgentNextTurnRefresh() {
117
117
  this._isSafetyRefusal?.(turn.message) === true);
118
118
  if (!preserveFallbackForFailure && (turn.toolResults.length === 0 || terminatingBatch)) {
119
119
  await this._agentEventQueue;
120
- await this._restoreFallbackModel();
120
+ await this._settleFallbackModelScope();
121
121
  }
122
122
  return {
123
123
  ...previousSnapshot,
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tool-hooks.js","sourceRoot":"","sources":["../../src/core/agent-session-tool-hooks.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAE/E,MAAM,UAAU,sBAAsB;IACrC,IAAI,CAAC,KAAK,CAAC,cAAc,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE;QACxD,MAAM,MAAM,GAAG,IAAI,CAAC,gBAAgB,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;YACtC,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,MAAM,IAAI,CAAC,gBAAgB,CAAC;QAE5B,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,YAAY,CAAC;gBACxC,IAAI,EAAE,WAAW;gBACjB,QAAQ,EAAE,QAAQ,CAAC,IAAI;gBACvB,UAAU,EAAE,QAAQ,CAAC,EAAE;gBACvB,KAAK,EAAE,IAA+B;aACtC,CAAC,CAAC;YAC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AK,EAAE;aACrC;YACD,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK;YAC7B,aAAa,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa;SAC7C,CAAC;IACH,CAAC,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC3C,sBAAsB;IACtB,4BAA4B;CAC5B,CAAC","sourcesContent":["import type { PrepareNextTurnContext } from \"@earendil-works/pi-agent-core\";\nimport { normalizeToolResultImages } from \"../utils/tool-result-images.js\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { assertToolPairingInvariant } from \"./context-tool-pairing.js\";\nimport { redirectOversizedToolResult } from \"./tools/oversized-tool-result.js\";\n\nexport function _installAgentToolHooks(this: AgentSession): void {\n\tthis.agent.beforeToolCall = async ({ toolCall, args }) => {\n\t\tconst runner = this._extensionRunner;\n\t\tif (!runner.hasHandlers(\"tool_call\")) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tawait this._agentEventQueue;\n\n\t\ttry {\n\t\t\tconst result = await runner.emitToolCall({\n\t\t\t\ttype: \"tool_call\",\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t});\n\t\t\tif (result?.block && result.terminate === true) {\n\t\t\t\tthis._terminatingToolCallIds.add(toolCall.id);\n\t\t\t} else {\n\t\t\t\tthis._terminatingToolCallIds.delete(toolCall.id);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tif (err instanceof Error) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tthrow new Error(`Extension failed, blocking execution: ${String(err)}`);\n\t\t}\n\t};\n\n\tthis.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {\n\t\tconst runner = this._extensionRunner;\n\t\tconst hookResult = runner.hasHandlers(\"tool_result\")\n\t\t\t? await runner.emitToolResult({\n\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tdetails: result.details,\n\t\t\t\t\tisError,\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t\tconst hookContent = hookResult?.content ?? result.content;\n\t\t// Run after extension hooks so extension-injected images enter history at provider-safe sizes.\n\t\tconst normalizedContent = await normalizeToolResultImages(hookContent, {\n\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t});\n\t\tconst resultReplacement =\n\t\t\thookResult || normalizedContent !== hookContent\n\t\t\t\t? {\n\t\t\t\t\t\tcontent: normalizedContent,\n\t\t\t\t\t\tdetails: hookResult?.details,\n\t\t\t\t\t\tisError: hookResult?.isError ?? isError,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst finalResult = {\n\t\t\tcontent: normalizedContent,\n\t\t\t// Preserve original details when an extension hook rewrites only content;\n\t\t\t// the redirect check only replaces model-visible content blocks.\n\t\t\tdetails: hookResult?.details ?? result.details,\n\t\t};\n\t\tconst finalIsError = hookResult?.isError ?? isError;\n\t\tconst redirectReplacement = await redirectOversizedToolResult({\n\t\t\ttoolName: toolCall.name,\n\t\t\ttoolCallId: toolCall.id,\n\t\t\tresult: finalResult,\n\t\t\tisError: finalIsError,\n\t\t\tsessionId: this.sessionManager.getSessionId(),\n\t\t\tsessionDir: this.sessionManager.getSessionDir() || undefined,\n\t\t\tmaxResultSizeChars: this.getToolDefinition(toolCall.name)?.maxResultSizeChars,\n\t\t});\n\n\t\tif (result.terminate === true) this._terminatingToolCallIds.add(toolCall.id);\n\t\telse this._terminatingToolCallIds.delete(toolCall.id);\n\t\treturn redirectReplacement ?? resultReplacement;\n\t};\n}\n\n/**\n * Install a prepareNextTurnWithContext hook so that extension tool changes\n * (e.g. setActiveTools) and before_agent_start systemPrompt overrides are\n * applied to the next provider request within the same run.\n */\nexport function _installAgentNextTurnRefresh(this: AgentSession): void {\n\tconst previousPrepareNextTurnWithContext =\n\t\tthis.agent.prepareNextTurnWithContext ??\n\t\t(this.agent.prepareNextTurn\n\t\t\t? async (_turn: PrepareNextTurnContext, signal?: AbortSignal) => await this.agent.prepareNextTurn?.(signal)\n\t\t\t: undefined);\n\tconst previousTransformContext = this.agent.transformContext;\n\tthis.agent.transformContext = async (messages, signal) => {\n\t\tconst transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;\n\t\tconst guarded = this._finishPostToolCompactionPreflight(transformed);\n\t\t// Last checkpoint before provider conversion: a structurally invalid context\n\t\t// here becomes an unrecoverable provider 400, so surface it as an Atomic error.\n\t\tassertToolPairingInvariant(guarded);\n\t\treturn guarded;\n\t};\n\tthis.agent.prepareNextTurnWithContext = async (turn, signal) => {\n\t\tconst previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);\n\t\tconst previousContext = previousSnapshot?.context ?? turn.context;\n\t\tconst toolCallIds = turn.message.content.filter((part) => part.type === \"toolCall\").map((part) => part.id);\n\t\tconst terminatingBatch =\n\t\t\ttoolCallIds.length > 0 && toolCallIds.every((id) => this._terminatingToolCallIds.has(id));\n\t\tfor (const id of toolCallIds) this._terminatingToolCallIds.delete(id);\n\t\tconst messages =\n\t\t\tturn.toolResults.length > 0 && !terminatingBatch\n\t\t\t\t? await this._preflightPostToolContext(previousContext.messages, signal)\n\t\t\t\t: previousContext.messages;\n\n\t\t// Restore before queued follow-up messages are polled, but keep the\n\t\t// fallback for deceptive completions that event processing must retry on\n\t\t// the same model (safety refusal, empty completion, or length truncation).\n\t\tconst preserveFallbackForFailure =\n\t\t\tturn.message.role === \"assistant\" &&\n\t\t\t!this.agent.hasQueuedMessages() &&\n\t\t\t(turn.message.stopReason === \"length\" ||\n\t\t\t\tthis._isEmptyCompletion?.(turn.message) === true ||\n\t\t\t\tthis._isSafetyRefusal?.(turn.message) === true);\n\t\tif (!preserveFallbackForFailure && (turn.toolResults.length === 0 || terminatingBatch)) {\n\t\t\tawait this._agentEventQueue;\n\t\t\tawait this._restoreFallbackModel();\n\t\t}\n\n\t\treturn {\n\t\t\t...previousSnapshot,\n\t\t\tcontext: {\n\t\t\t\t...previousContext,\n\t\t\t\tmessages,\n\t\t\t\tsystemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,\n\t\t\t\ttools: this.agent.state.tools.slice(),\n\t\t\t},\n\t\t\tmodel: this.agent.state.model,\n\t\t\tthinkingLevel: this.agent.state.thinkingLevel,\n\t\t};\n\t};\n}\n\nexport const agentSessionToolHooksMethods = {\n\t_installAgentToolHooks,\n\t_installAgentNextTurnRefresh,\n};\n"]}
1
+ {"version":3,"file":"agent-session-tool-hooks.js","sourceRoot":"","sources":["../../src/core/agent-session-tool-hooks.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAE/E,MAAM,UAAU,sBAAsB;IACrC,IAAI,CAAC,KAAK,CAAC,cAAc,GAAG,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE;QACxD,MAAM,MAAM,GAAG,IAAI,CAAC,gBAAgB,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;YACtC,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,MAAM,IAAI,CAAC,gBAAgB,CAAC;QAE5B,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,YAAY,CAAC;gBACxC,IAAI,EAAE,WAAW;gBACjB,QAAQ,EAAE,QAAQ,CAAC,IAAI;gBACvB,UAAU,EAAE,QAAQ,CAAC,EAAE;gBACvB,KAAK,EAAE,IAA+B;aACtC,CAAC,CAAC;YACH,IAAI,MAAM,EAA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YACD,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK;YAC7B,aAAa,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa;SAC7C,CAAC;IACH,CAAC,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC3C,sBAAsB;IACtB,4BAA4B;CAC5B,CAAC","sourcesContent":["import type { PrepareNextTurnContext } from \"@earendil-works/pi-agent-core\";\nimport { normalizeToolResultImages } from \"../utils/tool-result-images.js\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { assertToolPairingInvariant } from \"./context-tool-pairing.js\";\nimport { redirectOversizedToolResult } from \"./tools/oversized-tool-result.js\";\n\nexport function _installAgentToolHooks(this: AgentSession): void {\n\tthis.agent.beforeToolCall = async ({ toolCall, args }) => {\n\t\tconst runner = this._extensionRunner;\n\t\tif (!runner.hasHandlers(\"tool_call\")) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tawait this._agentEventQueue;\n\n\t\ttry {\n\t\t\tconst result = await runner.emitToolCall({\n\t\t\t\ttype: \"tool_call\",\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t});\n\t\t\tif (result?.block && result.terminate === true) {\n\t\t\t\tthis._terminatingToolCallIds.add(toolCall.id);\n\t\t\t} else {\n\t\t\t\tthis._terminatingToolCallIds.delete(toolCall.id);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tif (err instanceof Error) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tthrow new Error(`Extension failed, blocking execution: ${String(err)}`);\n\t\t}\n\t};\n\n\tthis.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {\n\t\tconst runner = this._extensionRunner;\n\t\tconst hookResult = runner.hasHandlers(\"tool_result\")\n\t\t\t? await runner.emitToolResult({\n\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tdetails: result.details,\n\t\t\t\t\tisError,\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t\tconst hookContent = hookResult?.content ?? result.content;\n\t\t// Run after extension hooks so extension-injected images enter history at provider-safe sizes.\n\t\tconst normalizedContent = await normalizeToolResultImages(hookContent, {\n\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t});\n\t\tconst resultReplacement =\n\t\t\thookResult || normalizedContent !== hookContent\n\t\t\t\t? {\n\t\t\t\t\t\tcontent: normalizedContent,\n\t\t\t\t\t\tdetails: hookResult?.details,\n\t\t\t\t\t\tisError: hookResult?.isError ?? isError,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst finalResult = {\n\t\t\tcontent: normalizedContent,\n\t\t\t// Preserve original details when an extension hook rewrites only content;\n\t\t\t// the redirect check only replaces model-visible content blocks.\n\t\t\tdetails: hookResult?.details ?? result.details,\n\t\t};\n\t\tconst finalIsError = hookResult?.isError ?? isError;\n\t\tconst redirectReplacement = await redirectOversizedToolResult({\n\t\t\ttoolName: toolCall.name,\n\t\t\ttoolCallId: toolCall.id,\n\t\t\tresult: finalResult,\n\t\t\tisError: finalIsError,\n\t\t\tsessionId: this.sessionManager.getSessionId(),\n\t\t\tsessionDir: this.sessionManager.getSessionDir() || undefined,\n\t\t\tmaxResultSizeChars: this.getToolDefinition(toolCall.name)?.maxResultSizeChars,\n\t\t});\n\n\t\tif (result.terminate === true) this._terminatingToolCallIds.add(toolCall.id);\n\t\telse this._terminatingToolCallIds.delete(toolCall.id);\n\t\treturn redirectReplacement ?? resultReplacement;\n\t};\n}\n\n/**\n * Install a prepareNextTurnWithContext hook so that extension tool changes\n * (e.g. setActiveTools) and before_agent_start systemPrompt overrides are\n * applied to the next provider request within the same run.\n */\nexport function _installAgentNextTurnRefresh(this: AgentSession): void {\n\tconst previousPrepareNextTurnWithContext =\n\t\tthis.agent.prepareNextTurnWithContext ??\n\t\t(this.agent.prepareNextTurn\n\t\t\t? async (_turn: PrepareNextTurnContext, signal?: AbortSignal) => await this.agent.prepareNextTurn?.(signal)\n\t\t\t: undefined);\n\tconst previousTransformContext = this.agent.transformContext;\n\tthis.agent.transformContext = async (messages, signal) => {\n\t\tconst transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;\n\t\tconst guarded = this._finishPostToolCompactionPreflight(transformed);\n\t\t// Last checkpoint before provider conversion: a structurally invalid context\n\t\t// here becomes an unrecoverable provider 400, so surface it as an Atomic error.\n\t\tassertToolPairingInvariant(guarded);\n\t\treturn guarded;\n\t};\n\tthis.agent.prepareNextTurnWithContext = async (turn, signal) => {\n\t\tconst previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);\n\t\tconst previousContext = previousSnapshot?.context ?? turn.context;\n\t\tconst toolCallIds = turn.message.content.filter((part) => part.type === \"toolCall\").map((part) => part.id);\n\t\tconst terminatingBatch =\n\t\t\ttoolCallIds.length > 0 && toolCallIds.every((id) => this._terminatingToolCallIds.has(id));\n\t\tfor (const id of toolCallIds) this._terminatingToolCallIds.delete(id);\n\t\tconst messages =\n\t\t\tturn.toolResults.length > 0 && !terminatingBatch\n\t\t\t\t? await this._preflightPostToolContext(previousContext.messages, signal)\n\t\t\t\t: previousContext.messages;\n\n\t\t// Settle before queued follow-up messages are polled, but keep the fallback\n\t\t// lifecycle open for deceptive completions that event processing must retry\n\t\t// on the same model (safety refusal, empty completion, or length truncation).\n\t\tconst preserveFallbackForFailure =\n\t\t\tturn.message.role === \"assistant\" &&\n\t\t\t!this.agent.hasQueuedMessages() &&\n\t\t\t(turn.message.stopReason === \"length\" ||\n\t\t\t\tthis._isEmptyCompletion?.(turn.message) === true ||\n\t\t\t\tthis._isSafetyRefusal?.(turn.message) === true);\n\t\tif (!preserveFallbackForFailure && (turn.toolResults.length === 0 || terminatingBatch)) {\n\t\t\tawait this._agentEventQueue;\n\t\t\tawait this._settleFallbackModelScope();\n\t\t}\n\n\t\treturn {\n\t\t\t...previousSnapshot,\n\t\t\tcontext: {\n\t\t\t\t...previousContext,\n\t\t\t\tmessages,\n\t\t\t\tsystemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,\n\t\t\t\ttools: this.agent.state.tools.slice(),\n\t\t\t},\n\t\t\tmodel: this.agent.state.model,\n\t\t\tthinkingLevel: this.agent.state.thinkingLevel,\n\t\t};\n\t};\n}\n\nexport const agentSessionToolHooksMethods = {\n\t_installAgentToolHooks,\n\t_installAgentNextTurnRefresh,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"atomic-guide-command.d.ts","sourceRoot":"","sources":["../../src/core/atomic-guide-command.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,eAAO,MAAM,yBAAyB,WAAW,CAAC;AAClD,eAAO,MAAM,gCAAgC,qCAAqC,CAAC;AA6NnF,QAAA,MAAM,cAAc;mBAEZ,UAAU;;oBAET,UAAU;0BACJ,oBAAoB;;;mBAI3B,WAAW;;oBAEV,WAAW;0BACL,iBAAiB;;;mBAIxB,SAAS;;oBAER,SAAS;0BACH,0BAA0B;;;mBAIjC,WAAW;;oBAEV,YAAY;0BACN,sBAAsB;;EASlC,CAAC;AAEJ,KAAK,kBAAkB,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC;AAC1D,KAAK,sBAAsB,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAEzD,MAAM,MAAM,qBAAqB,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,sBAAsB,CAAC;AAE9D,eAAO,MAAM,yBAAyB,EAAE,SAAS,qBAAqB,EAErE,CAAC;AAcF,wBAAgB,uBAAuB,CAAC,MAAM,E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,MAAM,IAAI,qBAAqB,CAEvF;AA6BD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAKtE;AAED,wBAAgB,iCAAiC,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,CAW3F;AAED,iBAAS,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CActD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGhF;AAED,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,qBAAqB,GAAG,eAAe,CAEvF"}
@@ -25,7 +25,7 @@ Atomic turns non-trivial work into executable, inspectable workflows. Default to
25
25
  | On-call / broken behavior | Use a focused workflow to reproduce, diagnose, repair, and validate; direct debugger/subagent calls remain useful as stages or for tiny deterministic diagnosis |
26
26
  | Research → spec → implementation | Use \`/skill:research-codebase\`, then \`/skill:create-spec\`, then a named or custom implementation workflow with explicit validation and review |
27
27
  | Testing / regression hardening | Use a workflow for test/fix loops so retries, evidence, and the passing stop condition are tracked |
28
- | Large repo discovery | Run \`/parallel codebase-locator "map the area" -> codebase-analyzer "trace the current flow" -> codebase-pattern-finder "find patterns"\`, or use repository-focused \`fan-out-and-synthesize\` branches plus a synthesis barrier |
28
+ | Large repo discovery | Use repository-focused \`fan-out-and-synthesize\` branches plus a synthesis barrier, or launch locator/analyzer/pattern-finder children with the \`subagent\` tool |
29
29
  | UI / product polish | Run \`/skill:impeccable\` for interface critique and refinement, or \`/workflow open-claude-design\` for one generated preview plus a live review session and export |
30
30
 
31
31
  ## Built-in workflows
@@ -52,7 +52,7 @@ Use \`/workflow list\` to see what is available and \`/workflow inputs <name>\`
52
52
  | \`create-spec\` | turn research into an implementation-ready plan | \`/skill:create-spec from research/docs/<date>-<topic>.md\` |
53
53
  | \`tdd\` | do test-first feature or bug work | \`/skill:tdd\` |
54
54
  | \`prompt-engineer\` | tighten a vague prompt before a long run | \`/skill:prompt-engineer Draft a sharper implementation prompt for ...\` |
55
- | \`subagent\` | learn delegation patterns and exact \`/run\` and \`/parallel\` usage | \`/skill:subagent\` |
55
+ | \`subagent\` | learn when and how to delegate with the \`subagent\` tool | \`/skill:subagent\` |
56
56
  | \`impeccable\` | critique or refine frontend and product UI | \`/skill:impeccable\` |
57
57
  | \`show-me\` | explain a topic visually with concise diagrams, code-shape sketches, or focused HTML artifacts (HumanLayer, MIT) | \`/skill:show-me\` |
58
58
 
@@ -67,9 +67,6 @@ Subagents are focused child Atomic sessions you can point at one job inside the
67
67
  | \`codebase-pattern-finder\` | find existing code to model after |
68
68
  | \`debugger\` | reproduce, diagnose, and fix broken behavior |
69
69
 
70
- How the direct commands map to repo work:
71
- - \`/run\` = one specialist on one job, for example \`/run codebase-locator "Map the webhook retry flow"\`
72
- - \`/parallel\` = several independent specialists at once, for example \`/parallel codebase-locator "map retry files" -> codebase-pattern-finder "find existing retry/backoff patterns" -> codebase-online-researcher "research current retry guidance"\`
73
70
 
74
71
  ─────────────────────────────────────────────────────────────────
75
72
 
@@ -115,11 +112,7 @@ Loop or stop-condition phrasing is a key workflow signal. Encode \`do X until Y\
115
112
 
116
113
  Use the workflow's deterministic evidence, verifier decision, remaining-work report, and bound-exhaustion state to decide whether to ship, repair, unblock, or clarify. Keep PR/MR creation, deployment, and publication as separately authorized post-approval actions.
117
114
 
118
- If you implemented directly instead of using a workflow, you can still run:
119
-
120
- \`/parallel-review current diff\`
121
-
122
- Atomic will synthesize reviewer feedback and ask before applying fixes.
115
+ If you implemented directly instead of using a workflow, launch a fresh-context cleanup pass with the \`subagent\` tool and apply only the synthesized fixes you accept.
123
116
 
124
117
  ─────────────────────────────────────────────────────────────────
125
118
 
@@ -1 +1 @@
1
- {"version":3,"file":"atomic-guide-command.js","sourceRoot":"","sources":["../../src/core/atomic-guide-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,gBAA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AACzD,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport type { AutocompleteItem } from \"@earendil-works/pi-tui\";\nimport { getChangelogPath, parseChangelog } from \"../utils/changelog.ts\";\n\nexport const ATOMIC_GUIDE_COMMAND_NAME = \"atomic\";\nexport const ATOMIC_GUIDE_COMMAND_DESCRIPTION = \"Atomic onboarding and help guide\";\n\nconst OVERVIEW = `# Atomic overview\n\nAtomic turns non-trivial work into executable, inspectable workflows. Default to a workflow for implementation, build, debugging, bug fixes, migrations, features, scoped multi-file changes, and validated docs/code work, or whenever a request has dependencies, handoffs, uncertainty, review gates, measurable done criteria, or evidence requirements. Use direct chat for tiny deterministic low-risk answers or edits. Loop-shaped prompts such as \\`do X until Y\\`, \\`review/fix until passing\\`, or \\`run checks and fix until green\\` are especially strong workflow signals. Workflow-first is not builtin-only or monolithic: use named workflows, direct modes, author a custom TypeScript \\`workflow({...})\\` inline, or import reusable project/package and builtin definitions from \\`@bastani/workflows/builtin\\` and nest them with \\`ctx.workflow(...)\\`. Nested children may compose further children within \\`maxDepth\\`, enabling powerful research → implementation → verification → approval graphs from reusable parts. Start Atomic in a project with \\`atomic\\`, then talk to it normally. Use \\`@file\\` to attach files, \\`!command\\` to run shell output through the model, and \\`!!command\\` to run shell output without adding it to context.\n\n## Core session commands\n\n| Command | Use |\n|---|---|\n| \\`/login\\` | configure auth |\n| \\`/model\\` | switch model |\n| \\`/settings\\` | thinking level, theme, message delivery, transport |\n| \\`/new\\`, \\`/resume\\` | start or resume sessions |\n| \\`/tree\\`, \\`/fork\\`, \\`/clone\\` | branch or navigate session history |\n| \\`/compact\\` | delete safe older context verbatim |\n| \\`/hotkeys\\`, \\`/changelog\\` | local help and release notes |\n\n## Examples of using Atomic\n\n| Goal | How to use |\n|---|---|\n| On-call / broken behavior | Use a focused workflow to reproduce, diagnose, repair, and validate; direct debugger/subagent calls remain useful as stages or for tiny deterministic diagnosis |\n| Research → spec → implementation | Use \\`/skill:research-codebase\\`, then \\`/skill:create-spec\\`, then a named or custom implementation workflow with explicit validation and review |\n| Testing / regression hardening | Use a workflow for test/fix loops so retries, evidence, and the passing stop condition are tracked |\n| Large repo discovery | Run \\`/parallel codebase-locator \"map the area\" -> codebase-analyzer \"trace the current flow\" -> codebase-pattern-finder \"find patterns\"\\`, or use repository-focused \\`fan-out-and-synthesize\\` branches plus a synthesis barrier |\n| UI / product polish | Run \\`/skill:impeccable\\` for interface critique and refinement, or \\`/workflow open-claude-design\\` for one generated preview plus a live review session and export |\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`classify-and-act\\` | structured routing with a low-confidence human fallback | \\`/workflow classify-and-act prompt=\"Triage this request\"\\` |\n| \\`fan-out-and-synthesize\\` | independent slices or repository-focused research with artifact synthesis | \\`/workflow fan-out-and-synthesize prompt=\"Map payment retries by subsystem\"\\` |\n| \\`adversarial-verification\\` | fresh verification and bounded repair of a candidate | \\`/workflow adversarial-verification task=\"Verify the migration patch\"\\` |\n| \\`generate-and-filter\\` | generate many candidates and keep a distinct shortlist | \\`/workflow generate-and-filter prompt=\"Propose command names\"\\` |\n| \\`tournament\\` | compare whole solutions through balanced pairwise judging | \\`/workflow tournament prompt=\"Design the retry strategy\"\\` |\n| \\`loop-until-done\\` | iterate until explicit evidence passes or the bound is exhausted | \\`/workflow loop-until-done prompt=\"Repair failures until tests pass\"\\` |\n| \\`goal\\` | ledger-backed autonomous work with receipts and reviewer-gated completion | \\`/workflow goal objective=\"Update CLI docs and validate the docs build\"\\` |\n| \\`ralph\\` | research-first delegated implementation with bounded multi-model review | \\`/workflow ralph prompt=\"Implement specs/rate-limit.md\"\\` |\n| \\`open-claude-design\\` | UI and design-system generation with one live review session and export | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow list\\` to see what is available and \\`/workflow inputs <name>\\` to inspect inputs in your environment.\n\n## Top skills\n\n| Skill | When to use | How to run |\n|---|---|---|\n| \\`research-codebase\\` | write a grounded research artifact for one subsystem or question | \\`/skill:research-codebase how the rate limiter works in src/middleware/\\` |\n| \\`create-spec\\` | turn research into an implementation-ready plan | \\`/skill:create-spec from research/docs/<date>-<topic>.md\\` |\n| \\`tdd\\` | do test-first feature or bug work | \\`/skill:tdd\\` |\n| \\`prompt-engineer\\` | tighten a vague prompt before a long run | \\`/skill:prompt-engineer Draft a sharper implementation prompt for ...\\` |\n| \\`subagent\\` | learn delegation patterns and exact \\`/run\\` and \\`/parallel\\` usage | \\`/skill:subagent\\` |\n| \\`impeccable\\` | critique or refine frontend and product UI | \\`/skill:impeccable\\` |\n| \\`show-me\\` | explain a topic visually with concise diagrams, code-shape sketches, or focused HTML artifacts (HumanLayer, MIT) | \\`/skill:show-me\\` |\n\n## Subagents\n\nSubagents are focused child Atomic sessions you can point at one job inside the repo.\n\n| Built-in subagent | Use |\n|---|---|\n| \\`codebase-locator\\` | find relevant files, tests, entrypoints, and configs |\n| \\`codebase-analyzer\\` | explain current behavior with file:line refs |\n| \\`codebase-pattern-finder\\` | find existing code to model after |\n| \\`debugger\\` | reproduce, diagnose, and fix broken behavior |\n\nHow the direct commands map to repo work:\n- \\`/run\\` = one specialist on one job, for example \\`/run codebase-locator \"Map the webhook retry flow\"\\`\n- \\`/parallel\\` = several independent specialists at once, for example \\`/parallel codebase-locator \"map retry files\" -> codebase-pattern-finder \"find existing retry/backoff patterns\" -> codebase-online-researcher \"research current retry guidance\"\\`\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic example\\` — see the pieces used on a code task\n\\`/atomic workflows\\` — learn when to use workflows`;\n\nconst EXAMPLE = `# Practical example\n\nThis example shows a spec-driven development process whose clearly delegated autonomous implementation benefits from durable workflow execution. For interactive or conversation-led work, stay inline or use bounded subagents while the parent remains in control. Type the examples below into the Atomic TUI chat after starting \\`atomic\\` in your project.\n\n## 1. Research what exists\n\nUse \\`/skill:research-codebase\\` for a scoped area, subsystem, or directory:\n\n\\`/skill:research-codebase how the rate limiter works in src/middleware/\\`\n\nFor repository-wide research, use \\`fan-out-and-synthesize\\` with distinct subsystem partitions, artifact outputs, and a synthesis prompt that cites concrete paths:\n\n\\`/workflow fan-out-and-synthesize prompt=\"Partition payment retries by subsystem and synthesize cited end-to-end findings\"\\`\n\nIf the research prompt is vague, tighten it first with \\`/skill:prompt-engineer\\`:\n\n\\`/skill:prompt-engineer Draft a sharper repo-research prompt for understanding payment retries end to end, including retries, queues, and failure handling.\\`\n\n## 2. Create a spec when requirements are fuzzy\n\nSkip this if the implementation request is already precise.\n\n\\`/skill:create-spec from research/docs/<date>-<topic>.md\\`\n\n## 3. Implement with review built in\n\nDefault to a workflow for non-trivial implementation and review. Use direct chat only for tiny deterministic low-risk edits; use focused subagents inside workflow stages or for bounded specialist passes. Choose an installed workflow when it fits, or author a custom TypeScript workflow inline from the starter patterns when the task needs a richer graph.\n\nFor implementation with review built in, author a task-specific worker → fresh verifier → reducer loop. Give it literal acceptance criteria, deterministic checks, evidence-backed repair payloads, and a bounded stop condition:\n\n\\`Create and run a workflow that implements specs/<date>-<topic>.md, runs focused tests, sends the patch to fresh verifiers, and repairs findings until the documented behavior passes or the iteration bound is reached.\\`\n\nLoop or stop-condition phrasing is a key workflow signal. Encode \\`do X until Y\\`, \\`review/fix until passing\\`, or \\`run checks and fix until green\\` as explicit bounded workflow gates rather than informal retries.\n\n## 4. Decide and land\n\nUse the workflow's deterministic evidence, verifier decision, remaining-work report, and bound-exhaustion state to decide whether to ship, repair, unblock, or clarify. Keep PR/MR creation, deployment, and publication as separately authorized post-approval actions.\n\nIf you implemented directly instead of using a workflow, you can still run:\n\n\\`/parallel-review current diff\\`\n\nAtomic will synthesize reviewer feedback and ask before applying fixes.\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic workflows\\` — learn when to use workflows\n\\`/atomic overview\\` — quick refresh`;\n\nconst WORKFLOWS = `# Workflows primer\n\nA workflow is a TypeScript-defined pipeline exported from \\`workflow({...})\\`. It can run tasks, chains, parallel fan-out, human-in-the-loop prompts, background status, and model fallback chains.\n\nDefault to workflows for non-trivial work and requests with inherent structure plus a verifiable objective. Implementation, debugging, migrations, multi-file changes, validation, review, evidence requirements, and explicit stop conditions are workflow-shaped; use direct chat only for tiny deterministic low-risk answers or edits.\n\nWorkflow-first is not builtin-only or monolithic. Atomic can author custom TypeScript \\`workflow({...})\\` definitions inline, and workflows can import reusable project/package definitions or builtins from \\`@bastani/workflows/builtin\\`, then nest them with \\`ctx.workflow(...)\\`. Imported children can nest further children within \\`maxDepth\\`, so compose proven research, implementation, design, verification, and approval workflows instead of copying their stages. Use the documented starter patterns for classify-and-act routing, dynamic fan-out and synthesis, adversarial verification, candidate selection, and bounded convergence. Atomic writes the parent definition, reloads it, and runs the composed graph.\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`classify-and-act\\` | structured routing | \\`/workflow classify-and-act prompt=\"Triage this request\"\\` |\n| \\`fan-out-and-synthesize\\` | independent slices or repository research | \\`/workflow fan-out-and-synthesize prompt=\"Map payment retries by subsystem\"\\` |\n| \\`adversarial-verification\\` | fresh verification and bounded repair | \\`/workflow adversarial-verification task=\"Verify the patch\"\\` |\n| \\`generate-and-filter\\` | candidate generation and shortlisting | \\`/workflow generate-and-filter prompt=\"Propose command names\"\\` |\n| \\`tournament\\` | balanced whole-solution comparison | \\`/workflow tournament prompt=\"Design the retry strategy\"\\` |\n| \\`loop-until-done\\` | bounded convergence on explicit evidence | \\`/workflow loop-until-done prompt=\"Repair failures until tests pass\"\\` |\n| \\`goal\\` | durable ledger, bounded orchestration, and reviewer-gated completion | \\`/workflow goal objective=\"Update CLI docs and validate the docs build\"\\` |\n| \\`ralph\\` | research-first delegated implementation and iterative review | \\`/workflow ralph prompt=\"Implement specs/rate-limit.md\"\\` |\n| \\`open-claude-design\\` | frontend and product design | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow inputs <name>\\` to inspect exact inputs. Goal and Ralph skip PR creation unless \\`create_pr=true\\` explicitly authorizes their post-approval final stage. Use \\`/skill:research-codebase\\` for one focused subsystem and repository-focused \\`fan-out-and-synthesize\\` for independent whole-repository slices.\n\nIf you are drafting research, reviewer, or synthesis prompts for a workflow, use \\`/skill:prompt-engineer\\` first. It is a good fit when a stage prompt feels vague, overloaded, or underspecified.\n\n## What good workflow authoring looks like\n\nA good workflow request is explicit about stage purpose, model choice, handoff, and the decision each step must return.\n\nFor workflow-owned side effects such as filesystem writes, network mutations, and external API actions, prefer \\`ctx.tool(name, args, fn)\\`: completed calls are durably cached, so resume returns the saved result without rerunning \\`fn\\`. Keep pure computation as ordinary TypeScript, and do not wrap agent-stage internals or every function call indiscriminately.\n\nExample: ask Atomic in chat with something like this:\n\n~~~text\nCreate a reusable workflow called review-changes.\n\nIt should accept one required text input called target for a diff, PR summary, or review target.\n\nRun two independent review stages in parallel with fresh context:\n- one reviewer focused on correctness, regressions, and missing tests using openai-codex/gpt-5.5 at xhigh thinking\n- one reviewer focused on edge cases, maintainability, and hidden risks using anthropic/claude-opus-4-8 at xhigh thinking\n\nThen add an aggregate stage that consolidates both reviews, deduplicates overlap, keeps only evidence-backed issues, and separates blockers from optional suggestions using openai/gpt-5.5 at high thinking.\n\nFinally add an adjudicate stage using anthropic/claude-sonnet-4 at high thinking that decides what to fix now, what to defer, and what to reject. Return a short action list with rationale.\n\nThe workflow should return structured output with consolidated_review and decision fields.\n~~~\n\nWhy this is good:\n- it names the workflow and required input\n- it specifies which stages are parallel vs sequential\n- each stage has one job\n- it defines the handoff and final outputs\n- it calls out model choice and thinking level where that matters\n\n## Run and inspect\n\n\\`/workflow list\\`\n\n\\`/workflow inputs fan-out-and-synthesize\\`\n\n\\`/workflow fan-out-and-synthesize prompt=\"Partition the settings flow by subsystem and synthesize cited findings\"\\`\n\n\\`/workflow inputs adversarial-verification\\`\n\n\\`/workflow adversarial-verification task=\"Verify the settings form validation patch\"\\`\n\n\\`/workflow status\\`\n\n\\`/workflow connect <run-id>\\`\n\n\\`/workflow interrupt <run-id>\\`\n\n\\`/workflow quit <run-id>\\`\n\n\\`/workflow resume <run-id>\\`\n\nWorkflows run as background tasks. Use F2 or \\`/workflow connect <run-id>\\` for the graph viewer. Human-in-the-loop prompts appear there, not as chat modals, and awaiting-input states do not wake the main chat agent. Completion and failure notices are steered back into the main chat; answers submitted in the workflow UI interrupt stale main-chat questions so the model does not ask again.\n\n## Author your own\n\nDescribe your workflow in plain chat — say what you want the workflow to accomplish, what inputs it should accept, what stages should run, and what final output or decision it should return. Atomic will use the workflow docs to scaffold a reusable definition under \\`.atomic/workflows/\\`, ask clarifying questions when stage purpose, models, or handoffs are ambiguous, and run \\`/workflow reload\\` so you can launch it immediately.\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic example\\` — see workflows in a normal task flow\n\\`/atomic overview\\` — quick refresh`;\n\nconst GUIDE_SECTIONS = [\n\t{\n\t\tname: \"overview\",\n\t\taliases: [],\n\t\tlabel: \"overview\",\n\t\tdescription: \"30-second overview\",\n\t\trender: () => OVERVIEW,\n\t},\n\t{\n\t\tname: \"workflows\",\n\t\taliases: [\"workflow\"],\n\t\tlabel: \"workflows\",\n\t\tdescription: \"Workflow primer\",\n\t\trender: () => WORKFLOWS,\n\t},\n\t{\n\t\tname: \"example\",\n\t\taliases: [\"examples\"],\n\t\tlabel: \"example\",\n\t\tdescription: \"Practical first workflow\",\n\t\trender: () => EXAMPLE,\n\t},\n\t{\n\t\tname: \"whats-new\",\n\t\taliases: [\"what's new\", \"whats new\", \"news\", \"updates\", \"changelog\"],\n\t\tlabel: \"what's new\",\n\t\tdescription: \"Recent release notes\",\n\t\trender: readLatestStableChangelog,\n\t},\n] as const satisfies readonly {\n\treadonly name: string;\n\treadonly aliases: readonly string[];\n\treadonly label: string;\n\treadonly description: string;\n\treadonly render: (cwd: string) => string;\n}[];\n\ntype AtomicGuideSection = (typeof GUIDE_SECTIONS)[number];\ntype AtomicGuideSectionName = AtomicGuideSection[\"name\"];\n\nexport type AtomicGuideHelpChoice = AtomicGuideSection[\"label\"];\n\nexport type AtomicGuideMode = \"help\" | AtomicGuideSectionName;\n\nexport const ATOMIC_GUIDE_HELP_CHOICES: readonly AtomicGuideHelpChoice[] = GUIDE_SECTIONS.map(\n\t(section) => section.label,\n);\n\nconst GUIDE_SECTIONS_BY_NAME = new Map<AtomicGuideSectionName, AtomicGuideSection>(\n\tGUIDE_SECTIONS.map((section) => [section.name, section]),\n);\nconst GUIDE_SECTIONS_BY_LABEL = new Map<string, AtomicGuideSection>(\n\tGUIDE_SECTIONS.map((section) => [section.label, section]),\n);\nconst GUIDE_SECTIONS_BY_INPUT = new Map<string, AtomicGuideSection>(\n\tGUIDE_SECTIONS.flatMap((section) =>\n\t\t[section.name, section.label, ...section.aliases].map((input) => [input, section] as const),\n\t),\n);\n\nexport function isAtomicGuideHelpChoice(choice: string): choice is AtomicGuideHelpChoice {\n\treturn GUIDE_SECTIONS_BY_LABEL.has(choice);\n}\n\nconst ATOMIC_GUIDE_TRAILING_PUNCTUATION = \"?!.,;:\";\n\nfunction stripTrailingAtomicGuidePunctuation(value: string): string {\n\tlet end = value.length;\n\twhile (end > 0 && ATOMIC_GUIDE_TRAILING_PUNCTUATION.includes(value.charAt(end - 1))) {\n\t\tend--;\n\t}\n\treturn value.slice(0, end);\n}\n\nfunction getGuideSectionForChoice(choice: string): AtomicGuideSection | undefined {\n\treturn GUIDE_SECTIONS_BY_LABEL.get(choice);\n}\n\nfunction getGuideSectionForMode(mode: AtomicGuideSectionName): AtomicGuideSection {\n\tconst section = GUIDE_SECTIONS_BY_NAME.get(mode);\n\tif (!section) throw new Error(`Unknown Atomic guide section: ${mode}`);\n\treturn section;\n}\n\nfunction getAtomicGuideHelpMenu(): string {\n\tconst sectionHelp = GUIDE_SECTIONS.map(\n\t\t(section) => `- \\`${section.label}\\` — run \\`/atomic ${section.label}\\``,\n\t).join(\"\\n\");\n\treturn `# Atomic\\n\\nSelect where to start:\\n\\n${sectionHelp}`;\n}\n\nexport function normalizeAtomicGuideMode(args: string): AtomicGuideMode {\n\tconst normalized = stripTrailingAtomicGuidePunctuation(args.trim().toLowerCase());\n\tif (!normalized) return \"help\";\n\n\treturn GUIDE_SECTIONS_BY_INPUT.get(normalized)?.name ?? \"help\";\n}\n\nexport function getAtomicGuideArgumentCompletions(prefix: string): AutocompleteItem[] | null {\n\tconst query = prefix.trim().toLowerCase();\n\tconst items = GUIDE_SECTIONS.map((section) => ({\n\t\tvalue: section.label,\n\t\tlabel: section.label,\n\t\tdescription: section.description,\n\t}));\n\tconst filtered = query\n\t\t? items.filter((item) => item.value.startsWith(query) || item.label.startsWith(query))\n\t\t: items;\n\treturn filtered.length > 0 ? filtered : null;\n}\n\nfunction readLatestStableChangelog(cwd: string): string {\n\tconst changelogPath = getChangelogPath();\n\tconst stableSections = parseChangelog(changelogPath)\n\t\t.filter((entry) => entry.prerelease === null)\n\t\t.slice(0, 3)\n\t\t.map((entry) => entry.content.trim())\n\t\t.filter(Boolean);\n\n\tif (stableSections.length === 0) {\n\t\treturn `# What's new\\n\\nNo stable release sections were found. Try \\`/changelog\\` for the interactive changelog viewer.\\n\\n─────────────────────────────────────────────────────────────────\\n\\nWhere to next:\\n\\n\\`/atomic example\\` — see a practical first workflow\\n\\`/atomic overview\\` — quick refresh`;\n\t}\n\n\tconst relativePath = path.relative(cwd, changelogPath) || changelogPath;\n\treturn `# What's new\\n\\n${stableSections.join(\"\\n\\n\")}\\n\\nSource: \\`${relativePath}\\`\\n\\n─────────────────────────────────────────────────────────────────\\n\\nWhere to next:\\n\\n\\`/atomic example\\` — see a practical first workflow\\n\\`/atomic overview\\` — quick refresh`;\n}\n\nexport function getAtomicGuideMessage(mode: AtomicGuideMode, cwd: string): string {\n\tif (mode === \"help\") return getAtomicGuideHelpMenu();\n\treturn getGuideSectionForMode(mode).render(cwd);\n}\n\nexport function atomicGuideModeForChoice(choice: AtomicGuideHelpChoice): AtomicGuideMode {\n\treturn getGuideSectionForChoice(choice)?.name ?? \"help\";\n}\n"]}
1
+ {"version":3,"file":"atomic-guide-command.js","sourceRoot":"","sources":["../../src/core/atomic-guide-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEzE,MAAM,CAAC,MAAM,yBAAyB,GAAG,QAAQ,CAAC;AAClD,MAAM,CAAC,MAAM,gCAAgC,GAAG,kCAAkC,CAAC;AAEnF,MAAM,QAAQ,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oDAuEmC,CAAC;AAErD,MAAM,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qCA6CqB,CAAC;AAEtC,MAAM,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qCA0FmB,CAAC;AAEtC,MAAM,cAAc,GAAG;IACtB;QACC,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE,EAAE;QACX,KAAK,EAAE,UAAU;QACjB,WAAW,EAAE,oBAAoB;QACjC,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ;KACtB;IACD;QACC,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,CAAC,UAAU,CAAC;QACrB,KAAK,EAAE,WAAW;QAClB,WAAW,EAAE,iBAAiB;QAC9B,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS;KACvB;IACD;QACC,IAAI,EAAE,SAAS;QACf,OAAO,EAAE,CAAC,UAAU,CAAC;QACrB,KAAK,EAAE,SAAS;QAChB,WAAW,EAAE,0BAA0B;QACvC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO;KACrB;IACD;QACC,IAAI,EAAE,WAAW;QACjB,OAAO,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IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,MAA6B;IACrE,OAAO,wBAAwB,CAAC,MAAM,CAAC,EAAE,IAAI,IAAI,MAAM,CAAC;AACzD,CAAC","sourcesContent":["import * as path from \"node:path\";\nimport type { AutocompleteItem } from \"@earendil-works/pi-tui\";\nimport { getChangelogPath, parseChangelog } from \"../utils/changelog.ts\";\n\nexport const ATOMIC_GUIDE_COMMAND_NAME = \"atomic\";\nexport const ATOMIC_GUIDE_COMMAND_DESCRIPTION = \"Atomic onboarding and help guide\";\n\nconst OVERVIEW = `# Atomic overview\n\nAtomic turns non-trivial work into executable, inspectable workflows. Default to a workflow for implementation, build, debugging, bug fixes, migrations, features, scoped multi-file changes, and validated docs/code work, or whenever a request has dependencies, handoffs, uncertainty, review gates, measurable done criteria, or evidence requirements. Use direct chat for tiny deterministic low-risk answers or edits. Loop-shaped prompts such as \\`do X until Y\\`, \\`review/fix until passing\\`, or \\`run checks and fix until green\\` are especially strong workflow signals. Workflow-first is not builtin-only or monolithic: use named workflows, direct modes, author a custom TypeScript \\`workflow({...})\\` inline, or import reusable project/package and builtin definitions from \\`@bastani/workflows/builtin\\` and nest them with \\`ctx.workflow(...)\\`. Nested children may compose further children within \\`maxDepth\\`, enabling powerful research → implementation → verification → approval graphs from reusable parts. Start Atomic in a project with \\`atomic\\`, then talk to it normally. Use \\`@file\\` to attach files, \\`!command\\` to run shell output through the model, and \\`!!command\\` to run shell output without adding it to context.\n\n## Core session commands\n\n| Command | Use |\n|---|---|\n| \\`/login\\` | configure auth |\n| \\`/model\\` | switch model |\n| \\`/settings\\` | thinking level, theme, message delivery, transport |\n| \\`/new\\`, \\`/resume\\` | start or resume sessions |\n| \\`/tree\\`, \\`/fork\\`, \\`/clone\\` | branch or navigate session history |\n| \\`/compact\\` | delete safe older context verbatim |\n| \\`/hotkeys\\`, \\`/changelog\\` | local help and release notes |\n\n## Examples of using Atomic\n\n| Goal | How to use |\n|---|---|\n| On-call / broken behavior | Use a focused workflow to reproduce, diagnose, repair, and validate; direct debugger/subagent calls remain useful as stages or for tiny deterministic diagnosis |\n| Research → spec → implementation | Use \\`/skill:research-codebase\\`, then \\`/skill:create-spec\\`, then a named or custom implementation workflow with explicit validation and review |\n| Testing / regression hardening | Use a workflow for test/fix loops so retries, evidence, and the passing stop condition are tracked |\n| Large repo discovery | Use repository-focused \\`fan-out-and-synthesize\\` branches plus a synthesis barrier, or launch locator/analyzer/pattern-finder children with the \\`subagent\\` tool |\n| UI / product polish | Run \\`/skill:impeccable\\` for interface critique and refinement, or \\`/workflow open-claude-design\\` for one generated preview plus a live review session and export |\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`classify-and-act\\` | structured routing with a low-confidence human fallback | \\`/workflow classify-and-act prompt=\"Triage this request\"\\` |\n| \\`fan-out-and-synthesize\\` | independent slices or repository-focused research with artifact synthesis | \\`/workflow fan-out-and-synthesize prompt=\"Map payment retries by subsystem\"\\` |\n| \\`adversarial-verification\\` | fresh verification and bounded repair of a candidate | \\`/workflow adversarial-verification task=\"Verify the migration patch\"\\` |\n| \\`generate-and-filter\\` | generate many candidates and keep a distinct shortlist | \\`/workflow generate-and-filter prompt=\"Propose command names\"\\` |\n| \\`tournament\\` | compare whole solutions through balanced pairwise judging | \\`/workflow tournament prompt=\"Design the retry strategy\"\\` |\n| \\`loop-until-done\\` | iterate until explicit evidence passes or the bound is exhausted | \\`/workflow loop-until-done prompt=\"Repair failures until tests pass\"\\` |\n| \\`goal\\` | ledger-backed autonomous work with receipts and reviewer-gated completion | \\`/workflow goal objective=\"Update CLI docs and validate the docs build\"\\` |\n| \\`ralph\\` | research-first delegated implementation with bounded multi-model review | \\`/workflow ralph prompt=\"Implement specs/rate-limit.md\"\\` |\n| \\`open-claude-design\\` | UI and design-system generation with one live review session and export | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow list\\` to see what is available and \\`/workflow inputs <name>\\` to inspect inputs in your environment.\n\n## Top skills\n\n| Skill | When to use | How to run |\n|---|---|---|\n| \\`research-codebase\\` | write a grounded research artifact for one subsystem or question | \\`/skill:research-codebase how the rate limiter works in src/middleware/\\` |\n| \\`create-spec\\` | turn research into an implementation-ready plan | \\`/skill:create-spec from research/docs/<date>-<topic>.md\\` |\n| \\`tdd\\` | do test-first feature or bug work | \\`/skill:tdd\\` |\n| \\`prompt-engineer\\` | tighten a vague prompt before a long run | \\`/skill:prompt-engineer Draft a sharper implementation prompt for ...\\` |\n| \\`subagent\\` | learn when and how to delegate with the \\`subagent\\` tool | \\`/skill:subagent\\` |\n| \\`impeccable\\` | critique or refine frontend and product UI | \\`/skill:impeccable\\` |\n| \\`show-me\\` | explain a topic visually with concise diagrams, code-shape sketches, or focused HTML artifacts (HumanLayer, MIT) | \\`/skill:show-me\\` |\n\n## Subagents\n\nSubagents are focused child Atomic sessions you can point at one job inside the repo.\n\n| Built-in subagent | Use |\n|---|---|\n| \\`codebase-locator\\` | find relevant files, tests, entrypoints, and configs |\n| \\`codebase-analyzer\\` | explain current behavior with file:line refs |\n| \\`codebase-pattern-finder\\` | find existing code to model after |\n| \\`debugger\\` | reproduce, diagnose, and fix broken behavior |\n\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic example\\` — see the pieces used on a code task\n\\`/atomic workflows\\` — learn when to use workflows`;\n\nconst EXAMPLE = `# Practical example\n\nThis example shows a spec-driven development process whose clearly delegated autonomous implementation benefits from durable workflow execution. For interactive or conversation-led work, stay inline or use bounded subagents while the parent remains in control. Type the examples below into the Atomic TUI chat after starting \\`atomic\\` in your project.\n\n## 1. Research what exists\n\nUse \\`/skill:research-codebase\\` for a scoped area, subsystem, or directory:\n\n\\`/skill:research-codebase how the rate limiter works in src/middleware/\\`\n\nFor repository-wide research, use \\`fan-out-and-synthesize\\` with distinct subsystem partitions, artifact outputs, and a synthesis prompt that cites concrete paths:\n\n\\`/workflow fan-out-and-synthesize prompt=\"Partition payment retries by subsystem and synthesize cited end-to-end findings\"\\`\n\nIf the research prompt is vague, tighten it first with \\`/skill:prompt-engineer\\`:\n\n\\`/skill:prompt-engineer Draft a sharper repo-research prompt for understanding payment retries end to end, including retries, queues, and failure handling.\\`\n\n## 2. Create a spec when requirements are fuzzy\n\nSkip this if the implementation request is already precise.\n\n\\`/skill:create-spec from research/docs/<date>-<topic>.md\\`\n\n## 3. Implement with review built in\n\nDefault to a workflow for non-trivial implementation and review. Use direct chat only for tiny deterministic low-risk edits; use focused subagents inside workflow stages or for bounded specialist passes. Choose an installed workflow when it fits, or author a custom TypeScript workflow inline from the starter patterns when the task needs a richer graph.\n\nFor implementation with review built in, author a task-specific worker → fresh verifier → reducer loop. Give it literal acceptance criteria, deterministic checks, evidence-backed repair payloads, and a bounded stop condition:\n\n\\`Create and run a workflow that implements specs/<date>-<topic>.md, runs focused tests, sends the patch to fresh verifiers, and repairs findings until the documented behavior passes or the iteration bound is reached.\\`\n\nLoop or stop-condition phrasing is a key workflow signal. Encode \\`do X until Y\\`, \\`review/fix until passing\\`, or \\`run checks and fix until green\\` as explicit bounded workflow gates rather than informal retries.\n\n## 4. Decide and land\n\nUse the workflow's deterministic evidence, verifier decision, remaining-work report, and bound-exhaustion state to decide whether to ship, repair, unblock, or clarify. Keep PR/MR creation, deployment, and publication as separately authorized post-approval actions.\n\nIf you implemented directly instead of using a workflow, launch a fresh-context cleanup pass with the \\`subagent\\` tool and apply only the synthesized fixes you accept.\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic workflows\\` — learn when to use workflows\n\\`/atomic overview\\` — quick refresh`;\n\nconst WORKFLOWS = `# Workflows primer\n\nA workflow is a TypeScript-defined pipeline exported from \\`workflow({...})\\`. It can run tasks, chains, parallel fan-out, human-in-the-loop prompts, background status, and model fallback chains.\n\nDefault to workflows for non-trivial work and requests with inherent structure plus a verifiable objective. Implementation, debugging, migrations, multi-file changes, validation, review, evidence requirements, and explicit stop conditions are workflow-shaped; use direct chat only for tiny deterministic low-risk answers or edits.\n\nWorkflow-first is not builtin-only or monolithic. Atomic can author custom TypeScript \\`workflow({...})\\` definitions inline, and workflows can import reusable project/package definitions or builtins from \\`@bastani/workflows/builtin\\`, then nest them with \\`ctx.workflow(...)\\`. Imported children can nest further children within \\`maxDepth\\`, so compose proven research, implementation, design, verification, and approval workflows instead of copying their stages. Use the documented starter patterns for classify-and-act routing, dynamic fan-out and synthesis, adversarial verification, candidate selection, and bounded convergence. Atomic writes the parent definition, reloads it, and runs the composed graph.\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`classify-and-act\\` | structured routing | \\`/workflow classify-and-act prompt=\"Triage this request\"\\` |\n| \\`fan-out-and-synthesize\\` | independent slices or repository research | \\`/workflow fan-out-and-synthesize prompt=\"Map payment retries by subsystem\"\\` |\n| \\`adversarial-verification\\` | fresh verification and bounded repair | \\`/workflow adversarial-verification task=\"Verify the patch\"\\` |\n| \\`generate-and-filter\\` | candidate generation and shortlisting | \\`/workflow generate-and-filter prompt=\"Propose command names\"\\` |\n| \\`tournament\\` | balanced whole-solution comparison | \\`/workflow tournament prompt=\"Design the retry strategy\"\\` |\n| \\`loop-until-done\\` | bounded convergence on explicit evidence | \\`/workflow loop-until-done prompt=\"Repair failures until tests pass\"\\` |\n| \\`goal\\` | durable ledger, bounded orchestration, and reviewer-gated completion | \\`/workflow goal objective=\"Update CLI docs and validate the docs build\"\\` |\n| \\`ralph\\` | research-first delegated implementation and iterative review | \\`/workflow ralph prompt=\"Implement specs/rate-limit.md\"\\` |\n| \\`open-claude-design\\` | frontend and product design | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow inputs <name>\\` to inspect exact inputs. Goal and Ralph skip PR creation unless \\`create_pr=true\\` explicitly authorizes their post-approval final stage. Use \\`/skill:research-codebase\\` for one focused subsystem and repository-focused \\`fan-out-and-synthesize\\` for independent whole-repository slices.\n\nIf you are drafting research, reviewer, or synthesis prompts for a workflow, use \\`/skill:prompt-engineer\\` first. It is a good fit when a stage prompt feels vague, overloaded, or underspecified.\n\n## What good workflow authoring looks like\n\nA good workflow request is explicit about stage purpose, model choice, handoff, and the decision each step must return.\n\nFor workflow-owned side effects such as filesystem writes, network mutations, and external API actions, prefer \\`ctx.tool(name, args, fn)\\`: completed calls are durably cached, so resume returns the saved result without rerunning \\`fn\\`. Keep pure computation as ordinary TypeScript, and do not wrap agent-stage internals or every function call indiscriminately.\n\nExample: ask Atomic in chat with something like this:\n\n~~~text\nCreate a reusable workflow called review-changes.\n\nIt should accept one required text input called target for a diff, PR summary, or review target.\n\nRun two independent review stages in parallel with fresh context:\n- one reviewer focused on correctness, regressions, and missing tests using openai-codex/gpt-5.5 at xhigh thinking\n- one reviewer focused on edge cases, maintainability, and hidden risks using anthropic/claude-opus-4-8 at xhigh thinking\n\nThen add an aggregate stage that consolidates both reviews, deduplicates overlap, keeps only evidence-backed issues, and separates blockers from optional suggestions using openai/gpt-5.5 at high thinking.\n\nFinally add an adjudicate stage using anthropic/claude-sonnet-4 at high thinking that decides what to fix now, what to defer, and what to reject. Return a short action list with rationale.\n\nThe workflow should return structured output with consolidated_review and decision fields.\n~~~\n\nWhy this is good:\n- it names the workflow and required input\n- it specifies which stages are parallel vs sequential\n- each stage has one job\n- it defines the handoff and final outputs\n- it calls out model choice and thinking level where that matters\n\n## Run and inspect\n\n\\`/workflow list\\`\n\n\\`/workflow inputs fan-out-and-synthesize\\`\n\n\\`/workflow fan-out-and-synthesize prompt=\"Partition the settings flow by subsystem and synthesize cited findings\"\\`\n\n\\`/workflow inputs adversarial-verification\\`\n\n\\`/workflow adversarial-verification task=\"Verify the settings form validation patch\"\\`\n\n\\`/workflow status\\`\n\n\\`/workflow connect <run-id>\\`\n\n\\`/workflow interrupt <run-id>\\`\n\n\\`/workflow quit <run-id>\\`\n\n\\`/workflow resume <run-id>\\`\n\nWorkflows run as background tasks. Use F2 or \\`/workflow connect <run-id>\\` for the graph viewer. Human-in-the-loop prompts appear there, not as chat modals, and awaiting-input states do not wake the main chat agent. Completion and failure notices are steered back into the main chat; answers submitted in the workflow UI interrupt stale main-chat questions so the model does not ask again.\n\n## Author your own\n\nDescribe your workflow in plain chat — say what you want the workflow to accomplish, what inputs it should accept, what stages should run, and what final output or decision it should return. Atomic will use the workflow docs to scaffold a reusable definition under \\`.atomic/workflows/\\`, ask clarifying questions when stage purpose, models, or handoffs are ambiguous, and run \\`/workflow reload\\` so you can launch it immediately.\n\n─────────────────────────────────────────────────────────────────\n\nWhere to next:\n\n\\`/atomic example\\` — see workflows in a normal task flow\n\\`/atomic overview\\` — quick refresh`;\n\nconst GUIDE_SECTIONS = [\n\t{\n\t\tname: \"overview\",\n\t\taliases: [],\n\t\tlabel: \"overview\",\n\t\tdescription: \"30-second overview\",\n\t\trender: () => OVERVIEW,\n\t},\n\t{\n\t\tname: \"workflows\",\n\t\taliases: [\"workflow\"],\n\t\tlabel: \"workflows\",\n\t\tdescription: \"Workflow primer\",\n\t\trender: () => WORKFLOWS,\n\t},\n\t{\n\t\tname: \"example\",\n\t\taliases: [\"examples\"],\n\t\tlabel: \"example\",\n\t\tdescription: \"Practical first workflow\",\n\t\trender: () => EXAMPLE,\n\t},\n\t{\n\t\tname: \"whats-new\",\n\t\taliases: [\"what's new\", \"whats new\", \"news\", \"updates\", \"changelog\"],\n\t\tlabel: \"what's new\",\n\t\tdescription: \"Recent release notes\",\n\t\trender: readLatestStableChangelog,\n\t},\n] as const satisfies readonly {\n\treadonly name: string;\n\treadonly aliases: readonly string[];\n\treadonly label: string;\n\treadonly description: string;\n\treadonly render: (cwd: string) => string;\n}[];\n\ntype AtomicGuideSection = (typeof GUIDE_SECTIONS)[number];\ntype AtomicGuideSectionName = AtomicGuideSection[\"name\"];\n\nexport type AtomicGuideHelpChoice = AtomicGuideSection[\"label\"];\n\nexport type AtomicGuideMode = \"help\" | AtomicGuideSectionName;\n\nexport const ATOMIC_GUIDE_HELP_CHOICES: readonly AtomicGuideHelpChoice[] = GUIDE_SECTIONS.map(\n\t(section) => section.label,\n);\n\nconst GUIDE_SECTIONS_BY_NAME = new Map<AtomicGuideSectionName, AtomicGuideSection>(\n\tGUIDE_SECTIONS.map((section) => [section.name, section]),\n);\nconst GUIDE_SECTIONS_BY_LABEL = new Map<string, AtomicGuideSection>(\n\tGUIDE_SECTIONS.map((section) => [section.label, section]),\n);\nconst GUIDE_SECTIONS_BY_INPUT = new Map<string, AtomicGuideSection>(\n\tGUIDE_SECTIONS.flatMap((section) =>\n\t\t[section.name, section.label, ...section.aliases].map((input) => [input, section] as const),\n\t),\n);\n\nexport function isAtomicGuideHelpChoice(choice: string): choice is AtomicGuideHelpChoice {\n\treturn GUIDE_SECTIONS_BY_LABEL.has(choice);\n}\n\nconst ATOMIC_GUIDE_TRAILING_PUNCTUATION = \"?!.,;:\";\n\nfunction stripTrailingAtomicGuidePunctuation(value: string): string {\n\tlet end = value.length;\n\twhile (end > 0 && ATOMIC_GUIDE_TRAILING_PUNCTUATION.includes(value.charAt(end - 1))) {\n\t\tend--;\n\t}\n\treturn value.slice(0, end);\n}\n\nfunction getGuideSectionForChoice(choice: string): AtomicGuideSection | undefined {\n\treturn GUIDE_SECTIONS_BY_LABEL.get(choice);\n}\n\nfunction getGuideSectionForMode(mode: AtomicGuideSectionName): AtomicGuideSection {\n\tconst section = GUIDE_SECTIONS_BY_NAME.get(mode);\n\tif (!section) throw new Error(`Unknown Atomic guide section: ${mode}`);\n\treturn section;\n}\n\nfunction getAtomicGuideHelpMenu(): string {\n\tconst sectionHelp = GUIDE_SECTIONS.map(\n\t\t(section) => `- \\`${section.label}\\` — run \\`/atomic ${section.label}\\``,\n\t).join(\"\\n\");\n\treturn `# Atomic\\n\\nSelect where to start:\\n\\n${sectionHelp}`;\n}\n\nexport function normalizeAtomicGuideMode(args: string): AtomicGuideMode {\n\tconst normalized = stripTrailingAtomicGuidePunctuation(args.trim().toLowerCase());\n\tif (!normalized) return \"help\";\n\n\treturn GUIDE_SECTIONS_BY_INPUT.get(normalized)?.name ?? \"help\";\n}\n\nexport function getAtomicGuideArgumentCompletions(prefix: string): AutocompleteItem[] | null {\n\tconst query = prefix.trim().toLowerCase();\n\tconst items = GUIDE_SECTIONS.map((section) => ({\n\t\tvalue: section.label,\n\t\tlabel: section.label,\n\t\tdescription: section.description,\n\t}));\n\tconst filtered = query\n\t\t? items.filter((item) => item.value.startsWith(query) || item.label.startsWith(query))\n\t\t: items;\n\treturn filtered.length > 0 ? filtered : null;\n}\n\nfunction readLatestStableChangelog(cwd: string): string {\n\tconst changelogPath = getChangelogPath();\n\tconst stableSections = parseChangelog(changelogPath)\n\t\t.filter((entry) => entry.prerelease === null)\n\t\t.slice(0, 3)\n\t\t.map((entry) => entry.content.trim())\n\t\t.filter(Boolean);\n\n\tif (stableSections.length === 0) {\n\t\treturn `# What's new\\n\\nNo stable release sections were found. Try \\`/changelog\\` for the interactive changelog viewer.\\n\\n─────────────────────────────────────────────────────────────────\\n\\nWhere to next:\\n\\n\\`/atomic example\\` — see a practical first workflow\\n\\`/atomic overview\\` — quick refresh`;\n\t}\n\n\tconst relativePath = path.relative(cwd, changelogPath) || changelogPath;\n\treturn `# What's new\\n\\n${stableSections.join(\"\\n\\n\")}\\n\\nSource: \\`${relativePath}\\`\\n\\n─────────────────────────────────────────────────────────────────\\n\\nWhere to next:\\n\\n\\`/atomic example\\` — see a practical first workflow\\n\\`/atomic overview\\` — quick refresh`;\n}\n\nexport function getAtomicGuideMessage(mode: AtomicGuideMode, cwd: string): string {\n\tif (mode === \"help\") return getAtomicGuideHelpMenu();\n\treturn getGuideSectionForMode(mode).render(cwd);\n}\n\nexport function atomicGuideModeForChoice(choice: AtomicGuideHelpChoice): AtomicGuideMode {\n\treturn getGuideSectionForChoice(choice)?.name ?? \"help\";\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/core/event-bus.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,QAAQ;IACxB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAC3C,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAClE;AAED,MAAM,WAAW,kBAAmB,SAAQ,QAAQ;IACnD,KAAK,IAAI,IAAI,CAAC;CACd;AAED,wBAAgB,cAAc,IAAI,kBAAkB,CAqBnD;AASD;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAE3E;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE1D"}
1
+ {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/core/event-bus.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,QAAQ;IACxB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAC3C,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAClE;AAED,MAAM,WAAW,kBAAmB,SAAQ,QAAQ;IACnD,KAAK,IAAI,IAAI,CAAC;CACd;AAED,wBAAgB,cAAc,IAAI,kBAAkB,CAqBnD;AA4BD;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAE3E;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE1D"}
@@ -22,18 +22,34 @@ export function createEventBus() {
22
22
  },
23
23
  };
24
24
  }
25
+ /**
26
+ * Shared by duplicate host-module instances in packaged/split-loader builds.
27
+ * The `@1` suffix versions the stored WeakMap shape.
28
+ */
29
+ const CANONICAL_EVENT_BUSES_KEY = Symbol.for("atomic-coding-agent/canonical-event-buses@1");
30
+ function canonicalEventBusBag() {
31
+ return globalThis;
32
+ }
25
33
  /**
26
34
  * Per-extension `events` facades mapped back to the canonical EventBus each
27
35
  * forwards to. Weak so neither facades nor buses are retained: an entry lives
28
36
  * exactly as long as the facade it keys on.
29
37
  */
30
- const canonicalEventBuses = new WeakMap();
38
+ function getCanonicalEventBuses() {
39
+ const bag = canonicalEventBusBag();
40
+ const existing = bag[CANONICAL_EVENT_BUSES_KEY];
41
+ if (existing !== undefined)
42
+ return existing;
43
+ const created = new WeakMap();
44
+ bag[CANONICAL_EVENT_BUSES_KEY] = created;
45
+ return created;
46
+ }
31
47
  /**
32
48
  * Register `facade` as forwarding to `bus`, so `canonicalEventBusFor(facade)`
33
49
  * resolves to `bus`.
34
50
  */
35
51
  export function registerCanonicalEventBus(facade, bus) {
36
- canonicalEventBuses.set(facade, bus);
52
+ getCanonicalEventBuses().set(facade, bus);
37
53
  }
38
54
  /**
39
55
  * Resolve a scope object to the canonical EventBus it forwards to. A
@@ -42,6 +58,6 @@ export function registerCanonicalEventBus(facade, bus) {
42
58
  * so canonical buses are fixed points.
43
59
  */
44
60
  export function canonicalEventBusFor(scope) {
45
- return canonicalEventBuses.get(scope) ?? scope;
61
+ return getCanonicalEventBuses().get(scope) ?? scope;
46
62
  }
47
63
  //# sourceMappingURL=event-bus.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../src/core/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,MAAM,UAAU,cAAc;IAC7B,MAAM,OAAO,GAAG,IAAI,YAAY,EAAE,CAAC;IACnC,OAAO;QACN,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE;YACvB,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC;QACD,EAAE,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;YACxB,MAAM,WAAW,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE;gBAC3C,IAAI,CAAC;oBACJ,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;gBACrB,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACd,OAAO,CAAC,KAAK,CAAC,wBAAwB,OAAO,IAAI,EAAE,GAAG,CAAC,CAAC;gBACzD,CAAC;YACF,CAAC,CAAC;YACF,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YACjC,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QAChD,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACX,OAAO,CAAC,kBAAkB,EAAE,CAAC;QAC9B,CAAC;KACD,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAAkB,CAAC;AAE1D;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,MAAc,EAAE,GAAW;IACpE,mBAAmB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACtC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAa;IACjD,OAAO,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC;AAChD,CAAC","sourcesContent":["import { EventEmitter } from \"node:events\";\n\nexport interface EventBus {\n\temit(channel: string, data: unknown): void;\n\ton(channel: string, handler: (data: unknown) => void): () => void;\n}\n\nexport interface EventBusController extends EventBus {\n\tclear(): void;\n}\n\nexport function createEventBus(): EventBusController {\n\tconst emitter = new EventEmitter();\n\treturn {\n\t\temit: (channel, data) => {\n\t\t\temitter.emit(channel, data);\n\t\t},\n\t\ton: (channel, handler) => {\n\t\t\tconst safeHandler = async (data: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait handler(data);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.error(`Event handler error (${channel}):`, err);\n\t\t\t\t}\n\t\t\t};\n\t\t\temitter.on(channel, safeHandler);\n\t\t\treturn () => emitter.off(channel, safeHandler);\n\t\t},\n\t\tclear: () => {\n\t\t\temitter.removeAllListeners();\n\t\t},\n\t};\n}\n\n/**\n * Per-extension `events` facades mapped back to the canonical EventBus each\n * forwards to. Weak so neither facades nor buses are retained: an entry lives\n * exactly as long as the facade it keys on.\n */\nconst canonicalEventBuses = new WeakMap<object, object>();\n\n/**\n * Register `facade` as forwarding to `bus`, so `canonicalEventBusFor(facade)`\n * resolves to `bus`.\n */\nexport function registerCanonicalEventBus(facade: object, bus: object): void {\n\tcanonicalEventBuses.set(facade, bus);\n}\n\n/**\n * Resolve a scope object to the canonical EventBus it forwards to. A\n * registered per-extension `events` facade yields the shared bus behind it;\n * anything else — including a canonical bus itself — is returned unchanged,\n * so canonical buses are fixed points.\n */\nexport function canonicalEventBusFor(scope: object): object {\n\treturn canonicalEventBuses.get(scope) ?? scope;\n}\n"]}
1
+ {"version":3,"file":"event-bus.js","sourceRoot":"","sources":["../../src/core/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,MAAM,UAAU,cAAc;IAC7B,MAAM,OAAO,GAAG,IAAI,YAAY,EAAE,CAAC;IACnC,OAAO;QACN,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE;YACvB,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC7B,CAAC;QACD,EAAE,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE;YACxB,MAAM,WAAW,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE;gBAC3C,IAAI,CAAC;oBACJ,MAAM,OAAO,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Bus {\n\temit(channel: string, data: unknown): void;\n\ton(channel: string, handler: (data: unknown) => void): () => void;\n}\n\nexport interface EventBusController extends EventBus {\n\tclear(): void;\n}\n\nexport function createEventBus(): EventBusController {\n\tconst emitter = new EventEmitter();\n\treturn {\n\t\temit: (channel, data) => {\n\t\t\temitter.emit(channel, data);\n\t\t},\n\t\ton: (channel, handler) => {\n\t\t\tconst safeHandler = async (data: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait handler(data);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.error(`Event handler error (${channel}):`, err);\n\t\t\t\t}\n\t\t\t};\n\t\t\temitter.on(channel, safeHandler);\n\t\t\treturn () => emitter.off(channel, safeHandler);\n\t\t},\n\t\tclear: () => {\n\t\t\temitter.removeAllListeners();\n\t\t},\n\t};\n}\n\n/**\n * Shared by duplicate host-module instances in packaged/split-loader builds.\n * The `@1` suffix versions the stored WeakMap shape.\n */\nconst CANONICAL_EVENT_BUSES_KEY = Symbol.for(\"atomic-coding-agent/canonical-event-buses@1\");\n\ntype CanonicalEventBuses = WeakMap<object, object>;\n\nfunction canonicalEventBusBag(): Record<symbol, CanonicalEventBuses | undefined> {\n\treturn globalThis as typeof globalThis & Record<symbol, CanonicalEventBuses | undefined>;\n}\n\n/**\n * Per-extension `events` facades mapped back to the canonical EventBus each\n * forwards to. Weak so neither facades nor buses are retained: an entry lives\n * exactly as long as the facade it keys on.\n */\nfunction getCanonicalEventBuses(): CanonicalEventBuses {\n\tconst bag = canonicalEventBusBag();\n\tconst existing = bag[CANONICAL_EVENT_BUSES_KEY];\n\tif (existing !== undefined) return existing;\n\tconst created = new WeakMap<object, object>();\n\tbag[CANONICAL_EVENT_BUSES_KEY] = created;\n\treturn created;\n}\n\n/**\n * Register `facade` as forwarding to `bus`, so `canonicalEventBusFor(facade)`\n * resolves to `bus`.\n */\nexport function registerCanonicalEventBus(facade: object, bus: object): void {\n\tgetCanonicalEventBuses().set(facade, bus);\n}\n\n/**\n * Resolve a scope object to the canonical EventBus it forwards to. A\n * registered per-extension `events` facade yields the shared bus behind it;\n * anything else — including a canonical bus itself — is returned unchanged,\n * so canonical buses are fixed points.\n */\nexport function canonicalEventBusFor(scope: object): object {\n\treturn getCanonicalEventBuses().get(scope) ?? scope;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAO/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sBAAsB,CAAC,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,gBAAgB,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAAC;CACpH;AAiPD,wBAAgB,qCAAqC,CAAC,cAAc,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,CAgDvG;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA8BrE,CAAC;AAEF,eAAO,MAAM,gCAAgC,EAAE,aAAa,CAAC,mBAAmB,CAiB/E,CAAC"}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAO/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sBAAsB,CAAC,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,gBAAgB,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAAC;CACpH;AAiPD,wBAAgB,qCAAqC,CAAC,cAAc,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,CAgDvG;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CA8BrE,CAAC;AAEF,eAAO,MAAM,gCAAgC,EAAE,aAAa,CAAC,mBAAmB,CAc/E,CAAC"}
@@ -292,9 +292,6 @@ export const BUNDLED_EXTENSION_SLASH_COMMANDS = [
292
292
  description: "Run or inspect Atomic workflows. Usage: /workflow <name> [key=value…] | /workflow [list|status|connect|attach|interrupt|quit|pause|resume|inputs|reload] [args]",
293
293
  getArgumentCompletions: getBundledWorkflowArgumentCompletions,
294
294
  },
295
- { name: "run", description: "Run a subagent directly: /run agent[output=file] [task] [--fork]" },
296
- { name: "parallel", description: "Run agents in parallel: /parallel scout task1 -> reviewer task2 [--fork]" },
297
- { name: "subagents-doctor", description: "Show subagent diagnostics" },
298
295
  { name: "mcp", description: "Show MCP server status" },
299
296
  { name: "mcp-auth", description: "Authenticate with an MCP server (OAuth)" },
300
297
  { name: "curator", description: "Toggle or configure the search curator workflow" },