@bastani/atomic 0.9.10 → 0.9.11-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +6 -0
  3. package/dist/builtin/cursor/package.json +2 -2
  4. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  5. package/dist/builtin/intercom/package.json +2 -2
  6. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  7. package/dist/builtin/mcp/package.json +1 -1
  8. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  9. package/dist/builtin/subagents/package.json +1 -1
  10. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  11. package/dist/builtin/web-access/package.json +1 -1
  12. package/dist/builtin/workflows/CHANGELOG.md +17 -0
  13. package/dist/builtin/workflows/README.md +8 -3
  14. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +1 -1
  15. package/dist/builtin/workflows/package.json +1 -1
  16. package/dist/builtin/workflows/src/durable/backend.ts +2 -2
  17. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +173 -0
  18. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +36 -12
  19. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +9 -3
  20. package/dist/builtin/workflows/src/durable/factory.ts +35 -6
  21. package/dist/builtin/workflows/src/durable/local-command.ts +11 -2
  22. package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +14 -2
  23. package/dist/builtin/workflows/src/extension/public-types.ts +3 -4
  24. package/dist/builtin/workflows/src/extension/render-call.ts +4 -0
  25. package/dist/builtin/workflows/src/extension/render-result.ts +31 -1
  26. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +5 -2
  27. package/dist/builtin/workflows/src/extension/workflow-schema.ts +3 -2
  28. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -0
  29. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +88 -2
  30. package/dist/builtin/workflows/src/extension/workflow-tool.ts +13 -0
  31. package/dist/core/agent-session-events.d.ts.map +1 -1
  32. package/dist/core/agent-session-events.js +2 -1
  33. package/dist/core/agent-session-events.js.map +1 -1
  34. package/dist/core/agent-session-retry.d.ts.map +1 -1
  35. package/dist/core/agent-session-retry.js +7 -0
  36. package/dist/core/agent-session-retry.js.map +1 -1
  37. package/dist/core/agent-session-runtime.d.ts +13 -0
  38. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  39. package/dist/core/agent-session-runtime.js +12 -0
  40. package/dist/core/agent-session-runtime.js.map +1 -1
  41. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  42. package/dist/core/atomic-guide-command.js +2 -0
  43. package/dist/core/atomic-guide-command.js.map +1 -1
  44. package/dist/core/auth-storage-backends.d.ts +4 -0
  45. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  46. package/dist/core/auth-storage-backends.js +48 -3
  47. package/dist/core/auth-storage-backends.js.map +1 -1
  48. package/dist/core/auth-storage.d.ts.map +1 -1
  49. package/dist/core/auth-storage.js +27 -11
  50. package/dist/core/auth-storage.js.map +1 -1
  51. package/dist/core/codex-errors.d.ts +3 -0
  52. package/dist/core/codex-errors.d.ts.map +1 -0
  53. package/dist/core/codex-errors.js +12 -0
  54. package/dist/core/codex-errors.js.map +1 -0
  55. package/dist/core/slash-commands.js +1 -1
  56. package/dist/core/slash-commands.js.map +1 -1
  57. package/dist/modes/interactive/interactive-auth-routing.d.ts +2 -1
  58. package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
  59. package/dist/modes/interactive/interactive-auth-routing.js +10 -5
  60. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  61. package/dist/modes/interactive/interactive-autocomplete.js +12 -2
  62. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  63. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +3 -1
  64. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  65. package/dist/modes/interactive-engine/extension-ui-bridge.js +6 -0
  66. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  67. package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -5
  68. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  69. package/dist/modes/interactive-engine/isolated-runtime.js +14 -24
  70. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  71. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +15 -0
  72. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -0
  73. package/dist/modes/interactive-engine/remote-model-catalog.js +67 -0
  74. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -0
  75. package/dist/modes/rpc/rpc-client-api.d.ts +8 -1
  76. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  77. package/dist/modes/rpc/rpc-client-api.js +9 -0
  78. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  79. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  80. package/dist/modes/rpc/rpc-command-handler.js +30 -0
  81. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  82. package/dist/modes/rpc/rpc-types.d.ts +67 -7
  83. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  84. package/dist/modes/rpc/rpc-types.js.map +1 -1
  85. package/docs/docs.json +9 -1
  86. package/docs/models/artificial-analysis-index.md +82 -0
  87. package/docs/models/model-selection.md +63 -0
  88. package/docs/models/pareto-efficiency.md +64 -0
  89. package/docs/providers.md +5 -1
  90. package/docs/quickstart.md +1 -1
  91. package/docs/rpc.md +27 -0
  92. package/docs/workflows.md +20 -7
  93. package/npm-shrinkwrap.json +24 -24
  94. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,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AC;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,iCAAiC;IACjC,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { normalizeToolArgumentsForModel } from \"./copilot-gemini-tool-arguments.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n\nconst THINKING_SUFFIXES = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const satisfies readonly ThinkingLevel[];\nconst THINKING_SUFFIX_SET: ReadonlySet<string> = new Set(THINKING_SUFFIXES);\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction splitFallbackModel(value: string): { modelId: string; thinkingLevel?: ThinkingLevel } {\n\tconst trimmed = value.trim();\n\tconst index = trimmed.lastIndexOf(\":\");\n\tif (index < 0) return { modelId: trimmed };\n\tconst suffix = trimmed.slice(index + 1);\n\tif (!THINKING_SUFFIX_SET.has(suffix)) return { modelId: trimmed };\n\treturn { modelId: trimmed.slice(0, index), thinkingLevel: suffix as ThinkingLevel };\n}\n\nfunction resolveFallbackModel(this: AgentSession, value: string): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\tconst parsed = splitFallbackModel(value);\n\tif (!parsed.modelId.includes(\"/\")) {\n\t\tconst available = this._modelRegistry.getAvailable().filter((model) => model.id === parsed.modelId);\n\t\tconst preferredProvider = this.model?.provider ?? this.settingsManager.getDefaultProvider();\n\t\tconst model = available.find((candidate) => candidate.provider === preferredProvider) ?? (available.length === 1 ? available[0] : undefined);\n\t\treturn model ? { model, thinkingLevel: parsed.thinkingLevel } : undefined;\n\t}\n\tconst slash = parsed.modelId.indexOf(\"/\");\n\tconst provider = parsed.modelId.slice(0, slash);\n\tconst modelId = parsed.modelId.slice(slash + 1);\n\tconst model = this._modelRegistry.find(provider, modelId);\n\tif (!model || !this._modelRegistry.hasConfiguredAuth(model)) return undefined;\n\treturn { model, thinkingLevel: parsed.thinkingLevel };\n}\n\nfunction fallbackKey(model: Model<Api>, thinkingLevel: ThinkingLevel | undefined): string {\n\treturn `${model.provider}/${model.id}:${thinkingLevel ?? \"\"}`;\n}\n\nfunction hasProviderTransportDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") {\n\t\treturn /provider_transport_failure|websocket.*error|sse.*404/i.test(String(value));\n\t}\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage, record.status, record.statusCode]\n\t\t: [record.type, record.code, record.name, record.status, record.statusCode];\n\tfor (const field of fields) {\n\t\t if (typeof field === \"string\" || typeof field === \"number\") {\n\t\t\tif (/provider_transport_failure|websocket.*error|sse.*404|\\b404\\b/i.test(String(field))) return true;\n\t\t}\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderTransportDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasProviderModelUnavailableDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage]\n\t\t: [record.type, record.code, record.name, record.errorMessage];\n\tfor (const field of fields) {\n\t\tif (typeof field === \"string\" && /model(?:[_\\s-].*)?(?:not[_\\s-]?found|unavailable|unknown|disabled)|model[_-]?not[_-]?found/i.test(field)) return true;\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderModelUnavailableDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\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\tif (hasProviderTransportDiagnostic(message) || hasProviderModelUnavailableDiagnostic(message)) return true;\n\tif (!message.errorMessage) return false;\n\n\tconst err = message.errorMessage;\n\n\t// Safety triggers surface through structured API signals that pi-ai maps to\n\t// stopReason \"error\":\n\t// - Anthropic `refusal` stops become pi-ai's canned \"The model refused to\n\t// complete the request\" error message;\n\t// - OpenAI-style APIs (and github-copilot CAPI, which also maps spurious\n\t// Gemini RECITATION/safety blocks this way) surface\n\t// `finish_reason: content_filter`.\n\t// Spurious safety triggers are common in agentic settings, so these are\n\t// re-requested like transient failures, bounded by maxRetries (issue #1608).\n\tif (/refused to complete the request|finish.?reason:?\\s*content.?filter/i.test(err)) {\n\t\treturn true;\n\t}\n\n\t// Match: overloaded_error, provider returned error, rate limit, quota/usage-limit exhaustion (e.g. \"Codex error: The usage limit has been reached\" — retryable so configured fallbackModels can advance to a provider/model with remaining headroom), 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, premature stream endings, HTTP/2 closed before response, terminated, retry delay exceeded, and a bare/transient provider finish_reason \"error\" (e.g. github-copilot Gemini's CAPI mapping of MALFORMED_FUNCTION_CALL/OTHER/UNEXPECTED_TOOL_CALL). These are provider-agnostic transient failures.\n\treturn /overloaded|provider.?returned.?error|rate.?limit|usage.?limit|quota|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay|finish.?reason:?\\s*error/i.test(\n\t\terr,\n\t);\n}\n\n/**\n * For GitHub Copilot Gemini, reconstruct flattened tool-call arguments\n * (for example `edits[0].newText`) into the nested arrays/objects Gemini\n * produced before the assistant message is persisted, so saved transcripts\n * never carry the flattened CAPI wire shape and replays loaded from disk match\n * the structure Gemini signed. In-place, gated to Copilot Gemini, and a no-op\n * for well-formed arguments or any other provider/model. The outbound replay\n * normalizer still heals already-persisted (legacy) sessions on the wire.\n */\n\nexport function _normalizePersistedGeminiToolArgs(this: AgentSession, message: AssistantMessage): void {\n\tconst model = this.model;\n\tif (!model || !isCopilotGeminiModel(model)) return;\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst tool = this._toolRegistry.get(block.name);\n\t\tconst normalized = normalizeToolArgumentsForModel(block.arguments, model, tool?.parameters);\n\t\tif (normalized !== block.arguments && normalized !== null && typeof normalized === \"object\") {\n\t\t\tblock.arguments = normalized as Record<string, unknown>;\n\t\t}\n\t}\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\n/**\n * Handle retryable errors with exponential backoff.\n * @returns true if retry was initiated, false if max retries exceeded or disabled\n */\n\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._fallbackModels.length === 0 || !this.model) return false;\n\n\tthis._fallbackAttemptedKeys.add(fallbackKey(this.model, this.thinkingLevel));\n\tconst fromModel = this.model;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst key = fallbackKey(candidate.model, candidate.thinkingLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tconst nextModel = this._withContextWindowForModelSwitch(candidate.model);\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ?? this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (modelsAreEqual(candidate.model, fromModel) && nextLevel === this.thinkingLevel) continue;\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\tthis._appendContextWindowChangeIfChanged(fromModel, nextModel);\n\t\tthis.agent.state.thinkingLevel = nextLevel;\n\t\tthis.sessionManager.appendThinkingLevelChange(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\tsetTimeout(() => {\n\t\t\tthis.agent.continue().then(\n\t\t\t\t() => {\n\t\t\t\t\t// A resolved continuation may still have produced an assistant\n\t\t\t\t\t// error that will be classified by agent_end and may advance to\n\t\t\t\t\t// the next fallback. Do not emit a successful fallback end here;\n\t\t\t\t\t// agent_end/turn_end clear UI state for successful turns, while\n\t\t\t\t\t// fallback exhaustion emits the failure end event.\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), to: modelLabel(nextModel), finalError });\n\t\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t\tthis._resolveRetry();\n\t\t\t\t},\n\t\t\t);\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), finalError: message.errorMessage });\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled) {\n\t\treturn this._trySwitchToFallbackModel(message);\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\tthis._retryAttempt++;\n\n\tif (this._retryAttempt > settings.maxRetries) {\n\t\tif (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 = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);\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_normalizePersistedGeminiToolArgs,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\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":"AAEA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACrG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AAIpF,MAAM,iBAAiB,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAA6C,CAAC;AAClI,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAE5E,SAAS,UAAU,CAAC,KAA6B;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;AAClE,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACxC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACvC,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;IAC3C,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;IACxC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,MAA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,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,iCAAiC;IACjC,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { normalizeToolArgumentsForModel } from \"./copilot-gemini-tool-arguments.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n\nconst THINKING_SUFFIXES = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const satisfies readonly ThinkingLevel[];\nconst THINKING_SUFFIX_SET: ReadonlySet<string> = new Set(THINKING_SUFFIXES);\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction splitFallbackModel(value: string): { modelId: string; thinkingLevel?: ThinkingLevel } {\n\tconst trimmed = value.trim();\n\tconst index = trimmed.lastIndexOf(\":\");\n\tif (index < 0) return { modelId: trimmed };\n\tconst suffix = trimmed.slice(index + 1);\n\tif (!THINKING_SUFFIX_SET.has(suffix)) return { modelId: trimmed };\n\treturn { modelId: trimmed.slice(0, index), thinkingLevel: suffix as ThinkingLevel };\n}\n\nfunction resolveFallbackModel(this: AgentSession, value: string): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\tconst parsed = splitFallbackModel(value);\n\tif (!parsed.modelId.includes(\"/\")) {\n\t\tconst available = this._modelRegistry.getAvailable().filter((model) => model.id === parsed.modelId);\n\t\tconst preferredProvider = this.model?.provider ?? this.settingsManager.getDefaultProvider();\n\t\tconst model = available.find((candidate) => candidate.provider === preferredProvider) ?? (available.length === 1 ? available[0] : undefined);\n\t\treturn model ? { model, thinkingLevel: parsed.thinkingLevel } : undefined;\n\t}\n\tconst slash = parsed.modelId.indexOf(\"/\");\n\tconst provider = parsed.modelId.slice(0, slash);\n\tconst modelId = parsed.modelId.slice(slash + 1);\n\tconst model = this._modelRegistry.find(provider, modelId);\n\tif (!model || !this._modelRegistry.hasConfiguredAuth(model)) return undefined;\n\treturn { model, thinkingLevel: parsed.thinkingLevel };\n}\n\nfunction fallbackKey(model: Model<Api>, thinkingLevel: ThinkingLevel | undefined): string {\n\treturn `${model.provider}/${model.id}:${thinkingLevel ?? \"\"}`;\n}\n\nfunction hasProviderTransportDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") {\n\t\treturn /provider_transport_failure|websocket.*error|sse.*404/i.test(String(value));\n\t}\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage, record.status, record.statusCode]\n\t\t: [record.type, record.code, record.name, record.status, record.statusCode];\n\tfor (const field of fields) {\n\t\t if (typeof field === \"string\" || typeof field === \"number\") {\n\t\t\tif (/provider_transport_failure|websocket.*error|sse.*404|\\b404\\b/i.test(String(field))) return true;\n\t\t}\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderTransportDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasProviderModelUnavailableDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage]\n\t\t: [record.type, record.code, record.name, record.errorMessage];\n\tfor (const field of fields) {\n\t\tif (typeof field === \"string\" && /model(?:[_\\s-].*)?(?:not[_\\s-]?found|unavailable|unknown|disabled)|model[_-]?not[_-]?found/i.test(field)) return true;\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderModelUnavailableDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\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\t// A definitive Codex authentication rejection is terminal. It takes\n\t// precedence over transport diagnostics recorded during WebSocket-to-SSE\n\t// fallback so those earlier diagnostics cannot trigger a pointless retry.\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && isCodexTokenInvalidationError(provider, message.errorMessage)) return false;\n\n\tif (hasProviderTransportDiagnostic(message) || hasProviderModelUnavailableDiagnostic(message)) return true;\n\tif (!message.errorMessage) return false;\n\n\tconst err = message.errorMessage;\n\n\t// Safety triggers surface through structured API signals that pi-ai maps to\n\t// stopReason \"error\":\n\t// - Anthropic `refusal` stops become pi-ai's canned \"The model refused to\n\t// complete the request\" error message;\n\t// - OpenAI-style APIs (and github-copilot CAPI, which also maps spurious\n\t// Gemini RECITATION/safety blocks this way) surface\n\t// `finish_reason: content_filter`.\n\t// Spurious safety triggers are common in agentic settings, so these are\n\t// re-requested like transient failures, bounded by maxRetries (issue #1608).\n\tif (/refused to complete the request|finish.?reason:?\\s*content.?filter/i.test(err)) {\n\t\treturn true;\n\t}\n\n\t// Match: overloaded_error, provider returned error, rate limit, quota/usage-limit exhaustion (e.g. \"Codex error: The usage limit has been reached\" — retryable so configured fallbackModels can advance to a provider/model with remaining headroom), 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, premature stream endings, HTTP/2 closed before response, terminated, retry delay exceeded, and a bare/transient provider finish_reason \"error\" (e.g. github-copilot Gemini's CAPI mapping of MALFORMED_FUNCTION_CALL/OTHER/UNEXPECTED_TOOL_CALL). These are provider-agnostic transient failures.\n\treturn /overloaded|provider.?returned.?error|rate.?limit|usage.?limit|quota|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay|finish.?reason:?\\s*error/i.test(\n\t\terr,\n\t);\n}\n\n/**\n * For GitHub Copilot Gemini, reconstruct flattened tool-call arguments\n * (for example `edits[0].newText`) into the nested arrays/objects Gemini\n * produced before the assistant message is persisted, so saved transcripts\n * never carry the flattened CAPI wire shape and replays loaded from disk match\n * the structure Gemini signed. In-place, gated to Copilot Gemini, and a no-op\n * for well-formed arguments or any other provider/model. The outbound replay\n * normalizer still heals already-persisted (legacy) sessions on the wire.\n */\n\nexport function _normalizePersistedGeminiToolArgs(this: AgentSession, message: AssistantMessage): void {\n\tconst model = this.model;\n\tif (!model || !isCopilotGeminiModel(model)) return;\n\tfor (const block of message.content) {\n\t\tif (block.type !== \"toolCall\") continue;\n\t\tconst tool = this._toolRegistry.get(block.name);\n\t\tconst normalized = normalizeToolArgumentsForModel(block.arguments, model, tool?.parameters);\n\t\tif (normalized !== block.arguments && normalized !== null && typeof normalized === \"object\") {\n\t\t\tblock.arguments = normalized as Record<string, unknown>;\n\t\t}\n\t}\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\n/**\n * Handle retryable errors with exponential backoff.\n * @returns true if retry was initiated, false if max retries exceeded or disabled\n */\n\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._fallbackModels.length === 0 || !this.model) return false;\n\n\tthis._fallbackAttemptedKeys.add(fallbackKey(this.model, this.thinkingLevel));\n\tconst fromModel = this.model;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst key = fallbackKey(candidate.model, candidate.thinkingLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tconst nextModel = this._withContextWindowForModelSwitch(candidate.model);\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ?? this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (modelsAreEqual(candidate.model, fromModel) && nextLevel === this.thinkingLevel) continue;\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\tthis._appendContextWindowChangeIfChanged(fromModel, nextModel);\n\t\tthis.agent.state.thinkingLevel = nextLevel;\n\t\tthis.sessionManager.appendThinkingLevelChange(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\tsetTimeout(() => {\n\t\t\tthis.agent.continue().then(\n\t\t\t\t() => {\n\t\t\t\t\t// A resolved continuation may still have produced an assistant\n\t\t\t\t\t// error that will be classified by agent_end and may advance to\n\t\t\t\t\t// the next fallback. Do not emit a successful fallback end here;\n\t\t\t\t\t// agent_end/turn_end clear UI state for successful turns, while\n\t\t\t\t\t// fallback exhaustion emits the failure end event.\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), to: modelLabel(nextModel), finalError });\n\t\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t\tthis._resolveRetry();\n\t\t\t\t},\n\t\t\t);\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), finalError: message.errorMessage });\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled) {\n\t\treturn this._trySwitchToFallbackModel(message);\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\tthis._retryAttempt++;\n\n\tif (this._retryAttempt > settings.maxRetries) {\n\t\tif (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 = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);\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_normalizePersistedGeminiToolArgs,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
@@ -1,8 +1,11 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai/compat";
1
3
  import type { AgentSession } from "./agent-session.ts";
2
4
  import type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from "./agent-session-services.ts";
3
5
  import type { ProjectTrustContext, ReplacedSessionContext, SessionStartEvent } from "./extensions/index.ts";
4
6
  import type { CreateAgentSessionResult } from "./sdk.ts";
5
7
  import { SessionManager } from "./session-manager.ts";
8
+ import type { AuthStatus } from "./auth-storage.ts";
6
9
  /**
7
10
  * Result returned by runtime creation.
8
11
  *
@@ -13,6 +16,15 @@ export interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResul
13
16
  services: AgentSessionServices;
14
17
  diagnostics: AgentSessionRuntimeDiagnostic[];
15
18
  }
19
+ export interface LogoutProviderResult {
20
+ provider: string;
21
+ authStatus: AuthStatus;
22
+ models: Model<Api>[];
23
+ scopedModels?: Array<{
24
+ model: Model<Api>;
25
+ thinkingLevel?: ThinkingLevel;
26
+ }>;
27
+ }
16
28
  /**
17
29
  * Creates a full runtime for a target cwd and session manager.
18
30
  *
@@ -55,6 +67,7 @@ export declare class AgentSessionRuntime {
55
67
  get cwd(): string;
56
68
  get diagnostics(): readonly AgentSessionRuntimeDiagnostic[];
57
69
  get modelFallbackMessage(): string | undefined;
70
+ logoutProvider(provider: string): Promise<LogoutProviderResult>;
58
71
  setRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void;
59
72
  /**
60
73
  * Set a synchronous callback that runs after `session_shutdown` handlers finish
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-runtime.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,6BAA6B,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACvG,OAAO,KAAK,EACX,mBAAmB,EACnB,sBAAsB,EAEtB,iBAAiB,EACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,WAAW,+BAAgC,SAAQ,wBAAwB;IAChF,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,WAAW,EAAE,6BAA6B,EAAE,CAAC;CAC7C;AAED;;;;;;GAMG;AACH,MAAM,MAAM,gCAAgC,GAAG,CAAC,OAAO,EAAE;IACxD,GAAG,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AAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAuFxD;IAED;;;;;;OAMG;IACG,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC,CAmC9F;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAO7B;CACD;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC9C,aAAa,EAAE,gCAAgC,EAC/C,OAAO,EAAE;IACR,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC,GACC,OAAO,CAAC,mBAAmB,CAAC,CAU9B;AAED,OAAO,EACN,KAAK,6BAA6B,EAClC,KAAK,oBAAoB,EACzB,KAAK,qCAAqC,EAC1C,KAAK,iCAAiC,EACtC,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC"}
@@ -53,6 +53,18 @@ export class AgentSessionRuntime {
53
53
  get modelFallbackMessage() {
54
54
  return this._modelFallbackMessage;
55
55
  }
56
+ async logoutProvider(provider) {
57
+ const registry = this.session.modelRegistry;
58
+ await registry.authStorage.logoutAsync(provider);
59
+ await registry.refresh({ allowNetwork: false });
60
+ this.session.refreshCurrentModelFromRegistry();
61
+ return {
62
+ provider,
63
+ authStatus: registry.getProviderAuthStatus(provider),
64
+ models: registry.getAvailable(),
65
+ scopedModels: [...this.session.scopedModels],
66
+ };
67
+ }
56
68
  setRebindSession(rebindSession) {
57
69
  this.rebindSession = rebindSession;
58
70
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;A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AC,OAAO;QACZ,MAAM,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE;YAC5D,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,MAAM;SACd,CAAC,CAAC;QACH,IAAI,CAAC,uBAAuB,EAAE,EAAE,CAAC;QACjC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,aAA+C,EAC/C,OAKC;IAED,sBAAsB,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,IAAI,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,CAC3B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\n\tdeclare private _session: AgentSession;\n\tdeclare private _services: AgentSessionServices;\n\tdeclare private readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tdeclare private _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tdeclare private _modelFallbackMessage?: string;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t\tprojectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\tif (options?.parentSession) {\n\t\t\tsessionManager.newSession({ parentSession: options.parentSession });\n\t\t}\n\n\t\tawait this.teardownCurrent(\"new\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"new\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.agent.state.messages = this.session.sessionManager.buildSessionContext().messages;\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\t\t\tsessionManager.newSession({ parentSession: currentSessionFile });\n\t\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\t\tthis.apply(\n\t\t\t\t\tawait this.createRuntime({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\t\tsessionManager,\n\t\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This session has not been saved yet. Wait for the first assistant response before cloning or forking it.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\tif (!forkedSessionPath) {\n\t\t\t\tthrow new Error(\"Failed to create forked session\");\n\t\t\t}\n\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t}),\n\t\t\t);\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: this.session.sessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tconst destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (resolve(destinationPath) !== resolvedPath) {\n\t\t\tcopyFileSync(resolvedPath, destinationPath);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\n"]}
1
+ {"version":3,"file":"agent-session-runtime.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAShD,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAoCtD;;GAEG;AACH,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAGxD,YAAY,QAAgB;QAC3B,KAAK,CAAC,mBAAmB,QAAQ,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;QAC7C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,SAAS,sBAAsB,CAAC,OAAwD;IACvF,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,OAAO,OAAO;SACZ,MAAM,CAAC,CAAC,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AuB,EAAE,EAAE,CAAC;QACjC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACD;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,aAA+C,EAC/C,OAKC;IAED,sBAAsB,CAAC,OAAO,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,IAAI,mBAAmB,CAC7B,MAAM,CAAC,OAAO,EACd,MAAM,CAAC,QAAQ,EACf,aAAa,EACb,MAAM,CAAC,WAAW,EAClB,MAAM,CAAC,oBAAoB,CAC3B,CAAC;AACH,CAAC;AAED,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC","sourcesContent":["import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from \"./agent-session-services.ts\";\nimport type {\n\tProjectTrustContext,\n\tReplacedSessionContext,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n} from \"./extensions/index.ts\";\nimport { emitSessionShutdownEvent } from \"./extensions/runner.ts\";\nimport type { CreateAgentSessionResult } from \"./sdk.ts\";\nimport { assertSessionCwdExists } from \"./session-cwd.ts\";\nimport { SessionManager } from \"./session-manager.ts\";\nimport type { AuthStatus } from \"./auth-storage.ts\";\n\n/**\n * Result returned by runtime creation.\n *\n * The caller gets the created session, its cwd-bound services, and all\n * diagnostics collected during setup.\n */\nexport interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {\n\tservices: AgentSessionServices;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nexport interface LogoutProviderResult {\n\tprovider: string;\n\tauthStatus: AuthStatus;\n\tmodels: Model<Api>[];\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n}\n\n/**\n * Creates a full runtime for a target cwd and session manager.\n *\n * The factory closes over process-global fixed inputs, recreates cwd-bound\n * services for the effective cwd, resolves session options against those\n * services, and finally creates the AgentSession.\n */\nexport type CreateAgentSessionRuntimeFactory = (options: {\n\tcwd: string;\n\tagentDir: string;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tprojectTrustContext?: ProjectTrustContext;\n}) => Promise<CreateAgentSessionRuntimeResult>;\n\n/**\n * Thrown when /import references a JSONL file path that does not exist.\n */\nexport class SessionImportFileNotFoundError extends Error {\n\treadonly filePath: string;\n\n\tconstructor(filePath: string) {\n\t\tsuper(`File not found: ${filePath}`);\n\t\tthis.name = \"SessionImportFileNotFoundError\";\n\t\tthis.filePath = filePath;\n\t}\n}\n\nfunction extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\n\treturn content\n\t\t.filter((part): part is { type: \"text\"; text: string } => part.type === \"text\" && typeof part.text === \"string\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\");\n}\n\n/**\n * Owns the current AgentSession plus its cwd-bound services.\n *\n * Session replacement methods tear down the current runtime first, then create\n * and apply the next runtime. If creation fails, the error is propagated to the\n * caller. The caller is responsible for user-facing error handling.\n */\nexport class AgentSessionRuntime {\n\tprivate rebindSession?: (session: AgentSession) => Promise<void>;\n\tprivate beforeSessionInvalidate?: () => void;\n\n\tdeclare private _session: AgentSession;\n\tdeclare private _services: AgentSessionServices;\n\tdeclare private readonly createRuntime: CreateAgentSessionRuntimeFactory;\n\tdeclare private _diagnostics: AgentSessionRuntimeDiagnostic[];\n\tdeclare private _modelFallbackMessage?: string;\n\n\tconstructor(\n\t\t_session: AgentSession,\n\t\t_services: AgentSessionServices,\n\t\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\t\t_diagnostics: AgentSessionRuntimeDiagnostic[] = [],\n\t\t_modelFallbackMessage?: string,\n\t) {\n\t\tthis._session = _session;\n\t\tthis._services = _services;\n\t\tthis.createRuntime = createRuntime;\n\t\tthis._diagnostics = _diagnostics;\n\t\tthis._modelFallbackMessage = _modelFallbackMessage;\n\t}\n\n\tget services(): AgentSessionServices {\n\t\treturn this._services;\n\t}\n\n\tget session(): AgentSession {\n\t\treturn this._session;\n\t}\n\n\tget cwd(): string {\n\t\treturn this._services.cwd;\n\t}\n\n\tget diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {\n\t\treturn this._diagnostics;\n\t}\n\n\tget modelFallbackMessage(): string | undefined {\n\t\treturn this._modelFallbackMessage;\n\t}\n\n\tasync logoutProvider(provider: string): Promise<LogoutProviderResult> {\n\t\tconst registry = this.session.modelRegistry;\n\t\tawait registry.authStorage.logoutAsync(provider);\n\t\tawait registry.refresh({ allowNetwork: false });\n\t\tthis.session.refreshCurrentModelFromRegistry();\n\t\treturn {\n\t\t\tprovider,\n\t\t\tauthStatus: registry.getProviderAuthStatus(provider),\n\t\t\tmodels: registry.getAvailable(),\n\t\t\tscopedModels: [...this.session.scopedModels],\n\t\t};\n\t}\n\n\tsetRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {\n\t\tthis.rebindSession = rebindSession;\n\t}\n\n\t/**\n\t * Set a synchronous callback that runs after `session_shutdown` handlers finish\n\t * but before the current session is invalidated.\n\t *\n\t * This is for host-owned UI teardown that must not yield to the event loop,\n\t * such as detaching extension-provided TUI components before the old extension\n\t * context becomes stale.\n\t */\n\tsetBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {\n\t\tthis.beforeSessionInvalidate = beforeSessionInvalidate;\n\t}\n\n\tprivate async emitBeforeSwitch(\n\t\treason: \"new\" | \"resume\",\n\t\ttargetSessionFile?: string,\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_switch\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_switch\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async emitBeforeFork(\n\t\tentryId: string,\n\t\toptions: { position: \"before\" | \"at\" },\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst runner = this.session.extensionRunner;\n\t\tif (!runner.hasHandlers(\"session_before_fork\")) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\tconst result = await runner.emit({\n\t\t\ttype: \"session_before_fork\",\n\t\t\tentryId,\n\t\t\t...options,\n\t\t});\n\t\treturn { cancelled: result?.cancel === true };\n\t}\n\n\tprivate async teardownCurrent(reason: SessionShutdownEvent[\"reason\"], targetSessionFile?: string): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason,\n\t\t\ttargetSessionFile,\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n\n\tprivate apply(result: CreateAgentSessionRuntimeResult): void {\n\t\tthis._session = result.session;\n\t\tthis._services = result.services;\n\t\tthis._diagnostics = result.diagnostics;\n\t\tthis._modelFallbackMessage = result.modelFallbackMessage;\n\t}\n\n\tprivate async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {\n\t\tif (this.rebindSession) {\n\t\t\tawait this.rebindSession(this.session);\n\t\t}\n\t\tif (withSession) {\n\t\t\tawait withSession(this.session.createReplacedSessionContext());\n\t\t}\n\t}\n\n\tasync switchSession(\n\t\tsessionPath: string,\n\t\toptions?: {\n\t\t\tcwdOverride?: string;\n\t\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t\t\tprojectTrustContextFactory?: (cwd: string) => ProjectTrustContext;\n\t\t},\n\t): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", sessionPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t\tprojectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()),\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }> {\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"new\");\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\tif (options?.parentSession) {\n\t\t\tsessionManager.newSession({ parentSession: options.parentSession });\n\t\t}\n\n\t\tawait this.teardownCurrent(\"new\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"new\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.session.sessionManager);\n\t\t\tthis.session.agent.state.messages = this.session.sessionManager.buildSessionContext().messages;\n\t\t}\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false };\n\t}\n\n\tasync fork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean; selectedText?: string }> {\n\t\tconst position = options?.position ?? \"before\";\n\t\tconst beforeResult = await this.emitBeforeFork(entryId, { position });\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn { cancelled: true };\n\t\t}\n\t\tlet targetLeafId: string | null;\n\t\tlet selectedText: string | undefined;\n\n\t\tconst selectedEntry = this.session.sessionManager.getEntry(entryId);\n\t\tif (!selectedEntry) {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tif (position === \"at\") {\n\t\t\ttargetLeafId = selectedEntry.id;\n\t\t} else {\n\t\t\tif (selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t\t}\n\t\t\ttargetLeafId = selectedEntry.parentId;\n\t\t\tselectedText = extractUserMessageText(selectedEntry.message.content);\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (this.session.sessionManager.isPersisted()) {\n\t\t\tconst currentSessionFile = this.session.sessionFile;\n\t\t\tif (!currentSessionFile) {\n\t\t\t\tthrow new Error(\"Persisted session is missing a session file\");\n\t\t\t}\n\t\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\t\tif (!targetLeafId) {\n\t\t\t\tconst sessionManager = SessionManager.create(this.cwd, sessionDir);\n\t\t\t\tsessionManager.newSession({ parentSession: currentSessionFile });\n\t\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\t\tthis.apply(\n\t\t\t\t\tawait this.createRuntime({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\t\tsessionManager,\n\t\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\t\treturn { cancelled: false, selectedText };\n\t\t\t}\n\n\t\t\tif (!existsSync(currentSessionFile)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This session has not been saved yet. Wait for the first assistant response before cloning or forking it.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst sessionManager = SessionManager.open(currentSessionFile, sessionDir);\n\t\t\tconst forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);\n\t\t\tif (!forkedSessionPath) {\n\t\t\t\tthrow new Error(\"Failed to create forked session\");\n\t\t\t}\n\t\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\t\tthis.apply(\n\t\t\t\tawait this.createRuntime({\n\t\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\t\tsessionManager,\n\t\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t\t}),\n\t\t\t);\n\t\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\t\treturn { cancelled: false, selectedText };\n\t\t}\n\n\t\tconst sessionManager = this.session.sessionManager;\n\t\tif (!targetLeafId) {\n\t\t\tsessionManager.newSession({ parentSession: this.session.sessionFile });\n\t\t} else {\n\t\t\tsessionManager.createBranchedSession(targetLeafId);\n\t\t}\n\t\tawait this.teardownCurrent(\"fork\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"fork\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement(options?.withSession);\n\t\treturn { cancelled: false, selectedText };\n\t}\n\n\t/**\n\t * Import a session JSONL file and switch runtime state to the imported session.\n\t *\n\t * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.\n\t * @throws {SessionImportFileNotFoundError} When the input path does not exist.\n\t * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.\n\t */\n\tasync importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {\n\t\tconst resolvedPath = resolvePath(inputPath);\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tthrow new SessionImportFileNotFoundError(resolvedPath);\n\t\t}\n\n\t\tconst sessionDir = this.session.sessionManager.getSessionDir();\n\t\tif (!existsSync(sessionDir)) {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t}\n\n\t\tconst destinationPath = join(sessionDir, basename(resolvedPath));\n\t\tconst beforeResult = await this.emitBeforeSwitch(\"resume\", destinationPath);\n\t\tif (beforeResult.cancelled) {\n\t\t\treturn beforeResult;\n\t\t}\n\n\t\tconst previousSessionFile = this.session.sessionFile;\n\t\tif (resolve(destinationPath) !== resolvedPath) {\n\t\t\tcopyFileSync(resolvedPath, destinationPath);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);\n\t\tassertSessionCwdExists(sessionManager, this.cwd);\n\t\tawait this.teardownCurrent(\"resume\", sessionManager.getSessionFile());\n\t\tthis.apply(\n\t\t\tawait this.createRuntime({\n\t\t\t\tcwd: sessionManager.getCwd(),\n\t\t\t\tagentDir: this.services.agentDir,\n\t\t\t\tsessionManager,\n\t\t\t\tsessionStartEvent: { type: \"session_start\", reason: \"resume\", previousSessionFile },\n\t\t\t}),\n\t\t);\n\t\tawait this.finishSessionReplacement();\n\t\treturn { cancelled: false };\n\t}\n\n\tasync dispose(): Promise<void> {\n\t\tawait emitSessionShutdownEvent(this.session.extensionRunner, {\n\t\t\ttype: \"session_shutdown\",\n\t\t\treason: \"quit\",\n\t\t});\n\t\tthis.beforeSessionInvalidate?.();\n\t\tthis.session.dispose();\n\t}\n}\n\n/**\n * Create the initial runtime from a runtime factory and initial session target.\n *\n * The same factory is stored on the returned AgentSessionRuntime and reused for\n * later /new, /resume, /fork, and import flows.\n */\nexport async function createAgentSessionRuntime(\n\tcreateRuntime: CreateAgentSessionRuntimeFactory,\n\toptions: {\n\t\tcwd: string;\n\t\tagentDir: string;\n\t\tsessionManager: SessionManager;\n\t\tsessionStartEvent?: SessionStartEvent;\n\t},\n): Promise<AgentSessionRuntime> {\n\tassertSessionCwdExists(options.sessionManager, options.cwd);\n\tconst result = await createRuntime(options);\n\treturn new AgentSessionRuntime(\n\t\tresult.session,\n\t\tresult.services,\n\t\tcreateRuntime,\n\t\tresult.diagnostics,\n\t\tresult.modelFallbackMessage,\n\t);\n}\n\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\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,qCACT,CAAC;AA6NrC,QAAA,MAAM,cAAc;mBAEV,UAAU;;oBAET,UAAU;0BACJ,oBAAoB;;;mBAI3B,WAAW;;oBAEV,WAAW;0BACL,iBAAiB;;;mBAIxB,SAAS;;oBAER,SAAS;0BACH,0BAA0B;;;mBAIjC,WAAW;;oBAEV,YAAY;0BACN,sBAAsB;;EASpC,CAAC;A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,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,EACtB,CAAC;AAiBjD,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,MAAM,GACb,MAAM,IAAI,qBAAqB,CAEjC;AAoCD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAOtE;AAED,wBAAgB,iCAAiC,CAC/C,MAAM,EAAE,MAAM,GACb,gBAAgB,EAAE,GAAG,IAAI,CAa3B;AAED,iBAAS,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CActD;AAED,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,eAAe,EACrB,GAAG,EAAE,MAAM,GACV,MAAM,CAGR;AAED,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,qBAAqB,GAC5B,eAAe,CAEjB"}
@@ -159,6 +159,8 @@ If you are drafting research, reviewer, or synthesis prompts for a workflow, use
159
159
 
