@arhan-w/ibex 0.0.0-stage → 3.6.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/LICENSE +21 -0
- package/README.md +295 -2
- package/npm-package/LICENSE +21 -0
- package/npm-package/README.md +176 -0
- package/npm-package/bin/goat.js +3 -0
- package/npm-package/bin/ibex.js +77 -0
- package/npm-package/package.json +58 -0
- package/npm-package/scripts/install-binary.js +168 -0
- package/package.json +69 -6
- package/src/agent.ts +695 -0
- package/src/agents/loader.ts +110 -0
- package/src/ambient.d.ts +2 -0
- package/src/code/extract.ts +292 -0
- package/src/code/find.ts +244 -0
- package/src/code/grammars.ts +88 -0
- package/src/code/indexer.ts +242 -0
- package/src/code/semantic.ts +253 -0
- package/src/code/slash.ts +88 -0
- package/src/code/tool.ts +40 -0
- package/src/collab/client.ts +141 -0
- package/src/collab/handlers.ts +141 -0
- package/src/collab/invite.ts +39 -0
- package/src/collab/relay.ts +106 -0
- package/src/collab/sync.ts +131 -0
- package/src/commands.tsx +943 -0
- package/src/computer.ts +629 -0
- package/src/config.ts +318 -0
- package/src/constants.ts +18 -0
- package/src/context.ts +73 -0
- package/src/data/providers.json +2342 -0
- package/src/diff.ts +50 -0
- package/src/doctor.ts +443 -0
- package/src/errors.ts +139 -0
- package/src/gflash.ts +170 -0
- package/src/hooks.ts +133 -0
- package/src/ide/assets.gen.ts +3 -0
- package/src/ide/index.html +844 -0
- package/src/ide/server.ts +506 -0
- package/src/ide/vendor/marked.umd.js +80 -0
- package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
- package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
- package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
- package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
- package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
- package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
- package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
- package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
- package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
- package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
- package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
- package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
- package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
- package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
- package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
- package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
- package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
- package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
- package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
- package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
- package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
- package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
- package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
- package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
- package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
- package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
- package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
- package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
- package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
- package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
- package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
- package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
- package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
- package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
- package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
- package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
- package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
- package/src/ide/vendor/vs/editor/editor.main.css +8 -0
- package/src/ide/vendor/vs/editor/editor.main.js +798 -0
- package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
- package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
- package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
- package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
- package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
- package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
- package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
- package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
- package/src/ide/vendor/vs/loader.js +11 -0
- package/src/index-shared.ts +117 -0
- package/src/index.ts +586 -0
- package/src/llm.ts +721 -0
- package/src/logger.ts +39 -0
- package/src/mcp/client.ts +121 -0
- package/src/mcp/types.ts +27 -0
- package/src/oauth.ts +205 -0
- package/src/onboarding.ts +140 -0
- package/src/palette.tsx +199 -0
- package/src/permissions.ts +123 -0
- package/src/plugins/loader.ts +120 -0
- package/src/plugins/marketplace.ts +252 -0
- package/src/plugins/sandbox.ts +303 -0
- package/src/plugins/tar.ts +241 -0
- package/src/pricing.ts +78 -0
- package/src/protocol/client.ts +102 -0
- package/src/protocol/rpc.ts +43 -0
- package/src/protocol/serve.ts +136 -0
- package/src/providers.ts +402 -0
- package/src/rate-limiter.ts +101 -0
- package/src/refs.ts +97 -0
- package/src/runtime.ts +144 -0
- package/src/session.ts +401 -0
- package/src/skills/loader.ts +136 -0
- package/src/statusline.ts +70 -0
- package/src/system-prompt.ts +28 -0
- package/src/tools.ts +1280 -0
- package/src/tui.tsx +1355 -0
- package/src/update.ts +236 -0
- package/src/vendor/flashServer.ts +2 -0
- package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
- package/src/virtual-list.tsx +125 -0
- package/src/window.ts +31 -0
- package/tsconfig.json +16 -0
package/src/agent.ts
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent loop: prompt -> stream -> tool calls -> results -> repeat.
|
|
3
|
+
* Model-agnostic: one ChatClient interface (from llm.make_client) behind
|
|
4
|
+
* every provider. Events are yielded so the UI can render incrementally.
|
|
5
|
+
*/
|
|
6
|
+
import { buildSystemPrompt } from "./system-prompt.ts";
|
|
7
|
+
import { contentChars, isRetryableLLMError, textOf, type ChatClient, type ContentPart, type Message, type StreamEvent, type ToolCall, type ToolSpec } from "./llm.ts";
|
|
8
|
+
import { Session, summarize } from "./session.ts";
|
|
9
|
+
import { ToolKit, getToolSpec, type PermissionFn, type Todo, type ToolEvent, type ToolResult } from "./tools.ts";
|
|
10
|
+
import type { AgentDef } from "./agents/loader.ts";
|
|
11
|
+
import { fireHooks, MAX_STOP_HOOK_CONTINUES } from "./hooks.ts";
|
|
12
|
+
import { SUBAGENT_MAX_STEPS, ULTRACODE_FANOUT } from "./constants.ts";
|
|
13
|
+
import { costUsd } from "./pricing.ts";
|
|
14
|
+
import { ConfigError, ProviderError, AuthError, RateLimitError, GoatError, GenericError } from "./errors.ts";
|
|
15
|
+
|
|
16
|
+
export const COMPACT_TRIGGER_CHARS = 220_000;
|
|
17
|
+
/** Attempt budget for transient LLM failures (429/5xx/network) within one step. */
|
|
18
|
+
export const LLM_MAX_ATTEMPTS = 4;
|
|
19
|
+
export const RETRY_BASE_MS = 1_000;
|
|
20
|
+
export const RETRY_MAX_MS = 20_000;
|
|
21
|
+
/** Per-attempt wall clock: a provider that hangs gets cut off and retried. */
|
|
22
|
+
export const REQUEST_TIMEOUT_MS = (() => {
|
|
23
|
+
const n = Number(process.env.GOAT_REQUEST_TIMEOUT);
|
|
24
|
+
return Number.isFinite(n) && n > 0 ? n * 1000 : 120_000;
|
|
25
|
+
})();
|
|
26
|
+
|
|
27
|
+
export type AgentEvent =
|
|
28
|
+
| { kind: "text"; text: string }
|
|
29
|
+
| { kind: "thinking"; text: string }
|
|
30
|
+
| { kind: "tool_start"; tool: string; args: Record<string, unknown>; callId?: string }
|
|
31
|
+
| { kind: "tool_output"; callId: string; tool: string; text: string }
|
|
32
|
+
| { kind: "tool_end"; tool: string; result: string; ok: boolean; callId?: string; durationMs?: number }
|
|
33
|
+
| { kind: "usage"; text: string; usage?: { prompt: number; completion: number; cacheRead?: number; cacheWrite?: number } }
|
|
34
|
+
| { kind: "tool_calls"; toolCalls: ToolCall[] }
|
|
35
|
+
| { kind: "retry"; attempt: number; waitMs: number; reason: string }
|
|
36
|
+
| { kind: "fallback"; from: string; to: string; reason: string }
|
|
37
|
+
| { kind: "todo"; todos: Todo[] }
|
|
38
|
+
| { kind: "error"; text: string }
|
|
39
|
+
| { kind: "done" };
|
|
40
|
+
|
|
41
|
+
/** Read-only tools the agent may run concurrently within one step
|
|
42
|
+
* (Claude Code parallelizes these too). Excludes anything that can raise a
|
|
43
|
+
* permission prompt — two simultaneous prompts would deadlock one of them. */
|
|
44
|
+
export const CONCURRENT_SAFE = new Set(["read", "glob", "grep", "tasks"]);
|
|
45
|
+
|
|
46
|
+
export interface AgentDeps {
|
|
47
|
+
client: ChatClient;
|
|
48
|
+
/** Anthropic prompt caching (system+tools ephemeral cache). */
|
|
49
|
+
cache?: boolean;
|
|
50
|
+
/** Cheaper client for background work (compaction, explore subagents). */
|
|
51
|
+
smallClient?: ChatClient;
|
|
52
|
+
session: Session;
|
|
53
|
+
tools: ToolKit;
|
|
54
|
+
maxTokens: number;
|
|
55
|
+
temperature: number | null;
|
|
56
|
+
maxSteps: number;
|
|
57
|
+
/** Extra system context: skills list, GOAT.md, MCP notes. */
|
|
58
|
+
extraSystem?: string;
|
|
59
|
+
/** Retry tuning (tests shrink these; production uses the exported defaults). */
|
|
60
|
+
retryBaseMs?: number;
|
|
61
|
+
maxAttempts?: number;
|
|
62
|
+
/** Per-attempt request deadline in ms (default REQUEST_TIMEOUT_MS). */
|
|
63
|
+
requestTimeoutMs?: number;
|
|
64
|
+
/** Tools hidden from the model AND refused at dispatch (subagent guardrails). */
|
|
65
|
+
disallowedTools?: Set<string>;
|
|
66
|
+
/** Providers tried, in order, when the primary hard-fails before streaming
|
|
67
|
+
* any content (quota exhausted, bad/expired auth, provider down). */
|
|
68
|
+
fallbacks?: Array<{ client: ChatClient; model: string }>;
|
|
69
|
+
/** Live tool telemetry sink (UI wiring). Forwarded to tools.toolEvent. */
|
|
70
|
+
onToolEvent?: (ev: ToolEvent) => void;
|
|
71
|
+
/** Custom subagent definitions (subagent_type -> persona + tool allowlist). */
|
|
72
|
+
customAgents?: AgentDef[];
|
|
73
|
+
/** Resolve an arbitrary model string ("provider/model") to a live client.
|
|
74
|
+
* Powers the custom-agent `model:` override; when absent (tests) the
|
|
75
|
+
* override falls back to the parent's client. */
|
|
76
|
+
resolveClientFor?: (model: string) => Promise<ChatClient>;
|
|
77
|
+
/** Hard spend ceiling in USD for this session. When the accumulated cost
|
|
78
|
+
* (priced models only) reaches it, the turn stops with a clear error
|
|
79
|
+
* instead of burning silently. Unset or 0 = no cap. */
|
|
80
|
+
budgetUsd?: number;
|
|
81
|
+
/** Auto-title the session with the small model after the first turn. */
|
|
82
|
+
autoTitle?: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export class Agent {
|
|
86
|
+
client: ChatClient;
|
|
87
|
+
smallClient: ChatClient | null;
|
|
88
|
+
session: Session;
|
|
89
|
+
tools: ToolKit;
|
|
90
|
+
maxTokens: number;
|
|
91
|
+
temperature: number | null;
|
|
92
|
+
maxSteps: number;
|
|
93
|
+
extraSystem: string;
|
|
94
|
+
retryBaseMs: number;
|
|
95
|
+
maxAttempts: number;
|
|
96
|
+
requestTimeoutMs: number;
|
|
97
|
+
disallowedTools: Set<string>;
|
|
98
|
+
fallbacks: Array<{ client: ChatClient; model: string }>;
|
|
99
|
+
cache: boolean;
|
|
100
|
+
/** Custom subagent types this agent can spawn (name -> def). */
|
|
101
|
+
customAgents: AgentDef[];
|
|
102
|
+
/** Model-string -> live client resolver for custom-agent model overrides. */
|
|
103
|
+
resolveClientFor?: (model: string) => Promise<ChatClient>;
|
|
104
|
+
/** Hard spend ceiling (USD); turn stops when the priced cost reaches it. */
|
|
105
|
+
budgetUsd: number;
|
|
106
|
+
/** Generate a session title with the model after the first turn. */
|
|
107
|
+
autoTitle: boolean;
|
|
108
|
+
/** Real prompt-token count of the most recent API call (true context size). */
|
|
109
|
+
lastPromptTokens = 0;
|
|
110
|
+
/** Circuit breaker: tracks consecutive failures per provider to avoid rapid re-failure. */
|
|
111
|
+
private _circuitBreaker: Map<string, { failures: number; lastFailureTime: number }> = new Map();
|
|
112
|
+
/** Max consecutive failures before circuit opens (provider is skipped). */
|
|
113
|
+
static readonly CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
114
|
+
/** Time window (ms) for counting consecutive failures. */
|
|
115
|
+
static readonly CIRCUIT_BREAKER_WINDOW_MS = 60_000;
|
|
116
|
+
|
|
117
|
+
constructor(deps: AgentDeps) {
|
|
118
|
+
this.client = deps.client;
|
|
119
|
+
this.smallClient = deps.smallClient ?? null;
|
|
120
|
+
this.session = deps.session;
|
|
121
|
+
this.tools = deps.tools;
|
|
122
|
+
this.maxTokens = deps.maxTokens;
|
|
123
|
+
this.temperature = deps.temperature;
|
|
124
|
+
this.maxSteps = deps.maxSteps;
|
|
125
|
+
this.extraSystem = deps.extraSystem ?? "";
|
|
126
|
+
this.retryBaseMs = deps.retryBaseMs ?? RETRY_BASE_MS;
|
|
127
|
+
this.maxAttempts = deps.maxAttempts ?? LLM_MAX_ATTEMPTS;
|
|
128
|
+
this.requestTimeoutMs = deps.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
129
|
+
this.disallowedTools = deps.disallowedTools ?? new Set();
|
|
130
|
+
this.fallbacks = deps.fallbacks ? [...deps.fallbacks] : [];
|
|
131
|
+
this.cache = deps.cache ?? false;
|
|
132
|
+
this.customAgents = deps.customAgents ?? [];
|
|
133
|
+
this.resolveClientFor = deps.resolveClientFor;
|
|
134
|
+
this.budgetUsd = deps.budgetUsd ?? 0;
|
|
135
|
+
this.autoTitle = deps.autoTitle ?? false;
|
|
136
|
+
if (deps.onToolEvent) this.tools.toolEvent = deps.onToolEvent;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Record a failure for a provider in the circuit breaker. */
|
|
140
|
+
recordFailure(provider: string): void {
|
|
141
|
+
const now = Date.now();
|
|
142
|
+
const state = this._circuitBreaker.get(provider) ?? { failures: 0, lastFailureTime: 0 };
|
|
143
|
+
// Reset counter if outside the time window
|
|
144
|
+
if (now - state.lastFailureTime > Agent.CIRCUIT_BREAKER_WINDOW_MS) {
|
|
145
|
+
state.failures = 1;
|
|
146
|
+
} else {
|
|
147
|
+
state.failures += 1;
|
|
148
|
+
}
|
|
149
|
+
state.lastFailureTime = now;
|
|
150
|
+
this._circuitBreaker.set(provider, state);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Check if a provider's circuit is open (should be skipped). */
|
|
154
|
+
isCircuitOpen(provider: string): boolean {
|
|
155
|
+
const state = this._circuitBreaker.get(provider);
|
|
156
|
+
if (!state) return false;
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
if (now - state.lastFailureTime > Agent.CIRCUIT_BREAKER_WINDOW_MS) return false;
|
|
159
|
+
return state.failures >= Agent.CIRCUIT_BREAKER_THRESHOLD;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Reset circuit breaker for a provider (called on success). */
|
|
163
|
+
resetCircuit(provider: string): void {
|
|
164
|
+
this._circuitBreaker.delete(provider);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Get circuit breaker stats for display. */
|
|
168
|
+
getCircuitBreakerStats(): Array<{ provider: string; failures: number; open: boolean }> {
|
|
169
|
+
const now = Date.now();
|
|
170
|
+
const result: Array<{ provider: string; failures: number; open: boolean }> = [];
|
|
171
|
+
for (const [provider, state] of this._circuitBreaker) {
|
|
172
|
+
const isOpen = now - state.lastFailureTime <= Agent.CIRCUIT_BREAKER_WINDOW_MS &&
|
|
173
|
+
state.failures >= Agent.CIRCUIT_BREAKER_THRESHOLD;
|
|
174
|
+
result.push({ provider, failures: state.failures, open: isOpen });
|
|
175
|
+
}
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private messages(): Message[] {
|
|
180
|
+
const ctx = this.session.context();
|
|
181
|
+
const agentDescs = this.customAgents.map((a) => `${a.name}: ${a.description}${a.tools?.length ? ` (tools: ${a.tools.join(", ")})` : ""}`);
|
|
182
|
+
let sys = buildSystemPrompt(this.session.cwd, agentDescs);
|
|
183
|
+
if (this.extraSystem) sys += "\n\n" + this.extraSystem;
|
|
184
|
+
const msgs: Message[] = [{ role: "system", content: sys }];
|
|
185
|
+
if (this.session.compactedFrom > 0) {
|
|
186
|
+
const digest = this.session.digest ||
|
|
187
|
+
summarize(this.session.messages.slice(0, this.session.compactedFrom));
|
|
188
|
+
msgs.push({ role: "system", content: digest });
|
|
189
|
+
}
|
|
190
|
+
msgs.push(...ctx);
|
|
191
|
+
return msgs;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async *runTurn(userText: string | ContentPart[], signal?: AbortSignal): AsyncGenerator<AgentEvent> {
|
|
195
|
+
this.session.append({ role: "user", content: userText });
|
|
196
|
+
if (!this.session.title) {
|
|
197
|
+
const first = typeof userText === "string" ? userText : textOf(userText);
|
|
198
|
+
this.session.title = first.trim().split("\n")[0]?.slice(0, 80) ?? "session";
|
|
199
|
+
}
|
|
200
|
+
let steps = 0;
|
|
201
|
+
let stopContinues = 0;
|
|
202
|
+
while (steps < this.maxSteps) {
|
|
203
|
+
steps += 1;
|
|
204
|
+
const toolCalls: ToolCall[] = [];
|
|
205
|
+
let assistantText = "";
|
|
206
|
+
for await (const ev of this.streamWithRetry(signal)) {
|
|
207
|
+
if (ev.kind === "error") { yield ev; return; }
|
|
208
|
+
if (ev.kind === "text") { assistantText += ev.text; yield ev; }
|
|
209
|
+
else if (ev.kind === "thinking") yield ev;
|
|
210
|
+
else if (ev.kind === "usage") yield ev;
|
|
211
|
+
else if (ev.kind === "retry") yield ev;
|
|
212
|
+
else if (ev.kind === "fallback") yield ev;
|
|
213
|
+
else if (ev.kind === "tool_calls") toolCalls.push(...ev.toolCalls);
|
|
214
|
+
}
|
|
215
|
+
if (!toolCalls.length) {
|
|
216
|
+
this.session.append({ role: "assistant", content: assistantText });
|
|
217
|
+
// Spend-budget guard (checked on the natural turn end, never mid-stream):
|
|
218
|
+
// priced models only — unpriced ones can't be measured and never trip.
|
|
219
|
+
if (this.budgetUsd > 0) {
|
|
220
|
+
const spent = costUsd(this.session.model, this.session.usage);
|
|
221
|
+
if (spent != null && spent >= this.budgetUsd) {
|
|
222
|
+
this.session.save();
|
|
223
|
+
yield { kind: "error", text: `spend budget reached: $${spent.toFixed(2)} of $${this.budgetUsd.toFixed(2)} (budget_usd in config) — raise it or switch to a cheaper model to continue` };
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Auto-title: after the first exchange, ask the small (or main) model
|
|
228
|
+
// for a short title. Best-effort — failures never affect the turn.
|
|
229
|
+
if (this.autoTitle && !this.session.titleTouched) {
|
|
230
|
+
this.session.titleTouched = true;
|
|
231
|
+
void this.autoTitleSession();
|
|
232
|
+
}
|
|
233
|
+
// Stop hooks: a blocking hook feeds its reason back as a new user turn
|
|
234
|
+
// (capped) — Claude's "keep going until the guard is satisfied" model.
|
|
235
|
+
if (this.tools.hooks?.Stop?.length && stopContinues < MAX_STOP_HOOK_CONTINUES) {
|
|
236
|
+
const hr = await fireHooks(this.tools.hooks, "Stop", {
|
|
237
|
+
session_id: this.tools.sessionId, transcript_path: "", cwd: this.tools.root,
|
|
238
|
+
hook_event_name: "Stop", hookEventName: "Stop",
|
|
239
|
+
stop_hook_active: stopContinues > 0,
|
|
240
|
+
} as any, this.tools.sessionId);
|
|
241
|
+
if (hr.blocked && hr.reason) {
|
|
242
|
+
stopContinues += 1;
|
|
243
|
+
yield { kind: "text", text: `\n⟲ Stop hook: continuing (${stopContinues}/${MAX_STOP_HOOK_CONTINUES})\n` };
|
|
244
|
+
this.session.append({ role: "user", content: `[stop-hook feedback] ${hr.reason}` });
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
this.session.save();
|
|
249
|
+
yield { kind: "done" };
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const assistantMsg: Message & { toolCalls: ToolCall[] } = {
|
|
253
|
+
role: "assistant", content: assistantText, toolCalls,
|
|
254
|
+
};
|
|
255
|
+
this.session.append(assistantMsg as Message);
|
|
256
|
+
// per-tool wall clock for the UI (⎿ completed · 2.3s)
|
|
257
|
+
const durations = new Map<ToolCall, number>();
|
|
258
|
+
// Mark turn start for crash recovery (before tool execution).
|
|
259
|
+
this.session.markTurnStart(this.session.messages.length, toolCalls.map((tc) => ({
|
|
260
|
+
tool: tc.name,
|
|
261
|
+
args: tc.arguments,
|
|
262
|
+
callId: tc.id,
|
|
263
|
+
})));
|
|
264
|
+
// Dependency-aware parallel scheduler: tools whose writeSets don't overlap
|
|
265
|
+
// run concurrently. Read-only tools (read/grep/glob/...) naturally batch
|
|
266
|
+
// together; mutating tools (write/edit/bash/todo/...) run sequentially
|
|
267
|
+
// relative to each other but may overlap with pure reads. GOAT MODE
|
|
268
|
+
// (bypass) widens the batch to ULTRACODE_FANOUT so `task` calls really
|
|
269
|
+
// fan out to 8 as promised in the UI.
|
|
270
|
+
const MAX_PARALLEL = this.tools.goat ? ULTRACODE_FANOUT : 4;
|
|
271
|
+
const results = new Map<ToolCall, ToolResult>();
|
|
272
|
+
const pending: ToolCall[] = [...toolCalls];
|
|
273
|
+
const completed = new Set<string>();
|
|
274
|
+
|
|
275
|
+
while (pending.length > 0) {
|
|
276
|
+
// Build next batch: pick up to MAX_PARALLEL tools that don't conflict
|
|
277
|
+
// with already-running writes (this round) or any completed writes.
|
|
278
|
+
const batch: ToolCall[] = [];
|
|
279
|
+
const remaining = pending.filter((tc) => {
|
|
280
|
+
if (batch.length >= MAX_PARALLEL) return true; // keep in pending
|
|
281
|
+
const deps = getToolSpec(tc.name, tc.arguments);
|
|
282
|
+
// Check conflict against already-running tools in this batch
|
|
283
|
+
const conflicts = batch.some((other) => {
|
|
284
|
+
const otherDeps = getToolSpec(other.name, other.arguments);
|
|
285
|
+
return (
|
|
286
|
+
deps.writeSet.some((w) => otherDeps.writeSet.includes(w)) ||
|
|
287
|
+
deps.readSet.some((r) => otherDeps.writeSet.includes(r)) ||
|
|
288
|
+
otherDeps.readSet.some((r) => deps.writeSet.includes(r))
|
|
289
|
+
);
|
|
290
|
+
});
|
|
291
|
+
// Check conflict against completed writes
|
|
292
|
+
const conflictsCompleted = deps.writeSet.some((w) => completed.has(w)) ||
|
|
293
|
+
deps.readSet.some((r) => completed.has(r));
|
|
294
|
+
if (conflicts || conflictsCompleted) return true;
|
|
295
|
+
batch.push(tc);
|
|
296
|
+
return false;
|
|
297
|
+
});
|
|
298
|
+
pending.length = 0;
|
|
299
|
+
remaining.forEach((tc) => pending.push(tc));
|
|
300
|
+
|
|
301
|
+
if (batch.length === 0) {
|
|
302
|
+
// Deadlock: no tool can proceed (all conflict with completed writes).
|
|
303
|
+
// Fall back to sequential execution of the first pending tool.
|
|
304
|
+
const call = pending.shift()!;
|
|
305
|
+
batch.push(call);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Execute batch. Wrap toolEvent once around the batch: capture the
|
|
309
|
+
// per-call id dispatch assigns (start) and queue streamed output
|
|
310
|
+
// deltas so they can be yielded with the model-side ToolCall id.
|
|
311
|
+
// Always installed — deltas feed the UI even when no toolEvent sink
|
|
312
|
+
// is attached (the TUI consumes runTurn events directly).
|
|
313
|
+
const outerToolEvent = this.tools.toolEvent;
|
|
314
|
+
const callIds = new Map<ToolCall, string>();
|
|
315
|
+
const streamedDeltas: Array<{ callId: string; tool: string; text: string }> = [];
|
|
316
|
+
this.tools.toolEvent = (ev) => {
|
|
317
|
+
try { outerToolEvent?.(ev); } catch { /* sink errors are already isolated */ }
|
|
318
|
+
if (ev.kind === "start") {
|
|
319
|
+
const match = batch.find((c) => c.name === ev.tool && !callIds.has(c));
|
|
320
|
+
if (match) callIds.set(match, ev.callId);
|
|
321
|
+
} else if (ev.kind === "output") {
|
|
322
|
+
streamedDeltas.push({ callId: ev.callId, tool: ev.tool, text: ev.text ?? "" });
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
for (const call of batch) {
|
|
326
|
+
yield { kind: "tool_start", tool: call.name, args: call.arguments, callId: call.id };
|
|
327
|
+
}
|
|
328
|
+
const batchT0 = Date.now();
|
|
329
|
+
if (batch.length === 1) {
|
|
330
|
+
const call = batch[0];
|
|
331
|
+
const result = await (call.name === "task" && !this.disallowedTools.has("task")
|
|
332
|
+
? this.spawnSubagent(call.arguments, signal)
|
|
333
|
+
: this.tools.dispatch(call.name, call.arguments, signal));
|
|
334
|
+
results.set(call, result);
|
|
335
|
+
} else {
|
|
336
|
+
// Parallel execution for the batch
|
|
337
|
+
const settled = await Promise.all(
|
|
338
|
+
batch.map(async (call) => {
|
|
339
|
+
if (call.name === "task" && !this.disallowedTools.has("task")) {
|
|
340
|
+
return this.spawnSubagent(call.arguments, signal);
|
|
341
|
+
}
|
|
342
|
+
return this.tools.dispatch(call.name, call.arguments, signal);
|
|
343
|
+
}),
|
|
344
|
+
);
|
|
345
|
+
batch.forEach((call, k) => results.set(call, settled[k]));
|
|
346
|
+
}
|
|
347
|
+
const batchMs = Date.now() - batchT0;
|
|
348
|
+
for (const call of batch) durations.set(call, batchMs);
|
|
349
|
+
this.tools.toolEvent = outerToolEvent;
|
|
350
|
+
// Forward streamed output mapped to the model-side call id so the UI
|
|
351
|
+
// can attach deltas to the row it created for this ToolCall.
|
|
352
|
+
for (const d of streamedDeltas) {
|
|
353
|
+
const call = batch.find((c) => callIds.get(c) === d.callId);
|
|
354
|
+
yield { kind: "tool_output", callId: call?.id ?? d.callId, tool: d.tool, text: d.text };
|
|
355
|
+
}
|
|
356
|
+
// Record completed writes for conflict detection
|
|
357
|
+
for (const call of batch) {
|
|
358
|
+
const deps = getToolSpec(call.name, call.arguments);
|
|
359
|
+
deps.writeSet.forEach((w) => completed.add(w));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
for (const call of toolCalls) {
|
|
363
|
+
const result = results.get(call)!;
|
|
364
|
+
this.session.append({
|
|
365
|
+
role: "tool",
|
|
366
|
+
content: result.content ?? result.output.slice(0, 60_000),
|
|
367
|
+
toolCallId: call.id, name: call.name,
|
|
368
|
+
});
|
|
369
|
+
yield { kind: "tool_end", tool: call.name, result: result.output.slice(0, 2000), ok: result.ok, callId: call.id, durationMs: durations.get(call) };
|
|
370
|
+
if (call.name === "todo" && result.ok)
|
|
371
|
+
yield { kind: "todo", todos: this.tools.plan() };
|
|
372
|
+
}
|
|
373
|
+
// Clear crash recovery marker — turn completed successfully.
|
|
374
|
+
this.session.clearTurnMarker();
|
|
375
|
+
this.maybeCompact();
|
|
376
|
+
this.session.save();
|
|
377
|
+
}
|
|
378
|
+
yield { kind: "error", text: `stopped after ${this.maxSteps} steps` };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* One model step with retry: transient failures (429/5xx/network) that
|
|
383
|
+
* happen before any content streams are retried with exponential backoff +
|
|
384
|
+
* jitter, honoring a retry-after hint. Once tokens have flowed we surface
|
|
385
|
+
* the error instead of retrying — re-asking would duplicate partial output.
|
|
386
|
+
*/
|
|
387
|
+
private async *streamWithRetry(signal?: AbortSignal): AsyncGenerator<AgentEvent> {
|
|
388
|
+
for (let attempt = 1; ; attempt++) {
|
|
389
|
+
let sawContent = false;
|
|
390
|
+
let timedOut = false;
|
|
391
|
+
// per-attempt deadline: a hung provider becomes a retryable 408, not a freeze.
|
|
392
|
+
// (manual timer, cleared in finally — AbortSignal.timeout would keep the
|
|
393
|
+
// process alive on its pending timer long after the stream ended)
|
|
394
|
+
const ctrl = new AbortController();
|
|
395
|
+
const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, this.requestTimeoutMs);
|
|
396
|
+
const onUserAbort = () => ctrl.abort();
|
|
397
|
+
signal?.addEventListener("abort", onUserAbort);
|
|
398
|
+
const specs = this.tools.specs().filter((s) => !this.disallowedTools.has(s.name));
|
|
399
|
+
try {
|
|
400
|
+
for await (const ev of this.streamOnce(ctrl.signal, specs)) {
|
|
401
|
+
if (ev.kind === "text" || ev.kind === "thinking" || ev.kind === "tool_calls") sawContent = true;
|
|
402
|
+
yield ev;
|
|
403
|
+
}
|
|
404
|
+
return;
|
|
405
|
+
} catch (e: any) {
|
|
406
|
+
if (timedOut && !signal?.aborted) {
|
|
407
|
+
e = new Error(`request timed out after ${Math.round(this.requestTimeoutMs / 1000)}s`);
|
|
408
|
+
(e as any).status = 408;
|
|
409
|
+
}
|
|
410
|
+
const err = e instanceof GoatError ? e : new GenericError(`${e?.name ?? "Error"}: ${e?.message ?? e}`, {
|
|
411
|
+
suggestion: 'Check provider status or try a different provider'
|
|
412
|
+
});
|
|
413
|
+
const retryable = isRetryableLLMError(e) && !sawContent && attempt < this.maxAttempts && !signal?.aborted;
|
|
414
|
+
if (!retryable) {
|
|
415
|
+
// Primary is out of retries (or hit a hard error like quota/auth).
|
|
416
|
+
// Before killing the turn, walk the fallback chain — each entry gets
|
|
417
|
+
// one shot; the first that streams content wins and sticks for the
|
|
418
|
+
// rest of the session (this.client / session.model are swapped).
|
|
419
|
+
if (!sawContent && !signal?.aborted && this.fallbacks.length) {
|
|
420
|
+
const from = this.session.model;
|
|
421
|
+
const reason = String(e?.message ?? e).slice(0, 160);
|
|
422
|
+
let switched = false;
|
|
423
|
+
while (this.fallbacks.length) {
|
|
424
|
+
const fb = this.fallbacks.shift()!;
|
|
425
|
+
// Extract provider ID from model string (format: "provider/model")
|
|
426
|
+
const fbProvider = fb.model.split("/")[0];
|
|
427
|
+
// Skip if circuit is open for this provider
|
|
428
|
+
if (this.isCircuitOpen(fbProvider)) {
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const fbCtrl = new AbortController();
|
|
432
|
+
const fbTimer = setTimeout(() => fbCtrl.abort(), this.requestTimeoutMs);
|
|
433
|
+
const onFbAbort = () => fbCtrl.abort();
|
|
434
|
+
signal?.addEventListener("abort", onFbAbort);
|
|
435
|
+
try {
|
|
436
|
+
for await (const ev of this.streamOnce(fbCtrl.signal, specs, fb.client, fb.model)) {
|
|
437
|
+
if (ev.kind === "text" || ev.kind === "thinking" || ev.kind === "tool_calls") {
|
|
438
|
+
if (!switched) {
|
|
439
|
+
switched = true;
|
|
440
|
+
this.client = fb.client;
|
|
441
|
+
this.session.model = fb.model;
|
|
442
|
+
this.resetCircuit(fbProvider); // Success — reset circuit
|
|
443
|
+
yield { kind: "fallback", from, to: fb.model, reason };
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
yield ev;
|
|
447
|
+
}
|
|
448
|
+
if (switched) return; // stream completed on the fallback
|
|
449
|
+
} catch (fe: any) {
|
|
450
|
+
this.recordFailure(fbProvider); // Record failure in circuit breaker
|
|
451
|
+
if (switched) {
|
|
452
|
+
// already streamed partial output here — re-falling-back would
|
|
453
|
+
// duplicate it; surface the error instead (Claude semantics)
|
|
454
|
+
yield { kind: "error", text: `${fe?.name ?? "Error"}: ${fe?.message ?? fe}` };
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
/* this fallback failed pre-content — try the next */
|
|
458
|
+
} finally {
|
|
459
|
+
clearTimeout(fbTimer);
|
|
460
|
+
signal?.removeEventListener("abort", onFbAbort);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (switched) return;
|
|
464
|
+
yield { kind: "error", text: `all providers failed — ${err.code}: ${err.message}` };
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
yield { kind: "error", text: `${err.code}: ${err.message}\n 💡 ${err.suggestion ?? ''}` };
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const backoff = Math.min(RETRY_MAX_MS, this.retryBaseMs * 2 ** (attempt - 1));
|
|
471
|
+
const header = (e as any)?.retryAfterSec;
|
|
472
|
+
const waitMs = Math.min(
|
|
473
|
+
RETRY_MAX_MS,
|
|
474
|
+
Number.isFinite(header) && header! > 0 ? Math.round(header! * 1000) : Math.round(backoff * (0.75 + Math.random() * 0.5)),
|
|
475
|
+
);
|
|
476
|
+
yield { kind: "retry", attempt, waitMs, reason: String(e?.message ?? e).slice(0, 160) };
|
|
477
|
+
try {
|
|
478
|
+
await sleep(waitMs, signal);
|
|
479
|
+
} catch {
|
|
480
|
+
yield { kind: "error", text: "interrupted during retry" };
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
} finally {
|
|
484
|
+
clearTimeout(timer);
|
|
485
|
+
signal?.removeEventListener("abort", onUserAbort);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private async *streamOnce(signal?: AbortSignal, specs?: ToolSpec[],
|
|
491
|
+
client?: ChatClient, model?: string): AsyncGenerator<AgentEvent> {
|
|
492
|
+
for await (const ev of (client ?? this.client).streamChat(
|
|
493
|
+
this.messages(), specs ?? this.tools.specs(),
|
|
494
|
+
{ model: modelId(model ?? this.session.model), maxTokens: this.maxTokens, temperature: this.temperature, signal, cache: this.cache },
|
|
495
|
+
)) {
|
|
496
|
+
if (ev.textDelta) yield { kind: "text", text: ev.textDelta };
|
|
497
|
+
else if (ev.thinkingDelta) yield { kind: "thinking", text: ev.thinkingDelta };
|
|
498
|
+
else if (ev.usage) {
|
|
499
|
+
this.session.usage.in += ev.usage.prompt;
|
|
500
|
+
this.session.usage.out += ev.usage.completion;
|
|
501
|
+
// true context size = everything the model saw this call (uncached +
|
|
502
|
+
// cached prompt tokens)
|
|
503
|
+
this.lastPromptTokens = ev.usage.prompt + (ev.usage.cacheRead ?? 0) + (ev.usage.cacheWrite ?? 0);
|
|
504
|
+
if (ev.usage.cacheRead) this.session.usage.cacheRead = (this.session.usage.cacheRead ?? 0) + ev.usage.cacheRead;
|
|
505
|
+
if (ev.usage.cacheWrite) this.session.usage.cacheWrite = (this.session.usage.cacheWrite ?? 0) + ev.usage.cacheWrite;
|
|
506
|
+
yield { kind: "usage", text: `${ev.usage.prompt}+${ev.usage.completion} tok`, usage: ev.usage };
|
|
507
|
+
}
|
|
508
|
+
else if (ev.toolCalls) yield { kind: "tool_calls", toolCalls: ev.toolCalls };
|
|
509
|
+
else if (ev.error) yield { kind: "error", text: ev.error };
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Sub-agent: fresh context (no history bleed), cloned ToolKit so undo,
|
|
515
|
+
* permission rules, hooks and MCP all apply independently. Explore mode
|
|
516
|
+
* = read-only toolset. Returns the sub-agent's final text as the tool
|
|
517
|
+
* result.
|
|
518
|
+
*
|
|
519
|
+
* The cloned toolkit gets a fresh session with a "sub-" prefixed id so
|
|
520
|
+
* session fork metadata can track parent -> child relationships.
|
|
521
|
+
*/
|
|
522
|
+
private async spawnSubagent(args: Record<string, unknown>, signal?: AbortSignal): Promise<{ ok: boolean; output: string }> {
|
|
523
|
+
const prompt = String(args.prompt ?? "").trim();
|
|
524
|
+
if (!prompt) return { ok: false, output: "task requires a prompt" };
|
|
525
|
+
const description = String(args.description ?? "subagent").slice(0, 60);
|
|
526
|
+
const agentType = String(args.subagent_type ?? "");
|
|
527
|
+
const explore = agentType === "explore";
|
|
528
|
+
// custom agent types (loaded from ./.goat/agents, ./agents, ~/.goatcode/agents)
|
|
529
|
+
const custom = this.customAgents.find((a) => a.name === agentType);
|
|
530
|
+
if (agentType && agentType !== "general" && agentType !== "explore" && !custom)
|
|
531
|
+
return { ok: false, output: `unknown subagent_type "${agentType}" — available: general, explore${this.customAgents.length ? ", " + this.customAgents.map((a) => a.name).join(", ") : ""}` };
|
|
532
|
+
// explore = read-only; general and custom agents run with their documented
|
|
533
|
+
// toolsets. task/undo/computer stay off-limits for every subagent.
|
|
534
|
+
const disallowed = new Set<string>(["task", "undo", "computer"]);
|
|
535
|
+
if (explore) disallowed.add("write"), disallowed.add("edit"), disallowed.add("multiedit"), disallowed.add("bash");
|
|
536
|
+
// a custom agent's tool allowlist hides everything not listed (task/undo
|
|
537
|
+
// are blocked again below regardless of what the allowlist contains)
|
|
538
|
+
if (custom?.tools?.length) {
|
|
539
|
+
const allowed = new Set(custom.tools);
|
|
540
|
+
for (const s of this.tools.specs()) if (!allowed.has(s.name)) disallowed.add(s.name);
|
|
541
|
+
}
|
|
542
|
+
disallowed.add("task"); // subagents never spawn subagents
|
|
543
|
+
disallowed.add("undo"); // and never touch the undo stack
|
|
544
|
+
|
|
545
|
+
// --- isolated toolkit clone ---
|
|
546
|
+
const subToolKit = this.tools.clone();
|
|
547
|
+
subToolKit.parentSessionId = this.session.id;
|
|
548
|
+
const forkIdx = (this.session.subagentForks?.length ?? 0);
|
|
549
|
+
subToolKit.forkIndex = forkIdx;
|
|
550
|
+
|
|
551
|
+
// resolve the child's model: a custom agent's `model:` override wins,
|
|
552
|
+
// explore agents route to the cheap model when configured, else the parent's
|
|
553
|
+
let childClient = explore && this.smallClient ? this.smallClient : this.client;
|
|
554
|
+
if (custom?.model && this.resolveClientFor) {
|
|
555
|
+
try { childClient = await this.resolveClientFor(custom.model); }
|
|
556
|
+
catch { /* unresolvable override — fall back to the parent client */ }
|
|
557
|
+
}
|
|
558
|
+
const forkSession = new Session({
|
|
559
|
+
id: `sub-${crypto.randomUUID()}`,
|
|
560
|
+
cwd: this.session.cwd,
|
|
561
|
+
model: custom?.model ?? this.session.model,
|
|
562
|
+
});
|
|
563
|
+
forkSession.title = `subagent: ${description}`;
|
|
564
|
+
// record the fork in the parent session
|
|
565
|
+
this.session.addSubagentFork({
|
|
566
|
+
childId: forkSession.id,
|
|
567
|
+
description,
|
|
568
|
+
explore,
|
|
569
|
+
startedAt: Date.now(),
|
|
570
|
+
});
|
|
571
|
+
const child = new Agent({
|
|
572
|
+
client: childClient,
|
|
573
|
+
session: forkSession, tools: subToolKit,
|
|
574
|
+
maxTokens: this.maxTokens, temperature: this.temperature,
|
|
575
|
+
maxSteps: SUBAGENT_MAX_STEPS,
|
|
576
|
+
extraSystem: [this.extraSystem, custom?.body ? `## Agent: ${custom.name}\n\n${custom.body}` : ""]
|
|
577
|
+
.filter(Boolean).join("\n\n"),
|
|
578
|
+
retryBaseMs: this.retryBaseMs, maxAttempts: this.maxAttempts,
|
|
579
|
+
requestTimeoutMs: this.requestTimeoutMs, disallowedTools: disallowed,
|
|
580
|
+
});
|
|
581
|
+
let text = "";
|
|
582
|
+
let stepsUsed = 0;
|
|
583
|
+
let error = "";
|
|
584
|
+
for await (const ev of child.runTurn(prompt, signal)) {
|
|
585
|
+
if (ev.kind === "text") text += ev.text;
|
|
586
|
+
else if (ev.kind === "tool_start") stepsUsed++;
|
|
587
|
+
else if (ev.kind === "error") error = ev.text;
|
|
588
|
+
}
|
|
589
|
+
// record completion in the parent session
|
|
590
|
+
this.session.completeSubagentFork(forkSession.id, { stepsUsed, error });
|
|
591
|
+
|
|
592
|
+
const final = text.trim();
|
|
593
|
+
if (!final)
|
|
594
|
+
return { ok: false, output: `subagent "${description}" produced no answer${error ? `: ${error}` : ""}` };
|
|
595
|
+
return { ok: true, output: `[subagent ${description} · ${stepsUsed} tool uses]\n${final.slice(0, 30_000)}` };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Auto-title the session from the first exchange using the small model
|
|
600
|
+
* (fallback: main client). Writes a 3-6 word title, never throws.
|
|
601
|
+
*/
|
|
602
|
+
private async autoTitleSession(): Promise<void> {
|
|
603
|
+
const firstUser = [...this.session.messages].find((m) => m.role === "user");
|
|
604
|
+
if (!firstUser) return;
|
|
605
|
+
const brief = textOf(firstUser.content).replace(/\s+/g, " ").slice(0, 300);
|
|
606
|
+
try {
|
|
607
|
+
let acc = "";
|
|
608
|
+
for await (const ev of (this.smallClient ?? this.client).streamChat(
|
|
609
|
+
[
|
|
610
|
+
{ role: "system", content: "Write a 3-6 word title for a coding session started by this request. Plain text only: no quotes, no punctuation at the end, no preamble." },
|
|
611
|
+
{ role: "user", content: brief },
|
|
612
|
+
],
|
|
613
|
+
[],
|
|
614
|
+
{ model: modelId(this.session.model), maxTokens: 24, temperature: 0.3 },
|
|
615
|
+
)) {
|
|
616
|
+
if (ev.textDelta) acc += ev.textDelta;
|
|
617
|
+
if (ev.error) return;
|
|
618
|
+
}
|
|
619
|
+
const title = acc.trim().replace(/^["'#\s]+|["'.\s]+$/g, "").slice(0, 60);
|
|
620
|
+
if (title) {
|
|
621
|
+
this.session.title = title;
|
|
622
|
+
this.session.save();
|
|
623
|
+
}
|
|
624
|
+
} catch { /* titling is cosmetic — never surface */ }
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
private maybeCompact(): void {
|
|
628
|
+
const total = this.session.messages.reduce((s, m) => s + contentChars(m.content), 0);
|
|
629
|
+
if (total > COMPACT_TRIGGER_CHARS && this.session.messages.length > 12) {
|
|
630
|
+
const keep = Math.max(8, Math.floor(this.session.messages.length / 3));
|
|
631
|
+
let cut = this.session.messages.length - keep;
|
|
632
|
+
while (cut < this.session.messages.length && this.session.messages[cut]?.role === "tool") cut++;
|
|
633
|
+
if (cut < this.session.messages.length) this.session.compactedFrom = cut;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Model-written compaction (Claude Code /compact semantics): ask the model
|
|
639
|
+
* to summarize the fold zone, store it as the digest, move the cut. On any
|
|
640
|
+
* failure fall back to the deterministic digest — compaction never blocks.
|
|
641
|
+
* Returns { folded, summary, model }.
|
|
642
|
+
*/
|
|
643
|
+
async compactNow(signal?: AbortSignal): Promise<{ folded: number; summary: string; model: boolean }> {
|
|
644
|
+
const msgs = this.session.messages;
|
|
645
|
+
const keep = Math.max(8, Math.floor(msgs.length / 3));
|
|
646
|
+
let cut = Math.max(0, msgs.length - keep);
|
|
647
|
+
while (cut < msgs.length && msgs[cut]?.role === "tool") cut++;
|
|
648
|
+
if (cut <= this.session.compactedFrom)
|
|
649
|
+
return { folded: 0, summary: "", model: false };
|
|
650
|
+
const fold = msgs.slice(this.session.compactedFrom, cut);
|
|
651
|
+
const transcript = fold
|
|
652
|
+
.map((m) => `${m.role}${m.toolCalls?.length ? `(${m.toolCalls.map((tc) => tc.name).join(",")})` : ""}: ${textOf(m.content).slice(0, 700)}`)
|
|
653
|
+
.join("\n")
|
|
654
|
+
.slice(0, 120_000);
|
|
655
|
+
let summary = "";
|
|
656
|
+
let usedModel = false;
|
|
657
|
+
try {
|
|
658
|
+
let acc = "";
|
|
659
|
+
for await (const ev of (this.smallClient ?? this.client).streamChat(
|
|
660
|
+
[
|
|
661
|
+
{ role: "system", content: "You compress coding-agent transcripts. Write a dense continuation summary of the transcript below: user goals and constraints, decisions made, files created/edited (paths), current state, and open threads. Under 500 words. Plain text, no preamble." },
|
|
662
|
+
{ role: "user", content: transcript },
|
|
663
|
+
],
|
|
664
|
+
[],
|
|
665
|
+
{ model: modelId(this.session.model), maxTokens: 1024, temperature: 0.2, signal },
|
|
666
|
+
)) {
|
|
667
|
+
if (ev.textDelta) acc += ev.textDelta;
|
|
668
|
+
if (ev.error) throw new Error(ev.error);
|
|
669
|
+
}
|
|
670
|
+
if (acc.trim()) { summary = acc.trim(); usedModel = true; }
|
|
671
|
+
} catch { /* fall through to digest */ }
|
|
672
|
+
if (!summary) summary = summarize(fold);
|
|
673
|
+
this.session.digest = this.session.digest
|
|
674
|
+
? this.session.digest + "\n\n" + summary
|
|
675
|
+
: summary;
|
|
676
|
+
this.session.compactedFrom = cut;
|
|
677
|
+
this.session.save();
|
|
678
|
+
return { folded: cut, summary, model: usedModel };
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
export function modelId(sessionModel: string): string {
|
|
683
|
+
const i = sessionModel.indexOf("/");
|
|
684
|
+
return i > 0 ? sessionModel.slice(i + 1) : sessionModel;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Sleep that rejects early if the abort signal fires (esc during backoff). */
|
|
688
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
689
|
+
return new Promise((resolve, reject) => {
|
|
690
|
+
if (signal?.aborted) return reject(new Error("aborted"));
|
|
691
|
+
const onAbort = () => { clearTimeout(t); reject(new Error("aborted")); };
|
|
692
|
+
const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
|
|
693
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
694
|
+
});
|
|
695
|
+
}
|