@saturn-universe/runtime 0.0.0-stage → 0.1.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.
@@ -0,0 +1,905 @@
1
+ import { configForDerivedAgent, isLimited, normalizeFileUriForPlatform, settledModelTokens, } from '@saturn-universe/core';
2
+ const readonlyDisallowedTools = new Set([
3
+ 'edit_file',
4
+ 'write_file',
5
+ 'run_process',
6
+ 'start_process',
7
+ 'write_process',
8
+ 'stop_process',
9
+ ]);
10
+ const searchMetaTools = new Set(['submit_plan', 'explore_hypotheses']);
11
+ const verificationTools = new Set(['run_process', 'run_readonly_command', 'read_process']);
12
+ const inspectionTools = new Set([
13
+ 'list_dir',
14
+ 'read_file',
15
+ 'search_files',
16
+ 'glob',
17
+ 'grep',
18
+ 'run_readonly_command',
19
+ 'read_tool_result',
20
+ 'read_process',
21
+ ]);
22
+ export async function driveSelectiveSearch(d, scope, request, signal) {
23
+ const { runId } = scope;
24
+ const searchConfig = request.searchConfig;
25
+ const maxRollouts = Math.max(1, searchConfig.maxRollouts ?? 6);
26
+ const branchFactor = Math.max(1, Math.min(maxRollouts, searchConfig.branchFactor ?? Math.max(2, request.initialHypotheses.length || 2)));
27
+ const maxDepth = Math.max(1, searchConfig.maxDepth ?? 2);
28
+ const concurrency = Math.max(1, Math.min(4, searchConfig.concurrency ?? 2));
29
+ const maxBudgetRatio = searchConfig.maxBudgetRatio ?? 0.4;
30
+ const maxBranchSteps = Math.max(2, searchConfig.maxBranchSteps ?? 8);
31
+ let trees = (await d.state.searches?.(runId)) ?? [];
32
+ let tree = trees.find((item) => item.searchId === request.searchId);
33
+ if (!tree) {
34
+ await d.journal.append(`search:${runId}:${request.searchId}:start`, [
35
+ d.journal.event('run.search.started', scope, {
36
+ searchId: request.searchId,
37
+ trigger: request.trigger,
38
+ anchorAgentSessionId: request.anchorAgentSessionId,
39
+ goal: request.goal,
40
+ isolation: request.isolation,
41
+ maxRollouts,
42
+ branchFactor,
43
+ maxDepth,
44
+ concurrency,
45
+ }),
46
+ ]);
47
+ trees = (await d.state.searches?.(runId)) ?? [];
48
+ tree = trees.find((item) => item.searchId === request.searchId);
49
+ }
50
+ if (tree && tree.status !== 'running') {
51
+ return resultFromTree(tree);
52
+ }
53
+ const mainExecutionSearch = request.phase === 'execution' && request.isolation === 'readonly';
54
+ const runStartState = await d.state.run(runId);
55
+ const startTokens = searchTokenUsage(runStartState);
56
+ const firstBranch = tree?.branches[0];
57
+ const tokenCeiling = mainExecutionSearch && isLimited(request.baseConfig.limits.maxTotalTokens)
58
+ ? firstBranch
59
+ ? (await d.environment.load(runId, firstBranch.agentSessionId)).config.limits.maxTotalTokens
60
+ : startTokens +
61
+ Math.floor((request.baseConfig.limits.maxTotalTokens - startTokens) * Math.min(1, maxBudgetRatio))
62
+ : undefined;
63
+ const anchorSurface = d.surface
64
+ ? await d.surface.read(request.anchorAgentSessionId).catch(() => undefined)
65
+ : undefined;
66
+ const anchorBrief = !mainExecutionSearch && anchorSurface ? buildAnchorBrief(anchorSurface, request.anchorTurnId) : '';
67
+ const handles = new Map();
68
+ const reflections = [];
69
+ const expandedParents = new Set();
70
+ const evaluated = new Map();
71
+ let nextBranchNum = 1;
72
+ let widerRound = 0;
73
+ if (tree) {
74
+ for (const branch of tree.branches) {
75
+ const parsedNum = Number(/^b(\d+)$/.exec(branch.branchId)?.[1] ?? '0');
76
+ if (parsedNum >= nextBranchNum)
77
+ nextBranchNum = parsedNum + 1;
78
+ if (branch.parentBranchId)
79
+ expandedParents.add(branch.parentBranchId);
80
+ if (branch.status !== 'running') {
81
+ evaluated.set(branch.branchId, branch);
82
+ if (branch.reflection)
83
+ reflections.push(branch.reflection);
84
+ }
85
+ const env = await d.environment.load(runId, branch.agentSessionId).catch(() => undefined);
86
+ const fsPath = env ? uriToPath(env.workingDirectory) : request.rootWorkingDirectory;
87
+ handles.set(branch.branchId, {
88
+ searchId: request.searchId,
89
+ branchId: branch.branchId,
90
+ kind: branch.workspaceKind,
91
+ workingDirectory: fsPath,
92
+ ...(branch.degradedToReadonly ? { degradedToReadonly: true } : {}),
93
+ });
94
+ }
95
+ }
96
+ const seedQueue = normalizeInitialHypotheses(request.initialHypotheses, request.goal, branchFactor);
97
+ let nextSeedIndex = tree
98
+ ? Math.min(seedQueue.length, tree.branches.filter((b) => b.parentBranchId === null).length)
99
+ : 0;
100
+ try {
101
+ // 1. Resume any branches that were already running before a crash/restart.
102
+ if (tree) {
103
+ const runningBranches = tree.branches.filter((b) => b.status === 'running');
104
+ if (runningBranches.length > 0) {
105
+ const turns = await d.state.turns(runId);
106
+ const resumedWave = [];
107
+ for (const branch of runningBranches) {
108
+ const branchTurn = turns.filter((t) => t.agentSessionId === branch.agentSessionId).at(-1);
109
+ if (!branchTurn)
110
+ continue;
111
+ resumedWave.push({
112
+ spec: {
113
+ branchId: branch.branchId,
114
+ parentBranchId: branch.parentBranchId,
115
+ depth: branch.depth,
116
+ mode: branch.mode,
117
+ hypothesis: branch.hypothesis,
118
+ strategy: branch.strategy,
119
+ },
120
+ agentSessionId: branch.agentSessionId,
121
+ turnId: branchTurn.id,
122
+ inputMessageId: branchTurn.inputMessageId,
123
+ handle: handles.get(branch.branchId),
124
+ });
125
+ }
126
+ if (resumedWave.length > 0) {
127
+ await executeWave(resumedWave);
128
+ }
129
+ }
130
+ }
131
+ // 2. Selective Tree Search expansion waves.
132
+ while ((!hasSolvedBranch() || (mainExecutionSearch && nextSeedIndex < seedQueue.length)) &&
133
+ totalBranchCount() < maxRollouts) {
134
+ if (signal.aborted || (await d.state.run(runId)).status === 'cancelling')
135
+ break;
136
+ const runNow = await d.state.run(runId);
137
+ if ((tokenCeiling !== undefined && searchTokenUsage(runNow) >= tokenCeiling) ||
138
+ !hasSearchBudget(runNow, startTokens, request.baseConfig, maxBudgetRatio, Date.parse(d.now()))) {
139
+ break;
140
+ }
141
+ const remainingSlots = maxRollouts - totalBranchCount();
142
+ const waveSpecs = pickNextWave(remainingSlots);
143
+ if (!waveSpecs.length)
144
+ break;
145
+ const activeWave = [];
146
+ for (const spec of waveSpecs) {
147
+ if (signal.aborted)
148
+ break;
149
+ const created = await materializeBranch(spec);
150
+ activeWave.push(created);
151
+ }
152
+ if (!activeWave.length)
153
+ break;
154
+ await executeWave(activeWave);
155
+ }
156
+ }
157
+ finally {
158
+ // Ensure winner workspace is merged before cleaning up managed branch directories.
159
+ }
160
+ const allBranches = [...evaluated.values()];
161
+ const winner = selectWinner(allBranches);
162
+ let mergedFiles = [];
163
+ if (winner) {
164
+ const winnerHandle = handles.get(winner.branchId);
165
+ if (winnerHandle &&
166
+ winnerHandle.kind !== 'shared_readonly' &&
167
+ !winner.degradedToReadonly &&
168
+ d.workspace) {
169
+ try {
170
+ const merged = await d.workspace.mergeBranchWorkspace(winnerHandle, request.rootWorkingDirectory);
171
+ mergedFiles = merged.mergedFiles;
172
+ }
173
+ catch {
174
+ // Keep mergedFiles empty if merge fails; branches are still cleaned up below.
175
+ }
176
+ }
177
+ }
178
+ if (d.workspace) {
179
+ for (const handle of handles.values()) {
180
+ if (handle.kind === 'shared_readonly')
181
+ continue;
182
+ await d.workspace.cleanupBranchWorkspace(handle, request.rootWorkingDirectory).catch(() => { });
183
+ }
184
+ }
185
+ const outcome = winner
186
+ ? winner.status === 'solved'
187
+ ? 'solved'
188
+ : 'best_candidate'
189
+ : 'exhausted';
190
+ const winnerSummary = winner
191
+ ? (winner.summary ?? winner.hypothesis)
192
+ : 'No search branch succeeded within budget.';
193
+ const mergedReflections = dedupeStrings(reflections);
194
+ const degradedToReadonly = allBranches.some((b) => Boolean(b.degradedToReadonly));
195
+ if (!mainExecutionSearch || (await d.state.run(runId)).status === 'running')
196
+ await d.journal.append(`search:${runId}:${request.searchId}:converge`, [
197
+ d.journal.event('run.search.converged', scope, {
198
+ searchId: request.searchId,
199
+ winnerBranchId: winner?.branchId ?? null,
200
+ outcome,
201
+ winnerSummary,
202
+ mergedReflections,
203
+ ...(mergedFiles.length ? { mergedFiles } : {}),
204
+ }),
205
+ ]);
206
+ return {
207
+ searchId: request.searchId,
208
+ outcome,
209
+ winnerBranchId: winner?.branchId ?? null,
210
+ winnerSummary,
211
+ mergedReflections,
212
+ mergedFiles,
213
+ degradedToReadonly,
214
+ branchSummaries: allBranches.map((branch) => ({
215
+ branchId: branch.branchId,
216
+ hypothesis: branch.hypothesis,
217
+ verdict: branch.status === 'running' ? 'pruned' : branch.status,
218
+ combinedScore: branch.combinedScore ?? 0,
219
+ summary: branch.summary ?? branch.hypothesis,
220
+ ...(branch.reflection ? { reflection: branch.reflection } : {}),
221
+ })),
222
+ };
223
+ function totalBranchCount() {
224
+ return evaluated.size;
225
+ }
226
+ function hasSolvedBranch() {
227
+ for (const b of evaluated.values()) {
228
+ if (b.status === 'solved')
229
+ return true;
230
+ }
231
+ return false;
232
+ }
233
+ function pickNextWave(remainingSlots) {
234
+ const specs = [];
235
+ const waveLimit = Math.min(concurrency, remainingSlots);
236
+ if (evaluated.size === 0) {
237
+ if (mainExecutionSearch)
238
+ nextSeedIndex = Math.min(seedQueue.length, waveLimit);
239
+ for (const seed of seedQueue.slice(0, waveLimit)) {
240
+ specs.push({
241
+ branchId: `b${nextBranchNum++}`,
242
+ parentBranchId: null,
243
+ depth: 1,
244
+ mode: 'wider',
245
+ hypothesis: seed.summary,
246
+ strategy: seed.strategy,
247
+ ...(seed.verification ? { verification: seed.verification } : {}),
248
+ });
249
+ }
250
+ return specs;
251
+ }
252
+ if (nextSeedIndex < seedQueue.length) {
253
+ const slice = seedQueue.slice(nextSeedIndex, nextSeedIndex + waveLimit);
254
+ nextSeedIndex += slice.length;
255
+ for (const seed of slice) {
256
+ specs.push({
257
+ branchId: `b${nextBranchNum++}`,
258
+ parentBranchId: null,
259
+ depth: 1,
260
+ mode: 'wider',
261
+ hypothesis: seed.summary,
262
+ strategy: seed.strategy,
263
+ ...(seed.verification ? { verification: seed.verification } : {}),
264
+ });
265
+ }
266
+ return specs;
267
+ }
268
+ // Go Deeper if a promising branch has high score and depth < maxDepth.
269
+ const promising = [...evaluated.values()]
270
+ .filter((b) => b.status === 'promising' &&
271
+ (b.combinedScore ?? 0) >= 0.6 &&
272
+ b.depth < maxDepth &&
273
+ !expandedParents.has(b.branchId))
274
+ .sort((a, b) => (b.combinedScore ?? 0) - (a.combinedScore ?? 0));
275
+ if (promising.length > 0) {
276
+ const parent = promising[0];
277
+ expandedParents.add(parent.branchId);
278
+ specs.push({
279
+ branchId: `b${nextBranchNum++}`,
280
+ parentBranchId: parent.branchId,
281
+ depth: parent.depth + 1,
282
+ mode: 'deeper',
283
+ hypothesis: `Refine "${parent.hypothesis}"`,
284
+ strategy: `Build on prior branch ${parent.branchId} findings (${parent.summary ?? parent.hypothesis}) and complete verification.`,
285
+ });
286
+ return specs;
287
+ }
288
+ // Go Wider only if no promising candidate exists yet (all pruned) and rollouts remain.
289
+ const hasPromising = [...evaluated.values()].some((b) => b.status === 'promising');
290
+ if (!hasPromising && widerRound < 2) {
291
+ widerRound += 1;
292
+ specs.push({
293
+ branchId: `b${nextBranchNum++}`,
294
+ parentBranchId: null,
295
+ depth: 1,
296
+ mode: 'wider',
297
+ hypothesis: `Alternative approach #${widerRound} for: ${request.goal}`,
298
+ strategy: `Previous hypotheses failed or stalled. Try a fundamentally different diagnostic/fix angle avoiding recorded dead ends.`,
299
+ });
300
+ }
301
+ return specs;
302
+ }
303
+ async function materializeBranch(spec) {
304
+ const handle = d.workspace
305
+ ? await d.workspace.createBranchWorkspace({
306
+ rootDir: request.rootWorkingDirectory,
307
+ searchId: request.searchId,
308
+ branchId: spec.branchId,
309
+ mode: request.isolation,
310
+ ...(searchConfig.maxCopyBytes !== undefined ? { maxCopyBytes: searchConfig.maxCopyBytes } : {}),
311
+ })
312
+ : {
313
+ searchId: request.searchId,
314
+ branchId: spec.branchId,
315
+ kind: 'shared_readonly',
316
+ workingDirectory: request.rootWorkingDirectory,
317
+ };
318
+ handles.set(spec.branchId, handle);
319
+ const effectiveReadonly = request.isolation === 'readonly' || Boolean(handle.degradedToReadonly);
320
+ const branchAgentId = d.id();
321
+ const branchAgentSessionId = d.id();
322
+ const scopedBase = configForDerivedAgent(request.baseConfig, 'search', branchAgentSessionId);
323
+ const frozenBase = d.freezeBranchConfig
324
+ ? await d.freezeBranchConfig(scopedBase, {
325
+ readonly: effectiveReadonly,
326
+ phase: request.phase,
327
+ })
328
+ : scopedBase;
329
+ const currentRun = await d.state.run(runId);
330
+ const branchConfig = sanitizeBranchConfig(frozenBase, effectiveReadonly, currentRun, maxBranchSteps, mainExecutionSearch, tokenCeiling);
331
+ const branchTurnId = d.id();
332
+ const branchMessageId = d.id();
333
+ const createdAt = d.now();
334
+ const workingDirectoryUri = handle.kind === 'shared_readonly'
335
+ ? mainExecutionSearch
336
+ ? pathToFileUri(handle.workingDirectory)
337
+ : request.rootWorkingDirectoryUri
338
+ : pathToFileUri(handle.workingDirectory);
339
+ const branchScope = {
340
+ kind: 'agent_session',
341
+ workspaceId: scope.workspaceId,
342
+ sessionId: scope.sessionId,
343
+ runId,
344
+ agentId: branchAgentId,
345
+ agentSessionId: branchAgentSessionId,
346
+ };
347
+ const promptText = buildBranchPrompt(anchorBrief, request.goal, spec, reflections, effectiveReadonly);
348
+ const events = [
349
+ d.journal.event('agent.created', { kind: 'workspace', workspaceId: scope.workspaceId }, {
350
+ agent: {
351
+ id: branchAgentId,
352
+ workspaceId: scope.workspaceId,
353
+ role: 'specialist',
354
+ defaultScope: 'run',
355
+ modeRef: branchConfig.modeRef,
356
+ createdAt,
357
+ },
358
+ }),
359
+ d.journal.event('agent_session.created', branchScope, {
360
+ agentSession: {
361
+ id: branchAgentSessionId,
362
+ workspaceId: scope.workspaceId,
363
+ agentId: branchAgentId,
364
+ owner: { scope: 'run', sessionId: scope.sessionId, runId },
365
+ status: 'open',
366
+ createdAt,
367
+ },
368
+ }),
369
+ d.journal.event('run.agent.attached', scope, {
370
+ membership: {
371
+ runId,
372
+ agentId: branchAgentId,
373
+ agentSessionId: branchAgentSessionId,
374
+ role: 'worker',
375
+ searchBranchId: spec.branchId,
376
+ branchWorkingDirectoryUri: workingDirectoryUri,
377
+ config: branchConfig,
378
+ },
379
+ }),
380
+ d.journal.event('turn.queued', branchScope, {
381
+ turnId: branchTurnId,
382
+ ordinal: 1,
383
+ inputMessageId: branchMessageId,
384
+ }),
385
+ d.journal.event('message.user.added', branchScope, {
386
+ message: {
387
+ id: branchMessageId,
388
+ agentSessionId: branchAgentSessionId,
389
+ runId,
390
+ turnId: branchTurnId,
391
+ role: 'user',
392
+ content: [{ type: 'text', text: promptText }],
393
+ },
394
+ }),
395
+ d.journal.event('run.search.branch.created', scope, {
396
+ searchId: request.searchId,
397
+ branchId: spec.branchId,
398
+ parentBranchId: spec.parentBranchId,
399
+ depth: spec.depth,
400
+ mode: spec.mode,
401
+ hypothesis: spec.hypothesis,
402
+ strategy: spec.strategy,
403
+ agentSessionId: branchAgentSessionId,
404
+ workspaceKind: handle.kind,
405
+ ...(handle.degradedToReadonly ? { degradedToReadonly: true } : {}),
406
+ }),
407
+ ];
408
+ await d.journal.append(`search:${runId}:${request.searchId}:branch:${spec.branchId}`, events);
409
+ return {
410
+ spec,
411
+ agentSessionId: branchAgentSessionId,
412
+ turnId: branchTurnId,
413
+ inputMessageId: branchMessageId,
414
+ handle,
415
+ };
416
+ }
417
+ async function executeWave(wave) {
418
+ const pending = new Map();
419
+ for (const branch of wave) {
420
+ const input = {
421
+ workspaceId: scope.workspaceId,
422
+ sessionId: scope.sessionId,
423
+ runId,
424
+ agentId: (await d.environment.load(runId, branch.agentSessionId)).route.agentId,
425
+ agentSessionId: branch.agentSessionId,
426
+ turnId: branch.turnId,
427
+ inputMessageId: branch.inputMessageId,
428
+ };
429
+ const promise = d.agent.resume(input, signal).then(async (result) => {
430
+ if (mainExecutionSearch && result.status === 'paused')
431
+ await d.agent.resume(input, AbortSignal.abort());
432
+ return { branch, result };
433
+ });
434
+ pending.set(branch.spec.branchId, promise);
435
+ }
436
+ while (pending.size > 0) {
437
+ const { branch, result } = await Promise.race(pending.values());
438
+ pending.delete(branch.spec.branchId);
439
+ if (mainExecutionSearch && (await d.state.run(runId)).status !== 'running')
440
+ continue;
441
+ const branchSurface = d.surface
442
+ ? await d.surface.read(branch.agentSessionId).catch(() => undefined)
443
+ : undefined;
444
+ const evaluation = evaluateBranchResult(branch.spec, result, branchSurface, request.phase);
445
+ await d.journal.append(`search:${runId}:${request.searchId}:eval:${branch.spec.branchId}`, [
446
+ d.journal.event('run.search.branch.evaluated', scope, {
447
+ searchId: request.searchId,
448
+ branchId: branch.spec.branchId,
449
+ ...(evaluation.hardScore !== undefined ? { hardScore: evaluation.hardScore } : {}),
450
+ softScore: evaluation.softScore,
451
+ combinedScore: evaluation.combinedScore,
452
+ verdict: evaluation.verdict,
453
+ summary: evaluation.summary,
454
+ ...(evaluation.reflection ? { reflection: evaluation.reflection } : {}),
455
+ }),
456
+ ]);
457
+ evaluated.set(branch.spec.branchId, {
458
+ branchId: branch.spec.branchId,
459
+ parentBranchId: branch.spec.parentBranchId,
460
+ depth: branch.spec.depth,
461
+ mode: branch.spec.mode,
462
+ hypothesis: branch.spec.hypothesis,
463
+ strategy: branch.spec.strategy,
464
+ agentSessionId: branch.agentSessionId,
465
+ workspaceKind: branch.handle.kind,
466
+ ...(branch.handle.degradedToReadonly ? { degradedToReadonly: true } : {}),
467
+ status: evaluation.verdict,
468
+ ...(evaluation.hardScore !== undefined ? { hardScore: evaluation.hardScore } : {}),
469
+ softScore: evaluation.softScore,
470
+ combinedScore: evaluation.combinedScore,
471
+ summary: evaluation.summary,
472
+ ...(evaluation.reflection ? { reflection: evaluation.reflection } : {}),
473
+ });
474
+ if (evaluation.reflection)
475
+ reflections.push(evaluation.reflection);
476
+ }
477
+ }
478
+ }
479
+ function sanitizeBranchConfig(base, readonlyMode, runState, maxBranchSteps, restrictToInspectionTools = false, tokenCeiling) {
480
+ const { planner: _planner, team: _team, continuation: _continuation, search: _search, checkpoint: _checkpoint, ...rest } = base;
481
+ const allowed = (name) => !searchMetaTools.has(name) && (!readonlyMode || !readonlyDisallowedTools.has(name));
482
+ const snapshot = base.toolSnapshot ??
483
+ (!restrictToInspectionTools ? undefined : { version: base.toolSetVersion, definitions: [] });
484
+ const filteredSnapshot = snapshot
485
+ ? {
486
+ ...snapshot,
487
+ definitions: snapshot.definitions.filter((def) => allowed(def.name) &&
488
+ (!readonlyMode || def.effects === 'read') &&
489
+ (!restrictToInspectionTools || (def.source.kind === 'builtin' && inspectionTools.has(def.name)))),
490
+ }
491
+ : undefined;
492
+ const filteredExtensions = base.contextExtensions
493
+ ? {
494
+ ...base.contextExtensions,
495
+ ...(base.contextExtensions.mode
496
+ ? {
497
+ mode: {
498
+ ...base.contextExtensions.mode,
499
+ ...(base.contextExtensions.mode.allowedTools
500
+ ? { allowedTools: base.contextExtensions.mode.allowedTools.filter(allowed) }
501
+ : {}),
502
+ },
503
+ }
504
+ : {}),
505
+ }
506
+ : undefined;
507
+ return {
508
+ ...rest,
509
+ ...(filteredSnapshot ? { toolSnapshot: filteredSnapshot } : {}),
510
+ ...(base.pluginBindings
511
+ ? {
512
+ pluginBindings: {
513
+ ...base.pluginBindings,
514
+ tools: base.pluginBindings.tools.filter(({ name }) => filteredSnapshot
515
+ ? filteredSnapshot.definitions.some((definition) => definition.name === name)
516
+ : allowed(name)),
517
+ },
518
+ }
519
+ : {}),
520
+ ...(filteredExtensions ? { contextExtensions: filteredExtensions } : {}),
521
+ limits: {
522
+ ...base.limits,
523
+ ...(tokenCeiling === undefined ? {} : { maxTotalTokens: tokenCeiling }),
524
+ maxSteps: isLimited(base.limits.maxSteps)
525
+ ? Math.min(base.limits.maxSteps, runState.stepsStarted + maxBranchSteps)
526
+ : runState.stepsStarted + maxBranchSteps,
527
+ maxModelAttempts: isLimited(base.limits.maxModelAttempts)
528
+ ? Math.min(base.limits.maxModelAttempts, runState.modelAttempts + maxBranchSteps * 2)
529
+ : runState.modelAttempts + maxBranchSteps * 2,
530
+ },
531
+ };
532
+ }
533
+ export function searchTokenUsage(run) {
534
+ return settledModelTokens(run) + run.reservedTokens;
535
+ }
536
+ export function hasSearchBudget(run, startTokens, config, maxBudgetRatio, nowMs) {
537
+ const limits = config.limits;
538
+ const currentTokens = searchTokenUsage(run);
539
+ if (!Number.isFinite(maxBudgetRatio) || maxBudgetRatio <= 0)
540
+ return false;
541
+ if (isLimited(limits.maxTotalTokens)) {
542
+ const remainingTokens = limits.maxTotalTokens - currentTokens;
543
+ const allowedSearchTokens = Math.floor((limits.maxTotalTokens - startTokens) * maxBudgetRatio);
544
+ if (currentTokens - startTokens >= allowedSearchTokens)
545
+ return false;
546
+ if (remainingTokens / limits.maxTotalTokens < 0.2)
547
+ return false;
548
+ }
549
+ if (isLimited(limits.maxSteps) && (limits.maxSteps - run.stepsStarted) / limits.maxSteps < 0.2)
550
+ return false;
551
+ if (isLimited(limits.maxModelAttempts) &&
552
+ (limits.maxModelAttempts - run.modelAttempts) / limits.maxModelAttempts < 0.2)
553
+ return false;
554
+ if (isLimited(limits.maxToolCalls) && run.toolCallsStarted >= limits.maxToolCalls)
555
+ return false;
556
+ if (run.deadlineAt && isLimited(limits.wallTimeMs)) {
557
+ const remainingMs = Date.parse(run.deadlineAt) - nowMs;
558
+ if (!Number.isFinite(remainingMs) || remainingMs / limits.wallTimeMs < 0.2)
559
+ return false;
560
+ }
561
+ return true;
562
+ }
563
+ function evaluateBranchResult(spec, result, surface, phase) {
564
+ if (result.status !== 'completed') {
565
+ const reason = result.status === 'failed'
566
+ ? result.error.message
567
+ : result.status === 'interrupted'
568
+ ? `Interrupted (${result.reason})`
569
+ : `Paused (${result.reason})`;
570
+ return {
571
+ hardScore: 0,
572
+ softScore: 0.1,
573
+ combinedScore: 0.03,
574
+ verdict: 'pruned',
575
+ summary: `${spec.hypothesis} failed: ${reason}`,
576
+ reflection: `Hypothesis "${spec.hypothesis}" did not complete (${reason}).`,
577
+ };
578
+ }
579
+ let totalCalls = 0;
580
+ let successCalls = 0;
581
+ let failedCalls = 0;
582
+ let verifySuccess = false;
583
+ let verifyFailed = false;
584
+ let writeSuccess = false;
585
+ let readSuccess = false;
586
+ let finalText = '';
587
+ if (surface) {
588
+ const callNames = new Map();
589
+ for (const item of surface.items) {
590
+ if (!item.active)
591
+ continue;
592
+ if (item.message.role === 'assistant') {
593
+ for (const call of item.message.toolCalls) {
594
+ callNames.set(call.id, call.toolName);
595
+ }
596
+ const text = renderParts(item.message.content).trim();
597
+ if (text)
598
+ finalText = text;
599
+ }
600
+ else if (item.message.role === 'tool') {
601
+ totalCalls += 1;
602
+ const name = callNames.get(item.message.result.toolCallId) ?? '';
603
+ const outcome = item.message.result.outcome;
604
+ if (outcome.status === 'success') {
605
+ successCalls += 1;
606
+ const processRead = name === 'read_process';
607
+ const processData = outcome.data && typeof outcome.data === 'object' && !Array.isArray(outcome.data)
608
+ ? outcome.data
609
+ : undefined;
610
+ const exitedProcess = processRead && processData?.status === 'exited';
611
+ const exitCode = processRead ? processData?.exit_code : readExitCode(outcome.data);
612
+ if (verificationTools.has(name) && (!processRead || exitedProcess)) {
613
+ if ((processRead && exitCode !== 0) || (exitCode !== undefined && exitCode !== 0)) {
614
+ verifyFailed = true;
615
+ verifySuccess = false;
616
+ }
617
+ else {
618
+ verifySuccess = true;
619
+ verifyFailed = false;
620
+ }
621
+ }
622
+ else if (name === 'edit_file' || name === 'write_file') {
623
+ writeSuccess = true;
624
+ }
625
+ else if (inspectionTools.has(name)) {
626
+ readSuccess = true;
627
+ }
628
+ }
629
+ else {
630
+ failedCalls += 1;
631
+ if (verificationTools.has(name))
632
+ verifyFailed = true;
633
+ }
634
+ }
635
+ }
636
+ }
637
+ let hardScore = 0.35;
638
+ if (verifySuccess && !verifyFailed) {
639
+ hardScore = phase === 'execution' && writeSuccess ? 1.0 : 0.9;
640
+ }
641
+ else if (verifyFailed) {
642
+ hardScore = 0.15;
643
+ }
644
+ else if (totalCalls > 0 && failedCalls > successCalls) {
645
+ hardScore = 0.1;
646
+ }
647
+ else if (readSuccess && failedCalls === 0) {
648
+ hardScore = 0.65;
649
+ }
650
+ else if (writeSuccess && !verifySuccess) {
651
+ hardScore = 0.55;
652
+ }
653
+ const admitsFailure = /(cannot|unable|failed|error|dead end|wrong hypothesis|不存在|失败|无法解决|错误路径)/i.test(finalText);
654
+ const claimsSolved = /(solved|verified|all tests pass|root cause found|confirmed|fixed|通过|已验证|根因)/i.test(finalText);
655
+ let softScore = 0.3;
656
+ if (finalText.length >= 20)
657
+ softScore = 0.55;
658
+ if (finalText.length >= 40 && claimsSolved && !admitsFailure)
659
+ softScore = 0.9;
660
+ if (admitsFailure && !verifySuccess)
661
+ softScore = 0.2;
662
+ const combinedScore = Math.round((hardScore * 0.7 + softScore * 0.3) * 100) / 100;
663
+ const summary = finalText ? truncate(finalText.replace(/\s+/g, ' ').trim(), 280) : spec.hypothesis;
664
+ if (verifySuccess && !verifyFailed && !admitsFailure && (phase === 'execution' || claimsSolved)) {
665
+ return {
666
+ hardScore,
667
+ softScore,
668
+ combinedScore,
669
+ verdict: 'solved',
670
+ summary,
671
+ };
672
+ }
673
+ if (combinedScore < 0.4 || hardScore <= 0.2 || (admitsFailure && !verifySuccess)) {
674
+ return {
675
+ hardScore,
676
+ softScore,
677
+ combinedScore,
678
+ verdict: 'pruned',
679
+ summary,
680
+ reflection: `Avoid "${spec.hypothesis}": ${summary}`,
681
+ };
682
+ }
683
+ return {
684
+ hardScore,
685
+ softScore,
686
+ combinedScore,
687
+ verdict: 'promising',
688
+ summary,
689
+ };
690
+ }
691
+ function selectWinner(branches) {
692
+ const solved = branches.find((b) => b.status === 'solved');
693
+ if (solved)
694
+ return solved;
695
+ const candidates = branches
696
+ .filter((b) => b.status === 'promising')
697
+ .sort((a, b) => (b.combinedScore ?? 0) - (a.combinedScore ?? 0));
698
+ return candidates[0];
699
+ }
700
+ function normalizeInitialHypotheses(seeds, goal, branchFactor) {
701
+ if (seeds.length >= 2)
702
+ return [...seeds];
703
+ const fallback = [
704
+ ...seeds,
705
+ {
706
+ id: 'h-inspect',
707
+ summary: `Direct inspection & verification for: ${truncate(goal, 120)}`,
708
+ strategy: 'Inspect the primary files/symbols involved and verify the most direct hypothesis.',
709
+ },
710
+ {
711
+ id: 'h-alt',
712
+ summary: `Alternative root-cause check for: ${truncate(goal, 120)}`,
713
+ strategy: 'Check caller/config/test interactions or an alternative mechanism if the direct path fails.',
714
+ },
715
+ {
716
+ id: 'h-evidence',
717
+ summary: 'Check whether the reported failure originates in the verification setup.',
718
+ strategy: 'Compare the intended acceptance criteria with the test fixture and environment. Look for a minimal discriminating check.',
719
+ },
720
+ ];
721
+ return fallback.slice(0, Math.max(2, branchFactor));
722
+ }
723
+ function buildAnchorBrief(surface, anchorTurnId) {
724
+ const turnItems = new Map();
725
+ for (const item of surface.items) {
726
+ if (!item.active)
727
+ continue;
728
+ const list = turnItems.get(item.message.turnId);
729
+ if (list)
730
+ list.push(item);
731
+ else
732
+ turnItems.set(item.message.turnId, [item]);
733
+ if (item.message.turnId === anchorTurnId && item.message.role === 'user') {
734
+ // Include up to anchor turn user prompt & prior turns.
735
+ }
736
+ }
737
+ const recent = [...turnItems.entries()].slice(-4);
738
+ const blocks = [];
739
+ for (const [, items] of recent) {
740
+ const lines = [];
741
+ for (const item of items) {
742
+ if (item.message.role === 'user') {
743
+ const text = renderParts(item.message.content).trim();
744
+ if (text)
745
+ lines.push(`User: ${truncate(text, 400)}`);
746
+ }
747
+ else if (item.message.role === 'assistant') {
748
+ const text = renderParts(item.message.content).trim();
749
+ if (text)
750
+ lines.push(`Assistant: ${truncate(text, 400)}`);
751
+ }
752
+ }
753
+ if (lines.length)
754
+ blocks.push(lines.join('\n'));
755
+ }
756
+ return truncate(blocks.join('\n\n'), 3000);
757
+ }
758
+ function buildBranchPrompt(anchorBrief, goal, spec, reflections, readonlyMode) {
759
+ const lines = [];
760
+ if (anchorBrief) {
761
+ lines.push('Shared context brief (background data):', anchorBrief, '');
762
+ }
763
+ lines.push(`Search goal: ${goal}`, `Branch ${spec.branchId} (${spec.mode}, depth=${spec.depth}):`, `Hypothesis: ${spec.hypothesis}`, `Strategy: ${spec.strategy}`);
764
+ if (spec.verification)
765
+ lines.push(`Verification target: ${spec.verification}`);
766
+ if (readonlyMode) {
767
+ lines.push('Workspace mode: read-only inspection (do not attempt file edits).');
768
+ }
769
+ if (reflections.length) {
770
+ lines.push('', 'Dead ends / reflections from prior branches (avoid repeating):');
771
+ for (const r of reflections.slice(-6))
772
+ lines.push(`- ${r}`);
773
+ }
774
+ lines.push('', 'Investigate/execute this single hypothesis using tools, verify your findings, and provide a concise final report stating concrete evidence and whether the hypothesis succeeded or failed.');
775
+ return lines.join('\n');
776
+ }
777
+ function resultFromTree(tree) {
778
+ const outcome = tree.status === 'running' ? 'exhausted' : tree.status;
779
+ return {
780
+ searchId: tree.searchId,
781
+ outcome,
782
+ winnerBranchId: tree.winnerBranchId ?? null,
783
+ winnerSummary: tree.winnerSummary ?? '',
784
+ mergedReflections: tree.mergedReflections,
785
+ mergedFiles: tree.mergedFiles ?? [],
786
+ degradedToReadonly: tree.branches.some((b) => Boolean(b.degradedToReadonly)),
787
+ branchSummaries: tree.branches.map((b) => ({
788
+ branchId: b.branchId,
789
+ hypothesis: b.hypothesis,
790
+ verdict: b.status === 'running' ? 'pruned' : b.status,
791
+ combinedScore: b.combinedScore ?? 0,
792
+ summary: b.summary ?? b.hypothesis,
793
+ ...(b.reflection ? { reflection: b.reflection } : {}),
794
+ })),
795
+ };
796
+ }
797
+ function readExitCode(data) {
798
+ if (!data || typeof data !== 'object' || Array.isArray(data))
799
+ return undefined;
800
+ const exitCode = data.exitCode;
801
+ return typeof exitCode === 'number' ? exitCode : undefined;
802
+ }
803
+ function renderParts(parts) {
804
+ return parts.map((p) => (p.type === 'text' ? p.text : `[${p.type}]`)).join('\n');
805
+ }
806
+ function truncate(text, max) {
807
+ return text.length <= max ? text : `${text.slice(0, Math.max(0, max - 3))}...`;
808
+ }
809
+ function dedupeStrings(values) {
810
+ return [...new Set(values.map((v) => v.trim()).filter(Boolean))];
811
+ }
812
+ function pathToFileUri(fsPath) {
813
+ if (fsPath.startsWith('file://'))
814
+ return fsPath;
815
+ const getBuiltin = process.getBuiltinModule;
816
+ const urlMod = getBuiltin?.('node:url');
817
+ if (urlMod?.pathToFileURL)
818
+ return urlMod.pathToFileURL(fsPath).href;
819
+ const normalized = fsPath.replace(/\\/g, '/');
820
+ return normalized.startsWith('/') ? `file://${normalized}` : `file:///${normalized}`;
821
+ }
822
+ export function extractExploreHypothesesCall(surface, turnId) {
823
+ for (let i = surface.items.length - 1; i >= 0; i--) {
824
+ const item = surface.items[i];
825
+ if (!item.active || item.message.turnId !== turnId || item.message.role !== 'tool')
826
+ continue;
827
+ const outcome = item.message.result.outcome;
828
+ if (outcome.status !== 'success' ||
829
+ !outcome.data ||
830
+ typeof outcome.data !== 'object' ||
831
+ Array.isArray(outcome.data))
832
+ continue;
833
+ const data = outcome.data;
834
+ if (data.kind !== 'explore_hypotheses' ||
835
+ typeof data.goal !== 'string' ||
836
+ !Array.isArray(data.hypotheses))
837
+ continue;
838
+ const hypotheses = [];
839
+ for (const h of data.hypotheses) {
840
+ if (!h || typeof h !== 'object' || Array.isArray(h))
841
+ continue;
842
+ const rec = h;
843
+ if (typeof rec.id === 'string' && typeof rec.summary === 'string' && typeof rec.strategy === 'string') {
844
+ hypotheses.push({
845
+ id: rec.id,
846
+ summary: rec.summary,
847
+ strategy: rec.strategy,
848
+ ...(typeof rec.verification === 'string' && rec.verification.trim()
849
+ ? { verification: rec.verification.trim() }
850
+ : {}),
851
+ });
852
+ }
853
+ }
854
+ if (hypotheses.length >= 2) {
855
+ return {
856
+ goal: data.goal,
857
+ isolation: data.isolation === 'isolated' ? 'isolated' : 'readonly',
858
+ hypotheses,
859
+ };
860
+ }
861
+ }
862
+ return undefined;
863
+ }
864
+ export function formatSearchResultMessage(result, phase) {
865
+ const lines = [
866
+ `Selective tree search (${result.searchId}) converged: outcome=${result.outcome}, winner=${result.winnerBranchId ?? 'none'}.`,
867
+ `Winner summary: ${result.winnerSummary}`,
868
+ ];
869
+ if (result.degradedToReadonly) {
870
+ lines.push('Note: Workspace copy size exceeded limit; search branches ran in shared read-only mode.');
871
+ }
872
+ if (result.mergedFiles.length) {
873
+ lines.push(`Merged files into workspace: ${result.mergedFiles.join(', ')}`);
874
+ }
875
+ if (result.branchSummaries.length) {
876
+ lines.push('Branch evaluations:');
877
+ for (const b of result.branchSummaries) {
878
+ lines.push(`- ${b.branchId} [${b.verdict}, score=${b.combinedScore}]: ${b.summary}`);
879
+ }
880
+ }
881
+ if (result.mergedReflections.length) {
882
+ lines.push('Failure reflections (dead ends to avoid):');
883
+ for (const r of result.mergedReflections)
884
+ lines.push(`- ${r}`);
885
+ }
886
+ lines.push(phase === 'planning'
887
+ ? 'Now submit your grounded execution plan using submit_plan, incorporating the winning strategy, evidence, and reflections.'
888
+ : 'Use these converged findings and reflections to verify/finalize your answer or run any final checks.');
889
+ return lines.join('\n');
890
+ }
891
+ function uriToPath(uriOrPath) {
892
+ if (!uriOrPath.startsWith('file://'))
893
+ return uriOrPath;
894
+ const getBuiltin = process.getBuiltinModule;
895
+ const urlMod = getBuiltin?.('node:url');
896
+ if (urlMod?.fileURLToPath) {
897
+ try {
898
+ return urlMod.fileURLToPath(normalizeFileUriForPlatform(uriOrPath, process.platform));
899
+ }
900
+ catch {
901
+ return uriOrPath;
902
+ }
903
+ }
904
+ return uriOrPath;
905
+ }