160
160
  A good workflow request is explicit about stage purpose, model choice, handoff, and the decision each step must return.
161
161
 
162
+ For 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.
163
+
162
164
  Example: ask Atomic in chat with something like this:
163
165
 
164
166
  ~~~text
@@ -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,EAA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C;AAC1D,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 =\n \"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 | Chain \\`/skill:research-codebase\\` → \\`/skill:create-spec\\` → 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\" --bg\\`, or \\`/workflow deep-research-codebase\\` for whole-repo synthesis |\n| UI / product polish | Run \\`/skill:impeccable\\` for interface critique and refinement, or \\`/workflow open-claude-design\\` for generation + refinement loops |\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`deep-research-codebase\\` | broad repo or cross-cutting research before you decide what to change (for one area, use \\`/skill:research-codebase\\`; this indexes the whole repo) | \\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\` |\n| \\`goal\\` | autonomous work that benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion; add \\`create_pr=true\\` only for final PR handoff after approval | \\`/workflow goal objective=\"Implement specs/<date>-<topic>.md, run focused tests, and validate the changed behavior\"\\` |\n| \\`ralph\\` | autonomous work that benefits from a durable research-first pipeline, delegated implementation, and iterative review | \\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\` |\n| \\`open-claude-design\\` | UI and design-system work that benefits from generation and refinement loops | \\`/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\\`, \\`/parallel\\`, and \\`/chain\\` usage | \\`/skill:subagent\\` |\n| \\`impeccable\\` | critique or refine frontend and product UI | \\`/skill:impeccable\\` |\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\" --bg\\`\n- \\`/chain\\` = ordered handoffs, for example \\`/chain codebase-locator \"find the auth files\" -> codebase-analyzer \"trace the auth flow\" -> debugger \"patch the failing auth edge case\"\\`\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\nUse \\`deep-research-codebase\\` when the answer spans the whole repo or a cross-cutting implementation path:\n\n\\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\`\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 work that fits a durable goal ledger, bounded worker turns, and reviewer-gated completion, use \\`goal\\`:\n\n\\`/workflow goal objective=\"Implement specs/<date>-<topic>.md, run focused tests, and finish when the documented behavior is validated\"\\`\n\nLoop or stop-condition phrasing is a key workflow signal. When the user delegates a loop such as \\`do X until Y\\`, \\`repeat until\\`, \\`iterate until\\`, \\`review/fix until passing\\`, \\`run checks and fix until green\\`, or \\`keep going until done\\`, make the stop condition explicit in the Goal objective:\n\n\\`/workflow goal objective=\"Fix the flaky checkout test, adjust the smallest necessary code, and finish when the focused test passes three times\"\\`\n\nWhen a clearly delegated autonomous job benefits from a durable research-first pipeline with orchestration and iterative review, use \\`ralph\\`:\n\n\\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\"\\`\n\nAdd \\`create_pr=true\\` only when you want the final pull-request stage and report after the review gate approves.\n\n## 4. Decide and land\n\nIf you used \\`goal\\`, the workflow already persisted receipts in a goal ledger and reviewer-gated completion. Use its final status — \\`complete\\`, \\`blocked\\`, or \\`needs_human\\` — plus the remaining-work report to decide whether to ship, unblock, or clarify. If you enabled \\`create_pr=true\\`, use its final pull-request report to decide whether to ship or iterate again.\n\nIf you used \\`ralph\\`, the workflow transformed the prompt into a research question, researched the codebase, delegated implementation through sub-agents, reviewed, and iterated. If you enabled \\`create_pr=true\\`, use its final pull-request report to decide whether to ship or iterate again.\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| \\`deep-research-codebase\\` | broad repo or cross-cutting research before you decide what to change (for one area, use \\`/skill:research-codebase\\`; this indexes the whole repo) | \\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\` |\n| \\`goal\\` | autonomous work that benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion; add \\`create_pr=true\\` only for final PR handoff after approval | \\`/workflow goal objective=\"Update the CLI docs, include one usage example, and verify the docs build passes\"\\` |\n| \\`ralph\\` | autonomous work that benefits from a durable research-first pipeline, delegated implementation, and iterative review | \\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\` |\n| \\`open-claude-design\\` | frontend and product design work | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow inputs <name>\\` to inspect the exact inputs in your environment.\n\nUse \\`/skill:research-codebase ...\\` when you want research on one subsystem, directory, or focused question. Use \\`/workflow deep-research-codebase ...\\` when the answer needs end-to-end tracing across many parts of the repo.\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\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 goal\\`\n\n\\`/workflow goal objective=\"Fix the settings form validation bug, add the focused test, and finish when invalid emails show the inline error without submitting\"\\`\n\n\\`/workflow inputs ralph\\`\n\n\\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\`\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 {\n name: \"overview\",\n aliases: [],\n label: \"overview\",\n description: \"30-second overview\",\n render: () => OVERVIEW,\n },\n {\n name: \"workflows\",\n aliases: [\"workflow\"],\n label: \"workflows\",\n description: \"Workflow primer\",\n render: () => WORKFLOWS,\n },\n {\n name: \"example\",\n aliases: [\"examples\"],\n label: \"example\",\n description: \"Practical first workflow\",\n render: () => EXAMPLE,\n },\n {\n name: \"whats-new\",\n aliases: [\"what's new\", \"whats new\", \"news\", \"updates\", \"changelog\"],\n label: \"what's new\",\n description: \"Recent release notes\",\n render: readLatestStableChangelog,\n },\n] as const satisfies readonly {\n readonly name: string;\n readonly aliases: readonly string[];\n readonly label: string;\n readonly description: string;\n readonly 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[] =\n GUIDE_SECTIONS.map((section) => section.label);\n\nconst GUIDE_SECTIONS_BY_NAME = new Map<\n AtomicGuideSectionName,\n AtomicGuideSection\n>(GUIDE_SECTIONS.map((section) => [section.name, section]));\nconst GUIDE_SECTIONS_BY_LABEL = new Map<string, AtomicGuideSection>(\n GUIDE_SECTIONS.map((section) => [section.label, section]),\n);\nconst GUIDE_SECTIONS_BY_INPUT = new Map<string, AtomicGuideSection>(\n GUIDE_SECTIONS.flatMap((section) =>\n [section.name, section.label, ...section.aliases].map(\n (input) => [input, section] as const,\n ),\n ),\n);\n\nexport function isAtomicGuideHelpChoice(\n choice: string,\n): choice is AtomicGuideHelpChoice {\n return GUIDE_SECTIONS_BY_LABEL.has(choice);\n}\n\nconst ATOMIC_GUIDE_TRAILING_PUNCTUATION = \"?!.,;:\";\n\nfunction stripTrailingAtomicGuidePunctuation(value: string): string {\n let end = value.length;\n while (\n end > 0 &&\n ATOMIC_GUIDE_TRAILING_PUNCTUATION.includes(value.charAt(end - 1))\n ) {\n end--;\n }\n return value.slice(0, end);\n}\n\nfunction getGuideSectionForChoice(\n choice: string,\n): AtomicGuideSection | undefined {\n return GUIDE_SECTIONS_BY_LABEL.get(choice);\n}\n\nfunction getGuideSectionForMode(\n mode: AtomicGuideSectionName,\n): AtomicGuideSection {\n const section = GUIDE_SECTIONS_BY_NAME.get(mode);\n if (!section) throw new Error(`Unknown Atomic guide section: ${mode}`);\n return section;\n}\n\nfunction getAtomicGuideHelpMenu(): string {\n const sectionHelp = GUIDE_SECTIONS.map(\n (section) => `- \\`${section.label}\\` — run \\`/atomic ${section.label}\\``,\n ).join(\"\\n\");\n return `# Atomic\\n\\nSelect where to start:\\n\\n${sectionHelp}`;\n}\n\nexport function normalizeAtomicGuideMode(args: string): AtomicGuideMode {\n const normalized = stripTrailingAtomicGuidePunctuation(\n args.trim().toLowerCase(),\n );\n if (!normalized) return \"help\";\n\n return GUIDE_SECTIONS_BY_INPUT.get(normalized)?.name ?? \"help\";\n}\n\nexport function getAtomicGuideArgumentCompletions(\n prefix: string,\n): AutocompleteItem[] | null {\n const query = prefix.trim().toLowerCase();\n const items = GUIDE_SECTIONS.map((section) => ({\n value: section.label,\n label: section.label,\n description: section.description,\n }));\n const filtered = query\n ? items.filter(\n (item) => item.value.startsWith(query) || item.label.startsWith(query),\n )\n : items;\n return filtered.length > 0 ? filtered : null;\n}\n\nfunction readLatestStableChangelog(cwd: string): string {\n const changelogPath = getChangelogPath();\n const stableSections = parseChangelog(changelogPath)\n .filter((entry) => entry.prerelease === null)\n .slice(0, 3)\n .map((entry) => entry.content.trim())\n .filter(Boolean);\n\n if (stableSections.length === 0) {\n return `# 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 }\n\n const relativePath = path.relative(cwd, changelogPath) || changelogPath;\n return `# 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(\n mode: AtomicGuideMode,\n cwd: string,\n): string {\n if (mode === \"help\") return getAtomicGuideHelpMenu();\n return getGuideSectionForMode(mode).render(cwd);\n}\n\nexport function atomicGuideModeForChoice(\n choice: AtomicGuideHelpChoice,\n): AtomicGuideMode {\n return 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,GAC3C,kCAAkC,CAAC;AAErC,MAAM,QAAQ,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;oDAqEmC,CAAC;AAErD,MAAM,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AC;IACzC,MAAM,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC;SACjD,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC;SAC5C,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;SACX,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;SACpC,MAAM,CAAC,OAAO,CAAC,CAAC;IAEnB,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChC,OAAO,sSAAsS,CAAC;IAChT,CAAC;IAED,MAAM,YAAY,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,aAAa,CAAC,IAAI,aAAa,CAAC;IACxE,OAAO,mBAAmB,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,iBAAiB,YAAY,yLAAyL,CAAC;AAC9Q,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,IAAqB,EACrB,GAAW;IAEX,IAAI,IAAI,KAAK,MAAM;QAAE,OAAO,sBAAsB,EAAE,CAAC;IACrD,OAAO,sBAAsB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,MAA6B;IAE7B,OAAO,wBAAwB,CAAC,MAAM,CAAC,EAAE,IAAI,IAAI,MAAM,CAAC;AAC1D,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 =\n \"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 | Chain \\`/skill:research-codebase\\` → \\`/skill:create-spec\\` → 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\" --bg\\`, or \\`/workflow deep-research-codebase\\` for whole-repo synthesis |\n| UI / product polish | Run \\`/skill:impeccable\\` for interface critique and refinement, or \\`/workflow open-claude-design\\` for generation + refinement loops |\n\n## Built-in workflows\n\n| Workflow | When to use | How to run |\n|---|---|---|\n| \\`deep-research-codebase\\` | broad repo or cross-cutting research before you decide what to change (for one area, use \\`/skill:research-codebase\\`; this indexes the whole repo) | \\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\` |\n| \\`goal\\` | autonomous work that benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion; add \\`create_pr=true\\` only for final PR handoff after approval | \\`/workflow goal objective=\"Implement specs/<date>-<topic>.md, run focused tests, and validate the changed behavior\"\\` |\n| \\`ralph\\` | autonomous work that benefits from a durable research-first pipeline, delegated implementation, and iterative review | \\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\` |\n| \\`open-claude-design\\` | UI and design-system work that benefits from generation and refinement loops | \\`/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\\`, \\`/parallel\\`, and \\`/chain\\` usage | \\`/skill:subagent\\` |\n| \\`impeccable\\` | critique or refine frontend and product UI | \\`/skill:impeccable\\` |\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\" --bg\\`\n- \\`/chain\\` = ordered handoffs, for example \\`/chain codebase-locator \"find the auth files\" -> codebase-analyzer \"trace the auth flow\" -> debugger \"patch the failing auth edge case\"\\`\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\nUse \\`deep-research-codebase\\` when the answer spans the whole repo or a cross-cutting implementation path:\n\n\\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\`\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 work that fits a durable goal ledger, bounded worker turns, and reviewer-gated completion, use \\`goal\\`:\n\n\\`/workflow goal objective=\"Implement specs/<date>-<topic>.md, run focused tests, and finish when the documented behavior is validated\"\\`\n\nLoop or stop-condition phrasing is a key workflow signal. When the user delegates a loop such as \\`do X until Y\\`, \\`repeat until\\`, \\`iterate until\\`, \\`review/fix until passing\\`, \\`run checks and fix until green\\`, or \\`keep going until done\\`, make the stop condition explicit in the Goal objective:\n\n\\`/workflow goal objective=\"Fix the flaky checkout test, adjust the smallest necessary code, and finish when the focused test passes three times\"\\`\n\nWhen a clearly delegated autonomous job benefits from a durable research-first pipeline with orchestration and iterative review, use \\`ralph\\`:\n\n\\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\"\\`\n\nAdd \\`create_pr=true\\` only when you want the final pull-request stage and report after the review gate approves.\n\n## 4. Decide and land\n\nIf you used \\`goal\\`, the workflow already persisted receipts in a goal ledger and reviewer-gated completion. Use its final status — \\`complete\\`, \\`blocked\\`, or \\`needs_human\\` — plus the remaining-work report to decide whether to ship, unblock, or clarify. If you enabled \\`create_pr=true\\`, use its final pull-request report to decide whether to ship or iterate again.\n\nIf you used \\`ralph\\`, the workflow transformed the prompt into a research question, researched the codebase, delegated implementation through sub-agents, reviewed, and iterated. If you enabled \\`create_pr=true\\`, use its final pull-request report to decide whether to ship or iterate again.\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| \\`deep-research-codebase\\` | broad repo or cross-cutting research before you decide what to change (for one area, use \\`/skill:research-codebase\\`; this indexes the whole repo) | \\`/workflow deep-research-codebase prompt=\"How do payment retries work end to end?\"\\` |\n| \\`goal\\` | autonomous work that benefits from a durable goal ledger, bounded worker turns, named validation, and reviewer-gated completion; add \\`create_pr=true\\` only for final PR handoff after approval | \\`/workflow goal objective=\"Update the CLI docs, include one usage example, and verify the docs build passes\"\\` |\n| \\`ralph\\` | autonomous work that benefits from a durable research-first pipeline, delegated implementation, and iterative review | \\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\` |\n| \\`open-claude-design\\` | frontend and product design work | \\`/workflow open-claude-design prompt=\"Refresh the settings page hierarchy\"\\` |\n\nUse \\`/workflow inputs <name>\\` to inspect the exact inputs in your environment.\n\nUse \\`/skill:research-codebase ...\\` when you want research on one subsystem, directory, or focused question. Use \\`/workflow deep-research-codebase ...\\` when the answer needs end-to-end tracing across many parts of the repo.\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 goal\\`\n\n\\`/workflow goal objective=\"Fix the settings form validation bug, add the focused test, and finish when invalid emails show the inline error without submitting\"\\`\n\n\\`/workflow inputs ralph\\`\n\n\\`/workflow ralph prompt=\"Migrate the database layer to Drizzle\" create_pr=true\\`\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 {\n name: \"overview\",\n aliases: [],\n label: \"overview\",\n description: \"30-second overview\",\n render: () => OVERVIEW,\n },\n {\n name: \"workflows\",\n aliases: [\"workflow\"],\n label: \"workflows\",\n description: \"Workflow primer\",\n render: () => WORKFLOWS,\n },\n {\n name: \"example\",\n aliases: [\"examples\"],\n label: \"example\",\n description: \"Practical first workflow\",\n render: () => EXAMPLE,\n },\n {\n name: \"whats-new\",\n aliases: [\"what's new\", \"whats new\", \"news\", \"updates\", \"changelog\"],\n label: \"what's new\",\n description: \"Recent release notes\",\n render: readLatestStableChangelog,\n },\n] as const satisfies readonly {\n readonly name: string;\n readonly aliases: readonly string[];\n readonly label: string;\n readonly description: string;\n readonly 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[] =\n GUIDE_SECTIONS.map((section) => section.label);\n\nconst GUIDE_SECTIONS_BY_NAME = new Map<\n AtomicGuideSectionName,\n AtomicGuideSection\n>(GUIDE_SECTIONS.map((section) => [section.name, section]));\nconst GUIDE_SECTIONS_BY_LABEL = new Map<string, AtomicGuideSection>(\n GUIDE_SECTIONS.map((section) => [section.label, section]),\n);\nconst GUIDE_SECTIONS_BY_INPUT = new Map<string, AtomicGuideSection>(\n GUIDE_SECTIONS.flatMap((section) =>\n [section.name, section.label, ...section.aliases].map(\n (input) => [input, section] as const,\n ),\n ),\n);\n\nexport function isAtomicGuideHelpChoice(\n choice: string,\n): choice is AtomicGuideHelpChoice {\n return GUIDE_SECTIONS_BY_LABEL.has(choice);\n}\n\nconst ATOMIC_GUIDE_TRAILING_PUNCTUATION = \"?!.,;:\";\n\nfunction stripTrailingAtomicGuidePunctuation(value: string): string {\n let end = value.length;\n while (\n end > 0 &&\n ATOMIC_GUIDE_TRAILING_PUNCTUATION.includes(value.charAt(end - 1))\n ) {\n end--;\n }\n return value.slice(0, end);\n}\n\nfunction getGuideSectionForChoice(\n choice: string,\n): AtomicGuideSection | undefined {\n return GUIDE_SECTIONS_BY_LABEL.get(choice);\n}\n\nfunction getGuideSectionForMode(\n mode: AtomicGuideSectionName,\n): AtomicGuideSection {\n const section = GUIDE_SECTIONS_BY_NAME.get(mode);\n if (!section) throw new Error(`Unknown Atomic guide section: ${mode}`);\n return section;\n}\n\nfunction getAtomicGuideHelpMenu(): string {\n const sectionHelp = GUIDE_SECTIONS.map(\n (section) => `- \\`${section.label}\\` — run \\`/atomic ${section.label}\\``,\n ).join(\"\\n\");\n return `# Atomic\\n\\nSelect where to start:\\n\\n${sectionHelp}`;\n}\n\nexport function normalizeAtomicGuideMode(args: string): AtomicGuideMode {\n const normalized = stripTrailingAtomicGuidePunctuation(\n args.trim().toLowerCase(),\n );\n if (!normalized) return \"help\";\n\n return GUIDE_SECTIONS_BY_INPUT.get(normalized)?.name ?? \"help\";\n}\n\nexport function getAtomicGuideArgumentCompletions(\n prefix: string,\n): AutocompleteItem[] | null {\n const query = prefix.trim().toLowerCase();\n const items = GUIDE_SECTIONS.map((section) => ({\n value: section.label,\n label: section.label,\n description: section.description,\n }));\n const filtered = query\n ? items.filter(\n (item) => item.value.startsWith(query) || item.label.startsWith(query),\n )\n : items;\n return filtered.length > 0 ? filtered : null;\n}\n\nfunction readLatestStableChangelog(cwd: string): string {\n const changelogPath = getChangelogPath();\n const stableSections = parseChangelog(changelogPath)\n .filter((entry) => entry.prerelease === null)\n .slice(0, 3)\n .map((entry) => entry.content.trim())\n .filter(Boolean);\n\n if (stableSections.length === 0) {\n return `# 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 }\n\n const relativePath = path.relative(cwd, changelogPath) || changelogPath;\n return `# 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(\n mode: AtomicGuideMode,\n cwd: string,\n): string {\n if (mode === \"help\") return getAtomicGuideHelpMenu();\n return getGuideSectionForMode(mode).render(cwd);\n}\n\nexport function atomicGuideModeForChoice(\n choice: AtomicGuideHelpChoice,\n): AtomicGuideMode {\n return getGuideSectionForChoice(choice)?.name ?? \"help\";\n}\n"]}
@@ -17,6 +17,8 @@ export interface AuthStorageBackend {
17
17
  * `AuthStorage.reload()` falls back to a `withLock`-based read.
18
18
  */
19
19
  read?(): string | undefined;
20
+ deleteProvider?(provider: string): string | undefined;
21
+ deleteProviderAsync?(provider: string): Promise<string | undefined>;
20
22
  withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
21
23
  withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;
22
24
  }
@@ -37,6 +39,8 @@ export declare class FileAuthStorageBackend implements AuthStorageBackend {
37
39
  */
38
40
  private writeAtomic;
39
41
  read(): string | undefined;
42
+ deleteProvider(provider: string): string | undefined;
43
+ deleteProviderAsync(provider: string): Promise<string | undefined>;
40
44
  withLock<T>(fn: (current: string | undefined) => LockResult<T>): T;
41
45
  withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;
42
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage-backends.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage-backends.ts"],"names":[],"mappings":"AAOA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