@dreb/coding-agent 2.17.0 → 2.18.0
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.
- package/README.md +4 -2
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +1 -0
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/index.d.ts +6 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +9 -2
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +6 -0
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +28 -3
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/wait.d.ts +40 -0
- package/dist/core/tools/wait.d.ts.map +1 -0
- package/dist/core/tools/wait.js +87 -0
- package/dist/core/tools/wait.js.map +1 -0
- package/docs/extensions.md +2 -2
- package/package.json +1 -1
package/dist/core/sdk.d.ts
CHANGED
|
@@ -26,7 +26,7 @@ export interface CreateAgentSessionOptions {
|
|
|
26
26
|
model: Model<any>;
|
|
27
27
|
thinkingLevel?: ThinkingLevel;
|
|
28
28
|
}>;
|
|
29
|
-
/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */
|
|
29
|
+
/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent, wait]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */
|
|
30
30
|
tools?: Tool[];
|
|
31
31
|
/** Custom tools to register (in addition to built-in tools). */
|
|
32
32
|
customTools?: ToolDefinition[];
|
package/dist/core/sdk.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,KAAK,EAAW,KAAK,EAAE,MAAM,UAAU,CAAC;AAE/C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEnG,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAAwB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACN,QAAQ,EACR,QAAQ,EACR,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,0BAA0B,EAC1B,QAAQ,EACR,MAAM,EACN,qBAAqB,EACrB,aAAa,EACb,QAAQ,EACR,YAAY,EACZ,KAAK,IAAI,EAET,qBAAqB,EACrB,SAAS,EACT,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,WAAW,CAAC,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,EACR,MAAM,EACN,YAAY,EACZ,WAAW,EACX,aAAa,EACb,QAAQ,IAAI,eAAe,EAC3B,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,EACZ,kBAAkB,EAElB,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,GACrB,CAAC;AAQF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAmPnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@dreb/agent-core\";\nimport type { Message, Model } from \"@dreb/ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport { configValueWarnings } from \"./resolve-config-value.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateSubagentTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tgrepTool,\n\tlsTool,\n\tpruneBackgroundAgents,\n\treadOnlyTools,\n\treadTool,\n\tsubagentTool,\n\ttype Tool,\n\ttype ToolName,\n\twithFileMutationQueue,\n\twriteTool,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.dreb/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** UI type for system prompt context (e.g. \"tui\", \"telegram\", \"rpc\") */\n\tuiType?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tsubagentTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n\tcreateSubagentTool,\n\t// Background agent registry\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@dreb/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tconst hasApiKey = restoredModel ? !!(await modelRegistry.getApiKey(restoredModel)) : false;\n\t\tif (restoredModel && hasApiKey) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tconst reason = !restoredModel ? \"not found in registry\" : \"no API key available\";\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId} (${reason})`;\n\t\t\tconsole.warn(`[model-restore] ${modelFallbackMessage}`);\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\t// Tools that are always active when available (created by factory, not in allTools singleton)\n\tconst alwaysActiveBuiltins = [\"skill\", \"tasks_update\", \"search\", \"suggest_next\"];\n\tconst defaultActiveToolNames: ToolName[] = [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t];\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools), ...alwaysActiveBuiltins]\n\t\t: [...defaultActiveToolNames, ...alwaysActiveBuiltins];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst sessionRef: { current?: AgentSession } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getRetrySettings().maxDelayMs,\n\t\tonWarning: (code: string, message: string) => {\n\t\t\t// Wire provider-level warnings to the session for user/agent visibility\n\t\t\tconst informational =\n\t\t\t\tcode === \"sse_parse_error\" || code === \"ws_parse_error\" || code === \"json_parse_total_failure\";\n\t\t\tsessionRef.current?.warnInSession(message, { informational });\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t// Surface any config value resolution warnings (e.g. failed !command API keys)\n\t\t\tif (configValueWarnings.length > 0) {\n\t\t\t\tconst warnings = configValueWarnings.splice(0);\n\t\t\t\tfor (const w of warnings) {\n\t\t\t\t\tsessionRef.current?.warnInSession(w);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!key) {\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (isOAuth) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn key;\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(existingSession.messages);\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tuiType: options.uiType,\n\t});\n\tsessionRef.current = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t// Surface any resource diagnostics from initial load\n\tsession.warnResourceDiagnostics(resourceLoader);\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,aAAa,EAAE,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qBAAqB,GACrB,CAAC;AAQF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoPnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@dreb/agent-core\";\nimport type { Message, Model } from \"@dreb/ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport { configValueWarnings } from \"./resolve-config-value.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateSubagentTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tgrepTool,\n\tlsTool,\n\tpruneBackgroundAgents,\n\treadOnlyTools,\n\treadTool,\n\tsubagentTool,\n\ttype Tool,\n\ttype ToolName,\n\twithFileMutationQueue,\n\twriteTool,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.dreb/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent, wait]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** UI type for system prompt context (e.g. \"tui\", \"telegram\", \"rpc\") */\n\tuiType?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tsubagentTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n\tcreateSubagentTool,\n\t// Background agent registry\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@dreb/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tconst hasApiKey = restoredModel ? !!(await modelRegistry.getApiKey(restoredModel)) : false;\n\t\tif (restoredModel && hasApiKey) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tconst reason = !restoredModel ? \"not found in registry\" : \"no API key available\";\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId} (${reason})`;\n\t\t\tconsole.warn(`[model-restore] ${modelFallbackMessage}`);\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\t// Tools that are always active when available (created by factory, not in allTools singleton)\n\tconst alwaysActiveBuiltins = [\"skill\", \"tasks_update\", \"search\", \"suggest_next\"];\n\tconst defaultActiveToolNames: ToolName[] = [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t\t\"wait\",\n\t];\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools), ...alwaysActiveBuiltins]\n\t\t: [...defaultActiveToolNames, ...alwaysActiveBuiltins];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst sessionRef: { current?: AgentSession } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getRetrySettings().maxDelayMs,\n\t\tonWarning: (code: string, message: string) => {\n\t\t\t// Wire provider-level warnings to the session for user/agent visibility\n\t\t\tconst informational =\n\t\t\t\tcode === \"sse_parse_error\" || code === \"ws_parse_error\" || code === \"json_parse_total_failure\";\n\t\t\tsessionRef.current?.warnInSession(message, { informational });\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t// Surface any config value resolution warnings (e.g. failed !command API keys)\n\t\t\tif (configValueWarnings.length > 0) {\n\t\t\t\tconst warnings = configValueWarnings.splice(0);\n\t\t\t\tfor (const w of warnings) {\n\t\t\t\t\tsessionRef.current?.warnInSession(w);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!key) {\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (isOAuth) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn key;\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(existingSession.messages);\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tuiType: options.uiType,\n\t});\n\tsessionRef.current = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t// Surface any resource diagnostics from initial load\n\tsession.warnResourceDiagnostics(resourceLoader);\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
package/dist/core/sdk.js
CHANGED
|
@@ -140,6 +140,7 @@ export async function createAgentSession(options = {}) {
|
|
|
140
140
|
"web_search",
|
|
141
141
|
"web_fetch",
|
|
142
142
|
"subagent",
|
|
143
|
+
"wait",
|
|
143
144
|
];
|
|
144
145
|
const initialActiveToolNames = options.tools
|
|
145
146
|
? [...options.tools.map((t) => t.name).filter((n) => n in allTools), ...alwaysActiveBuiltins]
|
package/dist/core/sdk.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","source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K,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,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,kBAAkB;QAClB,MAAM,EAAE,OAAO,CAAC,MAAM;KACtB,CAAC,CAAC;IACH,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,qDAAqD;IACrD,OAAO,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAC;IAEhD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@dreb/agent-core\";\nimport type { Message, Model } from \"@dreb/ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport { configValueWarnings } from \"./resolve-config-value.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateSubagentTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tgrepTool,\n\tlsTool,\n\tpruneBackgroundAgents,\n\treadOnlyTools,\n\treadTool,\n\tsubagentTool,\n\ttype Tool,\n\ttype ToolName,\n\twithFileMutationQueue,\n\twriteTool,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.dreb/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** UI type for system prompt context (e.g. \"tui\", \"telegram\", \"rpc\") */\n\tuiType?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tsubagentTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n\tcreateSubagentTool,\n\t// Background agent registry\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@dreb/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tconst hasApiKey = restoredModel ? !!(await modelRegistry.getApiKey(restoredModel)) : false;\n\t\tif (restoredModel && hasApiKey) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tconst reason = !restoredModel ? \"not found in registry\" : \"no API key available\";\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId} (${reason})`;\n\t\t\tconsole.warn(`[model-restore] ${modelFallbackMessage}`);\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\t// Tools that are always active when available (created by factory, not in allTools singleton)\n\tconst alwaysActiveBuiltins = [\"skill\", \"tasks_update\", \"search\", \"suggest_next\"];\n\tconst defaultActiveToolNames: ToolName[] = [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t];\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools), ...alwaysActiveBuiltins]\n\t\t: [...defaultActiveToolNames, ...alwaysActiveBuiltins];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst sessionRef: { current?: AgentSession } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getRetrySettings().maxDelayMs,\n\t\tonWarning: (code: string, message: string) => {\n\t\t\t// Wire provider-level warnings to the session for user/agent visibility\n\t\t\tconst informational =\n\t\t\t\tcode === \"sse_parse_error\" || code === \"ws_parse_error\" || code === \"json_parse_total_failure\";\n\t\t\tsessionRef.current?.warnInSession(message, { informational });\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t// Surface any config value resolution warnings (e.g. failed !command API keys)\n\t\t\tif (configValueWarnings.length > 0) {\n\t\t\t\tconst warnings = configValueWarnings.splice(0);\n\t\t\t\tfor (const w of warnings) {\n\t\t\t\t\tsessionRef.current?.warnInSession(w);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!key) {\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (isOAuth) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn key;\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(existingSession.messages);\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tuiType: options.uiType,\n\t});\n\tsessionRef.current = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t// Surface any resource diagnostics from initial load\n\tsession.warnResourceDiagnostics(resourceLoader);\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAyC,MAAM,kBAAkB,CAAC;AAEhF,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,EACN,QAAQ,EACR,QAAQ,EACR,WAAW,EACX,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,0BAA0B,EAC1B,QAAQ,EACR,MAAM,EACN,qBAAqB,EACrB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,eAAe,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAChD,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACvB,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;QACzD,CAAC;IACF,CAAC;SAAM,CAAC;QACP,2FAA2F;QAC3F,IAAI,KAAK,EAAE,CAAC;YACX,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,CAAC;QACD,cAAc,CAAC,yBAAyB,CAAC,aAAa,CAAC,CAAC;IACzD,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC;QAChC,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,kBAAkB;QAClB,MAAM,EAAE,OAAO,CAAC,MAAM;KACtB,CAAC,CAAC;IACH,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,qDAAqD;IACrD,OAAO,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAC;IAEhD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, type ThinkingLevel } from \"@dreb/agent-core\";\nimport type { Message, Model } from \"@dreb/ai\";\nimport { getAgentDir, getDocsPath } from \"../config.js\";\nimport { AgentSession } from \"./agent-session.js\";\nimport { AuthStorage } from \"./auth-storage.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport type { ExtensionRunner, LoadExtensionsResult, ToolDefinition } from \"./extensions/index.js\";\nimport { convertToLlm } from \"./messages.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { findInitialModel } from \"./model-resolver.js\";\nimport { configValueWarnings } from \"./resolve-config-value.js\";\nimport type { ResourceLoader } from \"./resource-loader.js\";\nimport { DefaultResourceLoader } from \"./resource-loader.js\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { time } from \"./timings.js\";\nimport {\n\tallTools,\n\tbashTool,\n\tcodingTools,\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateSubagentTool,\n\tcreateWriteTool,\n\teditTool,\n\tfindTool,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tgrepTool,\n\tlsTool,\n\tpruneBackgroundAgents,\n\treadOnlyTools,\n\treadTool,\n\tsubagentTool,\n\ttype Tool,\n\ttype ToolName,\n\twithFileMutationQueue,\n\twriteTool,\n} from \"./tools/index.js\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.dreb/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: new ModelRegistry(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/** Built-in tools to use. Default: all standard tools [read, bash, edit, write, grep, find, ls, web_search, web_fetch, subagent, wait]. `skill`, `tasks_update`, and `search` are always active regardless of this setting. */\n\ttools?: Tool[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** UI type for system prompt context (e.g. \"tui\", \"telegram\", \"rpc\") */\n\tuiType?: string;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nexport type { PromptTemplate } from \"./prompt-templates.js\";\nexport type { Skill } from \"./skills.js\";\nexport type { Tool } from \"./tools/index.js\";\n\nexport {\n\t// Pre-built tools (use process.cwd())\n\treadTool,\n\tbashTool,\n\teditTool,\n\twriteTool,\n\tgrepTool,\n\tfindTool,\n\tlsTool,\n\tsubagentTool,\n\tcodingTools,\n\treadOnlyTools,\n\tallTools as allBuiltInTools,\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n\tcreateSubagentTool,\n\t// Background agent registry\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\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 '@dreb/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: [readTool, bashTool],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = options.cwd ?? process.cwd();\n\tconst agentDir = options.agentDir ?? getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tconst hasApiKey = restoredModel ? !!(await modelRegistry.getApiKey(restoredModel)) : false;\n\t\tif (restoredModel && hasApiKey) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tconst reason = !restoredModel ? \"not found in registry\" : \"no API key available\";\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId} (${reason})`;\n\t\t\tconsole.warn(`[model-restore] ${modelFallbackMessage}`);\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `No models available. Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}. Then use /model to select a model.`;\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model || !model.reasoning) {\n\t\tthinkingLevel = \"off\";\n\t}\n\n\t// Tools that are always active when available (created by factory, not in allTools singleton)\n\tconst alwaysActiveBuiltins = [\"skill\", \"tasks_update\", \"search\", \"suggest_next\"];\n\tconst defaultActiveToolNames: ToolName[] = [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t\t\"wait\",\n\t];\n\tconst initialActiveToolNames: string[] = options.tools\n\t\t? [...options.tools.map((t) => t.name).filter((n): n is ToolName => n in allTools), ...alwaysActiveBuiltins]\n\t\t: [...defaultActiveToolNames, ...alwaysActiveBuiltins];\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\tconst sessionRef: { current?: AgentSession } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getRetrySettings().maxDelayMs,\n\t\tonWarning: (code: string, message: string) => {\n\t\t\t// Wire provider-level warnings to the session for user/agent visibility\n\t\t\tconst informational =\n\t\t\t\tcode === \"sse_parse_error\" || code === \"ws_parse_error\" || code === \"json_parse_total_failure\";\n\t\t\tsessionRef.current?.warnInSession(message, { informational });\n\t\t},\n\t\tgetApiKey: async (provider) => {\n\t\t\t// Use the provider argument from the in-flight request;\n\t\t\t// agent.state.model may already be switched mid-turn.\n\t\t\tconst resolvedProvider = provider || agent.state.model?.provider;\n\t\t\tif (!resolvedProvider) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\t\t\tconst key = await modelRegistry.getApiKeyForProvider(resolvedProvider);\n\t\t\t// Surface any config value resolution warnings (e.g. failed !command API keys)\n\t\t\tif (configValueWarnings.length > 0) {\n\t\t\t\tconst warnings = configValueWarnings.splice(0);\n\t\t\t\tfor (const w of warnings) {\n\t\t\t\t\tsessionRef.current?.warnInSession(w);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!key) {\n\t\t\t\tconst model = agent.state.model;\n\t\t\t\tconst isOAuth = model && modelRegistry.isUsingOAuth(model);\n\t\t\t\tif (isOAuth) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Authentication failed for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t\t`Run '/login ${resolvedProvider}' to re-authenticate.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key found for \"${resolvedProvider}\". ` +\n\t\t\t\t\t\t`Set an API key environment variable or run '/login ${resolvedProvider}'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn key;\n\t\t},\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.replaceMessages(existingSession.messages);\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\textensionRunnerRef,\n\t\tuiType: options.uiType,\n\t});\n\tsessionRef.current = session;\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\t// Surface any resource diagnostics from initial load\n\tsession.warnResourceDiagnostics(resourceLoader);\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,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,kFAAkF;IAClF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,2CAA2C;IAC3C,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,qFAAqF;IACrF,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B;AAyBD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,CAkB9E;AA2ED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAsLhF","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport type { GitRepoState } from \"./git-repo-state.js\";\nimport { getMemoryInstructions } from \"./memory-prompt.js\";\nimport type { MemoryIndexes } from \"./resource-loader.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** UI type the agent is communicating through (e.g. \"tui\", \"telegram\", \"rpc\"). */\n\tuiType?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Memory indexes (global and project). */\n\tmemoryIndexes?: MemoryIndexes;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** Git repo state snapshot (branch, dirty count, recent commits, tags, open PRs). */\n\tgitRepoState?: GitRepoState;\n}\n\nfunction formatMemoryScope(sources: readonly import(\"./resource-loader.js\").MemorySource[], heading: string): string {\n\tif (sources.length === 0) return \"\";\n\n\tconst drebSources = sources.filter((s) => s.source === \"dreb\");\n\tconst claudeSources = sources.filter((s) => s.source === \"claude\");\n\n\tlet out = `\\n### ${heading}\\n`;\n\n\tfor (const source of drebSources) {\n\t\tout += `\\n#### dreb memory (${source.dir}/)\\n\\n${source.content}\\n`;\n\t}\n\n\tif (claudeSources.length > 0) {\n\t\tout += `\\n#### Claude Code memory (read-only)\\n`;\n\t\tout += `> **Note:** These memories were written by Claude Code and may reference Claude Code-specific features, tools, or conventions that don't exist in dreb. Treat the content as useful context, but verify any tool names or workflow references.\\n`;\n\t\tfor (const source of claudeSources) {\n\t\t\tout += `\\nSource: ${source.dir}/\\n\\n${source.content}\\n`;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * Format a dream last-run ISO timestamp as a human-readable relative age.\n * Returns \"Never\" if timestamp is null.\n * Uses hours for <24h, days otherwise.\n * @param isoTimestamp ISO timestamp string or null\n * @param now Reference date for computing age (default: current time)\n */\nexport function formatDreamAge(isoTimestamp: string | null, now?: Date): string {\n\tif (!isoTimestamp) return \"Never\";\n\n\tconst then = new Date(isoTimestamp);\n\tif (Number.isNaN(then.getTime())) return \"Never\";\n\n\tconst reference = now ?? new Date();\n\tconst diffMs = reference.getTime() - then.getTime();\n\n\t// Future or zero — treat as just now\n\tif (diffMs <= 0) return \"just now\";\n\n\tconst diffHours = Math.floor(diffMs / (1000 * 60 * 60));\n\tif (diffHours < 1) return \"less than an hour ago\";\n\tif (diffHours < 24) return `${diffHours} ${diffHours === 1 ? \"hour\" : \"hours\"} ago`;\n\n\tconst diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));\n\treturn `${diffDays} ${diffDays === 1 ? \"day\" : \"days\"} ago`;\n}\n\nfunction buildMemorySection(memoryIndexes?: MemoryIndexes): string {\n\tif (!memoryIndexes) return \"\";\n\n\t// Always include memory instructions so the agent knows the convention\n\tlet section = `\\n\\n${getMemoryInstructions({ globalMemoryDir: memoryIndexes.globalMemoryDir, projectMemoryDir: memoryIndexes.projectMemoryDir })}`;\n\n\tconst { global: globalSources, project: projectSources } = memoryIndexes;\n\n\t// Append dream last-run age indicator\n\tconst dreamAge = formatDreamAge(memoryIndexes.dreamLastRun);\n\tif (dreamAge === \"Never\") {\n\t\tsection += \"\\n\\nMemory last consolidated: Never\";\n\t} else {\n\t\tconst dateStr = memoryIndexes.dreamLastRun!.slice(0, 10);\n\t\tsection += `\\n\\nMemory last consolidated: ${dateStr} (${dreamAge})`;\n\t}\n\n\t// Append the actual memory indexes if any exist\n\tif (globalSources.length > 0 || projectSources.length > 0) {\n\t\tsection += \"\\n\\n## Current Memory Indexes\\n\";\n\t\tsection += formatMemoryScope(globalSources, \"Global Memory\");\n\t\tsection += formatMemoryScope(projectSources, \"Project Memory\");\n\t}\n\n\treturn section;\n}\n\n/** UI type descriptions for system prompt context */\nconst UI_DESCRIPTIONS: Record<string, string> = {\n\ttui: \"Terminal UI (interactive terminal with rich rendering)\",\n\ttelegram:\n\t\t\"Telegram (mobile messaging app — the user is on their phone so messages may be shorter or have typos, but this doesn't reflect less thought or intent. The user sees tool names and arguments but not tool output/results, so summarize key findings or changes when relevant)\",\n\trpc: \"RPC (programmatic interface — another application is consuming your output)\",\n\tcli: \"CLI (non-interactive command line — output will be printed and the process exits)\",\n\tagent: \"Subagent (running as a child agent — focus on the task, report results concisely)\",\n};\n\n/** Format the UI context section for the system prompt */\nfunction formatUiSection(uiType: string): string {\n\tconst description = UI_DESCRIPTIONS[uiType] || uiType;\n\treturn `\\nUI: ${description}`;\n}\n\n/** Format the git repo state section for the system prompt */\nfunction formatGitStateSection(state: GitRepoState): string {\n\tlet section = \"\\n\\n## Project state (true at session start only)\\n\\n\";\n\tsection += `- Branch: \\`${state.branch}\\`\\n`;\n\tsection += `- Status: ${state.dirtyCount === 0 ? \"clean\" : `${state.dirtyCount} uncommitted ${state.dirtyCount === 1 ? \"change\" : \"changes\"}`}\\n`;\n\n\tif (state.recentCommits.length > 0) {\n\t\tsection += \"- Recent commits:\\n\";\n\t\tfor (const commit of state.recentCommits) {\n\t\t\tsection += ` - \\`${commit.hash} — ${commit.subject}\\`\\n`;\n\t\t}\n\t}\n\n\tif (state.recentTags.length > 0) {\n\t\tsection += \"- Recent releases:\\n\";\n\t\tfor (const tag of state.recentTags) {\n\t\t\tsection += ` - \\`${tag.name}\\` (${tag.date})\\n`;\n\t\t}\n\t}\n\n\tif (state.openPRs.length > 0) {\n\t\tsection += \"- Open PRs on this branch:\\n\";\n\t\tfor (const pr of state.openPRs) {\n\t\t\tsection += ` - PR ${pr.number} — ${pr.title} (${pr.url})\\n`;\n\t\t}\n\t}\n\n\treturn section;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst date = new Date().toISOString().slice(0, 10);\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (when skill or read tool is available)\n\t\tconst customPromptHasSkillAccess =\n\t\t\t!selectedTools || selectedTools.includes(\"skill\") || selectedTools.includes(\"read\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append memory indexes\n\t\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t\t// Append git repo state\n\t\tif (options.gitRepoState) {\n\t\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\t\tif (options.uiType) {\n\t\t\tprompt += formatUiSection(options.uiType);\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasSearch = tools.includes(\"search\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\tif (hasSearch) {\n\t\t\taddGuideline(\n\t\t\t\t\"Start with `search` to explore and understand the codebase. Use grep/find/ls for exact text matches and specific file lookups. Prefer all of these over bash.\",\n\t\t\t);\n\t\t} else {\n\t\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t\t}\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside dreb, 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\nDreb documentation (read only when the user asks about dreb itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: 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), dreb packages (docs/packages.md)\n- When working on dreb topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read dreb .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (when skill or read tool is available)\n\tconst hasSkillAccess = hasRead || tools.includes(\"skill\");\n\tif (hasSkillAccess && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append memory indexes\n\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t// Append git repo state\n\tif (options.gitRepoState) {\n\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\tif (options.uiType) {\n\t\tprompt += formatUiSection(options.uiType);\n\t}\n\n\treturn prompt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,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,kFAAkF;IAClF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,2CAA2C;IAC3C,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,qFAAqF;IACrF,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B;AAyBD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,CAkB9E;AA2ED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAuLhF","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport type { GitRepoState } from \"./git-repo-state.js\";\nimport { getMemoryInstructions } from \"./memory-prompt.js\";\nimport type { MemoryIndexes } from \"./resource-loader.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** UI type the agent is communicating through (e.g. \"tui\", \"telegram\", \"rpc\"). */\n\tuiType?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Memory indexes (global and project). */\n\tmemoryIndexes?: MemoryIndexes;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** Git repo state snapshot (branch, dirty count, recent commits, tags, open PRs). */\n\tgitRepoState?: GitRepoState;\n}\n\nfunction formatMemoryScope(sources: readonly import(\"./resource-loader.js\").MemorySource[], heading: string): string {\n\tif (sources.length === 0) return \"\";\n\n\tconst drebSources = sources.filter((s) => s.source === \"dreb\");\n\tconst claudeSources = sources.filter((s) => s.source === \"claude\");\n\n\tlet out = `\\n### ${heading}\\n`;\n\n\tfor (const source of drebSources) {\n\t\tout += `\\n#### dreb memory (${source.dir}/)\\n\\n${source.content}\\n`;\n\t}\n\n\tif (claudeSources.length > 0) {\n\t\tout += `\\n#### Claude Code memory (read-only)\\n`;\n\t\tout += `> **Note:** These memories were written by Claude Code and may reference Claude Code-specific features, tools, or conventions that don't exist in dreb. Treat the content as useful context, but verify any tool names or workflow references.\\n`;\n\t\tfor (const source of claudeSources) {\n\t\t\tout += `\\nSource: ${source.dir}/\\n\\n${source.content}\\n`;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * Format a dream last-run ISO timestamp as a human-readable relative age.\n * Returns \"Never\" if timestamp is null.\n * Uses hours for <24h, days otherwise.\n * @param isoTimestamp ISO timestamp string or null\n * @param now Reference date for computing age (default: current time)\n */\nexport function formatDreamAge(isoTimestamp: string | null, now?: Date): string {\n\tif (!isoTimestamp) return \"Never\";\n\n\tconst then = new Date(isoTimestamp);\n\tif (Number.isNaN(then.getTime())) return \"Never\";\n\n\tconst reference = now ?? new Date();\n\tconst diffMs = reference.getTime() - then.getTime();\n\n\t// Future or zero — treat as just now\n\tif (diffMs <= 0) return \"just now\";\n\n\tconst diffHours = Math.floor(diffMs / (1000 * 60 * 60));\n\tif (diffHours < 1) return \"less than an hour ago\";\n\tif (diffHours < 24) return `${diffHours} ${diffHours === 1 ? \"hour\" : \"hours\"} ago`;\n\n\tconst diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));\n\treturn `${diffDays} ${diffDays === 1 ? \"day\" : \"days\"} ago`;\n}\n\nfunction buildMemorySection(memoryIndexes?: MemoryIndexes): string {\n\tif (!memoryIndexes) return \"\";\n\n\t// Always include memory instructions so the agent knows the convention\n\tlet section = `\\n\\n${getMemoryInstructions({ globalMemoryDir: memoryIndexes.globalMemoryDir, projectMemoryDir: memoryIndexes.projectMemoryDir })}`;\n\n\tconst { global: globalSources, project: projectSources } = memoryIndexes;\n\n\t// Append dream last-run age indicator\n\tconst dreamAge = formatDreamAge(memoryIndexes.dreamLastRun);\n\tif (dreamAge === \"Never\") {\n\t\tsection += \"\\n\\nMemory last consolidated: Never\";\n\t} else {\n\t\tconst dateStr = memoryIndexes.dreamLastRun!.slice(0, 10);\n\t\tsection += `\\n\\nMemory last consolidated: ${dateStr} (${dreamAge})`;\n\t}\n\n\t// Append the actual memory indexes if any exist\n\tif (globalSources.length > 0 || projectSources.length > 0) {\n\t\tsection += \"\\n\\n## Current Memory Indexes\\n\";\n\t\tsection += formatMemoryScope(globalSources, \"Global Memory\");\n\t\tsection += formatMemoryScope(projectSources, \"Project Memory\");\n\t}\n\n\treturn section;\n}\n\n/** UI type descriptions for system prompt context */\nconst UI_DESCRIPTIONS: Record<string, string> = {\n\ttui: \"Terminal UI (interactive terminal with rich rendering)\",\n\ttelegram:\n\t\t\"Telegram (mobile messaging app — the user is on their phone so messages may be shorter or have typos, but this doesn't reflect less thought or intent. The user sees tool names and arguments but not tool output/results, so summarize key findings or changes when relevant)\",\n\trpc: \"RPC (programmatic interface — another application is consuming your output)\",\n\tcli: \"CLI (non-interactive command line — output will be printed and the process exits)\",\n\tagent: \"Subagent (running as a child agent — focus on the task, report results concisely)\",\n};\n\n/** Format the UI context section for the system prompt */\nfunction formatUiSection(uiType: string): string {\n\tconst description = UI_DESCRIPTIONS[uiType] || uiType;\n\treturn `\\nUI: ${description}`;\n}\n\n/** Format the git repo state section for the system prompt */\nfunction formatGitStateSection(state: GitRepoState): string {\n\tlet section = \"\\n\\n## Project state (true at session start only)\\n\\n\";\n\tsection += `- Branch: \\`${state.branch}\\`\\n`;\n\tsection += `- Status: ${state.dirtyCount === 0 ? \"clean\" : `${state.dirtyCount} uncommitted ${state.dirtyCount === 1 ? \"change\" : \"changes\"}`}\\n`;\n\n\tif (state.recentCommits.length > 0) {\n\t\tsection += \"- Recent commits:\\n\";\n\t\tfor (const commit of state.recentCommits) {\n\t\t\tsection += ` - \\`${commit.hash} — ${commit.subject}\\`\\n`;\n\t\t}\n\t}\n\n\tif (state.recentTags.length > 0) {\n\t\tsection += \"- Recent releases:\\n\";\n\t\tfor (const tag of state.recentTags) {\n\t\t\tsection += ` - \\`${tag.name}\\` (${tag.date})\\n`;\n\t\t}\n\t}\n\n\tif (state.openPRs.length > 0) {\n\t\tsection += \"- Open PRs on this branch:\\n\";\n\t\tfor (const pr of state.openPRs) {\n\t\t\tsection += ` - PR ${pr.number} — ${pr.title} (${pr.url})\\n`;\n\t\t}\n\t}\n\n\treturn section;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst date = new Date().toISOString().slice(0, 10);\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (when skill or read tool is available)\n\t\tconst customPromptHasSkillAccess =\n\t\t\t!selectedTools || selectedTools.includes(\"skill\") || selectedTools.includes(\"read\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append memory indexes\n\t\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t\t// Append git repo state\n\t\tif (options.gitRepoState) {\n\t\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\t\tif (options.uiType) {\n\t\t\tprompt += formatUiSection(options.uiType);\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t\t\"wait\",\n\t];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasSearch = tools.includes(\"search\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\tif (hasSearch) {\n\t\t\taddGuideline(\n\t\t\t\t\"Start with `search` to explore and understand the codebase. Use grep/find/ls for exact text matches and specific file lookups. Prefer all of these over bash.\",\n\t\t\t);\n\t\t} else {\n\t\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t\t}\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside dreb, 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\nDreb documentation (read only when the user asks about dreb itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: 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), dreb packages (docs/packages.md)\n- When working on dreb topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read dreb .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (when skill or read tool is available)\n\tconst hasSkillAccess = hasRead || tools.includes(\"skill\");\n\tif (hasSkillAccess && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append memory indexes\n\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t// Append git repo state\n\tif (options.gitRepoState) {\n\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\tif (options.uiType) {\n\t\tprompt += formatUiSection(options.uiType);\n\t}\n\n\treturn prompt;\n}\n"]}
|
|
@@ -167,6 +167,7 @@ export function buildSystemPrompt(options = {}) {
|
|
|
167
167
|
"web_search",
|
|
168
168
|
"web_fetch",
|
|
169
169
|
"subagent",
|
|
170
|
+
"wait",
|
|
170
171
|
];
|
|
171
172
|
const visibleTools = tools.filter((name) => !!toolSnippets?.[name]);
|
|
172
173
|
const toolsList = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;G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;IACtD,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACpB,MAAM,IAAI,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport type { GitRepoState } from \"./git-repo-state.js\";\nimport { getMemoryInstructions } from \"./memory-prompt.js\";\nimport type { MemoryIndexes } from \"./resource-loader.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** UI type the agent is communicating through (e.g. \"tui\", \"telegram\", \"rpc\"). */\n\tuiType?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Memory indexes (global and project). */\n\tmemoryIndexes?: MemoryIndexes;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** Git repo state snapshot (branch, dirty count, recent commits, tags, open PRs). */\n\tgitRepoState?: GitRepoState;\n}\n\nfunction formatMemoryScope(sources: readonly import(\"./resource-loader.js\").MemorySource[], heading: string): string {\n\tif (sources.length === 0) return \"\";\n\n\tconst drebSources = sources.filter((s) => s.source === \"dreb\");\n\tconst claudeSources = sources.filter((s) => s.source === \"claude\");\n\n\tlet out = `\\n### ${heading}\\n`;\n\n\tfor (const source of drebSources) {\n\t\tout += `\\n#### dreb memory (${source.dir}/)\\n\\n${source.content}\\n`;\n\t}\n\n\tif (claudeSources.length > 0) {\n\t\tout += `\\n#### Claude Code memory (read-only)\\n`;\n\t\tout += `> **Note:** These memories were written by Claude Code and may reference Claude Code-specific features, tools, or conventions that don't exist in dreb. Treat the content as useful context, but verify any tool names or workflow references.\\n`;\n\t\tfor (const source of claudeSources) {\n\t\t\tout += `\\nSource: ${source.dir}/\\n\\n${source.content}\\n`;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * Format a dream last-run ISO timestamp as a human-readable relative age.\n * Returns \"Never\" if timestamp is null.\n * Uses hours for <24h, days otherwise.\n * @param isoTimestamp ISO timestamp string or null\n * @param now Reference date for computing age (default: current time)\n */\nexport function formatDreamAge(isoTimestamp: string | null, now?: Date): string {\n\tif (!isoTimestamp) return \"Never\";\n\n\tconst then = new Date(isoTimestamp);\n\tif (Number.isNaN(then.getTime())) return \"Never\";\n\n\tconst reference = now ?? new Date();\n\tconst diffMs = reference.getTime() - then.getTime();\n\n\t// Future or zero — treat as just now\n\tif (diffMs <= 0) return \"just now\";\n\n\tconst diffHours = Math.floor(diffMs / (1000 * 60 * 60));\n\tif (diffHours < 1) return \"less than an hour ago\";\n\tif (diffHours < 24) return `${diffHours} ${diffHours === 1 ? \"hour\" : \"hours\"} ago`;\n\n\tconst diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));\n\treturn `${diffDays} ${diffDays === 1 ? \"day\" : \"days\"} ago`;\n}\n\nfunction buildMemorySection(memoryIndexes?: MemoryIndexes): string {\n\tif (!memoryIndexes) return \"\";\n\n\t// Always include memory instructions so the agent knows the convention\n\tlet section = `\\n\\n${getMemoryInstructions({ globalMemoryDir: memoryIndexes.globalMemoryDir, projectMemoryDir: memoryIndexes.projectMemoryDir })}`;\n\n\tconst { global: globalSources, project: projectSources } = memoryIndexes;\n\n\t// Append dream last-run age indicator\n\tconst dreamAge = formatDreamAge(memoryIndexes.dreamLastRun);\n\tif (dreamAge === \"Never\") {\n\t\tsection += \"\\n\\nMemory last consolidated: Never\";\n\t} else {\n\t\tconst dateStr = memoryIndexes.dreamLastRun!.slice(0, 10);\n\t\tsection += `\\n\\nMemory last consolidated: ${dateStr} (${dreamAge})`;\n\t}\n\n\t// Append the actual memory indexes if any exist\n\tif (globalSources.length > 0 || projectSources.length > 0) {\n\t\tsection += \"\\n\\n## Current Memory Indexes\\n\";\n\t\tsection += formatMemoryScope(globalSources, \"Global Memory\");\n\t\tsection += formatMemoryScope(projectSources, \"Project Memory\");\n\t}\n\n\treturn section;\n}\n\n/** UI type descriptions for system prompt context */\nconst UI_DESCRIPTIONS: Record<string, string> = {\n\ttui: \"Terminal UI (interactive terminal with rich rendering)\",\n\ttelegram:\n\t\t\"Telegram (mobile messaging app — the user is on their phone so messages may be shorter or have typos, but this doesn't reflect less thought or intent. The user sees tool names and arguments but not tool output/results, so summarize key findings or changes when relevant)\",\n\trpc: \"RPC (programmatic interface — another application is consuming your output)\",\n\tcli: \"CLI (non-interactive command line — output will be printed and the process exits)\",\n\tagent: \"Subagent (running as a child agent — focus on the task, report results concisely)\",\n};\n\n/** Format the UI context section for the system prompt */\nfunction formatUiSection(uiType: string): string {\n\tconst description = UI_DESCRIPTIONS[uiType] || uiType;\n\treturn `\\nUI: ${description}`;\n}\n\n/** Format the git repo state section for the system prompt */\nfunction formatGitStateSection(state: GitRepoState): string {\n\tlet section = \"\\n\\n## Project state (true at session start only)\\n\\n\";\n\tsection += `- Branch: \\`${state.branch}\\`\\n`;\n\tsection += `- Status: ${state.dirtyCount === 0 ? \"clean\" : `${state.dirtyCount} uncommitted ${state.dirtyCount === 1 ? \"change\" : \"changes\"}`}\\n`;\n\n\tif (state.recentCommits.length > 0) {\n\t\tsection += \"- Recent commits:\\n\";\n\t\tfor (const commit of state.recentCommits) {\n\t\t\tsection += ` - \\`${commit.hash} — ${commit.subject}\\`\\n`;\n\t\t}\n\t}\n\n\tif (state.recentTags.length > 0) {\n\t\tsection += \"- Recent releases:\\n\";\n\t\tfor (const tag of state.recentTags) {\n\t\t\tsection += ` - \\`${tag.name}\\` (${tag.date})\\n`;\n\t\t}\n\t}\n\n\tif (state.openPRs.length > 0) {\n\t\tsection += \"- Open PRs on this branch:\\n\";\n\t\tfor (const pr of state.openPRs) {\n\t\t\tsection += ` - PR ${pr.number} — ${pr.title} (${pr.url})\\n`;\n\t\t}\n\t}\n\n\treturn section;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst date = new Date().toISOString().slice(0, 10);\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (when skill or read tool is available)\n\t\tconst customPromptHasSkillAccess =\n\t\t\t!selectedTools || selectedTools.includes(\"skill\") || selectedTools.includes(\"read\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append memory indexes\n\t\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t\t// Append git repo state\n\t\tif (options.gitRepoState) {\n\t\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\t\tif (options.uiType) {\n\t\t\tprompt += formatUiSection(options.uiType);\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasSearch = tools.includes(\"search\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\tif (hasSearch) {\n\t\t\taddGuideline(\n\t\t\t\t\"Start with `search` to explore and understand the codebase. Use grep/find/ls for exact text matches and specific file lookups. Prefer all of these over bash.\",\n\t\t\t);\n\t\t} else {\n\t\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t\t}\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside dreb, 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\nDreb documentation (read only when the user asks about dreb itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: 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), dreb packages (docs/packages.md)\n- When working on dreb topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read dreb .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (when skill or read tool is available)\n\tconst hasSkillAccess = hasRead || tools.includes(\"skill\");\n\tif (hasSkillAccess && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append memory indexes\n\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t// Append git repo state\n\tif (options.gitRepoState) {\n\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\tif (options.uiType) {\n\t\tprompt += formatUiSection(options.uiType);\n\t}\n\n\treturn 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;AAE3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AA2BhE,SAAS,iBAAiB,CAAC,OAA+D,EAAE,OAAe,EAAU;IACpH,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAEpC,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC;IAC/D,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC;IAEnE,IAAI,GAAG,GAAG,SAAS,OAAO,IAAI,CAAC;IAE/B,KAAK,MAAM,MAAM,IAAI,WAAW,EAAE,CAAC;QAClC,GAAG,IAAI,uBAAuB,MAAM,CAAC,GAAG,SAAS,MAAM,CAAC,OAAO,IAAI,CAAC;IACrE,CAAC;IAED,IAAI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AAO,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC1D,IAAI,cAAc,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,wBAAwB;IACxB,MAAM,IAAI,kBAAkB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IAEpD,wBAAwB;IACxB,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;QAC1B,MAAM,IAAI,qBAAqB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IACvD,CAAC;IAED,sCAAsC;IACtC,MAAM,IAAI,mBAAmB,IAAI,EAAE,CAAC;IACpC,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IACtD,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACpB,MAAM,IAAI,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport type { GitRepoState } from \"./git-repo-state.js\";\nimport { getMemoryInstructions } from \"./memory-prompt.js\";\nimport type { MemoryIndexes } from \"./resource-loader.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** UI type the agent is communicating through (e.g. \"tui\", \"telegram\", \"rpc\"). */\n\tuiType?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Memory indexes (global and project). */\n\tmemoryIndexes?: MemoryIndexes;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** Git repo state snapshot (branch, dirty count, recent commits, tags, open PRs). */\n\tgitRepoState?: GitRepoState;\n}\n\nfunction formatMemoryScope(sources: readonly import(\"./resource-loader.js\").MemorySource[], heading: string): string {\n\tif (sources.length === 0) return \"\";\n\n\tconst drebSources = sources.filter((s) => s.source === \"dreb\");\n\tconst claudeSources = sources.filter((s) => s.source === \"claude\");\n\n\tlet out = `\\n### ${heading}\\n`;\n\n\tfor (const source of drebSources) {\n\t\tout += `\\n#### dreb memory (${source.dir}/)\\n\\n${source.content}\\n`;\n\t}\n\n\tif (claudeSources.length > 0) {\n\t\tout += `\\n#### Claude Code memory (read-only)\\n`;\n\t\tout += `> **Note:** These memories were written by Claude Code and may reference Claude Code-specific features, tools, or conventions that don't exist in dreb. Treat the content as useful context, but verify any tool names or workflow references.\\n`;\n\t\tfor (const source of claudeSources) {\n\t\t\tout += `\\nSource: ${source.dir}/\\n\\n${source.content}\\n`;\n\t\t}\n\t}\n\n\treturn out;\n}\n\n/**\n * Format a dream last-run ISO timestamp as a human-readable relative age.\n * Returns \"Never\" if timestamp is null.\n * Uses hours for <24h, days otherwise.\n * @param isoTimestamp ISO timestamp string or null\n * @param now Reference date for computing age (default: current time)\n */\nexport function formatDreamAge(isoTimestamp: string | null, now?: Date): string {\n\tif (!isoTimestamp) return \"Never\";\n\n\tconst then = new Date(isoTimestamp);\n\tif (Number.isNaN(then.getTime())) return \"Never\";\n\n\tconst reference = now ?? new Date();\n\tconst diffMs = reference.getTime() - then.getTime();\n\n\t// Future or zero — treat as just now\n\tif (diffMs <= 0) return \"just now\";\n\n\tconst diffHours = Math.floor(diffMs / (1000 * 60 * 60));\n\tif (diffHours < 1) return \"less than an hour ago\";\n\tif (diffHours < 24) return `${diffHours} ${diffHours === 1 ? \"hour\" : \"hours\"} ago`;\n\n\tconst diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));\n\treturn `${diffDays} ${diffDays === 1 ? \"day\" : \"days\"} ago`;\n}\n\nfunction buildMemorySection(memoryIndexes?: MemoryIndexes): string {\n\tif (!memoryIndexes) return \"\";\n\n\t// Always include memory instructions so the agent knows the convention\n\tlet section = `\\n\\n${getMemoryInstructions({ globalMemoryDir: memoryIndexes.globalMemoryDir, projectMemoryDir: memoryIndexes.projectMemoryDir })}`;\n\n\tconst { global: globalSources, project: projectSources } = memoryIndexes;\n\n\t// Append dream last-run age indicator\n\tconst dreamAge = formatDreamAge(memoryIndexes.dreamLastRun);\n\tif (dreamAge === \"Never\") {\n\t\tsection += \"\\n\\nMemory last consolidated: Never\";\n\t} else {\n\t\tconst dateStr = memoryIndexes.dreamLastRun!.slice(0, 10);\n\t\tsection += `\\n\\nMemory last consolidated: ${dateStr} (${dreamAge})`;\n\t}\n\n\t// Append the actual memory indexes if any exist\n\tif (globalSources.length > 0 || projectSources.length > 0) {\n\t\tsection += \"\\n\\n## Current Memory Indexes\\n\";\n\t\tsection += formatMemoryScope(globalSources, \"Global Memory\");\n\t\tsection += formatMemoryScope(projectSources, \"Project Memory\");\n\t}\n\n\treturn section;\n}\n\n/** UI type descriptions for system prompt context */\nconst UI_DESCRIPTIONS: Record<string, string> = {\n\ttui: \"Terminal UI (interactive terminal with rich rendering)\",\n\ttelegram:\n\t\t\"Telegram (mobile messaging app — the user is on their phone so messages may be shorter or have typos, but this doesn't reflect less thought or intent. The user sees tool names and arguments but not tool output/results, so summarize key findings or changes when relevant)\",\n\trpc: \"RPC (programmatic interface — another application is consuming your output)\",\n\tcli: \"CLI (non-interactive command line — output will be printed and the process exits)\",\n\tagent: \"Subagent (running as a child agent — focus on the task, report results concisely)\",\n};\n\n/** Format the UI context section for the system prompt */\nfunction formatUiSection(uiType: string): string {\n\tconst description = UI_DESCRIPTIONS[uiType] || uiType;\n\treturn `\\nUI: ${description}`;\n}\n\n/** Format the git repo state section for the system prompt */\nfunction formatGitStateSection(state: GitRepoState): string {\n\tlet section = \"\\n\\n## Project state (true at session start only)\\n\\n\";\n\tsection += `- Branch: \\`${state.branch}\\`\\n`;\n\tsection += `- Status: ${state.dirtyCount === 0 ? \"clean\" : `${state.dirtyCount} uncommitted ${state.dirtyCount === 1 ? \"change\" : \"changes\"}`}\\n`;\n\n\tif (state.recentCommits.length > 0) {\n\t\tsection += \"- Recent commits:\\n\";\n\t\tfor (const commit of state.recentCommits) {\n\t\t\tsection += ` - \\`${commit.hash} — ${commit.subject}\\`\\n`;\n\t\t}\n\t}\n\n\tif (state.recentTags.length > 0) {\n\t\tsection += \"- Recent releases:\\n\";\n\t\tfor (const tag of state.recentTags) {\n\t\t\tsection += ` - \\`${tag.name}\\` (${tag.date})\\n`;\n\t\t}\n\t}\n\n\tif (state.openPRs.length > 0) {\n\t\tsection += \"- Open PRs on this branch:\\n\";\n\t\tfor (const pr of state.openPRs) {\n\t\t\tsection += ` - PR ${pr.number} — ${pr.title} (${pr.url})\\n`;\n\t\t}\n\t}\n\n\treturn section;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd ?? process.cwd();\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst date = new Date().toISOString().slice(0, 10);\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (when skill or read tool is available)\n\t\tconst customPromptHasSkillAccess =\n\t\t\t!selectedTools || selectedTools.includes(\"skill\") || selectedTools.includes(\"read\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append memory indexes\n\t\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t\t// Append git repo state\n\t\tif (options.gitRepoState) {\n\t\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\t\tif (options.uiType) {\n\t\t\tprompt += formatUiSection(options.uiType);\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"web_search\",\n\t\t\"web_fetch\",\n\t\t\"subagent\",\n\t\t\"wait\",\n\t];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasSearch = tools.includes(\"search\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\tif (hasSearch) {\n\t\t\taddGuideline(\n\t\t\t\t\"Start with `search` to explore and understand the codebase. Use grep/find/ls for exact text matches and specific file lookups. Prefer all of these over bash.\",\n\t\t\t);\n\t\t} else {\n\t\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t\t}\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside dreb, 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\nDreb documentation (read only when the user asks about dreb itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: 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), dreb packages (docs/packages.md)\n- When working on dreb topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read dreb .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (when skill or read tool is available)\n\tconst hasSkillAccess = hasRead || tools.includes(\"skill\");\n\tif (hasSkillAccess && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append memory indexes\n\tprompt += buildMemorySection(options.memoryIndexes);\n\n\t// Append git repo state\n\tif (options.gitRepoState) {\n\t\tprompt += formatGitStateSection(options.gitRepoState);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\tif (options.uiType) {\n\t\tprompt += formatUiSection(options.uiType);\n\t}\n\n\treturn prompt;\n}\n"]}
|
|
@@ -7,11 +7,12 @@ export { createLsTool, createLsToolDefinition, type LsOperations, type LsToolDet
|
|
|
7
7
|
export { createReadTool, createReadToolDefinition, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, readTool, readToolDefinition, } from "./read.js";
|
|
8
8
|
export { createSearchTool, createSearchToolDefinition, isSearchAvailable, type SearchToolDetails, type SearchToolInput, } from "./search.js";
|
|
9
9
|
export { createSkillTool, createSkillToolDefinition, type SkillToolDetails, type SkillToolInput, type SkillToolOptions, } from "./skill.js";
|
|
10
|
-
export { abortBackgroundAgents, type BackgroundAgentInfo, createSubagentTool, createSubagentToolDefinition, getBackgroundAgents, getRunningBackgroundAgents, pruneBackgroundAgents, type SubagentResult, type SubagentToolDetails, type SubagentToolInput, type SubagentToolOptions, subagentTool, subagentToolDefinition, } from "./subagent.js";
|
|
10
|
+
export { abortBackgroundAgents, type BackgroundAgentInfo, createSubagentTool, createSubagentToolDefinition, filterSubagentTools, getBackgroundAgents, getRunningBackgroundAgents, pruneBackgroundAgents, type SubagentResult, type SubagentToolDetails, type SubagentToolInput, type SubagentToolOptions, subagentTool, subagentToolDefinition, } from "./subagent.js";
|
|
11
11
|
export { createSuggestNextToolDefinition, type SuggestNextCallback, type SuggestNextDetails, type SuggestNextInput, } from "./suggest-next.js";
|
|
12
12
|
export { createTasksToolDefinition, type SessionTask, type TaskStatus, type TasksToolDetails, type TasksToolInput, type TasksUpdateCallback, } from "./tasks.js";
|
|
13
13
|
export { createTmpReadToolDefinition } from "./tmp-read.js";
|
|
14
14
|
export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, } from "./truncate.js";
|
|
15
|
+
export { createWaitToolDefinition, formatWaitCall, formatWaitResult, type WaitAgentInfo, type WaitToolDetails, type WaitToolInput, type WaitToolOptions, waitToolDefinition, } from "./wait.js";
|
|
15
16
|
export { createWebFetchTool, createWebFetchToolDefinition, createWebSearchTool, createWebSearchToolDefinition, type WebFetchToolDetails, type WebFetchToolInput, type WebSearchConfig, type WebSearchToolDetails, type WebSearchToolInput, webFetchTool, webFetchToolDefinition, webSearchTool, webSearchToolDefinition, } from "./web.js";
|
|
16
17
|
export { createWriteTool, createWriteToolDefinition, type WriteOperations, type WriteToolInput, type WriteToolOptions, writeTool, writeToolDefinition, } from "./write.js";
|
|
17
18
|
import type { AgentTool } from "@dreb/agent-core";
|
|
@@ -88,6 +89,7 @@ export declare const allTools: {
|
|
|
88
89
|
background: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
|
|
89
90
|
}>, any>;
|
|
90
91
|
tmp_read: AgentTool<any, any>;
|
|
92
|
+
wait: AgentTool<any, import("./wait.js").WaitToolDetails | undefined>;
|
|
91
93
|
};
|
|
92
94
|
export declare const allToolDefinitions: {
|
|
93
95
|
read: ToolDefinition<import("@sinclair/typebox").TObject<{
|
|
@@ -158,6 +160,9 @@ export declare const allToolDefinitions: {
|
|
|
158
160
|
background: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TBoolean>;
|
|
159
161
|
}>, import("./subagent.js").SubagentToolDetails | undefined, any>;
|
|
160
162
|
tmp_read: ToolDefinition<any, any, any>;
|
|
163
|
+
wait: ToolDefinition<import("@sinclair/typebox").TObject<{
|
|
164
|
+
reason: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
165
|
+
}>, import("./wait.js").WaitToolDetails | undefined, any>;
|
|
161
166
|
};
|
|
162
167
|
export type ToolName = keyof typeof allTools;
|
|
163
168
|
export interface ToolsOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAAkB,EAClB,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAAkB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,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AAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,IAAI,EAAE,CAE/E;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,MAAM,CAAC,QAAQ,GAAG,OAAO,EAAE,IAAI,CAAC,CA2BpG","sourcesContent":["export {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tbashTool,\n\tbashToolDefinition,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.js\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\teditTool,\n\teditToolDefinition,\n} from \"./edit.js\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.js\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tfindTool,\n\tfindToolDefinition,\n} from \"./find.js\";\nexport {\n\tcreateGrepTool,\n\tcreateGrepToolDefinition,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n\tgrepTool,\n\tgrepToolDefinition,\n} from \"./grep.js\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\tlsTool,\n\tlsToolDefinition,\n} from \"./ls.js\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\treadTool,\n\treadToolDefinition,\n} from \"./read.js\";\nexport {\n\tcreateSearchTool,\n\tcreateSearchToolDefinition,\n\tisSearchAvailable,\n\ttype SearchToolDetails,\n\ttype SearchToolInput,\n} from \"./search.js\";\nexport {\n\tcreateSkillTool,\n\tcreateSkillToolDefinition,\n\ttype SkillToolDetails,\n\ttype SkillToolInput,\n\ttype SkillToolOptions,\n} from \"./skill.js\";\nexport {\n\tabortBackgroundAgents,\n\ttype BackgroundAgentInfo,\n\tcreateSubagentTool,\n\tcreateSubagentToolDefinition,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n\ttype SubagentResult,\n\ttype SubagentToolDetails,\n\ttype SubagentToolInput,\n\ttype SubagentToolOptions,\n\tsubagentTool,\n\tsubagentToolDefinition,\n} from \"./subagent.js\";\nexport {\n\tcreateSuggestNextToolDefinition,\n\ttype SuggestNextCallback,\n\ttype SuggestNextDetails,\n\ttype SuggestNextInput,\n} from \"./suggest-next.js\";\nexport {\n\tcreateTasksToolDefinition,\n\ttype SessionTask,\n\ttype TaskStatus,\n\ttype TasksToolDetails,\n\ttype TasksToolInput,\n\ttype TasksUpdateCallback,\n} from \"./tasks.js\";\nexport { createTmpReadToolDefinition } from \"./tmp-read.js\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.js\";\nexport {\n\tcreateWebFetchTool,\n\tcreateWebFetchToolDefinition,\n\tcreateWebSearchTool,\n\tcreateWebSearchToolDefinition,\n\ttype WebFetchToolDetails,\n\ttype WebFetchToolInput,\n\ttype WebSearchConfig,\n\ttype WebSearchToolDetails,\n\ttype WebSearchToolInput,\n\twebFetchTool,\n\twebFetchToolDefinition,\n\twebSearchTool,\n\twebSearchToolDefinition,\n} from \"./web.js\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twriteTool,\n\twriteToolDefinition,\n} from \"./write.js\";\n\nimport type { AgentTool } from \"@dreb/agent-core\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport {\n\ttype BashToolOptions,\n\tbashTool,\n\tbashToolDefinition,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n} from \"./bash.js\";\nimport { createEditTool, createEditToolDefinition, editTool, editToolDefinition } from \"./edit.js\";\nimport { createFindTool, createFindToolDefinition, findTool, findToolDefinition } from \"./find.js\";\nimport { createGrepTool, createGrepToolDefinition, grepTool, grepToolDefinition } from \"./grep.js\";\nimport { createLsTool, createLsToolDefinition, lsTool, lsToolDefinition } from \"./ls.js\";\nimport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadToolOptions,\n\treadTool,\n\treadToolDefinition,\n} from \"./read.js\";\nimport { createSearchTool, createSearchToolDefinition, isSearchAvailable } from \"./search.js\";\nimport { createSkillTool, createSkillToolDefinition, type SkillToolOptions } from \"./skill.js\";\nimport {\n\tcreateSubagentTool,\n\tcreateSubagentToolDefinition,\n\ttype SubagentToolOptions,\n\tsubagentTool,\n\tsubagentToolDefinition,\n} from \"./subagent.js\";\nimport { createSuggestNextToolDefinition, type SuggestNextCallback } from \"./suggest-next.js\";\nimport { createTasksToolDefinition, type TasksUpdateCallback } from \"./tasks.js\";\nimport { createTmpReadToolDefinition } from \"./tmp-read.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport {\n\tcreateWebFetchTool,\n\tcreateWebFetchToolDefinition,\n\tcreateWebSearchTool,\n\tcreateWebSearchToolDefinition,\n\twebFetchTool,\n\twebFetchToolDefinition,\n\twebSearchTool,\n\twebSearchToolDefinition,\n} from \"./web.js\";\nimport { createWriteTool, createWriteToolDefinition, writeTool, writeToolDefinition } from \"./write.js\";\n\nexport type Tool = AgentTool<any>;\nexport type ToolDef = ToolDefinition<any, any>;\n\nexport const codingTools: Tool[] = [readTool, bashTool, editTool, writeTool];\nexport const readOnlyTools: Tool[] = [readTool, grepTool, findTool, lsTool];\n\nconst tmpReadToolDefinition = createTmpReadToolDefinition();\nconst tmpReadTool = wrapToolDefinition(tmpReadToolDefinition);\n\nexport const allTools = {\n\tread: readTool,\n\tbash: bashTool,\n\tedit: editTool,\n\twrite: writeTool,\n\tgrep: grepTool,\n\tfind: findTool,\n\tls: lsTool,\n\tweb_search: webSearchTool,\n\tweb_fetch: webFetchTool,\n\tsubagent: subagentTool,\n\ttmp_read: tmpReadTool,\n};\n\nexport const allToolDefinitions = {\n\tread: readToolDefinition,\n\tbash: bashToolDefinition,\n\tedit: editToolDefinition,\n\twrite: writeToolDefinition,\n\tgrep: grepToolDefinition,\n\tfind: findToolDefinition,\n\tls: lsToolDefinition,\n\tweb_search: webSearchToolDefinition,\n\tweb_fetch: webFetchToolDefinition,\n\tsubagent: subagentToolDefinition,\n\ttmp_read: tmpReadToolDefinition,\n};\n\nexport type ToolName = keyof typeof allTools;\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\tsubagent?: SubagentToolOptions;\n\tskill?: SkillToolOptions;\n\ttasks?: { onUpdate: TasksUpdateCallback };\n\tsuggestNext?: { onSuggest: SuggestNextCallback };\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateBashToolDefinition(cwd, options?.bash),\n\t\tcreateEditToolDefinition(cwd),\n\t\tcreateWriteToolDefinition(cwd),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateGrepToolDefinition(cwd),\n\t\tcreateFindToolDefinition(cwd),\n\t\tcreateLsToolDefinition(cwd),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record<ToolName | \"skill\", ToolDef> {\n\tconst tools: Record<string, ToolDef> = {\n\t\tread: createReadToolDefinition(cwd, options?.read),\n\t\tbash: createBashToolDefinition(cwd, options?.bash),\n\t\tedit: createEditToolDefinition(cwd),\n\t\twrite: createWriteToolDefinition(cwd),\n\t\tgrep: createGrepToolDefinition(cwd),\n\t\tfind: createFindToolDefinition(cwd),\n\t\tls: createLsToolDefinition(cwd),\n\t\tweb_search: createWebSearchToolDefinition(cwd),\n\t\tweb_fetch: createWebFetchToolDefinition(cwd),\n\t\tsubagent: createSubagentToolDefinition(cwd, options?.subagent),\n\t\ttmp_read: createTmpReadToolDefinition(options?.read),\n\t};\n\tif (isSearchAvailable()) {\n\t\ttools.search = createSearchToolDefinition(cwd);\n\t}\n\tif (options?.skill) {\n\t\ttools.skill = createSkillToolDefinition(cwd, options.skill);\n\t}\n\tif (options?.tasks) {\n\t\ttools.tasks_update = createTasksToolDefinition(options.tasks.onUpdate);\n\t}\n\tif (options?.suggestNext) {\n\t\ttools.suggest_next = createSuggestNextToolDefinition(options.suggestNext.onSuggest);\n\t}\n\treturn tools as Record<ToolName | \"skill\", ToolDef>;\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateBashTool(cwd, options?.bash),\n\t\tcreateEditTool(cwd),\n\t\tcreateWriteTool(cwd),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [createReadTool(cwd, options?.read), createGrepTool(cwd), createFindTool(cwd), createLsTool(cwd)];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record<ToolName | \"skill\", Tool> {\n\tconst tools: Record<string, Tool> = {\n\t\tread: createReadTool(cwd, options?.read),\n\t\tbash: createBashTool(cwd, options?.bash),\n\t\tedit: createEditTool(cwd),\n\t\twrite: createWriteTool(cwd),\n\t\tgrep: createGrepTool(cwd),\n\t\tfind: createFindTool(cwd),\n\t\tls: createLsTool(cwd),\n\t\tweb_search: createWebSearchTool(cwd),\n\t\tweb_fetch: createWebFetchTool(cwd),\n\t\tsubagent: createSubagentTool(cwd, options?.subagent),\n\t\ttmp_read: wrapToolDefinition(createTmpReadToolDefinition(options?.read)),\n\t};\n\tif (isSearchAvailable()) {\n\t\ttools.search = createSearchTool(cwd);\n\t}\n\tif (options?.skill) {\n\t\ttools.skill = createSkillTool(cwd, options.skill);\n\t}\n\tif (options?.tasks) {\n\t\ttools.tasks_update = wrapToolDefinition(createTasksToolDefinition(options.tasks.onUpdate));\n\t}\n\tif (options?.suggestNext) {\n\t\ttools.suggest_next = wrapToolDefinition(createSuggestNextToolDefinition(options.suggestNext.onSuggest));\n\t}\n\treturn tools as Record<ToolName | \"skill\", Tool>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAAkB,EAClB,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAAkB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAAkB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,QAAQ,EACR,kBAA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AAG,IAAI,EAAE,CAE/E;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,MAAM,CAAC,QAAQ,GAAG,OAAO,EAAE,IAAI,CAAC,CA4BpG","sourcesContent":["export {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tbashTool,\n\tbashToolDefinition,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.js\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\teditTool,\n\teditToolDefinition,\n} from \"./edit.js\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.js\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tfindTool,\n\tfindToolDefinition,\n} from \"./find.js\";\nexport {\n\tcreateGrepTool,\n\tcreateGrepToolDefinition,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n\tgrepTool,\n\tgrepToolDefinition,\n} from \"./grep.js\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\tlsTool,\n\tlsToolDefinition,\n} from \"./ls.js\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\treadTool,\n\treadToolDefinition,\n} from \"./read.js\";\nexport {\n\tcreateSearchTool,\n\tcreateSearchToolDefinition,\n\tisSearchAvailable,\n\ttype SearchToolDetails,\n\ttype SearchToolInput,\n} from \"./search.js\";\nexport {\n\tcreateSkillTool,\n\tcreateSkillToolDefinition,\n\ttype SkillToolDetails,\n\ttype SkillToolInput,\n\ttype SkillToolOptions,\n} from \"./skill.js\";\nexport {\n\tabortBackgroundAgents,\n\ttype BackgroundAgentInfo,\n\tcreateSubagentTool,\n\tcreateSubagentToolDefinition,\n\tfilterSubagentTools,\n\tgetBackgroundAgents,\n\tgetRunningBackgroundAgents,\n\tpruneBackgroundAgents,\n\ttype SubagentResult,\n\ttype SubagentToolDetails,\n\ttype SubagentToolInput,\n\ttype SubagentToolOptions,\n\tsubagentTool,\n\tsubagentToolDefinition,\n} from \"./subagent.js\";\nexport {\n\tcreateSuggestNextToolDefinition,\n\ttype SuggestNextCallback,\n\ttype SuggestNextDetails,\n\ttype SuggestNextInput,\n} from \"./suggest-next.js\";\nexport {\n\tcreateTasksToolDefinition,\n\ttype SessionTask,\n\ttype TaskStatus,\n\ttype TasksToolDetails,\n\ttype TasksToolInput,\n\ttype TasksUpdateCallback,\n} from \"./tasks.js\";\nexport { createTmpReadToolDefinition } from \"./tmp-read.js\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.js\";\nexport {\n\tcreateWaitToolDefinition,\n\tformatWaitCall,\n\tformatWaitResult,\n\ttype WaitAgentInfo,\n\ttype WaitToolDetails,\n\ttype WaitToolInput,\n\ttype WaitToolOptions,\n\twaitToolDefinition,\n} from \"./wait.js\";\nexport {\n\tcreateWebFetchTool,\n\tcreateWebFetchToolDefinition,\n\tcreateWebSearchTool,\n\tcreateWebSearchToolDefinition,\n\ttype WebFetchToolDetails,\n\ttype WebFetchToolInput,\n\ttype WebSearchConfig,\n\ttype WebSearchToolDetails,\n\ttype WebSearchToolInput,\n\twebFetchTool,\n\twebFetchToolDefinition,\n\twebSearchTool,\n\twebSearchToolDefinition,\n} from \"./web.js\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twriteTool,\n\twriteToolDefinition,\n} from \"./write.js\";\n\nimport type { AgentTool } from \"@dreb/agent-core\";\nimport type { ToolDefinition } from \"../extensions/types.js\";\nimport {\n\ttype BashToolOptions,\n\tbashTool,\n\tbashToolDefinition,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n} from \"./bash.js\";\nimport { createEditTool, createEditToolDefinition, editTool, editToolDefinition } from \"./edit.js\";\nimport { createFindTool, createFindToolDefinition, findTool, findToolDefinition } from \"./find.js\";\nimport { createGrepTool, createGrepToolDefinition, grepTool, grepToolDefinition } from \"./grep.js\";\nimport { createLsTool, createLsToolDefinition, lsTool, lsToolDefinition } from \"./ls.js\";\nimport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadToolOptions,\n\treadTool,\n\treadToolDefinition,\n} from \"./read.js\";\nimport { createSearchTool, createSearchToolDefinition, isSearchAvailable } from \"./search.js\";\nimport { createSkillTool, createSkillToolDefinition, type SkillToolOptions } from \"./skill.js\";\nimport {\n\tcreateSubagentTool,\n\tcreateSubagentToolDefinition,\n\tgetRunningBackgroundAgents,\n\ttype SubagentToolOptions,\n\tsubagentTool,\n\tsubagentToolDefinition,\n} from \"./subagent.js\";\nimport { createSuggestNextToolDefinition, type SuggestNextCallback } from \"./suggest-next.js\";\nimport { createTasksToolDefinition, type TasksUpdateCallback } from \"./tasks.js\";\nimport { createTmpReadToolDefinition } from \"./tmp-read.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport { createWaitToolDefinition, waitToolDefinition } from \"./wait.js\";\nimport {\n\tcreateWebFetchTool,\n\tcreateWebFetchToolDefinition,\n\tcreateWebSearchTool,\n\tcreateWebSearchToolDefinition,\n\twebFetchTool,\n\twebFetchToolDefinition,\n\twebSearchTool,\n\twebSearchToolDefinition,\n} from \"./web.js\";\nimport { createWriteTool, createWriteToolDefinition, writeTool, writeToolDefinition } from \"./write.js\";\n\nexport type Tool = AgentTool<any>;\nexport type ToolDef = ToolDefinition<any, any>;\n\nexport const codingTools: Tool[] = [readTool, bashTool, editTool, writeTool];\nexport const readOnlyTools: Tool[] = [readTool, grepTool, findTool, lsTool];\n\nconst tmpReadToolDefinition = createTmpReadToolDefinition();\nconst tmpReadTool = wrapToolDefinition(tmpReadToolDefinition);\nconst waitTool = wrapToolDefinition(waitToolDefinition);\n\nexport const allTools = {\n\tread: readTool,\n\tbash: bashTool,\n\tedit: editTool,\n\twrite: writeTool,\n\tgrep: grepTool,\n\tfind: findTool,\n\tls: lsTool,\n\tweb_search: webSearchTool,\n\tweb_fetch: webFetchTool,\n\tsubagent: subagentTool,\n\ttmp_read: tmpReadTool,\n\twait: waitTool,\n};\n\nexport const allToolDefinitions = {\n\tread: readToolDefinition,\n\tbash: bashToolDefinition,\n\tedit: editToolDefinition,\n\twrite: writeToolDefinition,\n\tgrep: grepToolDefinition,\n\tfind: findToolDefinition,\n\tls: lsToolDefinition,\n\tweb_search: webSearchToolDefinition,\n\tweb_fetch: webFetchToolDefinition,\n\tsubagent: subagentToolDefinition,\n\ttmp_read: tmpReadToolDefinition,\n\twait: waitToolDefinition,\n};\n\nexport type ToolName = keyof typeof allTools;\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\tsubagent?: SubagentToolOptions;\n\tskill?: SkillToolOptions;\n\ttasks?: { onUpdate: TasksUpdateCallback };\n\tsuggestNext?: { onSuggest: SuggestNextCallback };\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateBashToolDefinition(cwd, options?.bash),\n\t\tcreateEditToolDefinition(cwd),\n\t\tcreateWriteToolDefinition(cwd),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateGrepToolDefinition(cwd),\n\t\tcreateFindToolDefinition(cwd),\n\t\tcreateLsToolDefinition(cwd),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record<ToolName | \"skill\", ToolDef> {\n\tconst tools: Record<string, ToolDef> = {\n\t\tread: createReadToolDefinition(cwd, options?.read),\n\t\tbash: createBashToolDefinition(cwd, options?.bash),\n\t\tedit: createEditToolDefinition(cwd),\n\t\twrite: createWriteToolDefinition(cwd),\n\t\tgrep: createGrepToolDefinition(cwd),\n\t\tfind: createFindToolDefinition(cwd),\n\t\tls: createLsToolDefinition(cwd),\n\t\tweb_search: createWebSearchToolDefinition(cwd),\n\t\tweb_fetch: createWebFetchToolDefinition(cwd),\n\t\tsubagent: createSubagentToolDefinition(cwd, options?.subagent),\n\t\ttmp_read: createTmpReadToolDefinition(options?.read),\n\t\twait: createWaitToolDefinition({ getRunningAgents: getRunningBackgroundAgents }),\n\t};\n\tif (isSearchAvailable()) {\n\t\ttools.search = createSearchToolDefinition(cwd);\n\t}\n\tif (options?.skill) {\n\t\ttools.skill = createSkillToolDefinition(cwd, options.skill);\n\t}\n\tif (options?.tasks) {\n\t\ttools.tasks_update = createTasksToolDefinition(options.tasks.onUpdate);\n\t}\n\tif (options?.suggestNext) {\n\t\ttools.suggest_next = createSuggestNextToolDefinition(options.suggestNext.onSuggest);\n\t}\n\treturn tools as Record<ToolName | \"skill\", ToolDef>;\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateBashTool(cwd, options?.bash),\n\t\tcreateEditTool(cwd),\n\t\tcreateWriteTool(cwd),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [createReadTool(cwd, options?.read), createGrepTool(cwd), createFindTool(cwd), createLsTool(cwd)];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record<ToolName | \"skill\", Tool> {\n\tconst tools: Record<string, Tool> = {\n\t\tread: createReadTool(cwd, options?.read),\n\t\tbash: createBashTool(cwd, options?.bash),\n\t\tedit: createEditTool(cwd),\n\t\twrite: createWriteTool(cwd),\n\t\tgrep: createGrepTool(cwd),\n\t\tfind: createFindTool(cwd),\n\t\tls: createLsTool(cwd),\n\t\tweb_search: createWebSearchTool(cwd),\n\t\tweb_fetch: createWebFetchTool(cwd),\n\t\tsubagent: createSubagentTool(cwd, options?.subagent),\n\t\ttmp_read: wrapToolDefinition(createTmpReadToolDefinition(options?.read)),\n\t\twait: wrapToolDefinition(createWaitToolDefinition({ getRunningAgents: getRunningBackgroundAgents })),\n\t};\n\tif (isSearchAvailable()) {\n\t\ttools.search = createSearchTool(cwd);\n\t}\n\tif (options?.skill) {\n\t\ttools.skill = createSkillTool(cwd, options.skill);\n\t}\n\tif (options?.tasks) {\n\t\ttools.tasks_update = wrapToolDefinition(createTasksToolDefinition(options.tasks.onUpdate));\n\t}\n\tif (options?.suggestNext) {\n\t\ttools.suggest_next = wrapToolDefinition(createSuggestNextToolDefinition(options.suggestNext.onSuggest));\n\t}\n\treturn tools as Record<ToolName | \"skill\", Tool>;\n}\n"]}
|