@draht/coding-agent 2026.10.4-3 → 2026.10.8-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-JTLUBTZT.js → chunk-6QIFWMDF.js} +1 -1
- package/dist/bundle/chunks/{chunk-AFL4IDSI.js → chunk-AHGUOQPH.js} +2 -2
- package/dist/bundle/chunks/{chunk-VPYAVQLP.js → chunk-BOGY4QVF.js} +4 -4
- package/dist/bundle/chunks/chunk-GD2WVXWT.js +65 -0
- package/dist/bundle/chunks/{chunk-3HF756LN.js → chunk-KJJJSTND.js} +292 -153
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-V5HG6S2T.js → chunk-QVTLBSTH.js} +1 -1
- package/dist/bundle/chunks/{chunk-A4OX5CPR.js → chunk-U6LDZZGM.js} +1 -1
- package/dist/bundle/chunks/{chunk-XO3IECI5.js → chunk-VQOV5VFH.js} +1 -1
- package/dist/bundle/chunks/{cli-L74YA5GF.js → cli-O6OWCY7N.js} +1 -1
- package/dist/bundle/chunks/execute-4JU5WQXP.js +18 -0
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/google-gemini-cli.js +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/{runtime-RYUR6LRB.js → runtime-FIGQHW75.js} +1 -1
- package/dist/bundle/chunks/runtime-TJ3EAMJK.js +3 -0
- package/dist/bundle/chunks/{settings-manager-CHEMMAGQ.js → settings-manager-HC5RR36T.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-UIGTRGHQ.js +2 -0
- package/dist/bundle/chunks/xai.js +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +3 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +5 -2
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +65 -27
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts +15 -0
- package/dist/core/builtins/polyphase.d.ts.map +1 -0
- package/dist/core/builtins/polyphase.js +196 -0
- package/dist/core/builtins/polyphase.js.map +1 -0
- package/dist/core/builtins/subagent.d.ts +44 -34
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +827 -560
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/types.d.ts +17 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +30 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +4 -1
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +35 -0
- package/dist/core/polyphase/approval.d.ts.map +1 -0
- package/dist/core/polyphase/approval.js +184 -0
- package/dist/core/polyphase/approval.js.map +1 -0
- package/dist/core/polyphase/child-events.d.ts +107 -0
- package/dist/core/polyphase/child-events.d.ts.map +1 -0
- package/dist/core/polyphase/child-events.js +862 -0
- package/dist/core/polyphase/child-events.js.map +1 -0
- package/dist/core/polyphase/child-process.d.ts +65 -0
- package/dist/core/polyphase/child-process.d.ts.map +1 -0
- package/dist/core/polyphase/child-process.js +361 -0
- package/dist/core/polyphase/child-process.js.map +1 -0
- package/dist/core/polyphase/commands.d.ts +44 -0
- package/dist/core/polyphase/commands.d.ts.map +1 -0
- package/dist/core/polyphase/commands.js +244 -0
- package/dist/core/polyphase/commands.js.map +1 -0
- package/dist/core/polyphase/details.d.ts +40 -0
- package/dist/core/polyphase/details.d.ts.map +1 -0
- package/dist/core/polyphase/details.js +538 -0
- package/dist/core/polyphase/details.js.map +1 -0
- package/dist/core/polyphase/emitter.d.ts +20 -0
- package/dist/core/polyphase/emitter.d.ts.map +1 -0
- package/dist/core/polyphase/emitter.js +90 -0
- package/dist/core/polyphase/emitter.js.map +1 -0
- package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
- package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
- package/dist/core/polyphase/jsonl-reader.js +161 -0
- package/dist/core/polyphase/jsonl-reader.js.map +1 -0
- package/dist/core/polyphase/keyword.d.ts +27 -0
- package/dist/core/polyphase/keyword.d.ts.map +1 -0
- package/dist/core/polyphase/keyword.js +97 -0
- package/dist/core/polyphase/keyword.js.map +1 -0
- package/dist/core/polyphase/limiter.d.ts +38 -0
- package/dist/core/polyphase/limiter.d.ts.map +1 -0
- package/dist/core/polyphase/limiter.js +129 -0
- package/dist/core/polyphase/limiter.js.map +1 -0
- package/dist/core/polyphase/model-selection.d.ts +35 -0
- package/dist/core/polyphase/model-selection.d.ts.map +1 -0
- package/dist/core/polyphase/model-selection.js +72 -0
- package/dist/core/polyphase/model-selection.js.map +1 -0
- package/dist/core/polyphase/render/format.d.ts +52 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -0
- package/dist/core/polyphase/render/format.js +169 -0
- package/dist/core/polyphase/render/format.js.map +1 -0
- package/dist/core/polyphase/render/renderers.d.ts +63 -0
- package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
- package/dist/core/polyphase/render/renderers.js +277 -0
- package/dist/core/polyphase/render/renderers.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts +45 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
- package/dist/core/polyphase/render/run-block.js +843 -0
- package/dist/core/polyphase/render/run-block.js.map +1 -0
- package/dist/core/polyphase/render/snapshot.d.ts +106 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
- package/dist/core/polyphase/render/snapshot.js +292 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -0
- package/dist/core/polyphase/result-text.d.ts +41 -0
- package/dist/core/polyphase/result-text.d.ts.map +1 -0
- package/dist/core/polyphase/result-text.js +326 -0
- package/dist/core/polyphase/result-text.js.map +1 -0
- package/dist/core/polyphase/session.d.ts +33 -0
- package/dist/core/polyphase/session.d.ts.map +1 -0
- package/dist/core/polyphase/session.js +106 -0
- package/dist/core/polyphase/session.js.map +1 -0
- package/dist/core/polyphase/settings.d.ts +18 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -0
- package/dist/core/polyphase/settings.js +93 -0
- package/dist/core/polyphase/settings.js.map +1 -0
- package/dist/core/polyphase/store.d.ts +197 -0
- package/dist/core/polyphase/store.d.ts.map +1 -0
- package/dist/core/polyphase/store.js +558 -0
- package/dist/core/polyphase/store.js.map +1 -0
- package/dist/core/polyphase/types.d.ts +371 -0
- package/dist/core/polyphase/types.d.ts.map +1 -0
- package/dist/core/polyphase/types.js +36 -0
- package/dist/core/polyphase/types.js.map +1 -0
- package/dist/core/polyphase/ui/controller.d.ts +28 -0
- package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
- package/dist/core/polyphase/ui/controller.js +150 -0
- package/dist/core/polyphase/ui/controller.js.map +1 -0
- package/dist/core/polyphase/ui/dock.d.ts +27 -0
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
- package/dist/core/polyphase/ui/dock.js +121 -0
- package/dist/core/polyphase/ui/dock.js.map +1 -0
- package/dist/core/polyphase/ui/inspector.d.ts +117 -0
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
- package/dist/core/polyphase/ui/inspector.js +1016 -0
- package/dist/core/polyphase/ui/inspector.js.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.js +210 -0
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
- package/dist/core/polyphase/update-pump.d.ts +18 -0
- package/dist/core/polyphase/update-pump.d.ts.map +1 -0
- package/dist/core/polyphase/update-pump.js +132 -0
- package/dist/core/polyphase/update-pump.js.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.js +187 -0
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
- package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/guidance.js +119 -0
- package/dist/core/polyphase/workflow/guidance.js.map +1 -0
- package/dist/core/polyphase/workflow/launch.d.ts +41 -0
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/launch.js +173 -0
- package/dist/core/polyphase/workflow/launch.js.map +1 -0
- package/dist/core/polyphase/workflow/meta.d.ts +43 -0
- package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/meta.js +529 -0
- package/dist/core/polyphase/workflow/meta.js.map +1 -0
- package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
- package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/prelude.js +93 -0
- package/dist/core/polyphase/workflow/prelude.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.js +217 -0
- package/dist/core/polyphase/workflow/runtime.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
- package/dist/core/polyphase/workflow/saved.d.ts +55 -0
- package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/saved.js +299 -0
- package/dist/core/polyphase/workflow/saved.js.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.js +66 -0
- package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts +24 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/tool.js +139 -0
- package/dist/core/polyphase/workflow/tool.js.map +1 -0
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +27 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/socket-server/permission-relay.js +4 -0
- package/dist/core/socket-server/permission-relay.js.map +1 -1
- package/dist/core/trust-manager.d.ts +3 -2
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/experimental/micro/runtime.js +1 -1
- package/dist/experimental/micro/runtime.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +18 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +11 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/prompts/commands/orchestrate.md +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +7 -1
- package/dist/utils/shell.js.map +1 -1
- package/docs/docs.json +4 -0
- package/docs/duet.md +3 -3
- package/docs/environment-variables.md +11 -0
- package/docs/json.md +7 -0
- package/docs/keybindings.md +20 -0
- package/docs/polyphase.md +391 -0
- package/docs/rpc-commands.md +9 -9
- package/docs/settings.md +12 -0
- package/docs/virtual-models.md +3 -3
- package/examples/extensions/preset.ts +3 -3
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +1 -1
- package/examples/extensions/subagent/agents/worker.md +1 -1
- package/examples/extensions/summarize.ts +3 -3
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/package.json +10 -10
- package/prompts/commands/orchestrate.md +1 -1
- package/dist/bundle/chunks/chunk-SPZUYYP5.js +0 -170
- package/dist/bundle/chunks/execute-EMOVNTD6.js +0 -328
- package/dist/bundle/chunks/virtual-modules-OC56AAJ7.js +0 -2
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
|
|
2
|
+
import{Container,Spacer,Text,VisualLinePreview,getTextOutput,highlightCode,keyHint,replaceTabs,str}from"./chunk-BOGY4QVF.js";import{typebox_exports}from"./chunk-XHCO4PPH.js";import{CODEMODE_SOURCE_GRAMMAR,MCP_TYPESCRIPT_PREAMBLE,mcpStructuredContentSchema,renderDeclarations,renderToolSample,toCodemodeIdentifier}from"./chunk-PGJAHC3R.js";function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let entry of entries){let key,usage;if(entry.type==="message"&&entry.message.role==="assistant"?(key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage=entry.message.usage):entry.type==="usage"?(key=`${entry.provider}/${entry.model}`,usage=entry.usage):entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage?(key="Tools/summaries",usage=entry.message.usage):(entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage&&(key="Tools/summaries",usage=entry.usage),!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){return text.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(term=>term.length>0&&!STOP_WORDS.has(term)).map(stem)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,parts){if(isObject(schema)){if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,parts);schemaText(schema.items,parts);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,parts)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.name,tool.name.replaceAll("_"," "),tool.description];return schemaText(tool.parameters,parts),namespace&&parts.push(namespace.name,namespace.description??"",namespace.instructions??""),{name:tool.name,text:parts.filter(part=>part.trim()).join(" ")}}var Bm25Ranker=class{k1;b;constructor(options={}){this.k1=options.k1??1.2,this.b=options.b??.75}rank(query,documents,limit){let queryTerms=[...new Set(tokenize(query))];if(queryTerms.length===0||documents.length===0||limit<=0)return[];let termCounts=documents.map(document=>{let counts=new Map;for(let term of tokenize(document.text))counts.set(term,(counts.get(term)??0)+1);return counts}),lengths=termCounts.map(counts=>[...counts.values()].reduce((sum,count)=>sum+count,0)),averageLength=lengths.reduce((sum,length)=>sum+length,0)/documents.length||1,idf=new Map(queryTerms.map(term=>{let frequency=termCounts.filter(counts=>counts.has(term)).length;return[term,Math.log(1+(documents.length-frequency+.5)/(frequency+.5))]})),matches=[];return documents.forEach((document,index)=>{let score=0;for(let term of queryTerms){let count=termCounts[index].get(term);if(!count)continue;let norm=this.k1*(1-this.b+this.b*lengths[index]/averageLength);score+=(idf.get(term)??0)*(count*(this.k1+1)/(count+norm))}score>0&&matches.push({name:document.name,score})}),matches.sort((a,b)=>b.score-a.score).slice(0,limit)}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isToolSearchTool(tool){return tool.name===TOOL_SEARCH_TOOL_NAME&&tool.parameters===toolSearchSchema}function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
|
|
3
|
+
|
|
4
|
+
Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
|
|
5
|
+
|
|
6
|
+
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
|
|
7
|
+
${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
8
|
+
`)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-4JU5WQXP.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS?`${call.args.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
|
|
9
|
+
${theme.fg("error",call.error.split(`
|
|
10
|
+
`).join(`
|
|
11
|
+
`))}`),line}var codemodeRenderers={renderCall(args,theme,context){let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
12
|
+
`);component.addChild(context.expanded?new Text(highlighted,0,0):new VisualLinePreview({text:highlighted,maxVisualLines:CODE_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}))}return component},renderResult(result,options,theme,context){let component=context.lastComponent??new Container;component.clear();let calls=result.details?.calls??[];if(calls.length>0){let shown=options.expanded?calls:calls.slice(-CALL_PREVIEW_COUNT),lines=shown.map(call=>formatCall(call,theme,options.expanded));shown.length<calls.length&&lines.unshift(`${theme.fg("muted",`... (${calls.length-shown.length} earlier calls,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`);let priced=calls.filter(call=>call.cost);if(priced.length>1){let total=priced.reduce((sum,call)=>sum+(call.cost??0),0);lines.push(theme.fg("muted",`Model calls: ${formatCost(total)}`))}component.addChild(new Spacer(1)),component.addChild(new Text(lines.join(`
|
|
13
|
+
`),0,0))}let[first,...rest]=result.content,hasHeader=first?.type==="text"&&SCRIPT_HEADER.test(first.text),output=options.isPartial?"":getTextOutput({...result,content:hasHeader?rest:result.content},context.showImages).trim();if(output){let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
14
|
+
`).map(line=>theme.fg(color,line)).join(`
|
|
15
|
+
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}}return component}};var CODEMODE_TOOL_NAME="codemode",CODEMODE_STORE_ENTRY_TYPE="codemode-store",TEXT_OUTPUT_SCHEMA={type:"string"},codemodeSchema=typebox_exports.Object({code:typebox_exports.String({description:'Raw JavaScript source. Top-level await and return work. May start with a `// @options: {"max_output_tokens": 1000}` line.'})});function isCodemodeTool(tool){return tool.name===CODEMODE_TOOL_NAME&&tool.parameters===codemodeSchema}var codemodeToolSystemPromptContribution={snippet:"Run JavaScript that calls other tools (chains, loops, Promise.all, filtering large results)",guidelines:["Use codemode to batch or chain several tool calls, or to filter large tool output down to what you need, instead of issuing many individual tool calls. Batch independent calls in one codemode call using await Promise.allSettled([...])."]},DESCRIPTION_INTRO='Run JavaScript code to orchestrate/compose tool calls\n- Evaluates the provided JavaScript code in a fresh QuickJS sandbox as the body of an async function: top-level `await` and `return` work.\n- All nested tools are available on the global `tools` object, for example `await tools.read(...)`. Tool names are exposed as normalized JavaScript identifiers, for example `await tools.mcp__ologs__get_profile(...)`.\n- Nested tool methods take an object as their input argument.\n- Nested tools return either an object or a string, based on the description.\n- A nested tool call that fails, is blocked, or gets invalid arguments rejects with an Error carrying the tool\'s error text.\n- Runs raw JavaScript -- no Node, no file system, no network access, no timers.\n- Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences.\n- You may optionally start the tool input with a first line like `// @options: {"max_output_tokens": 1000, "timeout_ms": 60000}`.\n- `max_output_tokens` sets the token budget for the script\'s output. Defaults to 10000 tokens.\n- `timeout_ms` sets a hard deadline for the whole script. By default there is none.\n- When the JS code is fully evaluated, calls that are still running are cancelled and unawaited promises are silently discarded.\n- Tool calls are real and have side effects. If the script fails partway, earlier calls are not undone.\n- Scripts have a 256 MB memory limit; exceeding it throws `InternalError: out of memory`. Filter or aggregate large data instead of accumulating it.\n\n- Global helpers:\n- `exit()`: Immediately ends the current script successfully (like an early return from the top level).\n- `text(value: string | number | boolean | undefined | null)`: Appends a text item. Non-string values are stringified with `JSON.stringify(...)` when possible.\n- `image(imageUrlOrItem: string | { image_url: string } | ImageContent)`: Appends an image item. `image_url` should be a base64-encoded `data:` URL. To forward an MCP tool image, pass an individual `ImageContent` block from `result.content`, for example `image(result.content[0])`.\n- `store(key: string, value: any)`: stores a serializable value under a string key for later `codemode` calls in the same session. Storing `undefined` deletes the key. Writes are kept only if the script succeeds.\n- `load(key: string)`: returns the stored value for a string key, or `undefined` if it is missing.\n- `ALL_TOOLS`: metadata for the enabled nested tools as `{ name, description }` entries.\n- `searchTools(query: string, options?: { limit?: number; namespace?: string })`: resolves to the nested tools that best match the query (BM25, default limit 8), as `{ name, description }` entries like `ALL_TOOLS`.\n- `describeTool(name: string)`: resolves to the description and declaration of a nested tool, or `undefined`.\n- `describeNamespace(name: string)`: resolves to `{ name, description?, instructions?, tools }` for a namespace of nested tools, such as an MCP server: its usage instructions and the names of its tools, or `undefined`.\n- `console.log(...)` and the other `console` methods append a text item like `text()`.\n- `return value` at the top level appends the value like `text()`.',MODEL_TYPES=`type ModelType = "chat" | "image" | "classifier";
|
|
16
|
+
/** A model catalog entry. \`provider\` and \`id\` identify it; the other fields depend on the type. */
|
|
17
|
+
interface ModelInfo {
|
|
18
|
+
type?: ModelType;
|
|
19
|
+
provider: string;
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
api: string;
|
|
23
|
+
input: ("text" | "image")[];
|
|
24
|
+
contextWindow?: number;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
type ClassifierQuestion =
|
|
28
|
+
| { type: "choice"; instructions: string; criteria: Record<string, string> }
|
|
29
|
+
| { type: "score"; instructions: string; criteria: string[] }
|
|
30
|
+
| { type: "bool"; instructions: string; criteria: { true: string; false: string } };
|
|
31
|
+
type ClassifierAnswer =
|
|
32
|
+
| { type: "choice"; choice: string; probabilities: Record<string, number>; confidence: number }
|
|
33
|
+
| { type: "score"; score: number; confidence: number }
|
|
34
|
+
| { type: "bool"; probability: number };
|
|
35
|
+
interface ClassifierContext {
|
|
36
|
+
state: Record<string, unknown>;
|
|
37
|
+
questions: Record<string, ClassifierQuestion>;
|
|
38
|
+
}
|
|
39
|
+
interface ClassifierResult {
|
|
40
|
+
api: string;
|
|
41
|
+
provider: string;
|
|
42
|
+
model: string;
|
|
43
|
+
answers: Record<string, ClassifierAnswer>;
|
|
44
|
+
/** Set when the service reports token counts. Cost is in USD. */
|
|
45
|
+
usage?: { input: number; output: number; totalTokens: number; cost: { total: number } };
|
|
46
|
+
stopReason: "stop" | "error" | "aborted";
|
|
47
|
+
errorMessage?: string;
|
|
48
|
+
timestamp: number;
|
|
49
|
+
}`,MODEL_GLOBAL_DECLARATIONS=[{name:"models.getModelsOfType",description:"Every known model of a type, optionally for one provider.",signature:"(type: ModelType, provider?: string): Promise<ModelInfo[]>"},{name:"models.getAvailableOfType",description:"Models of a type whose provider has working credentials.",signature:"(type: ModelType, provider?: string): Promise<ModelInfo[]>"},{name:"models.getModelOfType",description:"One catalog entry, or undefined.",signature:"(type: ModelType, provider: string, id: string): Promise<ModelInfo | undefined>"},{name:"models.classify",description:"Run a classifier model on one state. Only `provider` and `id` of `model` are used. Provider errors do not throw: check `stopReason` and `errorMessage`.",signature:"(model: ModelInfo, context: ClassifierContext): Promise<ClassifierResult>"}],DEFERRED_TOOLS_GUIDANCE="Some nested tools may be omitted from this description, such as deferred tools and MCP tools. They are still available on the global `tools` object and listed in `ALL_TOOLS`.\nTo find one, call `await searchTools(query)` (pass `{ namespace }` to search one namespace), or filter `ALL_TOOLS` by `name` and `description`. `await describeNamespace(name)` returns a namespace's usage instructions and the names of its tools.",DEFAULT_CODEMODE_INLINE_BUDGET=3e3,CHARS_PER_TOKEN=4;function toCodemodeDeclaration(tool){return{name:tool.name,description:tool.description,inputSchema:tool.parameters,outputSchema:tool.outputSchema??TEXT_OUTPUT_SCHEMA}}function getCodemodeCallableTools(tools){return tools.filter(tool=>tool.name!==CODEMODE_TOOL_NAME)}function renderToolSection(declaration){let id=toCodemodeIdentifier(declaration.name);return`${id===declaration.name?`### \`${id}\``:`### \`${id}\` (\`${declaration.name}\`)`}
|
|
50
|
+
${renderToolSample(declaration).trim()}`}function selectCatalog(groups,budget){if(budget===void 0)return new Set(groups.flatMap(group=>group.entries.map(entry=>entry.name)));let queues=groups.map(group=>[...group.entries].sort((a,b)=>a.cost-b.cost)),shown=new Set,remaining=budget,active=queues.filter(queue=>queue.length>0);for(;active.length>0;)active=active.filter(queue=>{let next=queue[0];return next.cost>remaining?!1:(remaining-=next.cost,shown.add(next.name),queue.shift(),queue.length>0)});return shown}function createCodemodeDescription(tools,options={}){let declarations=getCodemodeCallableTools(tools).filter(tool=>!options.deferred?.has(tool.name)).map(toCodemodeDeclaration),groups=new Map([["",{namespace:void 0,entries:[]}]]);for(let declaration of declarations){let namespace=options.namespaces?.get(declaration.name),key=namespace?`ns:${namespace.name}`:"",group=groups.get(key)??{namespace,entries:[]};groups.set(key,group);let section=renderToolSection(declaration);group.entries.push({name:declaration.name,section,cost:Math.ceil(section.length/CHARS_PER_TOKEN)})}let ordered=[...groups.values()].sort((a,b)=>a.namespace===void 0?-1:b.namespace===void 0?1:a.namespace.name.localeCompare(b.namespace.name)),shown=selectCatalog(ordered,options.inlineBudget),sections=[DESCRIPTION_INTRO,DEFERRED_TOOLS_GUIDANCE];if(declarations.some(declaration=>shown.has(declaration.name)&&mcpStructuredContentSchema(declaration.outputSchema)!==void 0)&§ions.push(`Shared MCP Types:
|
|
51
|
+
\`\`\`ts
|
|
52
|
+
${MCP_TYPESCRIPT_PREAMBLE}
|
|
53
|
+
\`\`\``),options.models){let noop=()=>{},models=renderDeclarations({globals:MODEL_GLOBAL_DECLARATIONS.map(global=>({...global,execute:noop}))});sections.push(`Model API:
|
|
54
|
+
\`\`\`ts
|
|
55
|
+
${MODEL_TYPES}
|
|
56
|
+
|
|
57
|
+
${models}
|
|
58
|
+
\`\`\``)}if(declarations.length===0)return sections.join(`
|
|
59
|
+
|
|
60
|
+
`);let toolSections=["Nested tools:"];for(let{namespace,entries}of ordered){let visible=entries.filter(entry=>shown.has(entry.name));if(namespace){let listing=visible.length===entries.length?"":visible.length===0?" (tools not listed)":" (some tools not listed)",description=namespace.description?.trim();toolSections.push(`## ${namespace.name}${listing}${description?`
|
|
61
|
+
${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}return sections.push(toolSections.join(`
|
|
62
|
+
|
|
63
|
+
`)),sections.join(`
|
|
64
|
+
|
|
65
|
+
`)}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??"on",isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=renderToolSample(toCodemodeDeclaration(tool)));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]}));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{createUsageTotals,addUsageToTotals,combineUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,isToolSearchTool,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,isCodemodeTool,MODEL_GLOBAL_DECLARATIONS,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|