@bastani/atomic 0.9.10 → 0.9.11-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +6 -0
  3. package/dist/builtin/cursor/package.json +3 -3
  4. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  5. package/dist/builtin/intercom/package.json +3 -3
  6. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  7. package/dist/builtin/mcp/package.json +3 -3
  8. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  9. package/dist/builtin/subagents/package.json +4 -4
  10. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  11. package/dist/builtin/web-access/package.json +2 -2
  12. package/dist/builtin/workflows/CHANGELOG.md +23 -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 +2 -2
  16. package/dist/builtin/workflows/src/durable/backend.ts +2 -2
  17. package/dist/builtin/workflows/src/durable/child-primitive.ts +3 -0
  18. package/dist/builtin/workflows/src/durable/completed-catalog.ts +182 -33
  19. package/dist/builtin/workflows/src/durable/completed-inspection.ts +9 -4
  20. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +173 -0
  21. package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +36 -12
  22. package/dist/builtin/workflows/src/durable/dbos-envelope.ts +31 -8
  23. package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +9 -3
  24. package/dist/builtin/workflows/src/durable/factory.ts +35 -6
  25. package/dist/builtin/workflows/src/durable/local-command.ts +11 -2
  26. package/dist/builtin/workflows/src/durable/resume-runtime.ts +6 -2
  27. package/dist/builtin/workflows/src/durable/stage-primitive.ts +48 -10
  28. package/dist/builtin/workflows/src/durable/types.ts +11 -0
  29. package/dist/builtin/workflows/src/engine/run-durable-stage-session.ts +9 -9
  30. package/dist/builtin/workflows/src/engine/run-durable-topology.ts +89 -0
  31. package/dist/builtin/workflows/src/engine/run.ts +18 -16
  32. package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +14 -2
  33. package/dist/builtin/workflows/src/extension/public-types.ts +3 -4
  34. package/dist/builtin/workflows/src/extension/render-call.ts +4 -0
  35. package/dist/builtin/workflows/src/extension/render-result.ts +31 -1
  36. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +3 -0
  37. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +5 -2
  38. package/dist/builtin/workflows/src/extension/workflow-schema.ts +3 -2
  39. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -0
  40. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +88 -2
  41. package/dist/builtin/workflows/src/extension/workflow-tool.ts +13 -0
  42. package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +3 -0
  43. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +6 -3
  44. package/dist/builtin/workflows/src/runs/foreground/executor-stage-types.ts +2 -2
  45. package/dist/builtin/workflows/src/runs/foreground/executor-types.ts +4 -1
  46. package/dist/builtin/workflows/src/tui/workflow-resume-selector.ts +2 -3
  47. package/dist/cli/args.d.ts.map +1 -1
  48. package/dist/cli/args.js +2 -0
  49. package/dist/cli/args.js.map +1 -1
  50. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  51. package/dist/core/agent-session-compaction.js +7 -1
  52. package/dist/core/agent-session-compaction.js.map +1 -1
  53. package/dist/core/agent-session-events.d.ts.map +1 -1
  54. package/dist/core/agent-session-events.js +2 -1
  55. package/dist/core/agent-session-events.js.map +1 -1
  56. package/dist/core/agent-session-retry.d.ts.map +1 -1
  57. package/dist/core/agent-session-retry.js +7 -0
  58. package/dist/core/agent-session-retry.js.map +1 -1
  59. package/dist/core/agent-session-runtime.d.ts +13 -0
  60. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  61. package/dist/core/agent-session-runtime.js +12 -0
  62. package/dist/core/agent-session-runtime.js.map +1 -1
  63. package/dist/core/agent-session-services.d.ts.map +1 -1
  64. package/dist/core/agent-session-services.js +3 -0
  65. package/dist/core/agent-session-services.js.map +1 -1
  66. package/dist/core/agent-session-tree.d.ts.map +1 -1
  67. package/dist/core/agent-session-tree.js +4 -1
  68. package/dist/core/agent-session-tree.js.map +1 -1
  69. package/dist/core/agent-session-types.d.ts +15 -0
  70. package/dist/core/agent-session-types.d.ts.map +1 -1
  71. package/dist/core/agent-session-types.js.map +1 -1
  72. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  73. package/dist/core/atomic-guide-command.js +2 -0
  74. package/dist/core/atomic-guide-command.js.map +1 -1
  75. package/dist/core/auth-storage-backends.d.ts +4 -0
  76. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  77. package/dist/core/auth-storage-backends.js +48 -3
  78. package/dist/core/auth-storage-backends.js.map +1 -1
  79. package/dist/core/auth-storage.d.ts.map +1 -1
  80. package/dist/core/auth-storage.js +27 -11
  81. package/dist/core/auth-storage.js.map +1 -1
  82. package/dist/core/codex-errors.d.ts +3 -0
  83. package/dist/core/codex-errors.d.ts.map +1 -0
  84. package/dist/core/codex-errors.js +12 -0
  85. package/dist/core/codex-errors.js.map +1 -0
  86. package/dist/core/compaction/branch-summarization.d.ts +5 -1
  87. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  88. package/dist/core/compaction/branch-summarization.js +7 -8
  89. package/dist/core/compaction/branch-summarization.js.map +1 -1
  90. package/dist/core/compaction/compaction-runner.d.ts +3 -1
  91. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  92. package/dist/core/compaction/compaction-runner.js +6 -1
  93. package/dist/core/compaction/compaction-runner.js.map +1 -1
  94. package/dist/core/compaction/range-planner.d.ts +3 -0
  95. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  96. package/dist/core/compaction/range-planner.js +2 -1
  97. package/dist/core/compaction/range-planner.js.map +1 -1
  98. package/dist/core/model-registry.js +2 -2
  99. package/dist/core/model-registry.js.map +1 -1
  100. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  101. package/dist/core/model-resolver-defaults.js +2 -0
  102. package/dist/core/model-resolver-defaults.js.map +1 -1
  103. package/dist/core/prompt-templates.d.ts +1 -0
  104. package/dist/core/prompt-templates.d.ts.map +1 -1
  105. package/dist/core/prompt-templates.js +6 -4
  106. package/dist/core/prompt-templates.js.map +1 -1
  107. package/dist/core/remote-catalog-provider.d.ts +1 -1
  108. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  109. package/dist/core/remote-catalog-provider.js +25 -6
  110. package/dist/core/remote-catalog-provider.js.map +1 -1
  111. package/dist/core/sdk-exports.d.ts +1 -1
  112. package/dist/core/sdk-exports.d.ts.map +1 -1
  113. package/dist/core/sdk-exports.js.map +1 -1
  114. package/dist/core/sdk.d.ts.map +1 -1
  115. package/dist/core/sdk.js +4 -1
  116. package/dist/core/sdk.js.map +1 -1
  117. package/dist/core/session-manager-core.d.ts +1 -0
  118. package/dist/core/session-manager-core.d.ts.map +1 -1
  119. package/dist/core/session-manager-core.js +7 -4
  120. package/dist/core/session-manager-core.js.map +1 -1
  121. package/dist/core/session-manager-validation.d.ts.map +1 -1
  122. package/dist/core/session-manager-validation.js +3 -16
  123. package/dist/core/session-manager-validation.js.map +1 -1
  124. package/dist/core/slash-commands.js +1 -1
  125. package/dist/core/slash-commands.js.map +1 -1
  126. package/dist/core/summarization-retry.d.ts +11 -0
  127. package/dist/core/summarization-retry.d.ts.map +1 -0
  128. package/dist/core/summarization-retry.js +21 -0
  129. package/dist/core/summarization-retry.js.map +1 -0
  130. package/dist/core/tools/read.js +1 -1
  131. package/dist/core/tools/read.js.map +1 -1
  132. package/dist/index.d.ts +1 -1
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js.map +1 -1
  135. package/dist/main.d.ts.map +1 -1
  136. package/dist/main.js +2 -0
  137. package/dist/main.js.map +1 -1
  138. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  139. package/dist/modes/interactive/components/chat-session-host-events.js +16 -0
  140. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  141. package/dist/modes/interactive/components/footer.js +2 -2
  142. package/dist/modes/interactive/components/footer.js.map +1 -1
  143. package/dist/modes/interactive/interactive-agent-events.js +6 -0
  144. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  145. package/dist/modes/interactive/interactive-auth-routing.d.ts +2 -1
  146. package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
  147. package/dist/modes/interactive/interactive-auth-routing.js +10 -5
  148. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  149. package/dist/modes/interactive/interactive-autocomplete.js +12 -2
  150. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  151. package/dist/modes/interactive/interactive-model-catalog-startup.d.ts +13 -0
  152. package/dist/modes/interactive/interactive-model-catalog-startup.d.ts.map +1 -0
  153. package/dist/modes/interactive/interactive-model-catalog-startup.js +24 -0
  154. package/dist/modes/interactive/interactive-model-catalog-startup.js.map +1 -0
  155. package/dist/modes/interactive/interactive-model-routing.js +4 -3
  156. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  157. package/dist/modes/interactive/interactive-queueing.js +3 -2
  158. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  159. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  160. package/dist/modes/interactive/interactive-startup.js +4 -7
  161. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  162. package/dist/modes/interactive/interactive-summarization-retry-events.d.ts +8 -0
  163. package/dist/modes/interactive/interactive-summarization-retry-events.d.ts.map +1 -0
  164. package/dist/modes/interactive/interactive-summarization-retry-events.js +40 -0
  165. package/dist/modes/interactive/interactive-summarization-retry-events.js.map +1 -0
  166. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +3 -1
  167. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  168. package/dist/modes/interactive-engine/extension-ui-bridge.js +6 -0
  169. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  170. package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -5
  171. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  172. package/dist/modes/interactive-engine/isolated-runtime.js +14 -24
  173. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  174. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +15 -0
  175. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -0
  176. package/dist/modes/interactive-engine/remote-model-catalog.js +67 -0
  177. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -0
  178. package/dist/modes/rpc/rpc-client-api.d.ts +9 -1
  179. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  180. package/dist/modes/rpc/rpc-client-api.js +12 -0
  181. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  182. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  183. package/dist/modes/rpc/rpc-command-handler.js +35 -0
  184. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  185. package/dist/modes/rpc/rpc-types.d.ts +78 -7
  186. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  187. package/dist/modes/rpc/rpc-types.js.map +1 -1
  188. package/docs/docs.json +9 -1
  189. package/docs/extensions.md +3 -3
  190. package/docs/json.md +7 -1
  191. package/docs/models/artificial-analysis-index.md +82 -0
  192. package/docs/models/model-selection.md +63 -0
  193. package/docs/models/pareto-efficiency.md +64 -0
  194. package/docs/prompt-templates.md +1 -0
  195. package/docs/providers.md +9 -1
  196. package/docs/quickstart.md +1 -1
  197. package/docs/rpc.md +76 -0
  198. package/docs/sdk.md +3 -0
  199. package/docs/tui.md +2 -2
  200. package/docs/workflows.md +26 -13
  201. package/examples/extensions/README.md +1 -1
  202. package/examples/extensions/sandbox/package-lock.json +3 -3
  203. package/npm-shrinkwrap.json +37 -37
  204. package/package.json +7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,QAAQ,CAAC,eAAe;QACjD,aAAa,EAAE,OAAO,CAAC,QAAQ,CAAC,aAAa;QAC7C,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentConfigPaths, getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { endTimingSpan, startTimingSpan } from \"./timings.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tauthStorage?: AuthStorage;\n\tsettingsManager?: SettingsManager;\n\tmodelRegistry?: ModelRegistry;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tfallbackModels?: CreateAgentSessionOptions[\"fallbackModels\"];\n\tcontextWindow?: number;\n\tcontextWindowStrict?: boolean;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: CreateAgentSessionOptions[\"tools\"];\n\texcludedTools?: CreateAgentSessionOptions[\"excludedTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tauthStorage: AuthStorage;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst authStorageSpan = startTimingSpan(\"createAgentSessionServices.authStorage\");\n\tconst authStorage = options.authStorage ?? AuthStorage.create(join(agentDir, \"auth.json\"));\n\tendTimingSpan(authStorageSpan);\n\tconst settingsSpan = startTimingSpan(\"createAgentSessionServices.settingsManager\");\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tendTimingSpan(settingsSpan);\n\tconst modelRegistrySpan = startTimingSpan(\"createAgentSessionServices.modelRegistry\");\n\tconst modelsJsonPaths = agentDir === getAgentDir() ? getAgentConfigPaths(\"models.json\") : join(agentDir, \"models.json\");\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsJsonPaths);\n\tendTimingSpan(modelRegistrySpan);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tconst reloadSpan = startTimingSpan(\"createAgentSessionServices.resourceLoader.reload\");\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\tendTimingSpan(reloadSpan);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst providerSpan = startTimingSpan(\"createAgentSessionServices.providerRegistrations\");\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRegistry.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tendTimingSpan(providerSpan);\n\tconst flagSpan = startTimingSpan(\"createAgentSessionServices.extensionFlagValidation\");\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\tendTimingSpan(flagSpan);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tauthStorage,\n\t\tsettingsManager,\n\t\tmodelRegistry,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tauthStorage: options.services.authStorage,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tmodelRegistry: options.services.modelRegistry,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tfallbackModels: options.fallbackModels,\n\t\tcontextWindow: options.contextWindow,\n\t\tcontextWindowStrict: options.contextWindowStrict,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludedTools: options.excludedTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAiE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE7G,OAA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a;QACpC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;QAChD,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentConfigPaths, getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { endTimingSpan, startTimingSpan } from \"./timings.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tauthStorage?: AuthStorage;\n\tsettingsManager?: SettingsManager;\n\tmodelRegistry?: ModelRegistry;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tfallbackModels?: CreateAgentSessionOptions[\"fallbackModels\"];\n\tcontextWindow?: number;\n\tcontextWindowStrict?: boolean;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: CreateAgentSessionOptions[\"tools\"];\n\texcludedTools?: CreateAgentSessionOptions[\"excludedTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tauthStorage: AuthStorage;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst authStorageSpan = startTimingSpan(\"createAgentSessionServices.authStorage\");\n\tconst authStorage = options.authStorage ?? AuthStorage.create(join(agentDir, \"auth.json\"));\n\tendTimingSpan(authStorageSpan);\n\tconst settingsSpan = startTimingSpan(\"createAgentSessionServices.settingsManager\");\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tendTimingSpan(settingsSpan);\n\tconst modelRegistrySpan = startTimingSpan(\"createAgentSessionServices.modelRegistry\");\n\tconst modelsJsonPaths = agentDir === getAgentDir() ? getAgentConfigPaths(\"models.json\") : join(agentDir, \"models.json\");\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsJsonPaths);\n\tendTimingSpan(modelRegistrySpan);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tconst reloadSpan = startTimingSpan(\"createAgentSessionServices.resourceLoader.reload\");\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\tendTimingSpan(reloadSpan);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst providerSpan = startTimingSpan(\"createAgentSessionServices.providerRegistrations\");\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRegistry.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tendTimingSpan(providerSpan);\n\tconst catalogRestoreSpan = startTimingSpan(\"createAgentSessionServices.restoreModelCatalogs\");\n\tawait modelRegistry.refresh({ allowNetwork: false });\n\tendTimingSpan(catalogRestoreSpan);\n\tconst flagSpan = startTimingSpan(\"createAgentSessionServices.extensionFlagValidation\");\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\tendTimingSpan(flagSpan);\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tauthStorage,\n\t\tsettingsManager,\n\t\tmodelRegistry,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tauthStorage: options.services.authStorage,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tmodelRegistry: options.services.modelRegistry,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tfallbackModels: options.fallbackModels,\n\t\tcontextWindow: options.contextWindow,\n\t\tcontextWindowStrict: options.contextWindowStrict,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludedTools: options.excludedTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tree.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAgB,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAKrE;AAMD;;;;;;;;;;GAUG;AAEH,wBAAsB,YAAY,CAAC,IAAI,EAAE,YAAY,EACpD,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/G,OAAO,CAAC;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;I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,EAAE,kBAAkB,CAAA;CAAE,CAAC,CA0L5G;AAED;;GAEG;AAEH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAetG;AAGD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,MAAM,CAS5H;AAED;;GAEG;AAEH,eAAO,MAAM,uBAAuB;;;;;CAKnC,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { collectEntriesForBranchSummary, generateBranchSummary } from "./compaction/index.js";
