@bastani/atomic 0.8.17 → 0.8.18

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 (53) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +5 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/CHANGELOG.md +5 -0
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/CHANGELOG.md +5 -0
  7. package/dist/builtin/subagents/package.json +1 -1
  8. package/dist/builtin/web-access/CHANGELOG.md +5 -0
  9. package/dist/builtin/web-access/package.json +1 -1
  10. package/dist/builtin/workflows/CHANGELOG.md +25 -0
  11. package/dist/builtin/workflows/README.md +62 -3
  12. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +555 -537
  13. package/dist/builtin/workflows/builtin/goal.ts +5 -0
  14. package/dist/builtin/workflows/builtin/open-claude-design.ts +3 -3
  15. package/dist/builtin/workflows/builtin/ralph.ts +737 -713
  16. package/dist/builtin/workflows/builtin/shared-prompts.ts +11 -0
  17. package/dist/builtin/workflows/package.json +1 -1
  18. package/dist/builtin/workflows/src/extension/discovery.ts +61 -22
  19. package/dist/builtin/workflows/src/extension/index.ts +2 -0
  20. package/dist/builtin/workflows/src/extension/runtime.ts +4 -0
  21. package/dist/builtin/workflows/src/extension/workflow-schema.ts +4 -0
  22. package/dist/builtin/workflows/src/runs/foreground/executor.ts +96 -6
  23. package/dist/builtin/workflows/src/runs/foreground/stage-runner.ts +2 -0
  24. package/dist/builtin/workflows/src/runs/shared/workflow-runner.ts +7 -0
  25. package/dist/builtin/workflows/src/runs/shared/worktree.ts +214 -1
  26. package/dist/builtin/workflows/src/sdk-surface.ts +2 -0
  27. package/dist/builtin/workflows/src/shared/types.ts +32 -3
  28. package/dist/builtin/workflows/src/workflows/define-workflow.ts +18 -1
  29. package/dist/core/agent-session-services.d.ts +2 -1
  30. package/dist/core/agent-session-services.d.ts.map +1 -1
  31. package/dist/core/agent-session-services.js +1 -0
  32. package/dist/core/agent-session-services.js.map +1 -1
  33. package/dist/core/agent-session.d.ts +3 -0
  34. package/dist/core/agent-session.d.ts.map +1 -1
  35. package/dist/core/agent-session.js +16 -5
  36. package/dist/core/agent-session.js.map +1 -1
  37. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  38. package/dist/core/atomic-guide-command.js +40 -28
  39. package/dist/core/atomic-guide-command.js.map +1 -1
  40. package/dist/core/sdk.d.ts +9 -1
  41. package/dist/core/sdk.d.ts.map +1 -1
  42. package/dist/core/sdk.js +2 -2
  43. package/dist/core/sdk.js.map +1 -1
  44. package/dist/core/system-prompt.d.ts +2 -0
  45. package/dist/core/system-prompt.d.ts.map +1 -1
  46. package/dist/core/system-prompt.js +22 -13
  47. package/dist/core/system-prompt.js.map +1 -1
  48. package/docs/quickstart.md +13 -5
  49. package/docs/sdk.md +20 -5
  50. package/docs/workflows.md +44 -17
  51. package/examples/sdk/05-tools.ts +22 -1
  52. package/examples/sdk/README.md +7 -3
  53. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,KAAK,GAGN,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kBAAkB,EAIlB,YAAY,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CA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,aAAa,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;SAAM,CAAC;QACN,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACV,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAC/B,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACL,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACrB,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport {\n Agent,\n type AgentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { APP_NAME, getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled.\n */\n tools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\nfunction isHostOrSubdomain(rawUrl: string, host: string): boolean {\n try {\n const { hostname } = new URL(rawUrl);\n return hostname === host || hostname.endsWith(`.${host}`);\n } catch {\n return false;\n }\n}\n\nfunction getAttributionHeaders(\n model: Model<Api>,\n settingsManager: SettingsManager,\n sessionId?: string,\n): Record<string, string> | undefined {\n if (\n sessionId &&\n (model.provider === \"opencode\" || model.provider === \"opencode-go\" || isHostOrSubdomain(model.baseUrl, \"opencode.ai\"))\n ) {\n return { \"x-opencode-session\": sessionId, \"x-opencode-client\": APP_NAME };\n }\n\n if (!isInstallTelemetryEnabled(settingsManager)) {\n return undefined;\n }\n\n if (\n model.provider === \"openrouter\" ||\n isHostOrSubdomain(model.baseUrl, \"openrouter.ai\")\n ) {\n return {\n \"HTTP-Referer\": \"https://pi.dev\",\n \"X-OpenRouter-Title\": \"pi\",\n \"X-OpenRouter-Categories\": \"cli-agent\",\n };\n }\n\n if (\n model.provider === \"cloudflare-workers-ai\" ||\n model.provider === \"cloudflare-ai-gateway\" ||\n isHostOrSubdomain(model.baseUrl, \"api.cloudflare.com\") ||\n isHostOrSubdomain(model.baseUrl, \"gateway.ai.cloudflare.com\")\n ) {\n return {\n \"User-Agent\": APP_NAME,\n };\n }\n\n return undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = modelRegistry.find(\n existingSession.model.provider,\n existingSession.model.modelId,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n const defaultActiveToolNames = [...defaultToolNames];\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : defaultActiveToolNames;\n\n let agent: Agent;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n return converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, options) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n return streamSimple(model, context, {\n ...options,\n apiKey: auth.apiKey,\n timeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n maxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers:\n attributionHeaders || auth.headers || options?.headers\n ? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n : undefined,\n });\n },\n onPayload: async (payload, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return payload;\n }\n return runner.emitBeforeProviderRequest(payload);\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n };\n}\n"]}
1
+ {"version":3,"file":"sdk.js","source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gentMessage,\n type ThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport {\n clampThinkingLevel,\n type Api,\n type Message,\n type Model,\n streamSimple,\n} from \"@earendil-works/pi-ai\";\nimport { APP_NAME, getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type {\n ExtensionRunner,\n LoadExtensionsResult,\n SessionStartEvent,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n createBashTool,\n createCodingTools,\n createEditTool,\n createFindTool,\n createGrepTool,\n createLsTool,\n createReadOnlyTools,\n createReadTool,\n createWriteTool,\n defaultToolNames,\n withFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n /** Working directory for project-local discovery. Default: process.cwd() */\n cwd?: string;\n /** Global config directory. Default: ~/.atomic/agent */\n agentDir?: string;\n\n /** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n authStorage?: AuthStorage;\n /** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n modelRegistry?: ModelRegistry;\n\n /** Model to use. Default: from settings, else first available */\n model?: Model<Api>;\n /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n thinkingLevel?: ThinkingLevel;\n /** Models available for cycling (Ctrl+P in interactive mode) */\n scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n /**\n * Optional default tool suppression mode when no explicit allowlist is provided.\n *\n * - \"all\": start with no tools enabled\n * - \"builtin\": disable the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) but keep extension/custom tools enabled\n */\n noTools?: \"all\" | \"builtin\";\n /**\n * Optional allowlist of tool names.\n *\n * When omitted, pi enables the default built-in tools (read, bash, edit, write,\n * ask_user_question, todo) and leaves extension/custom tools enabled unless\n * `noTools` changes that default.\n * When provided, only the listed tool names are enabled, minus any names in\n * `excludeTools`.\n */\n tools?: string[];\n /**\n * Optional blocklist of tool names.\n *\n * Matching built-in, extension, and SDK custom tools are omitted from the\n * final session tool registry and active tool set. Unknown names are ignored.\n */\n excludeTools?: string[];\n /** Custom tools to register (in addition to built-in tools). */\n customTools?: ToolDefinition[];\n\n /** Resource loader. When omitted, DefaultResourceLoader is used. */\n resourceLoader?: ResourceLoader;\n\n /** Session manager. Default: SessionManager.create(cwd) */\n sessionManager?: SessionManager;\n\n /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n settingsManager?: SettingsManager;\n /** Session start event metadata for extension runtime startup. */\n sessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n /** The created session */\n session: AgentSession;\n /** Extensions result (for UI context setup in interactive mode) */\n extensionsResult: LoadExtensionsResult;\n /** Warning if session was restored with a different model than saved */\n modelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n ExtensionFactory,\n SlashCommandInfo,\n SlashCommandSource,\n ToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n withFileMutationQueue,\n // Tool factories (for custom cwd)\n createCodingTools,\n createReadOnlyTools,\n createReadTool,\n createBashTool,\n createEditTool,\n createWriteTool,\n createGrepTool,\n createFindTool,\n createLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n return getAgentDir();\n}\n\nfunction isHostOrSubdomain(rawUrl: string, host: string): boolean {\n try {\n const { hostname } = new URL(rawUrl);\n return hostname === host || hostname.endsWith(`.${host}`);\n } catch {\n return false;\n }\n}\n\nfunction getAttributionHeaders(\n model: Model<Api>,\n settingsManager: SettingsManager,\n sessionId?: string,\n): Record<string, string> | undefined {\n if (\n sessionId &&\n (model.provider === \"opencode\" || model.provider === \"opencode-go\" || isHostOrSubdomain(model.baseUrl, \"opencode.ai\"))\n ) {\n return { \"x-opencode-session\": sessionId, \"x-opencode-client\": APP_NAME };\n }\n\n if (!isInstallTelemetryEnabled(settingsManager)) {\n return undefined;\n }\n\n if (\n model.provider === \"openrouter\" ||\n isHostOrSubdomain(model.baseUrl, \"openrouter.ai\")\n ) {\n return {\n \"HTTP-Referer\": \"https://pi.dev\",\n \"X-OpenRouter-Title\": \"pi\",\n \"X-OpenRouter-Categories\": \"cli-agent\",\n };\n }\n\n if (\n model.provider === \"cloudflare-workers-ai\" ||\n model.provider === \"cloudflare-ai-gateway\" ||\n isHostOrSubdomain(model.baseUrl, \"api.cloudflare.com\") ||\n isHostOrSubdomain(model.baseUrl, \"gateway.ai.cloudflare.com\")\n ) {\n return {\n \"User-Agent\": APP_NAME,\n };\n }\n\n return undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(\n options: CreateAgentSessionOptions = {},\n): Promise<CreateAgentSessionResult> {\n const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n let resourceLoader = options.resourceLoader;\n\n // Use provided or create AuthStorage and ModelRegistry\n const authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n const modelsPath = options.agentDir\n ? join(agentDir, \"models.json\")\n : undefined;\n const authStorage = options.authStorage ?? AuthStorage.create(authPath);\n const modelRegistry =\n options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n const settingsManager =\n options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager =\n options.sessionManager ??\n SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({\n cwd,\n agentDir,\n settingsManager,\n });\n await resourceLoader.reload();\n time(\"resourceLoader.reload\");\n }\n\n // Check if session has existing data to restore\n const existingSession = sessionManager.buildSessionContext();\n const hasExistingSession = existingSession.messages.length > 0;\n const hasThinkingEntry = sessionManager\n .getBranch()\n .some((entry) => entry.type === \"thinking_level_change\");\n\n let model = options.model;\n let modelFallbackMessage: string | undefined;\n\n // If session has data, try to restore model from it\n if (!model && hasExistingSession && existingSession.model) {\n const restoredModel = modelRegistry.find(\n existingSession.model.provider,\n existingSession.model.modelId,\n );\n if (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n model = restoredModel;\n }\n if (!model) {\n modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n }\n }\n\n // If still no model, use findInitialModel (checks settings default, then provider defaults)\n if (!model) {\n const result = await findInitialModel({\n scopedModels: [],\n isContinuing: hasExistingSession,\n defaultProvider: settingsManager.getDefaultProvider(),\n defaultModelId: settingsManager.getDefaultModel(),\n defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n modelRegistry,\n });\n model = result.model;\n if (!model) {\n modelFallbackMessage = formatNoModelsAvailableMessage();\n } else if (modelFallbackMessage) {\n modelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n }\n }\n\n let thinkingLevel = options.thinkingLevel;\n\n // If session has data, restore thinking level from it\n if (thinkingLevel === undefined && hasExistingSession) {\n thinkingLevel = hasThinkingEntry\n ? (existingSession.thinkingLevel as ThinkingLevel)\n : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n }\n\n // Fall back to settings default\n if (thinkingLevel === undefined) {\n thinkingLevel =\n settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n }\n\n // Clamp to model capabilities\n if (!model) {\n thinkingLevel = \"off\";\n } else {\n thinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n }\n\n const allowedToolNames =\n options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n const initialActiveToolNames: string[] = options.tools\n ? [...options.tools]\n : options.noTools\n ? []\n : [...defaultToolNames];\n\n let agent: Agent;\n\n // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n const convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n const converted = convertToLlm(messages);\n // Check setting dynamically so mid-session changes take effect\n if (!settingsManager.getBlockImages()) {\n return converted;\n }\n // Filter out ImageContent from all messages, replacing with text placeholder\n return converted.map((msg) => {\n if (msg.role === \"user\" || msg.role === \"toolResult\") {\n const content = msg.content;\n if (Array.isArray(content)) {\n const hasImages = content.some((c) => c.type === \"image\");\n if (hasImages) {\n const filteredContent = content\n .map((c) =>\n c.type === \"image\"\n ? {\n type: \"text\" as const,\n text: \"Image reading is disabled.\",\n }\n : c,\n )\n .filter(\n (c, i, arr) =>\n // Dedupe consecutive \"Image reading is disabled.\" texts\n !(\n c.type === \"text\" &&\n c.text === \"Image reading is disabled.\" &&\n i > 0 &&\n arr[i - 1].type === \"text\" &&\n (arr[i - 1] as { type: \"text\"; text: string }).text ===\n \"Image reading is disabled.\"\n ),\n );\n return { ...msg, content: filteredContent };\n }\n }\n }\n return msg;\n });\n };\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n agent = new Agent({\n initialState: {\n systemPrompt: \"\",\n model,\n thinkingLevel,\n tools: [],\n },\n convertToLlm: convertToLlmWithBlockImages,\n streamFn: async (model, context, options) => {\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n const providerRetrySettings = settingsManager.getProviderRetrySettings();\n const attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n return streamSimple(model, context, {\n ...options,\n apiKey: auth.apiKey,\n timeoutMs: options?.timeoutMs ?? providerRetrySettings.timeoutMs,\n maxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n maxRetryDelayMs:\n options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n headers:\n attributionHeaders || auth.headers || options?.headers\n ? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n : undefined,\n });\n },\n onPayload: async (payload, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"before_provider_request\")) {\n return payload;\n }\n return runner.emitBeforeProviderRequest(payload);\n },\n onResponse: async (response, _model) => {\n const runner = extensionRunnerRef.current;\n if (!runner?.hasHandlers(\"after_provider_response\")) {\n return;\n }\n await runner.emit({\n type: \"after_provider_response\",\n status: response.status,\n headers: response.headers,\n });\n },\n sessionId: sessionManager.getSessionId(),\n transformContext: async (messages) => {\n const runner = extensionRunnerRef.current;\n if (!runner) return messages;\n return runner.emitContext(messages);\n },\n steeringMode: settingsManager.getSteeringMode(),\n followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n thinkingBudgets: settingsManager.getThinkingBudgets(),\n maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n });\n\n // Restore messages if session has existing data\n if (hasExistingSession) {\n agent.state.messages = existingSession.messages;\n if (!hasThinkingEntry) {\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n } else {\n // Save initial model and thinking level for new sessions so they can be restored on resume\n if (model) {\n sessionManager.appendModelChange(model.provider, model.id);\n }\n sessionManager.appendThinkingLevelChange(thinkingLevel);\n }\n\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd,\n scopedModels: options.scopedModels,\n resourceLoader,\n customTools: options.customTools,\n modelRegistry,\n initialActiveToolNames,\n allowedToolNames,\n excludedToolNames: options.excludeTools,\n extensionRunnerRef,\n sessionStartEvent: options.sessionStartEvent,\n });\n const extensionsResult = resourceLoader.getExtensions();\n\n return {\n session,\n extensionsResult,\n modelFallbackMessage,\n };\n}\n"]}
@@ -15,6 +15,8 @@ export interface BuildSystemPromptOptions {
15
15
  customPrompt?: string;
16
16
  /** Tools to include in prompt. Default: [read, bash, edit, write, ask_user_question, todo] */
17
17
  selectedTools?: string[];
18
+ /** Tool names explicitly excluded by the caller and omitted from generated guidance. */
19
+ excludedTools?: string[];
18
20
  /** Optional one-line tool snippets keyed by tool name. */
19
21
  toolSnippets?: Record<string, string>;
20
22
  /** Additional guideline bullets appended to the default system prompt guidelines. */
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,iBAAiB;IAChC,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,iDAAiD;IACjD,EAAE,EAAE,MAAM,CAAC;IACX,iDAAiD;IACjD,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,wBAAwB;IACvC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8FAA8F;IAC9F,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sEAAsE;IACtE,aAAa,CAAC,EAAE,iBAAiB,CAAC;IAClC,+DAA+D;IAC/D,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CAClB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAoO3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface SystemPromptModel {\n /** Provider identifier for the selected model. */\n provider: string;\n /** Stable provider-specific model identifier. */\n id: string;\n /** Human-readable model name, when available. */\n name?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n /** Custom system prompt (replaces default). */\n customPrompt?: string;\n /** Tools to include in prompt. Default: [read, bash, edit, write, ask_user_question, todo] */\n selectedTools?: string[];\n /** Optional one-line tool snippets keyed by tool name. */\n toolSnippets?: Record<string, string>;\n /** Additional guideline bullets appended to the default system prompt guidelines. */\n promptGuidelines?: string[];\n /** Text to append to system prompt. */\n appendSystemPrompt?: string;\n /** Working directory. */\n cwd: string;\n /** Currently selected model, used for model-aware prompt metadata. */\n selectedModel?: SystemPromptModel;\n /** Current reasoning/thinking level for the selected model. */\n selectedThinkingLevel?: string;\n /** Pre-loaded context files. */\n contextFiles?: Array<{ path: string; content: string }>;\n /** Pre-loaded skills. */\n skills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n const {\n customPrompt,\n selectedTools,\n toolSnippets,\n promptGuidelines,\n appendSystemPrompt,\n cwd,\n selectedModel,\n selectedThinkingLevel,\n contextFiles: providedContextFiles,\n skills: providedSkills,\n } = options;\n const resolvedCwd = cwd;\n const promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, \"0\");\n const day = String(now.getDate()).padStart(2, \"0\");\n const date = `${year}-${month}-${day}`;\n\n const appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n const modelName =\n selectedModel?.name?.trim() || selectedModel?.id || \"unknown\";\n const modelReasoningLevel = selectedThinkingLevel?.trim() || \"off\";\n\n const contextFiles = providedContextFiles ?? [];\n const skills = providedSkills ?? [];\n\n if (customPrompt) {\n let prompt = customPrompt;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n const customPromptHasRead =\n !selectedTools || selectedTools.includes(\"read\");\n if (customPromptHasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n }\n\n // Get absolute paths to documentation and examples\n const readmePath = getReadmePath();\n const docsPath = getDocsPath();\n const examplesPath = getExamplesPath();\n\n // Build tools list based on selected tools.\n // A tool appears in Available tools only when the caller provides a one-line snippet.\n const tools = selectedTools || [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"ask_user_question\",\n \"todo\",\n ];\n const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n const toolsList =\n visibleTools.length > 0\n ? visibleTools\n .map((name) => `- ${name}: ${toolSnippets![name]}`)\n .join(\"\\n\")\n : \"(none)\";\n\n // Build guidelines based on which tools are actually available\n const guidelinesList: string[] = [];\n const guidelinesSet = new Set<string>();\n const addGuideline = (guideline: string): void => {\n if (guidelinesSet.has(guideline)) {\n return;\n }\n guidelinesSet.add(guideline);\n guidelinesList.push(guideline);\n };\n\n const hasBash = tools.includes(\"bash\");\n const hasGrep = tools.includes(\"grep\");\n const hasFind = tools.includes(\"find\");\n const hasLs = tools.includes(\"ls\");\n const hasRead = tools.includes(\"read\");\n\n // File exploration guidelines\n if (hasBash && !hasGrep && !hasFind && !hasLs) {\n addGuideline(\"Use bash for file operations like ls, rg, find\");\n } else if (hasBash && (hasGrep || hasFind || hasLs)) {\n addGuideline(\n \"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\",\n );\n }\n\n for (const guideline of promptGuidelines ?? []) {\n const normalized = guideline.trim();\n if (normalized.length > 0) {\n addGuideline(normalized);\n }\n }\n\n // Always include these\n addGuideline(\"Be concise in your responses\");\n addGuideline(\"Show file paths clearly when working with files\");\n\n const guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n const engineering_guidelines = `<user_experience>\n- Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\n- If you find yourself circling in thought and asking what the user \"really\" wants, stop and ask the user for clarification. It's better to clarify intent rather than to guess.\n</user_experience>\n\n<tool_policies>\nFollow these tool selection and usage rules in order of priority:\n\n1. **To-do management**: If the user has a complex task that can be broken down into actionable steps, ALWAYS use the \\`todo\\` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\n\n2. **Browser search and automation**:\n\nUse web search tools, playwright-cli (refer to playwright-cli skill) for ALL browser automation tasks, including web research, form filling, and UI interaction:\n - ALWAYS load the playwright-cli skill before usage.\n - ALWAYS ASSUME playwright-cli is installed. If the \\`playwright-cli\\` command fails, fall back to \\`npx playwright-cli\\`.\n\n3. **Testing**: ALWAYS invoke your tdd skill BEFORE creating or modifying any tests.\n\n4. **Sub-agent Orchestration**: To avoid draining your context window, prefer to use subagents for complex tasks all non-trivial operations should be delegated to subagents.\n\nYou should delegate running bash commands (particularly ones that are likely to produce lots of output) such as investigating with the \\`aws\\` CLI, using the \\`gh\\` CLI, digging through logs to \\`bash\\` subagents.\n\nYou should use separate subagents for separate tasks, and you may launch them in parallel, but do not delegate multiple tasks that are likely to have significant overlap to separate subagents.\n\nIMPORTANT: if the user has already given you a task, you should proceed with that task using this approach.\nIMPORTANT: sometimes subagents will take a long time. DO NOT attempt to do the job yourself while waiting for the subagent to respond. Instead, use the time to plan out your next steps, or ask the user follow-up questions to clarify the task requirements.\n\nIf you have not already been explicitly given a task, you should ask the user what task they would like for you to work on--do not assume or begin working on a ticket automatically without a clear problem statement and verifiable acceptance criteria from the user.\n\n5. **Debugging**: When a user asks about debugging, spawn a debugger subagent first.\n - Do not attempt to debug or analyze code yourself without first consulting the debugger subagent.\n - Explain the debugger's insights to the user clearly and concisely.\n - Once the user confirms, implement the necessary code changes based on those insights.\n - If the user has follow-up questions, spawn additional debugger and research subagents as needed.\n</tool_policies>\n\n<engineering_principles>\nSoftware engineering is fundamentally about **managing complexity** to prevent technical debt. When implementing features, prioritize maintainability and testability over cleverness.\n\n**Core Principles:**\n- **Single Responsibility (SRP):** Every class and module must have exactly one reason to change. If a unit does more than one job, split it.\n- **Dependency Inversion (DIP):** Depend on abstractions (interfaces), never on concrete implementations. Inject dependencies; do not instantiate them internally.\n- **KISS:** Keep solutions as simple as possible. Reject unnecessary abstraction layers.\n- **YAGNI:** Do not build generic frameworks or add configurability for hypothetical future requirements. Solve the problem at hand.\n\n**Design Patterns** — Use Gang of Four patterns as a shared vocabulary for recurring problems:\n- **Creational:** Use _Factory_ or _Builder_ to abstract complex object creation and isolate construction logic.\n- **Structural:** Use _Adapter_ or _Facade_ to decouple core logic from external APIs or legacy code.\n- **Behavioral:** Use _Strategy_ to make algorithms interchangeable. Use _Observer_ for event-driven communication between decoupled components.\n\n**Architectural Hygiene:**\n- **Separation of Concerns:** Isolate business logic (Domain) from infrastructure (Database, UI, networking). Never let infrastructure details leak into domain code.\n- **Anti-Pattern Detection:** Watch for **God Objects** (classes with too many responsibilities) and **Spaghetti Code** (tightly coupled, hard-to-follow control flow). Refactor them using polymorphism and clear interfaces.\n\nCreate **seams** in your software using interfaces and abstractions. This ensures code remains flexible, testable, and capable of evolving independently.\n</engineering_principles>`;\n\n let prompt = `You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nEngineering guidelines:\n${engineering_guidelines}\n\nAtomic documentation (read only when the user asks about customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (hasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAWhE,MAAM,WAAW,iBAAiB;IAChC,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,iDAAiD;IACjD,EAAE,EAAE,MAAM,CAAC;IACX,iDAAiD;IACjD,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,wBAAwB;IACvC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8FAA8F;IAC9F,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,wFAAwF;IACxF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sEAAsE;IACtE,aAAa,CAAC,EAAE,iBAAiB,CAAC;IAClC,+DAA+D;IAC/D,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CAClB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAyO3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"ask_user_question\",\n \"todo\",\n] as const;\n\nexport interface SystemPromptModel {\n /** Provider identifier for the selected model. */\n provider: string;\n /** Stable provider-specific model identifier. */\n id: string;\n /** Human-readable model name, when available. */\n name?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n /** Custom system prompt (replaces default). */\n customPrompt?: string;\n /** Tools to include in prompt. Default: [read, bash, edit, write, ask_user_question, todo] */\n selectedTools?: string[];\n /** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n excludedTools?: string[];\n /** Optional one-line tool snippets keyed by tool name. */\n toolSnippets?: Record<string, string>;\n /** Additional guideline bullets appended to the default system prompt guidelines. */\n promptGuidelines?: string[];\n /** Text to append to system prompt. */\n appendSystemPrompt?: string;\n /** Working directory. */\n cwd: string;\n /** Currently selected model, used for model-aware prompt metadata. */\n selectedModel?: SystemPromptModel;\n /** Current reasoning/thinking level for the selected model. */\n selectedThinkingLevel?: string;\n /** Pre-loaded context files. */\n contextFiles?: Array<{ path: string; content: string }>;\n /** Pre-loaded skills. */\n skills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n const {\n customPrompt,\n selectedTools,\n excludedTools,\n toolSnippets,\n promptGuidelines,\n appendSystemPrompt,\n cwd,\n selectedModel,\n selectedThinkingLevel,\n contextFiles: providedContextFiles,\n skills: providedSkills,\n } = options;\n const resolvedCwd = cwd;\n const promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, \"0\");\n const day = String(now.getDate()).padStart(2, \"0\");\n const date = `${year}-${month}-${day}`;\n\n const appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n const modelName =\n selectedModel?.name?.trim() || selectedModel?.id || \"unknown\";\n const modelReasoningLevel = selectedThinkingLevel?.trim() || \"off\";\n\n const contextFiles = providedContextFiles ?? [];\n const skills = providedSkills ?? [];\n const explicitlyExcludedTools = new Set(excludedTools ?? []);\n const isPromptToolAvailable = (name: string): boolean =>\n (!selectedTools || selectedTools.includes(name)) &&\n !explicitlyExcludedTools.has(name);\n\n if (customPrompt) {\n let prompt = customPrompt;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (isPromptToolAvailable(\"read\") && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n }\n\n // Get absolute paths to documentation and examples\n const readmePath = getReadmePath();\n const docsPath = getDocsPath();\n const examplesPath = getExamplesPath();\n\n // Build tools list based on selected tools.\n // A tool appears in Available tools only when the caller provides a one-line snippet.\n const tools = (selectedTools ?? DEFAULT_PROMPT_TOOLS).filter(\n (name) => !explicitlyExcludedTools.has(name),\n );\n const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n const toolsList =\n visibleTools.length > 0\n ? visibleTools\n .map((name) => `- ${name}: ${toolSnippets![name]}`)\n .join(\"\\n\")\n : \"(none)\";\n\n // Build guidelines based on which tools are actually available\n const guidelinesList: string[] = [];\n const guidelinesSet = new Set<string>();\n const addGuideline = (guideline: string): void => {\n if (guidelinesSet.has(guideline)) {\n return;\n }\n guidelinesSet.add(guideline);\n guidelinesList.push(guideline);\n };\n\n const hasBash = tools.includes(\"bash\");\n const hasGrep = tools.includes(\"grep\");\n const hasFind = tools.includes(\"find\");\n const hasLs = tools.includes(\"ls\");\n const hasRead = tools.includes(\"read\");\n\n // File exploration guidelines\n if (hasBash && !hasGrep && !hasFind && !hasLs) {\n addGuideline(\"Use bash for file operations like ls, rg, find\");\n } else if (hasBash && (hasGrep || hasFind || hasLs)) {\n addGuideline(\n \"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\",\n );\n }\n\n for (const guideline of promptGuidelines ?? []) {\n const normalized = guideline.trim();\n if (normalized.length > 0) {\n addGuideline(normalized);\n }\n }\n\n // Always include these\n addGuideline(\"Be concise in your responses\");\n addGuideline(\"Show file paths clearly when working with files\");\n\n const guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n const askUserQuestionGuidance = explicitlyExcludedTools.has(\"ask_user_question\")\n ? \"Always ask clarifying questions if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\"\n : \"Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\";\n const todoGuidance = explicitlyExcludedTools.has(\"todo\")\n ? \"If the user has a complex task that can be broken down into actionable steps, maintain a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\"\n : \"If the user has a complex task that can be broken down into actionable steps, ALWAYS use the `todo` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\";\n\n const engineering_guidelines = `<user_experience>\n- ${askUserQuestionGuidance}\n- If you find yourself circling in thought and asking what the user \"really\" wants, stop and ask the user for clarification. It's better to clarify intent rather than to guess.\n</user_experience>\n\n<tool_policies>\nFollow these tool selection and usage rules in order of priority:\n\n1. **To-do management**: ${todoGuidance}\n\n2. **Browser search and automation**:\n\nUse web search tools, playwright-cli (refer to playwright-cli skill) for ALL browser automation tasks, including web research, form filling, and UI interaction:\n - ALWAYS load the playwright-cli skill before usage.\n - ALWAYS ASSUME playwright-cli is installed. If the \\`playwright-cli\\` command fails, fall back to \\`npx playwright-cli\\`.\n\n3. **Testing**: ALWAYS invoke your tdd skill BEFORE creating or modifying any tests.\n\n4. **Sub-agent Orchestration**: To avoid draining your context window, prefer to use subagents for complex tasks all non-trivial operations should be delegated to subagents.\n\nYou should delegate running bash commands (particularly ones that are likely to produce lots of output) such as investigating with the \\`aws\\` CLI, using the \\`gh\\` CLI, digging through logs to \\`bash\\` subagents.\n\nYou should use separate subagents for separate tasks, and you may launch them in parallel, but do not delegate multiple tasks that are likely to have significant overlap to separate subagents.\n\nIMPORTANT: if the user has already given you a task, you should proceed with that task using this approach.\nIMPORTANT: sometimes subagents will take a long time. DO NOT attempt to do the job yourself while waiting for the subagent to respond. Instead, use the time to plan out your next steps, or ask the user follow-up questions to clarify the task requirements.\n\nIf you have not already been explicitly given a task, you should ask the user what task they would like for you to work on--do not assume or begin working on a ticket automatically without a clear problem statement and verifiable acceptance criteria from the user.\n\n5. **Debugging**: When a user asks about debugging, spawn a debugger subagent first.\n - Do not attempt to debug or analyze code yourself without first consulting the debugger subagent.\n - Explain the debugger's insights to the user clearly and concisely.\n - Once the user confirms, implement the necessary code changes based on those insights.\n - If the user has follow-up questions, spawn additional debugger and research subagents as needed.\n</tool_policies>\n\n<engineering_principles>\nSoftware engineering is fundamentally about **managing complexity** to prevent technical debt. When implementing features, prioritize maintainability and testability over cleverness.\n\n**Core Principles:**\n- **Single Responsibility (SRP):** Every class and module must have exactly one reason to change. If a unit does more than one job, split it.\n- **Dependency Inversion (DIP):** Depend on abstractions (interfaces), never on concrete implementations. Inject dependencies; do not instantiate them internally.\n- **KISS:** Keep solutions as simple as possible. Reject unnecessary abstraction layers.\n- **YAGNI:** Do not build generic frameworks or add configurability for hypothetical future requirements. Solve the problem at hand.\n\n**Design Patterns** — Use Gang of Four patterns as a shared vocabulary for recurring problems:\n- **Creational:** Use _Factory_ or _Builder_ to abstract complex object creation and isolate construction logic.\n- **Structural:** Use _Adapter_ or _Facade_ to decouple core logic from external APIs or legacy code.\n- **Behavioral:** Use _Strategy_ to make algorithms interchangeable. Use _Observer_ for event-driven communication between decoupled components.\n\n**Architectural Hygiene:**\n- **Separation of Concerns:** Isolate business logic (Domain) from infrastructure (Database, UI, networking). Never let infrastructure details leak into domain code.\n- **Anti-Pattern Detection:** Watch for **God Objects** (classes with too many responsibilities) and **Spaghetti Code** (tightly coupled, hard-to-follow control flow). Refactor them using polymorphism and clear interfaces.\n\nCreate **seams** in your software using interfaces and abstractions. This ensures code remains flexible, testable, and capable of evolving independently.\n</engineering_principles>`;\n\n let prompt = `You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nEngineering guidelines:\n${engineering_guidelines}\n\nAtomic documentation (read only when the user asks about customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (hasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n}\n"]}
@@ -3,9 +3,17 @@
3
3
  */
4
4
  import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
5
5
  import { formatSkillsForPrompt } from "./skills.js";
6
+ const DEFAULT_PROMPT_TOOLS = [
7
+ "read",
8
+ "bash",
9
+ "edit",
10
+ "write",
11
+ "ask_user_question",
12
+ "todo",
13
+ ];
6
14
  /** Build the system prompt with tools, guidelines, and context */
7
15
  export function buildSystemPrompt(options) {
8
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, selectedModel, selectedThinkingLevel, contextFiles: providedContextFiles, skills: providedSkills, } = options;
16
+ const { customPrompt, selectedTools, excludedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, selectedModel, selectedThinkingLevel, contextFiles: providedContextFiles, skills: providedSkills, } = options;
9
17
  const resolvedCwd = cwd;
10
18
  const promptCwd = resolvedCwd.replace(/\\/g, "/");
11
19
  const now = new Date();
@@ -18,6 +26,9 @@ export function buildSystemPrompt(options) {
18
26
  const modelReasoningLevel = selectedThinkingLevel?.trim() || "off";
19
27
  const contextFiles = providedContextFiles ?? [];
20
28
  const skills = providedSkills ?? [];
29
+ const explicitlyExcludedTools = new Set(excludedTools ?? []);
30
+ const isPromptToolAvailable = (name) => (!selectedTools || selectedTools.includes(name)) &&
31
+ !explicitlyExcludedTools.has(name);
21
32
  if (customPrompt) {
22
33
  let prompt = customPrompt;
23
34
  if (appendSection) {
@@ -32,8 +43,7 @@ export function buildSystemPrompt(options) {
32
43
  }
33
44
  }
34
45
  // Append skills section (only if read tool is available)
35
- const customPromptHasRead = !selectedTools || selectedTools.includes("read");
36
- if (customPromptHasRead && skills.length > 0) {
46
+ if (isPromptToolAvailable("read") && skills.length > 0) {
37
47
  prompt += formatSkillsForPrompt(skills);
38
48
  }
39
49
  // Add model metadata, date, and working directory last
@@ -49,14 +59,7 @@ export function buildSystemPrompt(options) {
49
59
  const examplesPath = getExamplesPath();
50
60
  // Build tools list based on selected tools.
51
61
  // A tool appears in Available tools only when the caller provides a one-line snippet.
52
- const tools = selectedTools || [
53
- "read",
54
- "bash",
55
- "edit",
56
- "write",
57
- "ask_user_question",
58
- "todo",
59
- ];
62
+ const tools = (selectedTools ?? DEFAULT_PROMPT_TOOLS).filter((name) => !explicitlyExcludedTools.has(name));
60
63
  const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);
61
64
  const toolsList = visibleTools.length > 0
62
65
  ? visibleTools
@@ -95,15 +98,21 @@ export function buildSystemPrompt(options) {
95
98
  addGuideline("Be concise in your responses");
96
99
  addGuideline("Show file paths clearly when working with files");
97
100
  const guidelines = guidelinesList.map((g) => `- ${g}`).join("\n");
101
+ const askUserQuestionGuidance = explicitlyExcludedTools.has("ask_user_question")
102
+ ? "Always ask clarifying questions if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants."
103
+ : "Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.";
104
+ const todoGuidance = explicitlyExcludedTools.has("todo")
105
+ ? "If the user has a complex task that can be broken down into actionable steps, maintain a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations."
106
+ : "If the user has a complex task that can be broken down into actionable steps, ALWAYS use the `todo` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.";
98
107
  const engineering_guidelines = `<user_experience>
99
- - Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.
108
+ - ${askUserQuestionGuidance}
100
109
  - If you find yourself circling in thought and asking what the user "really" wants, stop and ask the user for clarification. It's better to clarify intent rather than to guess.
101
110
  </user_experience>
102
111
 
103
112
  <tool_policies>
104
113
  Follow these tool selection and usage rules in order of priority:
105
114
 
106
- 1. **To-do management**: If the user has a complex task that can be broken down into actionable steps, ALWAYS use the \`todo\` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.
115
+ 1. **To-do management**: ${todoGuidance}
107
116
 
108
117
  2. **Browser search and automation**:
109
118
 
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;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,CAAC;QACjC,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;IAED,uDAAuD;IACvD,MAAM,IAAI,+CAA+C,SAAS,EAAE,CAAC;IACrE,MAAM,IAAI,4BAA4B,mBAAmB,EAAE,CAAC;IAC5D,MAAM,IAAI,mBAAmB,IAAI,EAAE,CAAC;IACpC,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface SystemPromptModel {\n /** Provider identifier for the selected model. */\n provider: string;\n /** Stable provider-specific model identifier. */\n id: string;\n /** Human-readable model name, when available. */\n name?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n /** Custom system prompt (replaces default). */\n customPrompt?: string;\n /** Tools to include in prompt. Default: [read, bash, edit, write, ask_user_question, todo] */\n selectedTools?: string[];\n /** Optional one-line tool snippets keyed by tool name. */\n toolSnippets?: Record<string, string>;\n /** Additional guideline bullets appended to the default system prompt guidelines. */\n promptGuidelines?: string[];\n /** Text to append to system prompt. */\n appendSystemPrompt?: string;\n /** Working directory. */\n cwd: string;\n /** Currently selected model, used for model-aware prompt metadata. */\n selectedModel?: SystemPromptModel;\n /** Current reasoning/thinking level for the selected model. */\n selectedThinkingLevel?: string;\n /** Pre-loaded context files. */\n contextFiles?: Array<{ path: string; content: string }>;\n /** Pre-loaded skills. */\n skills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n const {\n customPrompt,\n selectedTools,\n toolSnippets,\n promptGuidelines,\n appendSystemPrompt,\n cwd,\n selectedModel,\n selectedThinkingLevel,\n contextFiles: providedContextFiles,\n skills: providedSkills,\n } = options;\n const resolvedCwd = cwd;\n const promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, \"0\");\n const day = String(now.getDate()).padStart(2, \"0\");\n const date = `${year}-${month}-${day}`;\n\n const appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n const modelName =\n selectedModel?.name?.trim() || selectedModel?.id || \"unknown\";\n const modelReasoningLevel = selectedThinkingLevel?.trim() || \"off\";\n\n const contextFiles = providedContextFiles ?? [];\n const skills = providedSkills ?? [];\n\n if (customPrompt) {\n let prompt = customPrompt;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n const customPromptHasRead =\n !selectedTools || selectedTools.includes(\"read\");\n if (customPromptHasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n }\n\n // Get absolute paths to documentation and examples\n const readmePath = getReadmePath();\n const docsPath = getDocsPath();\n const examplesPath = getExamplesPath();\n\n // Build tools list based on selected tools.\n // A tool appears in Available tools only when the caller provides a one-line snippet.\n const tools = selectedTools || [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"ask_user_question\",\n \"todo\",\n ];\n const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n const toolsList =\n visibleTools.length > 0\n ? visibleTools\n .map((name) => `- ${name}: ${toolSnippets![name]}`)\n .join(\"\\n\")\n : \"(none)\";\n\n // Build guidelines based on which tools are actually available\n const guidelinesList: string[] = [];\n const guidelinesSet = new Set<string>();\n const addGuideline = (guideline: string): void => {\n if (guidelinesSet.has(guideline)) {\n return;\n }\n guidelinesSet.add(guideline);\n guidelinesList.push(guideline);\n };\n\n const hasBash = tools.includes(\"bash\");\n const hasGrep = tools.includes(\"grep\");\n const hasFind = tools.includes(\"find\");\n const hasLs = tools.includes(\"ls\");\n const hasRead = tools.includes(\"read\");\n\n // File exploration guidelines\n if (hasBash && !hasGrep && !hasFind && !hasLs) {\n addGuideline(\"Use bash for file operations like ls, rg, find\");\n } else if (hasBash && (hasGrep || hasFind || hasLs)) {\n addGuideline(\n \"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\",\n );\n }\n\n for (const guideline of promptGuidelines ?? []) {\n const normalized = guideline.trim();\n if (normalized.length > 0) {\n addGuideline(normalized);\n }\n }\n\n // Always include these\n addGuideline(\"Be concise in your responses\");\n addGuideline(\"Show file paths clearly when working with files\");\n\n const guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n const engineering_guidelines = `<user_experience>\n- Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\n- If you find yourself circling in thought and asking what the user \"really\" wants, stop and ask the user for clarification. It's better to clarify intent rather than to guess.\n</user_experience>\n\n<tool_policies>\nFollow these tool selection and usage rules in order of priority:\n\n1. **To-do management**: If the user has a complex task that can be broken down into actionable steps, ALWAYS use the \\`todo\\` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\n\n2. **Browser search and automation**:\n\nUse web search tools, playwright-cli (refer to playwright-cli skill) for ALL browser automation tasks, including web research, form filling, and UI interaction:\n - ALWAYS load the playwright-cli skill before usage.\n - ALWAYS ASSUME playwright-cli is installed. If the \\`playwright-cli\\` command fails, fall back to \\`npx playwright-cli\\`.\n\n3. **Testing**: ALWAYS invoke your tdd skill BEFORE creating or modifying any tests.\n\n4. **Sub-agent Orchestration**: To avoid draining your context window, prefer to use subagents for complex tasks all non-trivial operations should be delegated to subagents.\n\nYou should delegate running bash commands (particularly ones that are likely to produce lots of output) such as investigating with the \\`aws\\` CLI, using the \\`gh\\` CLI, digging through logs to \\`bash\\` subagents.\n\nYou should use separate subagents for separate tasks, and you may launch them in parallel, but do not delegate multiple tasks that are likely to have significant overlap to separate subagents.\n\nIMPORTANT: if the user has already given you a task, you should proceed with that task using this approach.\nIMPORTANT: sometimes subagents will take a long time. DO NOT attempt to do the job yourself while waiting for the subagent to respond. Instead, use the time to plan out your next steps, or ask the user follow-up questions to clarify the task requirements.\n\nIf you have not already been explicitly given a task, you should ask the user what task they would like for you to work on--do not assume or begin working on a ticket automatically without a clear problem statement and verifiable acceptance criteria from the user.\n\n5. **Debugging**: When a user asks about debugging, spawn a debugger subagent first.\n - Do not attempt to debug or analyze code yourself without first consulting the debugger subagent.\n - Explain the debugger's insights to the user clearly and concisely.\n - Once the user confirms, implement the necessary code changes based on those insights.\n - If the user has follow-up questions, spawn additional debugger and research subagents as needed.\n</tool_policies>\n\n<engineering_principles>\nSoftware engineering is fundamentally about **managing complexity** to prevent technical debt. When implementing features, prioritize maintainability and testability over cleverness.\n\n**Core Principles:**\n- **Single Responsibility (SRP):** Every class and module must have exactly one reason to change. If a unit does more than one job, split it.\n- **Dependency Inversion (DIP):** Depend on abstractions (interfaces), never on concrete implementations. Inject dependencies; do not instantiate them internally.\n- **KISS:** Keep solutions as simple as possible. Reject unnecessary abstraction layers.\n- **YAGNI:** Do not build generic frameworks or add configurability for hypothetical future requirements. Solve the problem at hand.\n\n**Design Patterns** — Use Gang of Four patterns as a shared vocabulary for recurring problems:\n- **Creational:** Use _Factory_ or _Builder_ to abstract complex object creation and isolate construction logic.\n- **Structural:** Use _Adapter_ or _Facade_ to decouple core logic from external APIs or legacy code.\n- **Behavioral:** Use _Strategy_ to make algorithms interchangeable. Use _Observer_ for event-driven communication between decoupled components.\n\n**Architectural Hygiene:**\n- **Separation of Concerns:** Isolate business logic (Domain) from infrastructure (Database, UI, networking). Never let infrastructure details leak into domain code.\n- **Anti-Pattern Detection:** Watch for **God Objects** (classes with too many responsibilities) and **Spaghetti Code** (tightly coupled, hard-to-follow control flow). Refactor them using polymorphism and clear interfaces.\n\nCreate **seams** in your software using interfaces and abstractions. This ensures code remains flexible, testable, and capable of evolving independently.\n</engineering_principles>`;\n\n let prompt = `You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nEngineering guidelines:\n${engineering_guidelines}\n\nAtomic documentation (read only when the user asks about customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (hasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG;IAC3B,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;IACP,mBAAmB;IACnB,MAAM;CACE,CAAC;AAoCX,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,OAAiC;IACjE,MAAM,EACJ,YAAY,EACZ,aAAa,EACb,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,aAAa,EACb,qBAAqB,EACrB,YAAY,EAAE,oBAAoB,EAClC,MAAM,EAAE,cAAc,GACvB,GAAG,OAAO,CAAC;IACZ,MAAM,WAAW,GAAG,GAAG,CAAC;IACxB,MAAM,SAAS,GAAG,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAElD,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAC1D,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CA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AAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"ask_user_question\",\n \"todo\",\n] as const;\n\nexport interface SystemPromptModel {\n /** Provider identifier for the selected model. */\n provider: string;\n /** Stable provider-specific model identifier. */\n id: string;\n /** Human-readable model name, when available. */\n name?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n /** Custom system prompt (replaces default). */\n customPrompt?: string;\n /** Tools to include in prompt. Default: [read, bash, edit, write, ask_user_question, todo] */\n selectedTools?: string[];\n /** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n excludedTools?: string[];\n /** Optional one-line tool snippets keyed by tool name. */\n toolSnippets?: Record<string, string>;\n /** Additional guideline bullets appended to the default system prompt guidelines. */\n promptGuidelines?: string[];\n /** Text to append to system prompt. */\n appendSystemPrompt?: string;\n /** Working directory. */\n cwd: string;\n /** Currently selected model, used for model-aware prompt metadata. */\n selectedModel?: SystemPromptModel;\n /** Current reasoning/thinking level for the selected model. */\n selectedThinkingLevel?: string;\n /** Pre-loaded context files. */\n contextFiles?: Array<{ path: string; content: string }>;\n /** Pre-loaded skills. */\n skills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n const {\n customPrompt,\n selectedTools,\n excludedTools,\n toolSnippets,\n promptGuidelines,\n appendSystemPrompt,\n cwd,\n selectedModel,\n selectedThinkingLevel,\n contextFiles: providedContextFiles,\n skills: providedSkills,\n } = options;\n const resolvedCwd = cwd;\n const promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, \"0\");\n const day = String(now.getDate()).padStart(2, \"0\");\n const date = `${year}-${month}-${day}`;\n\n const appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n const modelName =\n selectedModel?.name?.trim() || selectedModel?.id || \"unknown\";\n const modelReasoningLevel = selectedThinkingLevel?.trim() || \"off\";\n\n const contextFiles = providedContextFiles ?? [];\n const skills = providedSkills ?? [];\n const explicitlyExcludedTools = new Set(excludedTools ?? []);\n const isPromptToolAvailable = (name: string): boolean =>\n (!selectedTools || selectedTools.includes(name)) &&\n !explicitlyExcludedTools.has(name);\n\n if (customPrompt) {\n let prompt = customPrompt;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (isPromptToolAvailable(\"read\") && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n }\n\n // Get absolute paths to documentation and examples\n const readmePath = getReadmePath();\n const docsPath = getDocsPath();\n const examplesPath = getExamplesPath();\n\n // Build tools list based on selected tools.\n // A tool appears in Available tools only when the caller provides a one-line snippet.\n const tools = (selectedTools ?? DEFAULT_PROMPT_TOOLS).filter(\n (name) => !explicitlyExcludedTools.has(name),\n );\n const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n const toolsList =\n visibleTools.length > 0\n ? visibleTools\n .map((name) => `- ${name}: ${toolSnippets![name]}`)\n .join(\"\\n\")\n : \"(none)\";\n\n // Build guidelines based on which tools are actually available\n const guidelinesList: string[] = [];\n const guidelinesSet = new Set<string>();\n const addGuideline = (guideline: string): void => {\n if (guidelinesSet.has(guideline)) {\n return;\n }\n guidelinesSet.add(guideline);\n guidelinesList.push(guideline);\n };\n\n const hasBash = tools.includes(\"bash\");\n const hasGrep = tools.includes(\"grep\");\n const hasFind = tools.includes(\"find\");\n const hasLs = tools.includes(\"ls\");\n const hasRead = tools.includes(\"read\");\n\n // File exploration guidelines\n if (hasBash && !hasGrep && !hasFind && !hasLs) {\n addGuideline(\"Use bash for file operations like ls, rg, find\");\n } else if (hasBash && (hasGrep || hasFind || hasLs)) {\n addGuideline(\n \"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\",\n );\n }\n\n for (const guideline of promptGuidelines ?? []) {\n const normalized = guideline.trim();\n if (normalized.length > 0) {\n addGuideline(normalized);\n }\n }\n\n // Always include these\n addGuideline(\"Be concise in your responses\");\n addGuideline(\"Show file paths clearly when working with files\");\n\n const guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n const askUserQuestionGuidance = explicitlyExcludedTools.has(\"ask_user_question\")\n ? \"Always ask clarifying questions if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\"\n : \"Always ask clarifying questions (using the ask_user_question tool if available) if the user's request is ambiguous or lacks necessary details. NEVER make assumptions about what the user wants.\";\n const todoGuidance = explicitlyExcludedTools.has(\"todo\")\n ? \"If the user has a complex task that can be broken down into actionable steps, maintain a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\"\n : \"If the user has a complex task that can be broken down into actionable steps, ALWAYS use the `todo` tool to create a task list before proceeding. This ensures clarity and alignment with the user's goals and that you have a way to track your work and ensure you are meeting the user's expectations.\";\n\n const engineering_guidelines = `<user_experience>\n- ${askUserQuestionGuidance}\n- If you find yourself circling in thought and asking what the user \"really\" wants, stop and ask the user for clarification. It's better to clarify intent rather than to guess.\n</user_experience>\n\n<tool_policies>\nFollow these tool selection and usage rules in order of priority:\n\n1. **To-do management**: ${todoGuidance}\n\n2. **Browser search and automation**:\n\nUse web search tools, playwright-cli (refer to playwright-cli skill) for ALL browser automation tasks, including web research, form filling, and UI interaction:\n - ALWAYS load the playwright-cli skill before usage.\n - ALWAYS ASSUME playwright-cli is installed. If the \\`playwright-cli\\` command fails, fall back to \\`npx playwright-cli\\`.\n\n3. **Testing**: ALWAYS invoke your tdd skill BEFORE creating or modifying any tests.\n\n4. **Sub-agent Orchestration**: To avoid draining your context window, prefer to use subagents for complex tasks all non-trivial operations should be delegated to subagents.\n\nYou should delegate running bash commands (particularly ones that are likely to produce lots of output) such as investigating with the \\`aws\\` CLI, using the \\`gh\\` CLI, digging through logs to \\`bash\\` subagents.\n\nYou should use separate subagents for separate tasks, and you may launch them in parallel, but do not delegate multiple tasks that are likely to have significant overlap to separate subagents.\n\nIMPORTANT: if the user has already given you a task, you should proceed with that task using this approach.\nIMPORTANT: sometimes subagents will take a long time. DO NOT attempt to do the job yourself while waiting for the subagent to respond. Instead, use the time to plan out your next steps, or ask the user follow-up questions to clarify the task requirements.\n\nIf you have not already been explicitly given a task, you should ask the user what task they would like for you to work on--do not assume or begin working on a ticket automatically without a clear problem statement and verifiable acceptance criteria from the user.\n\n5. **Debugging**: When a user asks about debugging, spawn a debugger subagent first.\n - Do not attempt to debug or analyze code yourself without first consulting the debugger subagent.\n - Explain the debugger's insights to the user clearly and concisely.\n - Once the user confirms, implement the necessary code changes based on those insights.\n - If the user has follow-up questions, spawn additional debugger and research subagents as needed.\n</tool_policies>\n\n<engineering_principles>\nSoftware engineering is fundamentally about **managing complexity** to prevent technical debt. When implementing features, prioritize maintainability and testability over cleverness.\n\n**Core Principles:**\n- **Single Responsibility (SRP):** Every class and module must have exactly one reason to change. If a unit does more than one job, split it.\n- **Dependency Inversion (DIP):** Depend on abstractions (interfaces), never on concrete implementations. Inject dependencies; do not instantiate them internally.\n- **KISS:** Keep solutions as simple as possible. Reject unnecessary abstraction layers.\n- **YAGNI:** Do not build generic frameworks or add configurability for hypothetical future requirements. Solve the problem at hand.\n\n**Design Patterns** — Use Gang of Four patterns as a shared vocabulary for recurring problems:\n- **Creational:** Use _Factory_ or _Builder_ to abstract complex object creation and isolate construction logic.\n- **Structural:** Use _Adapter_ or _Facade_ to decouple core logic from external APIs or legacy code.\n- **Behavioral:** Use _Strategy_ to make algorithms interchangeable. Use _Observer_ for event-driven communication between decoupled components.\n\n**Architectural Hygiene:**\n- **Separation of Concerns:** Isolate business logic (Domain) from infrastructure (Database, UI, networking). Never let infrastructure details leak into domain code.\n- **Anti-Pattern Detection:** Watch for **God Objects** (classes with too many responsibilities) and **Spaghetti Code** (tightly coupled, hard-to-follow control flow). Refactor them using polymorphism and clear interfaces.\n\nCreate **seams** in your software using interfaces and abstractions. This ensures code remains flexible, testable, and capable of evolving independently.\n</engineering_principles>`;\n\n let prompt = `You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nEngineering guidelines:\n${engineering_guidelines}\n\nAtomic documentation (read only when the user asks about customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n if (appendSection) {\n prompt += appendSection;\n }\n\n // Append project context files\n if (contextFiles.length > 0) {\n prompt += \"\\n\\n# Project Context\\n\\n\";\n prompt += \"Project-specific instructions and guidelines:\\n\\n\";\n for (const { path: filePath, content } of contextFiles) {\n prompt += `<context_file path=\\\"${filePath}\\\">\\n${content}\\n</context_file>\\n\\n`;\n }\n }\n\n // Append skills section (only if read tool is available)\n if (hasRead && skills.length > 0) {\n prompt += formatSkillsForPrompt(skills);\n }\n\n // Add model metadata, date, and working directory last\n prompt += `\\nModel name (used for commit attribution): ${modelName}`;\n prompt += `\\nModel reasoning level: ${modelReasoningLevel}`;\n prompt += `\\nCurrent date: ${date}`;\n prompt += `\\nCurrent working directory: ${promptCwd}`;\n\n return prompt;\n}\n"]}
@@ -73,13 +73,13 @@ Atomic ships with four workflows you can run immediately. Use `/workflow list` t
73
73
  | Workflow | When to use | Example |
74
74
  |---|---|---|
75
75
  | `deep-research-codebase` | Broad, cross-cutting research before you decide what to change. Scout → research-history → parallel specialist waves → aggregator. | `/workflow deep-research-codebase prompt="How do payment retries work end to end?"` |
76
- | `goal` | Focused implementation against a clear objective or spec. Persists a goal ledger, captures worker receipts, gates completion through reviewer quorum, and stops as complete, blocked, or needing human follow-up. | `/workflow goal objective="Implement specs/2026-03-rate-limit.md and validate the behavior"` |
77
- | `ralph` | Heavier spec-to-PR work. Writes an RFC-style plan, delegates implementation through sub-agents, simplifies, discovers review infrastructure, runs reviewers, iterates, and prepares a PR report. | `/workflow ralph prompt="Plan, implement, review, and prepare a PR for specs/2026-03-rate-limit.md"` |
76
+ | `goal` | Small-to-medium scope changes when you can identify the work surface, state the exact outcome, and name the validation that proves it is done — for example tests, lint/typecheck, docs builds, or observable behavior. Keeps the run bounded with a goal ledger, reviewer gates, and final status `complete`, `blocked`, or `needs_human`. | `/workflow goal objective="Implement specs/2026-03-rate-limit.md, run the focused tests, and finish when burst traffic returns 429"` |
77
+ | `ralph` | Larger migrations, broad refactors, multi-package changes, and spec-to-PR work where you want Atomic to plan the approach, delegate implementation through sub-agents, simplify, review, iterate, and prepare a pull-request report. | `/workflow ralph prompt="Plan the database migration, implement it, review it, and prepare a PR"` |
78
78
  | `open-claude-design` | UI and design-system work with generation, critique, and refinement loops; renders a live `preview.html` you can iterate against. | `/workflow open-claude-design prompt="Refresh the settings page hierarchy" output_type=page` |
79
79
 
80
80
  <p align="center"><img src="images/workflow-list.png" alt="Workflow List" width="600" /></p>
81
81
 
82
- Inputs are bare `key=value` tokens. Values are JSON-parsed when possible, so `count=5`, `flag=true`, and `objective="multi word value"` preserve useful types. If you call `/workflow <name>` without required inputs, the TUI opens an inline picker; pass `--no-picker` to skip it.
82
+ Inputs are bare `key=value` tokens. Values are JSON-parsed when possible, so `count=5`, `flag=true`, and `objective="multi word value"` preserve useful types. Some workflows expose reusable worktree inputs; for example, add `git_worktree_dir=../atomic-ralph-wt` to `ralph` to run its stages in a created/reused Git worktree while preserving your current repo-relative cwd. If you call `/workflow <name>` without required inputs, the TUI opens an inline picker; pass `--no-picker` to skip it.
83
83
 
84
84
  You can also launch workflows with **natural language** — just describe the task in chat and ask Atomic to run the matching workflow:
85
85
 
@@ -87,7 +87,15 @@ You can also launch workflows with **natural language** — just describe the ta
87
87
  Run a deep codebase research workflow on how the rate limiter behaves under burst traffic.
88
88
  ```
89
89
 
90
- Atomic picks the workflow, fills in inputs from the request, and confirms before launch. `goal` persists receipts in a goal ledger and stops only when reviewer quorum proves completion, the same blocker repeats enough times, or the turn limit requires human follow-up. `ralph` adds a planning/spec stage, sub-agent implementation orchestration, simplification, review-infrastructure discovery, and PR handoff.
90
+ ```text
91
+ Use the goal workflow to update the CLI docs for --json, include one example, run the docs build, and finish when the build passes.
92
+ ```
93
+
94
+ Atomic picks the workflow, fills in inputs from the request, and confirms before launch.
95
+
96
+ Use `goal` for small-to-medium scope changes when you can identify the work surface, state the exact outcome you want, and name the validation that proves it is done — for example specific tests, lint/typecheck commands, docs builds, or observable behavior. It keeps the run bounded, captures receipts in a goal ledger, gates completion through reviewers, and stops as `complete`, `blocked`, or `needs_human`.
97
+
98
+ Keep using `ralph` for larger migrations, broad refactors, multi-package changes, and spec-to-PR work where you want Atomic to plan the approach, delegate implementation through sub-agents, simplify, review, iterate, and prepare a pull-request report.
91
99
 
92
100
  ### Monitor and steer a run
93
101
 
@@ -116,7 +124,7 @@ Skills are reusable expert instructions. Trigger one with `/skill:<name>` follow
116
124
  | `tdd` | Test-first feature or bug work. | `/skill:tdd` |
117
125
  | `impeccable` | Critique or refine frontend and product UI. | `/skill:impeccable` |
118
126
 
119
- Use `/skill:research-codebase` for a focused area and `/workflow deep-research-codebase` when the answer spans the whole repo. A typical focused flow is `/skill:research-codebase` → `/skill:create-spec` → `/workflow goal` to implement and validate; use `/workflow ralph` when you also want an RFC-style plan, sub-agent orchestration, iterative review, and PR handoff.
127
+ Use `/skill:research-codebase` for a focused area and `/workflow deep-research-codebase` when the answer spans the whole repo. A typical focused flow is `/skill:research-codebase` → `/skill:create-spec` → `/workflow goal` with an objective that identifies the work surface, states the exact outcome, and names the validation that proves it is done. Keep using `/workflow ralph` for larger migrations, broad refactors, multi-package changes, and spec-to-PR work where you want Atomic to plan, delegate through sub-agents, simplify, review, iterate, and prepare a pull-request report.
120
128
 
121
129
  ### Create your own workflow in natural language
122
130
 
package/docs/sdk.md CHANGED
@@ -74,6 +74,8 @@ const { session } = await createAgentSession();
74
74
  const { session } = await createAgentSession({
75
75
  model: myModel,
76
76
  tools: ["read", "bash"],
77
+ // Or keep defaults and remove specific tools:
78
+ // excludeTools: ["ask_user_question"],
77
79
  sessionManager: SessionManager.inMemory(),
78
80
  });
79
81
  ```
@@ -480,12 +482,14 @@ const { session } = await createAgentSession({ resourceLoader: loader });
480
482
 
481
483
  ### Tools
482
484
 
483
- Specify which built-in tools to enable:
485
+ Specify which tools to expose by name:
484
486
 
485
- - Built-in tool names: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`
486
- - Default built-ins: `read`, `bash`, `edit`, `write`
487
+ - Built-in tool names: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, `ask_user_question`, `todo`
488
+ - The default active built-ins include `ask_user_question` and `todo` in addition to file and shell tools.
489
+ - `tools` is an allowlist: when provided, only the listed built-in, extension, and custom tool names are exposed.
490
+ - `excludeTools` is a blocklist: matching built-in, extension, and custom tool names are omitted from the final registry and active tool set. If both are provided, `tools` is applied first and `excludeTools` subtracts from it.
487
491
  - `noTools: "all"` disables all tools
488
- - `noTools: "builtin"` disables default built-ins while keeping extension and custom tools enabled
492
+ - `noTools: "builtin"` disables default built-ins while keeping extension and custom tools enabled, except names listed in `excludeTools`
489
493
 
490
494
  ```typescript
491
495
  import { createAgentSession } from "@bastani/atomic";
@@ -499,6 +503,17 @@ const { session } = await createAgentSession({
499
503
  const { session } = await createAgentSession({
500
504
  tools: ["read", "bash", "grep"],
501
505
  });
506
+
507
+ // Keep defaults but remove HITL prompts
508
+ const { session } = await createAgentSession({
509
+ excludeTools: ["ask_user_question"],
510
+ });
511
+
512
+ // Allowlist first, then subtract exclusions
513
+ const { session } = await createAgentSession({
514
+ tools: ["read", "bash", "ask_user_question"],
515
+ excludeTools: ["ask_user_question"], // final tools: read, bash
516
+ });
502
517
  ```
503
518
 
504
519
  #### Tools with Custom cwd
@@ -556,7 +571,7 @@ Use `defineTool()` for standalone definitions and arrays like `customTools: [myT
556
571
 
557
572
  Custom tools passed via `customTools` are combined with extension-registered tools. Extensions loaded by the ResourceLoader can also register tools via `pi.registerTool()`.
558
573
 
559
- If you pass `tools`, include each custom or extension tool name you want enabled, for example `tools: ["read", "bash", "my_tool"]`.
574
+ If you pass `tools`, include each custom or extension tool name you want enabled, for example `tools: ["read", "bash", "my_tool"]`. Use `excludeTools` to remove a custom or extension tool by name from the final exposed set.
560
575
 
561
576
  > See [examples/sdk/05-tools.ts](https://github.com/flora131/atomic/blob/main/packages/coding-agent/examples/sdk/05-tools.ts)
562
577