2
+ import { createSummarizationRetryCallbacks } from "./summarization-retry.js";
2
3
  export function setSessionName(name) {
3
4
  this.sessionManager.appendSessionInfo(name);
4
5
  const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
@@ -95,7 +96,9 @@ export async function navigateTree(targetId, options = {}) {
95
96
  customInstructions,
96
97
  replaceInstructions,
97
98
  reserveTokens: branchSummarySettings.reserveTokens,
98
- streamFn: this.agent.streamFn,
99
+ streamFn: this.agent.streamFunction,
100
+ retry: this.settingsManager.getRetrySettings(),
101
+ callbacks: createSummarizationRetryCallbacks(this, { source: "branchSummary" }),
99
102
  });
100
103
  if (result.aborted) {
101
104
  return { cancelled: true, aborted: true };
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tree.js","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAI9F,MAAM,UAAU,cAAc,CAAqB,IAAY;IAC9D,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,EAAE,IAAI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,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS;YAAE,SAAS;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QAE5C,MAAM,IAAI,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACjE,IAAI,IAAI,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAGD,MAAM,UAAU,uBAAuB,CAAqB,OAAwD;IACnH,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC;IAChD,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,OAAO;aACZ,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,cAAc;IACd,YAAY;IACZ,yBAAyB;IACzB,uBAAuB;CACvB,CAAC","sourcesContent":["import type { BranchSummaryEntry } from \"./session-manager.ts\";\nimport { collectEntriesForBranchSummary, generateBranchSummary } from \"./compaction/index.ts\";\nimport type { SessionBeforeTreeResult, TreePreparation } from \"./extensions/index.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport function setSessionName(this: AgentSession, name: string): void {\n\tthis.sessionManager.appendSessionInfo(name);\n\tconst event = { type: \"session_info_changed\", name: this.sessionManager.getSessionName() } as const;\n\tthis._emit(event);\n\tvoid this._extensionRunner.emit(event);\n}\n\n// =========================================================================\n// Tree Navigation\n// =========================================================================\n\n/**\n * Navigate to a different node in the session tree.\n * Unlike fork() which creates a new session file, this stays in the same file.\n *\n * @param targetId The entry ID to navigate to\n * @param options.summarize Whether user wants to summarize abandoned branch\n * @param options.customInstructions Custom instructions for summarizer\n * @param options.replaceInstructions If true, customInstructions replaces the default prompt\n * @param options.label Label to attach to the branch summary entry\n * @returns Result with editorText (if user message) and cancelled status\n */\n\nexport async function navigateTree(this: AgentSession, \n\ttargetId: string,\n\toptions: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},\n): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {\n\tconst oldLeafId = this.sessionManager.getLeafId();\n\n\t// No-op if already at target\n\tif (targetId === oldLeafId) {\n\t\treturn { cancelled: false };\n\t}\n\n\t// Model required for summarization\n\tif (options.summarize && !this.model) {\n\t\tthrow new Error(\"No model available for summarization\");\n\t}\n\n\tconst targetEntry = this.sessionManager.getEntry(targetId);\n\tif (!targetEntry) {\n\t\tthrow new Error(`Entry ${targetId} not found`);\n\t}\n\n\t// Collect entries to summarize (from old leaf to common ancestor)\n\tconst { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(\n\t\tthis.sessionManager,\n\t\toldLeafId,\n\t\ttargetId,\n\t);\n\n\t// Prepare event data - mutable so extensions can override\n\tlet customInstructions = options.customInstructions;\n\tlet replaceInstructions = options.replaceInstructions;\n\tlet label = options.label;\n\n\tconst preparation: TreePreparation = {\n\t\ttargetId,\n\t\toldLeafId,\n\t\tcommonAncestorId,\n\t\tentriesToSummarize,\n\t\tuserWantsSummary: options.summarize ?? false,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\tlabel,\n\t};\n\n\t// Set up abort controller for summarization\n\tthis._branchSummaryAbortController = new AbortController();\n\n\ttry {\n\t\tlet extensionSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromExtension = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._extensionRunner.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_tree\",\n\t\t\t\tpreparation,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t})) as SessionBeforeTreeResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { cancelled: true };\n\t\t\t}\n\n\t\t\tif (result?.summary && options.summarize) {\n\t\t\t\textensionSummary = result.summary;\n\t\t\t\tfromExtension = true;\n\t\t\t}\n\n\t\t\t// Allow extensions to override instructions and label\n\t\t\tif (result?.customInstructions !== undefined) {\n\t\t\t\tcustomInstructions = result.customInstructions;\n\t\t\t}\n\t\t\tif (result?.replaceInstructions !== undefined) {\n\t\t\t\treplaceInstructions = result.replaceInstructions;\n\t\t\t}\n\t\t\tif (result?.label !== undefined) {\n\t\t\t\tlabel = result.label;\n\t\t\t}\n\t\t}\n\n\t\t// Run default summarizer if needed\n\t\tlet summaryText: string | undefined;\n\t\tlet summaryDetails: unknown;\n\t\tif (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {\n\t\t\tconst model = this.model!;\n\t\t\tconst { apiKey, headers, baseUrl } = await this._getRequiredRequestAuth(model);\n\t\t\tconst branchSummarySettings = this.settingsManager.getBranchSummarySettings();\n\t\t\tconst result = await generateBranchSummary(entriesToSummarize, {\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tbaseUrl,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t\tcustomInstructions,\n\t\t\t\treplaceInstructions,\n\t\t\t\treserveTokens: branchSummarySettings.reserveTokens,\n\t\t\t\tstreamFn: this.agent.streamFn,\n\t\t\t});\n\t\t\tif (result.aborted) {\n\t\t\t\treturn { cancelled: true, aborted: true };\n\t\t\t}\n\t\t\tif (result.error) {\n\t\t\t\tthrow new Error(result.error);\n\t\t\t}\n\t\t\tsummaryText = result.summary;\n\t\t\tsummaryDetails = {\n\t\t\t\treadFiles: result.readFiles || [],\n\t\t\t\tmodifiedFiles: result.modifiedFiles || [],\n\t\t\t};\n\t\t} else if (extensionSummary) {\n\t\t\tsummaryText = extensionSummary.summary;\n\t\t\tsummaryDetails = extensionSummary.details;\n\t\t}\n\n\t\t// Determine the new leaf position based on target type\n\t\tlet newLeafId: string | null;\n\t\tlet editorText: string | undefined;\n\n\t\tif (targetEntry.type === \"message\" && targetEntry.message.role === \"user\") {\n\t\t\t// User message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText = this._extractUserMessageText(targetEntry.message.content);\n\t\t} else if (targetEntry.type === \"custom_message\") {\n\t\t\t// Custom message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText =\n\t\t\t\ttypeof targetEntry.content === \"string\"\n\t\t\t\t\t? targetEntry.content\n\t\t\t\t\t: targetEntry.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t} else {\n\t\t\t// Non-user message: leaf = selected node\n\t\t\tnewLeafId = targetId;\n\t\t}\n\n\t\t// Switch leaf (with or without summary)\n\t\t// Summary is attached at the navigation target position (newLeafId), not the old branch\n\t\tlet summaryEntry: BranchSummaryEntry | undefined;\n\t\tif (summaryText) {\n\t\t\t// Create summary at target position (can be null for root)\n\t\t\tconst summaryId = this.sessionManager.branchWithSummary(\n\t\t\t\tnewLeafId,\n\t\t\t\tsummaryText,\n\t\t\t\tsummaryDetails,\n\t\t\t\tfromExtension,\n\t\t\t);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\n\n\t\t\t// Attach label to the summary entry\n\t\t\tif (label) {\n\t\t\t\tthis.sessionManager.appendLabelChange(summaryId, label);\n\t\t\t}\n\t\t} else if (newLeafId === null) {\n\t\t\t// No summary, navigating to root - reset leaf\n\t\t\tthis.sessionManager.resetLeaf();\n\t\t} else {\n\t\t\t// No summary, navigating to non-root\n\t\t\tthis.sessionManager.branch(newLeafId);\n\t\t}\n\n\t\t// Attach label to target entry when not summarizing (no summary entry to label)\n\t\tif (label && !summaryText) {\n\t\t\tthis.sessionManager.appendLabelChange(targetId, label);\n\t\t}\n\n\t\t// Update agent state\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.state.messages = sessionContext.messages;\n\t\tthis._applyContextWindowReplay(sessionContext.contextWindow);\n\n\t\t// Emit session_tree event\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_tree\",\n\t\t\tnewLeafId: this.sessionManager.getLeafId(),\n\t\t\toldLeafId,\n\t\t\tsummaryEntry,\n\t\t\tfromExtension: summaryText ? fromExtension : undefined,\n\t\t});\n\n\t\t// Emit to custom tools\n\n\t\treturn { editorText, cancelled: false, summaryEntry };\n\t} finally {\n\t\tthis._branchSummaryAbortController = undefined;\n\t}\n}\n\n/**\n * Get all user messages from session for fork selector.\n */\n\nexport function getUserMessagesForForking(this: AgentSession): Array<{ entryId: string; text: string }> {\n\tconst entries = this.sessionManager.getEntries();\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\n\t\tconst text = this._extractUserMessageText(entry.message.content);\n\t\tif (text) {\n\t\t\tresult.push({ entryId: entry.id, text });\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\nexport function _extractUserMessageText(this: AgentSession, content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * Get session statistics.\n */\n\nexport const agentSessionTreeMethods = {\n\tsetSessionName,\n\tnavigateTree,\n\tgetUserMessagesForForking,\n\t_extractUserMessageText,\n};\n"]}
1
+ {"version":3,"file":"agent-session-tree.js","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG9F,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,MAAM,UAAU,cAAc,CAAqB,IAAY;IAC9D,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,sBAAsB,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,cAAc,EAAE,EAAW,CAAC;IACpG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAClB,KAAK,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC;AAED,4EAA4E;AAC5E,kBAAkB;AAClB,4EAA4E;AAE5E;;;;;;;;;;GAUG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY,CACjC,QAAgB,EAChB,OAAO,GAAwG,EAAE;IAEjH,MAAM,SAAS,GAAG,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC;IAElD,6BAA6B;IAC7B,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,mCAAmC;IACnC,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,C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OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,OAAO;aACZ,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,cAAc;IACd,YAAY;IACZ,yBAAyB;IACzB,uBAAuB;CACvB,CAAC","sourcesContent":["import type { BranchSummaryEntry } from \"./session-manager.ts\";\nimport { collectEntriesForBranchSummary, generateBranchSummary } from \"./compaction/index.ts\";\nimport type { SessionBeforeTreeResult, TreePreparation } from \"./extensions/index.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nexport function setSessionName(this: AgentSession, name: string): void {\n\tthis.sessionManager.appendSessionInfo(name);\n\tconst event = { type: \"session_info_changed\", name: this.sessionManager.getSessionName() } as const;\n\tthis._emit(event);\n\tvoid this._extensionRunner.emit(event);\n}\n\n// =========================================================================\n// Tree Navigation\n// =========================================================================\n\n/**\n * Navigate to a different node in the session tree.\n * Unlike fork() which creates a new session file, this stays in the same file.\n *\n * @param targetId The entry ID to navigate to\n * @param options.summarize Whether user wants to summarize abandoned branch\n * @param options.customInstructions Custom instructions for summarizer\n * @param options.replaceInstructions If true, customInstructions replaces the default prompt\n * @param options.label Label to attach to the branch summary entry\n * @returns Result with editorText (if user message) and cancelled status\n */\n\nexport async function navigateTree(this: AgentSession, \n\ttargetId: string,\n\toptions: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},\n): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {\n\tconst oldLeafId = this.sessionManager.getLeafId();\n\n\t// No-op if already at target\n\tif (targetId === oldLeafId) {\n\t\treturn { cancelled: false };\n\t}\n\n\t// Model required for summarization\n\tif (options.summarize && !this.model) {\n\t\tthrow new Error(\"No model available for summarization\");\n\t}\n\n\tconst targetEntry = this.sessionManager.getEntry(targetId);\n\tif (!targetEntry) {\n\t\tthrow new Error(`Entry ${targetId} not found`);\n\t}\n\n\t// Collect entries to summarize (from old leaf to common ancestor)\n\tconst { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(\n\t\tthis.sessionManager,\n\t\toldLeafId,\n\t\ttargetId,\n\t);\n\n\t// Prepare event data - mutable so extensions can override\n\tlet customInstructions = options.customInstructions;\n\tlet replaceInstructions = options.replaceInstructions;\n\tlet label = options.label;\n\n\tconst preparation: TreePreparation = {\n\t\ttargetId,\n\t\toldLeafId,\n\t\tcommonAncestorId,\n\t\tentriesToSummarize,\n\t\tuserWantsSummary: options.summarize ?? false,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\tlabel,\n\t};\n\n\t// Set up abort controller for summarization\n\tthis._branchSummaryAbortController = new AbortController();\n\n\ttry {\n\t\tlet extensionSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromExtension = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._extensionRunner.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_tree\",\n\t\t\t\tpreparation,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t})) as SessionBeforeTreeResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { cancelled: true };\n\t\t\t}\n\n\t\t\tif (result?.summary && options.summarize) {\n\t\t\t\textensionSummary = result.summary;\n\t\t\t\tfromExtension = true;\n\t\t\t}\n\n\t\t\t// Allow extensions to override instructions and label\n\t\t\tif (result?.customInstructions !== undefined) {\n\t\t\t\tcustomInstructions = result.customInstructions;\n\t\t\t}\n\t\t\tif (result?.replaceInstructions !== undefined) {\n\t\t\t\treplaceInstructions = result.replaceInstructions;\n\t\t\t}\n\t\t\tif (result?.label !== undefined) {\n\t\t\t\tlabel = result.label;\n\t\t\t}\n\t\t}\n\n\t\t// Run default summarizer if needed\n\t\tlet summaryText: string | undefined;\n\t\tlet summaryDetails: unknown;\n\t\tif (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {\n\t\t\tconst model = this.model!;\n\t\t\tconst { apiKey, headers, baseUrl } = await this._getRequiredRequestAuth(model);\n\t\t\tconst branchSummarySettings = this.settingsManager.getBranchSummarySettings();\n\t\t\tconst result = await generateBranchSummary(entriesToSummarize, {\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tbaseUrl,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t\tcustomInstructions,\n\t\t\t\treplaceInstructions,\n\t\t\t\treserveTokens: branchSummarySettings.reserveTokens,\n\t\t\t\tstreamFn: this.agent.streamFunction,\n\t\t\t\tretry: this.settingsManager.getRetrySettings(),\n\t\t\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"branchSummary\" }),\n\t\t\t});\n\t\t\tif (result.aborted) {\n\t\t\t\treturn { cancelled: true, aborted: true };\n\t\t\t}\n\t\t\tif (result.error) {\n\t\t\t\tthrow new Error(result.error);\n\t\t\t}\n\t\t\tsummaryText = result.summary;\n\t\t\tsummaryDetails = {\n\t\t\t\treadFiles: result.readFiles || [],\n\t\t\t\tmodifiedFiles: result.modifiedFiles || [],\n\t\t\t};\n\t\t} else if (extensionSummary) {\n\t\t\tsummaryText = extensionSummary.summary;\n\t\t\tsummaryDetails = extensionSummary.details;\n\t\t}\n\n\t\t// Determine the new leaf position based on target type\n\t\tlet newLeafId: string | null;\n\t\tlet editorText: string | undefined;\n\n\t\tif (targetEntry.type === \"message\" && targetEntry.message.role === \"user\") {\n\t\t\t// User message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText = this._extractUserMessageText(targetEntry.message.content);\n\t\t} else if (targetEntry.type === \"custom_message\") {\n\t\t\t// Custom message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText =\n\t\t\t\ttypeof targetEntry.content === \"string\"\n\t\t\t\t\t? targetEntry.content\n\t\t\t\t\t: targetEntry.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t} else {\n\t\t\t// Non-user message: leaf = selected node\n\t\t\tnewLeafId = targetId;\n\t\t}\n\n\t\t// Switch leaf (with or without summary)\n\t\t// Summary is attached at the navigation target position (newLeafId), not the old branch\n\t\tlet summaryEntry: BranchSummaryEntry | undefined;\n\t\tif (summaryText) {\n\t\t\t// Create summary at target position (can be null for root)\n\t\t\tconst summaryId = this.sessionManager.branchWithSummary(\n\t\t\t\tnewLeafId,\n\t\t\t\tsummaryText,\n\t\t\t\tsummaryDetails,\n\t\t\t\tfromExtension,\n\t\t\t);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\n\n\t\t\t// Attach label to the summary entry\n\t\t\tif (label) {\n\t\t\t\tthis.sessionManager.appendLabelChange(summaryId, label);\n\t\t\t}\n\t\t} else if (newLeafId === null) {\n\t\t\t// No summary, navigating to root - reset leaf\n\t\t\tthis.sessionManager.resetLeaf();\n\t\t} else {\n\t\t\t// No summary, navigating to non-root\n\t\t\tthis.sessionManager.branch(newLeafId);\n\t\t}\n\n\t\t// Attach label to target entry when not summarizing (no summary entry to label)\n\t\tif (label && !summaryText) {\n\t\t\tthis.sessionManager.appendLabelChange(targetId, label);\n\t\t}\n\n\t\t// Update agent state\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.state.messages = sessionContext.messages;\n\t\tthis._applyContextWindowReplay(sessionContext.contextWindow);\n\n\t\t// Emit session_tree event\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_tree\",\n\t\t\tnewLeafId: this.sessionManager.getLeafId(),\n\t\t\toldLeafId,\n\t\t\tsummaryEntry,\n\t\t\tfromExtension: summaryText ? fromExtension : undefined,\n\t\t});\n\n\t\t// Emit to custom tools\n\n\t\treturn { editorText, cancelled: false, summaryEntry };\n\t} finally {\n\t\tthis._branchSummaryAbortController = undefined;\n\t}\n}\n\n/**\n * Get all user messages from session for fork selector.\n */\n\nexport function getUserMessagesForForking(this: AgentSession): Array<{ entryId: string; text: string }> {\n\tconst entries = this.sessionManager.getEntries();\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\n\t\tconst text = this._extractUserMessageText(entry.message.content);\n\t\tif (text) {\n\t\t\tresult.push({ entryId: entry.id, text });\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\nexport function _extractUserMessageText(this: AgentSession, content: string | Array<{ type: string; text?: string }>): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * Get session statistics.\n */\n\nexport const agentSessionTreeMethods = {\n\tsetSessionName,\n\tnavigateTree,\n\tgetUserMessagesForForking,\n\t_extractUserMessageText,\n};\n"]}
@@ -54,6 +54,21 @@ export type AgentSessionEvent = AgentEvent | {
54
54
  success: boolean;
55
55
  attempt: number;
56
56
  finalError?: string;
57
+ } | {
58
+ type: "summarization_retry_scheduled";
59
+ attempt: number;
60
+ maxAttempts: number;
61
+ delayMs: number;
62
+ errorMessage: string;
63
+ } | {
64
+ type: "summarization_retry_attempt_start";
65
+ source: "branchSummary";
66
+ } | {
67
+ type: "summarization_retry_attempt_start";
68
+ source: "compaction";
69
+ reason: "manual" | "threshold" | "overflow";
70
+ } | {
71
+ type: "summarization_retry_finished";
57
72
  } | {
58
73
  type: "model_fallback_start";
59
74
  from: string;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-types.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,KAAK,EACL,UAAU,EACV,YAAY,EACZ,SAAS,EACT,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EACX,YAAY,EACZ,8BAA8B,EAC9B,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAEtE,MAAM,MAAM,iBAAiB,GAC1B,UAAU,GACV;IACA,IAAI,EAAE,cAAc,CAAC;IACrB,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3B,GACD;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,MAAM,EAAE,QAAQ,GAAG,WA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C5B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE;QACP,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;QACnB,KAAK,EAAE,MAAM,CAAC;KACd,CAAC;IACF,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,cAAc,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,eAAO,MAAM,eAAe,EAAE,aAAa,EAAgE,CAAC;AAE5G,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAE5E;AAED,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-types.js","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAsEA,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACvD,+BAA+B,EAAE,IAAI;CAC5B,CAAC;AAsBX,MAAM,UAAU,sBAAsB,CAAC,KAA2C;IACjF,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,MAAM,OAAO,GAAmB,EAAE,CAAC;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,8BAA8B,CAAC,KAAyB;I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AAQ,OAA4D,CAAC,kBAAkB,KAAK,IAAI,CAAC;AAClG,CAAC","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\"; midTurn?: boolean }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"context_window_changed\"; contextWindow: number }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: VerbatimCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\tunresolvedOverflow?: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tmidTurn?: boolean;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t| { type: \"model_fallback_start\"; from: string; to: string; reason: string; attempt: number }\n\t| { type: \"model_fallback_end\"; success: boolean; from?: string; to?: string; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport type ContextWindowReplaySource = \"session\" | \"model-settings\" | \"global-settings\";\n\nexport interface ContextWindowReplayRequest {\n\tcontextWindow: number;\n\tsource: ContextWindowReplaySource;\n}\n\nexport const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = {\n\tallowCopilotLongContextFallback: true,\n} as const;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase().replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tfallbackModels?: string[];\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface AgentSessionReloadOptions {\n\treason?: \"startup\" | \"reload\";\n\t/** Runs after resources and the extension runtime are rebuilt, immediately before session_start. */\n\tbeforeSessionStart?: () => void | Promise<void>;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}
1
+ {"version":3,"file":"agent-session-types.js","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAoFA,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACvD,+BAA+B,EAAE,IAAI;CAC5B,CAAC;AAsBX,MAAM,UAAU,sBAAsB,CAAC,KAA2C;IACjF,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,MAAM,OAAO,GAAmB,EAAE,CAAC;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,8BAA8B,CAAC,KAAyB;IACvE,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAA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,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\"; midTurn?: boolean }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"context_window_changed\"; contextWindow: number }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: VerbatimCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\tunresolvedOverflow?: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tmidTurn?: boolean;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t| {\n\t\t\ttype: \"summarization_retry_scheduled\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\tdelayMs: number;\n\t\t\terrorMessage: string;\n\t }\n\t| { type: \"summarization_retry_attempt_start\"; source: \"branchSummary\" }\n\t| {\n\t\t\ttype: \"summarization_retry_attempt_start\";\n\t\t\tsource: \"compaction\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t }\n\t| { type: \"summarization_retry_finished\" }\n\t| { type: \"model_fallback_start\"; from: string; to: string; reason: string; attempt: number }\n\t| { type: \"model_fallback_end\"; success: boolean; from?: string; to?: string; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport type ContextWindowReplaySource = \"session\" | \"model-settings\" | \"global-settings\";\n\nexport interface ContextWindowReplayRequest {\n\tcontextWindow: number;\n\tsource: ContextWindowReplaySource;\n}\n\nexport const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = {\n\tallowCopilotLongContextFallback: true,\n} as const;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase().replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tfallbackModels?: string[];\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface AgentSessionReloadOptions {\n\treason?: \"startup\" | \"reload\";\n\t/** Runs after resources and the extension runtime are rebuilt, immediately before session_start. */\n\tbeforeSessionStart?: () => void | Promise<void>;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\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,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;0BACN,sBAAsB;;EASpC,CAAC;AAEJ,KAAK,kBAAkB,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC;AAC1D,KAAK,sBAAsB,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAEzD,MAAM,MAAM,qBAAqB,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,sBAAsB,CAAC;AAE9D,eAAO,MAAM,yBAAyB,EAAE,SAAS,qBAAqB,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,OA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wB,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\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,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,GAAW;IAC5C,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;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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CAAW;IAEpC,YACC,QAAQ,GAAE,MAAyC,EACnD,SAAS,GAAE,MAAM,EAAe,EAIhC;IAED,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,wBAAwB;IA2BhC,OAAO,CAAC,cAAc;IAatB;;;;;;OAMG;IACH,OAAO,CAAC,WAAW;IAoBnB,IAAI,IAAI,MAAM,GAAG,SAAS,CAEzB;IAED,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAenD;IAEK,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAqBvE;IAED,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAyBjE;IAEK,aAAa,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAiD9F;CACD;AAED,qBAAa,0BAA2B,YAAW,kBAAkB;IACpE,OAAO,CAAC,KAAK,CAAqB;IAElC,IAAI,IAAI,MAAM,GAAG,SAAS,CAEzB;IAED,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAMjE;IAEK,aAAa,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAM9F;CACD"}
@@ -65,13 +65,13 @@ export class FileAuthStorageBackend {
65
65
  * never observe a half-written file. The temp file is best-effort cleaned up
66
66
  * if the rename fails.
67
67
  */
68
- writeAtomic(content) {
69
- const dir = dirname(this.authPath);
68
+ writeAtomic(content, path = this.authPath) {
69
+ const dir = dirname(path);
70
70
  const tempPath = join(dir, `.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`);
71
71
  try {
72
72
  writeFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);
73
73
  chmodSync(tempPath, 0o600);
74
- renameSync(tempPath, this.authPath);
74
+ renameSync(tempPath, path);
75
75
  }
76
76
  catch (error) {
77
77
  try {
@@ -87,6 +87,51 @@ export class FileAuthStorageBackend {
87
87
  read() {
88
88
  return this.readMergedAuth();
89
89
  }
90
+ deleteProvider(provider) {
91
+ const paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();
92
+ const releases = [];
93
+ try {
94
+ for (const path of paths)
95
+ releases.push(this.acquireLockSyncWithRetry(path));
96
+ for (const path of paths) {
97
+ const data = JSON.parse(readFileSync(path, "utf-8"));
98
+ if (!(provider in data))
99
+ continue;
100
+ delete data[provider];
101
+ this.writeAtomic(JSON.stringify(data, null, 2), path);
102
+ }
103
+ return this.readMergedAuth();
104
+ }
105
+ finally {
106
+ for (const release of releases.reverse())
107
+ release();
108
+ }
109
+ }
110
+ async deleteProviderAsync(provider) {
111
+ const paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();
112
+ const releases = [];
113
+ try {
114
+ for (const path of paths) {
115
+ releases.push(await lockfile.lock(path, {
116
+ realpath: false,
117
+ retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10000, randomize: true },
118
+ stale: 30000,
119
+ }));
120
+ }
121
+ for (const path of paths) {
122
+ const data = JSON.parse(readFileSync(path, "utf-8"));
123
+ if (!(provider in data))
124
+ continue;
125
+ delete data[provider];
126
+ this.writeAtomic(JSON.stringify(data, null, 2), path);
127
+ }
128
+ return this.readMergedAuth();
129
+ }
130
+ finally {
131
+ for (const release of releases.reverse())
132
+ await release();
133
+ }
134
+ }
90
135
  withLock(fn) {
91
136
  this.ensureParentDir();
92
137
  let release;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage-backends.js","sourceRoot":"","sources":["../../src/core/auth-storage-backends.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACvG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAQlD,MAAM,uBAAuB,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAW,CAAC;AAqB5E,MAAM,OAAO,sBAAsB;IAIlC,YACC,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EACnD,SAAS,GAAa,CAAC,QAAQ,CAAC;QAEhC,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC;IACvE,CAAC;IAEO,eAAe;QACtB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;QAClD,CAAC;IACF,CAAC;IAEO,gBAAgB;QACvB,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAChC,aAAa,CAAC,IAAI,CAAC,QAAQ,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QACH,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IAED,QAAQ,CAAI,EAAkD;QAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,KAAK,CAAC,aAAa,CAAI,EAA2D;QACjF,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport type { AuthStorageData } from \"./auth-storage.ts\";\n\nexport type LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\t/**\n\t * Read the current credential snapshot WITHOUT acquiring the exclusive write\n\t * lock. Pure reads do not need cross-process write-exclusion: writers replace\n\t * the file atomically (temp file + rename), so a lock-free reader always\n\t * observes a complete previous-or-next snapshot, never a torn one. Keeping\n\t * reads lock-free is what prevents many concurrent sessions from starving each\n\t * other on `auth.json` and misreporting configured providers as unreadable\n\t * under contention (issue #1431).\n\t *\n\t * Optional for backward compatibility with custom backends that predate this\n\t * method (the released `AuthStorageBackend` interface): when absent,\n\t * `AuthStorage.reload()` falls back to a `withLock`-based read.\n\t */\n\tread?(): string | undefined;\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tdeclare private authPath: string;\n\tdeclare private readPaths: string[];\n\n\tconstructor(\n\t\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n\t\treadPaths: string[] = [authPath],\n\t) {\n\t\tthis.authPath = normalizePath(authPath);\n\t\tthis.readPaths = readPaths.map((readPath) => normalizePath(readPath));\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\tprivate readMergedAuth(): string | undefined {\n\t\tlet merged: AuthStorageData = {};\n\t\tlet found = false;\n\t\tfor (let i = this.readPaths.length - 1; i >= 0; i--) {\n\t\t\tconst readPath = this.readPaths[i]!;\n\t\t\tif (!existsSync(readPath)) continue;\n\t\t\tconst parsed = JSON.parse(readFileSync(readPath, \"utf-8\")) as AuthStorageData;\n\t\t\tmerged = { ...merged, ...parsed };\n\t\t\tfound = true;\n\t\t}\n\t\treturn found ? JSON.stringify(merged, null, 2) : undefined;\n\t}\n\n\t/**\n\t * Atomically replace `auth.json` with `content`: write a sibling temp file\n\t * (same directory, so `rename` is a same-filesystem atomic swap), fix its\n\t * permissions, then `rename` it over the target. Lock-free readers therefore\n\t * never observe a half-written file. The temp file is best-effort cleaned up\n\t * if the rename fails.\n\t */\n\tprivate writeAtomic(content: string): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tconst tempPath = join(\n\t\t\tdir,\n\t\t\t`.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`,\n\t\t);\n\t\ttry {\n\t\t\twriteFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(tempPath, 0o600);\n\t\t\trenameSync(tempPath, this.authPath);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (existsSync(tempPath)) rmSync(tempPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup; ignore.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tread(): string | undefined {\n\t\treturn this.readMergedAuth();\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (existsSync(this.authPath)) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t}\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\t\tthis.ensureFileExists();\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t\t}\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\tthis.ensureFileExists();\n\t\t\t}\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\tread(): string | undefined {\n\t\treturn this.value;\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n"]}
1
+ {"version":3,"file":"auth-storage-backends.js","sourceRoot":"","sources":["../../src/core/auth-storage-backends.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACvG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAQlD,MAAM,uBAAuB,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAW,CAAC;AAuB5E,MAAM,OAAO,sBAAsB;IAIlC,YACC,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EACnD,SAAS,GAAa,CAAC,QAAQ,CAAC;QAEhC,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAA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C;gBAAC,MAAM,CAAC;oBACR,iDAAiD;gBAClD,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;CACD;AAED,MAAM,OAAO,0BAA0B;IAGtC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IAED,QAAQ,CAAI,EAAkD;QAC7D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;IAED,KAAK,CAAC,aAAa,CAAI,EAA2D;QACjF,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport type { AuthStorageData } from \"./auth-storage.ts\";\n\nexport type LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\t/**\n\t * Read the current credential snapshot WITHOUT acquiring the exclusive write\n\t * lock. Pure reads do not need cross-process write-exclusion: writers replace\n\t * the file atomically (temp file + rename), so a lock-free reader always\n\t * observes a complete previous-or-next snapshot, never a torn one. Keeping\n\t * reads lock-free is what prevents many concurrent sessions from starving each\n\t * other on `auth.json` and misreporting configured providers as unreadable\n\t * under contention (issue #1431).\n\t *\n\t * Optional for backward compatibility with custom backends that predate this\n\t * method (the released `AuthStorageBackend` interface): when absent,\n\t * `AuthStorage.reload()` falls back to a `withLock`-based read.\n\t */\n\tread?(): string | undefined;\n\tdeleteProvider?(provider: string): string | undefined;\n\tdeleteProviderAsync?(provider: string): Promise<string | undefined>;\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tdeclare private authPath: string;\n\tdeclare private readPaths: string[];\n\n\tconstructor(\n\t\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n\t\treadPaths: string[] = [authPath],\n\t) {\n\t\tthis.authPath = normalizePath(authPath);\n\t\tthis.readPaths = readPaths.map((readPath) => normalizePath(readPath));\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\tprivate readMergedAuth(): string | undefined {\n\t\tlet merged: AuthStorageData = {};\n\t\tlet found = false;\n\t\tfor (let i = this.readPaths.length - 1; i >= 0; i--) {\n\t\t\tconst readPath = this.readPaths[i]!;\n\t\t\tif (!existsSync(readPath)) continue;\n\t\t\tconst parsed = JSON.parse(readFileSync(readPath, \"utf-8\")) as AuthStorageData;\n\t\t\tmerged = { ...merged, ...parsed };\n\t\t\tfound = true;\n\t\t}\n\t\treturn found ? JSON.stringify(merged, null, 2) : undefined;\n\t}\n\n\t/**\n\t * Atomically replace `auth.json` with `content`: write a sibling temp file\n\t * (same directory, so `rename` is a same-filesystem atomic swap), fix its\n\t * permissions, then `rename` it over the target. Lock-free readers therefore\n\t * never observe a half-written file. The temp file is best-effort cleaned up\n\t * if the rename fails.\n\t */\n\tprivate writeAtomic(content: string, path = this.authPath): void {\n\t\tconst dir = dirname(path);\n\t\tconst tempPath = join(\n\t\t\tdir,\n\t\t\t`.${`auth.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`}.tmp`,\n\t\t);\n\t\ttry {\n\t\t\twriteFileSync(tempPath, content, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(tempPath, 0o600);\n\t\t\trenameSync(tempPath, path);\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (existsSync(tempPath)) rmSync(tempPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Best-effort cleanup; ignore.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tread(): string | undefined {\n\t\treturn this.readMergedAuth();\n\t}\n\n\tdeleteProvider(provider: string): string | undefined {\n\t\tconst paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();\n\t\tconst releases: Array<() => void> = [];\n\t\ttry {\n\t\t\tfor (const path of paths) releases.push(this.acquireLockSyncWithRetry(path));\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst data = JSON.parse(readFileSync(path, \"utf-8\")) as AuthStorageData;\n\t\t\t\tif (!(provider in data)) continue;\n\t\t\t\tdelete data[provider];\n\t\t\t\tthis.writeAtomic(JSON.stringify(data, null, 2), path);\n\t\t\t}\n\t\t\treturn this.readMergedAuth();\n\t\t} finally {\n\t\t\tfor (const release of releases.reverse()) release();\n\t\t}\n\t}\n\n\tasync deleteProviderAsync(provider: string): Promise<string | undefined> {\n\t\tconst paths = [...new Set(this.readPaths.filter((path) => existsSync(path)))].sort();\n\t\tconst releases: Array<() => Promise<void>> = [];\n\t\ttry {\n\t\t\tfor (const path of paths) {\n\t\t\t\treleases.push(await lockfile.lock(path, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tretries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10000, randomize: true },\n\t\t\t\t\tstale: 30000,\n\t\t\t\t}));\n\t\t\t}\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst data = JSON.parse(readFileSync(path, \"utf-8\")) as AuthStorageData;\n\t\t\t\tif (!(provider in data)) continue;\n\t\t\t\tdelete data[provider];\n\t\t\t\tthis.writeAtomic(JSON.stringify(data, null, 2), path);\n\t\t\t}\n\t\t\treturn this.readMergedAuth();\n\t\t} finally {\n\t\t\tfor (const release of releases.reverse()) await release();\n\t\t}\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (existsSync(this.authPath)) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t}\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\t\tthis.ensureFileExists();\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\t\t}\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tif (!existsSync(this.authPath)) {\n\t\t\t\tthis.ensureFileExists();\n\t\t\t}\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = this.readMergedAuth();\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\tthis.writeAtomic(next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\tread(): string | undefined {\n\t\treturn this.value;\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n"]}