@myagentroam/agent 0.14.16 → 0.14.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/host/local-exec-tool.js +81 -49
- package/dist/model/responses-request.js +38 -10
- package/dist/prompts/subagent.d.ts +0 -1
- package/dist/prompts/subagent.js +0 -9
- package/dist/sdk/execution-tool-scope.d.ts +1 -2
- package/dist/sdk/execution-tool-scope.js +1 -8
- package/dist/sdk/session-execution-factory.js +0 -1
- package/dist/tools/agent/question.js +2 -2
- package/dist/tools/agent/skill.js +1 -1
- package/dist/tools/agent/smart-compact.js +2 -2
- package/dist/tools/agent/todo-tool.js +1 -1
- package/dist/tools/code-mode/index.js +7 -11
- package/dist/tools/contracts.d.ts +1 -1
- package/dist/tools/local/apply-patch.js +12 -2
- package/dist/tools/local/exec.js +4 -4
- package/dist/tools/local/read.js +7 -5
- package/dist/tools/local/view-image.js +1 -1
- package/dist/tools/mcp/tool-search.d.ts +1 -9
- package/dist/tools/mcp/tool-search.js +2 -25
- package/package.json +1 -1
|
@@ -39,15 +39,34 @@ export class ExecTool {
|
|
|
39
39
|
const input = parseExecInput(arguments_);
|
|
40
40
|
if ('processId' in input) {
|
|
41
41
|
this.#handles.assertType(input.processId);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
42
|
+
let process = this.#processes.get(input.processId);
|
|
43
|
+
let completed = this.#completed.get(input.processId);
|
|
44
|
+
const source = completed ?? process;
|
|
45
|
+
if (!source ||
|
|
46
|
+
process?.native ||
|
|
47
|
+
(owner !== undefined && source.ownerSessionId !== owner.sessionId))
|
|
48
|
+
throw new AgentError('MAR_AGENT_PROCESS_NOT_FOUND', 'Managed process was not found.');
|
|
49
|
+
if (onExecutionSource) {
|
|
50
|
+
await onExecutionSource(processSource(source));
|
|
49
51
|
if (signal?.aborted)
|
|
50
52
|
throw executionAbortReason(signal);
|
|
53
|
+
// Source publication can overlap terminal collection or eviction of this handle.
|
|
54
|
+
process = this.#processes.get(input.processId);
|
|
55
|
+
completed = this.#completed.get(input.processId);
|
|
56
|
+
}
|
|
57
|
+
let outcome;
|
|
58
|
+
if (process && input.action === 'poll') {
|
|
59
|
+
outcome = await waitForProcessCompletion('poll', input.processId, process, input.yieldMs, signal, waitInterrupt, onOutput);
|
|
60
|
+
// A skipped or displaced poll must not drain the active poll's output.
|
|
61
|
+
if (outcome === 'superseded' || (outcome === 'interrupted' && process.supersedePoll))
|
|
62
|
+
return {
|
|
63
|
+
...this.#result(input.processId, process, false),
|
|
64
|
+
waitOutcome: 'interrupted',
|
|
65
|
+
reason: outcome === 'superseded' ? 'superseded' : 'steer'
|
|
66
|
+
};
|
|
67
|
+
completed = this.#completed.get(input.processId);
|
|
68
|
+
}
|
|
69
|
+
if (completed) {
|
|
51
70
|
if (input.action === 'write')
|
|
52
71
|
throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Completed process cannot accept input.');
|
|
53
72
|
if (input.action === 'cancel')
|
|
@@ -58,17 +77,8 @@ export class ExecTool {
|
|
|
58
77
|
...(input.action === 'poll' ? waitMetadata('completion') : {})
|
|
59
78
|
};
|
|
60
79
|
}
|
|
61
|
-
if (!process
|
|
62
|
-
process.native ||
|
|
63
|
-
(owner !== undefined && process.ownerSessionId !== owner.sessionId))
|
|
80
|
+
if (!process)
|
|
64
81
|
throw new AgentError('MAR_AGENT_PROCESS_NOT_FOUND', 'Managed process was not found.');
|
|
65
|
-
if (onExecutionSource)
|
|
66
|
-
await onExecutionSource(processSource(process));
|
|
67
|
-
if (signal?.aborted)
|
|
68
|
-
throw executionAbortReason(signal);
|
|
69
|
-
let outcome;
|
|
70
|
-
if (input.action === 'poll')
|
|
71
|
-
outcome = await waitForProcessCompletion(input.processId, process, input.yieldMs, signal, waitInterrupt, onOutput);
|
|
72
82
|
if (input.action === 'write') {
|
|
73
83
|
if (process.status !== 'running')
|
|
74
84
|
throw new AgentError('MAR_AGENT_TOOL_INPUT_INVALID', 'Completed process cannot accept input.');
|
|
@@ -113,7 +123,7 @@ export class ExecTool {
|
|
|
113
123
|
}, Math.min(input.timeoutMs, TOOL_EXECUTION_LIMITS.execMaxTimeoutMs));
|
|
114
124
|
managed.timer.unref();
|
|
115
125
|
}
|
|
116
|
-
const outcome = await waitForProcessCompletion(id, managed, input.yieldMs ?? TOOL_EXECUTION_LIMITS.execDefaultYieldMs, signal, waitInterrupt, onOutput);
|
|
126
|
+
const outcome = await waitForProcessCompletion('initial', id, managed, input.yieldMs ?? TOOL_EXECUTION_LIMITS.execDefaultYieldMs, signal, waitInterrupt, onOutput);
|
|
117
127
|
const result = this.#result(id, managed);
|
|
118
128
|
if (managed.status !== 'running')
|
|
119
129
|
this.#retainCompleted(id, managed);
|
|
@@ -176,8 +186,7 @@ export class ExecTool {
|
|
|
176
186
|
...(child.signalCode == null ? {} : { exitSignal: child.signalCode }),
|
|
177
187
|
finalized: false,
|
|
178
188
|
terminalResultReturned: false,
|
|
179
|
-
waiters: new Set()
|
|
180
|
-
outputListeners: new Set()
|
|
189
|
+
waiters: new Set()
|
|
181
190
|
};
|
|
182
191
|
this.#processes.set(id, managed);
|
|
183
192
|
if (native) {
|
|
@@ -196,8 +205,7 @@ export class ExecTool {
|
|
|
196
205
|
return;
|
|
197
206
|
const decoded = Buffer.from(managed[name].decoder.write(chunk));
|
|
198
207
|
appendDisplay(managed[name === 'stdout' ? 'stdoutDisplay' : 'stderrDisplay'], decoded);
|
|
199
|
-
|
|
200
|
-
listener(name, decoded);
|
|
208
|
+
managed.outputSubscription?.onChunk(name, decoded);
|
|
201
209
|
appendOutput(managed[name], decoded, this.maxOutputBytes, chunk.length);
|
|
202
210
|
appendOutput(managed[name === 'stdout' ? 'stdoutHistory' : 'stderrHistory'], decoded, this.maxOutputBytes, chunk.length);
|
|
203
211
|
notifyProcessChange(managed);
|
|
@@ -236,8 +244,7 @@ export class ExecTool {
|
|
|
236
244
|
else {
|
|
237
245
|
const message = Buffer.from(error.message);
|
|
238
246
|
appendDisplay(managed.stderrDisplay, message);
|
|
239
|
-
|
|
240
|
-
listener('stderr', message);
|
|
247
|
+
managed.outputSubscription?.onChunk('stderr', message);
|
|
241
248
|
appendOutput(managed.stderr, message, this.maxOutputBytes);
|
|
242
249
|
appendOutput(managed.stderrHistory, message, this.maxOutputBytes);
|
|
243
250
|
notifyProcessChange(managed);
|
|
@@ -480,12 +487,13 @@ export class ExecTool {
|
|
|
480
487
|
})();
|
|
481
488
|
return managed.terminate;
|
|
482
489
|
}
|
|
483
|
-
#result(id, process) {
|
|
490
|
+
#result(id, process, consumeIncrement = true) {
|
|
484
491
|
// Uncollected terminal output is a live resource, not an expiring replay.
|
|
485
|
-
if (process.status !== 'running')
|
|
492
|
+
if (consumeIncrement && process.status !== 'running')
|
|
486
493
|
process.terminalResultReturned = true;
|
|
487
|
-
const
|
|
488
|
-
const
|
|
494
|
+
const empty = { value: '', droppedBytes: 0 };
|
|
495
|
+
const stdout = consumeIncrement ? consumeOutput(process.stdout) : empty;
|
|
496
|
+
const stderr = consumeIncrement ? consumeOutput(process.stderr) : empty;
|
|
489
497
|
return {
|
|
490
498
|
status: process.status,
|
|
491
499
|
processId: id,
|
|
@@ -543,10 +551,8 @@ function finalizeManagedProcess(managed, maximumOutputBytes, exitCode) {
|
|
|
543
551
|
const stderrEnd = Buffer.from(managed.stderr.decoder.end());
|
|
544
552
|
appendDisplay(managed.stdoutDisplay, stdoutEnd);
|
|
545
553
|
appendDisplay(managed.stderrDisplay, stderrEnd);
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
listener('stderr', stderrEnd);
|
|
549
|
-
}
|
|
554
|
+
managed.outputSubscription?.onChunk('stdout', stdoutEnd);
|
|
555
|
+
managed.outputSubscription?.onChunk('stderr', stderrEnd);
|
|
550
556
|
appendOutput(managed.stdout, stdoutEnd, maximumOutputBytes);
|
|
551
557
|
appendOutput(managed.stderr, stderrEnd, maximumOutputBytes);
|
|
552
558
|
appendOutput(managed.stdoutHistory, stdoutEnd, maximumOutputBytes);
|
|
@@ -640,27 +646,48 @@ function notifyProcessChange(managed) {
|
|
|
640
646
|
for (const resolve of managed.waiters)
|
|
641
647
|
resolve();
|
|
642
648
|
}
|
|
643
|
-
async function waitForProcessCompletion(processId, managed, waitMs, signal, interrupt, onOutput) {
|
|
644
|
-
|
|
649
|
+
async function waitForProcessCompletion(kind, processId, managed, waitMs, signal, interrupt, onOutput) {
|
|
650
|
+
// An immediately settled wait must not take over an active poll or output subscription.
|
|
651
|
+
signal?.throwIfAborted();
|
|
652
|
+
if (managed.finalized)
|
|
653
|
+
return 'ready';
|
|
654
|
+
if (interrupt?.pending())
|
|
655
|
+
return 'interrupted';
|
|
656
|
+
let stopOutput;
|
|
657
|
+
let superseded = false;
|
|
645
658
|
try {
|
|
646
|
-
|
|
647
|
-
ready: () => managed.finalized,
|
|
659
|
+
const outcome = await waitForToolCondition({
|
|
660
|
+
ready: () => managed.finalized || superseded,
|
|
648
661
|
subscribe: (notify) => {
|
|
662
|
+
const supersede = () => {
|
|
663
|
+
superseded = true;
|
|
664
|
+
stopOutput?.();
|
|
665
|
+
notify();
|
|
666
|
+
};
|
|
667
|
+
if (kind === 'poll') {
|
|
668
|
+
managed.supersedePoll?.();
|
|
669
|
+
managed.supersedePoll = supersede;
|
|
670
|
+
}
|
|
671
|
+
if (onOutput)
|
|
672
|
+
stopOutput = watchProcessOutput(processId, managed, onOutput);
|
|
649
673
|
managed.waiters.add(notify);
|
|
650
674
|
return () => {
|
|
651
675
|
managed.waiters.delete(notify);
|
|
676
|
+
if (managed.supersedePoll === supersede)
|
|
677
|
+
delete managed.supersedePoll;
|
|
652
678
|
};
|
|
653
679
|
},
|
|
654
680
|
waitMs,
|
|
655
681
|
signal,
|
|
656
682
|
interrupt
|
|
657
683
|
});
|
|
684
|
+
return superseded ? 'superseded' : outcome;
|
|
658
685
|
}
|
|
659
686
|
finally {
|
|
660
687
|
stopOutput?.();
|
|
661
688
|
}
|
|
662
689
|
}
|
|
663
|
-
/**
|
|
690
|
+
/** Replace the process's live subscriber and coalesce chunks without blocking the process. */
|
|
664
691
|
function watchProcessOutput(processId, managed, onOutput) {
|
|
665
692
|
let stopped = false;
|
|
666
693
|
let stdout = { value: Buffer.alloc(0), droppedBytes: 0 };
|
|
@@ -711,21 +738,26 @@ function watchProcessOutput(processId, managed, onOutput) {
|
|
|
711
738
|
}, TOOL_EXECUTION_LIMITS.execProgressIntervalMs);
|
|
712
739
|
timer.unref();
|
|
713
740
|
};
|
|
714
|
-
const
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
741
|
+
const subscription = {
|
|
742
|
+
onChunk(channel, chunk) {
|
|
743
|
+
if (chunk.length === 0)
|
|
744
|
+
return;
|
|
745
|
+
appendDisplay(channel === 'stdout' ? stdout : stderr, chunk);
|
|
746
|
+
schedule();
|
|
747
|
+
},
|
|
748
|
+
stop() {
|
|
749
|
+
stopped = true;
|
|
750
|
+
if (managed.outputSubscription === subscription)
|
|
751
|
+
delete managed.outputSubscription;
|
|
752
|
+
if (timer)
|
|
753
|
+
clearTimeout(timer);
|
|
754
|
+
}
|
|
719
755
|
};
|
|
720
|
-
managed.
|
|
756
|
+
managed.outputSubscription?.stop();
|
|
757
|
+
managed.outputSubscription = subscription;
|
|
721
758
|
if (initialSnapshot)
|
|
722
759
|
schedule();
|
|
723
|
-
return
|
|
724
|
-
stopped = true;
|
|
725
|
-
managed.outputListeners.delete(changed);
|
|
726
|
-
if (timer)
|
|
727
|
-
clearTimeout(timer);
|
|
728
|
-
};
|
|
760
|
+
return subscription.stop;
|
|
729
761
|
}
|
|
730
762
|
function executionAbortReason(signal) {
|
|
731
763
|
return signal?.reason ?? new AgentError('MAR_AGENT_EXECUTION_CANCELLED', 'Execution cancelled.');
|
|
@@ -169,6 +169,7 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
169
169
|
const providerCallIds = new Set();
|
|
170
170
|
const functionCallIds = new Set();
|
|
171
171
|
const customCallIds = new Set();
|
|
172
|
+
const searchCallIds = new Set();
|
|
172
173
|
const providerMessageTexts = new Set();
|
|
173
174
|
// Incremental input omits the calls already retained by the WebSocket response.
|
|
174
175
|
for (const item of previousOutputItems) {
|
|
@@ -178,6 +179,8 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
178
179
|
functionCallIds.add(item.call_id);
|
|
179
180
|
if (nativeTools && item.type === 'custom_tool_call')
|
|
180
181
|
customCallIds.add(item.call_id);
|
|
182
|
+
if (nativeTools && item.type === 'tool_search_call')
|
|
183
|
+
searchCallIds.add(item.call_id);
|
|
181
184
|
}
|
|
182
185
|
for (const message of compatibleMessages) {
|
|
183
186
|
if (message.role !== 'provider' || !message.item)
|
|
@@ -186,8 +189,10 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
186
189
|
providerCallIds.add(message.item.call_id);
|
|
187
190
|
functionCallIds.add(message.item.call_id);
|
|
188
191
|
}
|
|
189
|
-
if (message.item.type === 'tool_search_call' && typeof message.item.call_id === 'string')
|
|
192
|
+
if (message.item.type === 'tool_search_call' && typeof message.item.call_id === 'string') {
|
|
190
193
|
providerCallIds.add(message.item.call_id);
|
|
194
|
+
searchCallIds.add(message.item.call_id);
|
|
195
|
+
}
|
|
191
196
|
if (message.item.type === 'custom_tool_call' && typeof message.item.call_id === 'string') {
|
|
192
197
|
providerCallIds.add(message.item.call_id);
|
|
193
198
|
customCallIds.add(message.item.call_id);
|
|
@@ -204,12 +209,14 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
204
209
|
providerMessageTexts.add(value);
|
|
205
210
|
}
|
|
206
211
|
}
|
|
207
|
-
for (const message of compatibleMessages)
|
|
208
|
-
if (nativeTools
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
message.callId)
|
|
212
|
+
for (const message of compatibleMessages) {
|
|
213
|
+
if (!nativeTools || message.role !== 'tool_call' || !message.callId)
|
|
214
|
+
continue;
|
|
215
|
+
if (message.inputMode === 'freeform')
|
|
212
216
|
customCallIds.add(message.callId);
|
|
217
|
+
else if (message.name === 'tool_search')
|
|
218
|
+
searchCallIds.add(message.callId);
|
|
219
|
+
}
|
|
213
220
|
const orderedMessages = [];
|
|
214
221
|
for (const message of compatibleMessages) {
|
|
215
222
|
if (message.role === 'provider' && message.item?.type === 'configuration_update') {
|
|
@@ -223,10 +230,31 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
223
230
|
}
|
|
224
231
|
// SDK records the update after the user input; the wire item must precede
|
|
225
232
|
// that user message so the new effort applies to the response.
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
233
|
+
const input = [];
|
|
234
|
+
const searchDiagnostics = [];
|
|
235
|
+
const flushSearchDiagnostics = () => {
|
|
236
|
+
if (searchDiagnostics.length)
|
|
237
|
+
input.push({ role: 'user', content: searchDiagnostics.splice(0).join('\n\n') });
|
|
238
|
+
};
|
|
239
|
+
for (let message of orderedMessages) {
|
|
240
|
+
if (message.role === 'tool_call' && message.callId && providerCallIds.has(message.callId))
|
|
241
|
+
continue;
|
|
242
|
+
if (message.role === 'assistant' && providerMessageTexts.has(message.content))
|
|
243
|
+
continue;
|
|
244
|
+
if (message.role !== 'tool')
|
|
245
|
+
flushSearchDiagnostics();
|
|
246
|
+
else if (message.callId &&
|
|
247
|
+
searchCallIds.has(message.callId) &&
|
|
248
|
+
!functionCallIds.has(message.callId) &&
|
|
249
|
+
message.toolSearchTools === undefined) {
|
|
250
|
+
// Native search output has no text field; send the diagnostic after the tool batch.
|
|
251
|
+
searchDiagnostics.push(`Tool Search failed (call ID: ${message.callId}):\n${message.content}`);
|
|
252
|
+
message = { ...message, toolSearchTools: [] };
|
|
253
|
+
}
|
|
254
|
+
input.push(openAiInputItem(message, message === lastUser ? images : undefined, customCallIds, functionCallIds, nativeTools, tools));
|
|
255
|
+
}
|
|
256
|
+
flushSearchDiagnostics();
|
|
257
|
+
return input;
|
|
230
258
|
}
|
|
231
259
|
function openAiInputItem(message, images, customCallIds = new Set(), functionCallIds = new Set(), nativeTools = true, tools = []) {
|
|
232
260
|
const userImages = message.role === 'user' ? uniqueModelImages(message.images, images) : [];
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
export declare const subagentPrompt: string;
|
|
2
1
|
export declare const childSubagentInstruction = "You are a delegated subagent. Complete only the delegated objective within its read/write scope. Other agents share your workspace: preserve their changes and report an exact conflict or blocker to the parent instead of expanding scope. Return a concise factual handoff with findings, useful evidence paths, files changed, tests actually run and their outcomes, and remaining blockers or uncertainty.";
|
package/dist/prompts/subagent.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
export const subagentPrompt = [
|
|
2
|
-
'# Subagents',
|
|
3
|
-
'Unread child messages and terminal results are supplied before the next model request.',
|
|
4
|
-
'Call agent_start, agent_wait, agent_message and agent_cancel directly, never inside code_exec; they are absent from the cell tools namespace.',
|
|
5
|
-
'Delegate bounded, self-contained tasks when independent progress or context savings materially helps. Keep simple or tightly coupled work local; do not split work merely to use agents.',
|
|
6
|
-
'All agents share the filesystem. Give each child an objective, necessary context, expected output, and an exclusive write scope or a read-only boundary; avoid conflicting writes.',
|
|
7
|
-
'While children run, continue meaningful non-overlapping work without intervening status checks. Do not redo delegated work. Wait only when the next step needs the result; do not poll for reassurance.',
|
|
8
|
-
'Use concise handoffs and independently verify consequential changes and claims. Track child IDs, join or cancel required child work before final delivery, and retain responsibility for the final result.'
|
|
9
|
-
].join('\n');
|
|
10
1
|
export const childSubagentInstruction = 'You are a delegated subagent. Complete only the delegated objective within its read/write scope. Other agents share your workspace: preserve their changes and report an exact conflict or blocker to the parent instead of expanding scope. Return a concise factual handoff with findings, useful evidence paths, files changed, tests actually run and their outcomes, and remaining blockers or uncertainty.';
|
|
@@ -42,7 +42,6 @@ export declare function createExecutionToolScope(input: {
|
|
|
42
42
|
readonly currentExecutionToolImages: Parameters<typeof currentExecutionImages>[1];
|
|
43
43
|
readonly inputImageBytes: Map<string, ModelImage>;
|
|
44
44
|
snapshotTools(): readonly ClientToolDefinition[];
|
|
45
|
-
baseTools(): readonly ClientToolDefinition[];
|
|
46
45
|
captureTools(): ReturnType<ExtensionSession['capture']>;
|
|
47
46
|
promptComposition(tools: readonly ClientToolDefinition[], mode: ExecutionMode): ExtensionPromptComposition & {
|
|
48
47
|
sections: ExtensionPromptComposition['sections'];
|
|
@@ -63,6 +62,6 @@ export declare function createExecutionToolScope(input: {
|
|
|
63
62
|
composeSystemPrompt(): Promise<{
|
|
64
63
|
text: string;
|
|
65
64
|
blocks?: readonly import("../model/contracts.js").ModelTextBlock[];
|
|
66
|
-
sections?: readonly import("../
|
|
65
|
+
sections?: readonly import("../extensions.js").PromptPart[];
|
|
67
66
|
}>;
|
|
68
67
|
};
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { createExecutionCodeModeContext } from './execution-code-mode.js';
|
|
2
2
|
import { currentExecutionImages, publicExtensionToolEventData } from '../tools/output-projection.js';
|
|
3
3
|
import { requestSmartCompaction } from '../runtime/compaction/smart.js';
|
|
4
|
-
import { renderPromptSections } from '../prompts/prompt-sections.js';
|
|
5
4
|
import { withToolPermissions } from '../tools/permissions.js';
|
|
6
5
|
import { SESSION_CONTEXT_PROVIDER } from '../extensions/session-context.js';
|
|
7
6
|
/** Capture immutable round tool identities, parent scope and resource capabilities. */
|
|
8
7
|
export function createExecutionToolScope(input) {
|
|
9
|
-
const { store, host, sessionId, executionId, turnId, mode, controller, sessionWriterOwner, selectedModel, permissionPolicy, todo, waitInterrupt, skills, coreExtensions, operations, scheduleTool, sources, mcpRegistry, autoPermissionPrompt, currentExecutionToolImages, inputImageBytes, snapshotTools,
|
|
8
|
+
const { store, host, sessionId, executionId, turnId, mode, controller, sessionWriterOwner, selectedModel, permissionPolicy, todo, waitInterrupt, skills, coreExtensions, operations, scheduleTool, sources, mcpRegistry, autoPermissionPrompt, currentExecutionToolImages, inputImageBytes, snapshotTools, captureTools, promptComposition, smartInput, modelInputImages, startCompact, preparedPrompt, clearPreparedPrompt, operation, emit } = input;
|
|
10
9
|
const captureRoundToolScope = () => {
|
|
11
10
|
const roundTools = snapshotTools();
|
|
12
11
|
const availableBindings = captureTools();
|
|
@@ -17,8 +16,6 @@ export function createExecutionToolScope(input) {
|
|
|
17
16
|
...defaultComposition.sections,
|
|
18
17
|
{ id: 'core:auto-permission', text: autoPermissionPrompt }
|
|
19
18
|
];
|
|
20
|
-
const defaultSystemPrompt = renderPromptSections(defaultComposition.sections);
|
|
21
|
-
let systemPrompt = defaultSystemPrompt;
|
|
22
19
|
const roundMcpExpectations = new Map(roundTools
|
|
23
20
|
.filter((tool) => roundBindings.get(tool.name)?.mcp !== undefined)
|
|
24
21
|
.map((tool) => [tool.name, mcpRegistry.expectedTool(tool.name)]));
|
|
@@ -135,9 +132,6 @@ export function createExecutionToolScope(input) {
|
|
|
135
132
|
}),
|
|
136
133
|
searchMcpTools: (arguments_, searchSignal, caller) => input.withRecordProjection(() => mcpRegistry.expose(arguments_, {
|
|
137
134
|
signal: searchSignal,
|
|
138
|
-
base: baseTools(),
|
|
139
|
-
window: selectedModel.contextWindowTokens,
|
|
140
|
-
system: systemPrompt,
|
|
141
135
|
...(caller === 'programmatic'
|
|
142
136
|
? { publish: (names) => input.publishMcpDiscovery(names, searchSignal) }
|
|
143
137
|
: {})
|
|
@@ -169,7 +163,6 @@ export function createExecutionToolScope(input) {
|
|
|
169
163
|
const composed = preparedPrompt() ??
|
|
170
164
|
(await operation((call) => coreExtensions.composeModelSystem(defaultComposition, call)));
|
|
171
165
|
clearPreparedPrompt();
|
|
172
|
-
systemPrompt = composed.text;
|
|
173
166
|
return composed;
|
|
174
167
|
}
|
|
175
168
|
};
|
|
@@ -463,7 +463,6 @@ export function createSessionExecutionFactory(ports) {
|
|
|
463
463
|
currentExecutionToolImages,
|
|
464
464
|
inputImageBytes,
|
|
465
465
|
snapshotTools: () => projectTools(toolCatalog.tools),
|
|
466
|
-
baseTools: () => projectTools(baseTools()),
|
|
467
466
|
captureTools,
|
|
468
467
|
promptComposition,
|
|
469
468
|
smartInput: () => smartInput,
|
|
@@ -5,7 +5,7 @@ export const questionToolDefinition = {
|
|
|
5
5
|
name: 'question',
|
|
6
6
|
allowedCallers: ['direct'],
|
|
7
7
|
parallelSafety: 'safe',
|
|
8
|
-
description: 'Pause for
|
|
8
|
+
description: 'Pause for tightly related user-owned decisions that materially change the result and cannot be inferred from the request, conversation, or relevant safe discovery. Users can choose an option or enter a free-text answer. This is not a permission or approval tool.',
|
|
9
9
|
inputSchema: {
|
|
10
10
|
type: 'object',
|
|
11
11
|
properties: {
|
|
@@ -26,7 +26,7 @@ export const questionToolDefinition = {
|
|
|
26
26
|
type: 'array',
|
|
27
27
|
minItems: 2,
|
|
28
28
|
maxItems: 3,
|
|
29
|
-
description: 'Provide
|
|
29
|
+
description: 'Provide mutually exclusive choices with consequences. Put the recommended option first and identify it in its label or description.',
|
|
30
30
|
items: {
|
|
31
31
|
type: 'object',
|
|
32
32
|
properties: {
|
|
@@ -4,7 +4,7 @@ export const skillToolDefinition = {
|
|
|
4
4
|
name: 'skill_load',
|
|
5
5
|
allowedCallers: ['direct', 'programmatic'],
|
|
6
6
|
parallelSafety: 'safe',
|
|
7
|
-
description: 'Load a Skill by its exact catalog name.
|
|
7
|
+
description: 'Load a Skill by its exact catalog name. Returns { success: true }; instructions are injected into the next eligible model request, not returned by the tool.',
|
|
8
8
|
inputSchema: {
|
|
9
9
|
type: 'object',
|
|
10
10
|
properties: {
|
|
@@ -4,9 +4,9 @@ export const smartCompactToolDefinition = {
|
|
|
4
4
|
name: 'smart_compact',
|
|
5
5
|
allowedCallers: ['direct', 'programmatic'],
|
|
6
6
|
parallelSafety: 'safe',
|
|
7
|
-
description: 'Request background context compaction only when the current real user message
|
|
7
|
+
description: 'Request background context compaction only when the Runtime marks the current real user message with this note: ' +
|
|
8
8
|
SMART_COMPACTION_MARKER +
|
|
9
|
-
' The note indicates
|
|
9
|
+
' The note indicates eligibility, not a recommendation; historical notes do not qualify the current input. Call only if the transition is clear and a summary can preserve the key state needed to continue. Acceptance does not wait for generation or installation.',
|
|
10
10
|
inputSchema: { type: 'object', properties: {}, additionalProperties: false }
|
|
11
11
|
};
|
|
12
12
|
export function executeSmartCompact(arguments_, context) {
|
|
@@ -5,7 +5,7 @@ export const todoToolDefinition = {
|
|
|
5
5
|
name: 'todo',
|
|
6
6
|
allowedCallers: ['direct', 'programmatic'],
|
|
7
7
|
parallelSafety: 'safe',
|
|
8
|
-
description: 'Read or replace
|
|
8
|
+
description: 'Read or replace the session’s Todo list for coordination-heavy work. action=read returns revision and all items; omit items. action=write replaces the entire list with the supplied items array (empty clears it) and returns a text receipt with revision and count. In Code Mode, both actions return revision and items in data. No prior read or revision precondition is required. The list may contain at most one in_progress item.',
|
|
9
9
|
inputSchema: {
|
|
10
10
|
type: 'object',
|
|
11
11
|
properties: {
|
|
@@ -24,25 +24,21 @@ import { failedToolResultExtensions } from '../result-extensions.js';
|
|
|
24
24
|
export const codeModeToolDefinition = {
|
|
25
25
|
name: 'code_exec',
|
|
26
26
|
description: `Run JavaScript to orchestrate or compose tool calls.
|
|
27
|
-
- Code Mode Only by default: call the programmatic tools listed below through tools.NAME, including single-tool operations. Tools
|
|
28
|
-
-
|
|
29
|
-
- Complete known, bounded steps and deterministic result processing in code when this avoids a model round trip. Return to the model when interpretation or a new decision is needed; do not invent extra work to fill a cell.
|
|
30
|
-
- Observe only evidence needed for the next decision or verification: use observe.result for original results, observe.text for derived values, and observe.image for image values. Preserve source and failure details needed for reasoning; keep other intermediate data in the cell.
|
|
31
|
-
- Single-tool cells are valid. Keep loops and retries bounded, and do not blindly replay operations with side effects.
|
|
32
|
-
- Evaluates source in a fresh restricted ECMAScript runtime with top-level await and Promise.all. It is not Node.js or a browser. JavaScript globals do not survive between cells; bounded JSON state is available through state.
|
|
27
|
+
- Code Mode Only by default: call the programmatic tools listed below through tools.NAME, including single-tool operations. Tools exposed in both places may also be called directly.
|
|
28
|
+
- Evaluates source in a fresh restricted ECMAScript runtime with top-level await. It is not Node.js or a browser. JavaScript globals do not survive between cells; bounded JSON state is available through state.
|
|
33
29
|
- Accepts JavaScript source text. When exposed as a freeform tool, send the source directly; when exposed with a JSON input schema, put the source in its code field. JSON input example: \`{"code":"observe.text(1);"}\`. Do not add another JSON wrapper, quoted string, or markdown code fence inside the source.
|
|
34
|
-
- Do not paste Python literals such as None into JavaScript expressions.
|
|
35
30
|
- Use only standard ECMAScript built-ins and the explicitly documented tools, observe, state, catalog and cell namespaces. Do not use Node.js, browser or Web APIs. Module imports, filesystem and network APIs are unavailable. Obtain external capabilities only through available tools. Use tools.exec to start managed processes when permitted; follow exec_wait's calling guidance for process control.
|
|
36
31
|
|
|
37
32
|
Tool calls:
|
|
38
33
|
- tools.NAME(input) returns a Promise. Pass a JavaScript value matching the current catalog inputSchema. For parameterless tools prefer tools.NAME({}); tools.NAME() is accepted only for explicitly closed empty-object schemas.
|
|
39
34
|
- Results use the MAR envelope: { content?: string, data?: unknown, images?: Array<{mimeType:string,dataBase64:string,url?:string,urlExpiresAt?:number}>, truncated?: boolean }. Redundant JSON content is omitted when it exactly renders data; independent text remains in content. Prefer data for programmatic results: result.data.results[0].text for read source text and result.data.exitCode/result.data.stdout for exec. content, when present, is rendered text, not raw file bytes. Use only fields documented by that tool; do not invent success or ok flags.
|
|
40
|
-
-
|
|
41
|
-
-
|
|
35
|
+
- Await every tool call. Independent calls can run concurrently in an awaited Promise.all; use sequential await for dependent calls. Unawaited calls fail the cell. Runtime preserves safe/serial barriers and Host checks.
|
|
36
|
+
- Tool errors reject with code/message and may be caught, except nested Auto deny, which skips only that call and resolves with data.error/data.message. A failed cell preserves already emitted output alongside its status and error; completed tool effects are not rolled back. Check the failed cell result before retrying.
|
|
37
|
+
- Direct-only tools cannot be called here. When available, tools.tool_search discovers deferred tools for the next model request; the current cell's tools do not change.
|
|
42
38
|
|
|
43
39
|
Built-in namespaces:
|
|
44
|
-
- observe.result(result): void registers an unmodified complete tools.NAME result or caught tool error as a
|
|
45
|
-
- observe.text(value): void registers text/JSON values. observe.image(value): void registers one image value when image input is supported. Both accept original tool results for compatibility and
|
|
40
|
+
- observe.result(result): void registers an unmodified complete tools.NAME result or caught tool error as a tool_result observation, using the original text and all images without repeating program data. Non-original, copied or modified values are rejected.
|
|
41
|
+
- observe.text(value): void registers text/JSON values. observe.image(value): void registers one image value when image input is supported. Both accept original tool results for compatibility and register the full result as tool_result. Extracted images, copies and computed summaries are value observations. Observations are returned in registration order; registering one does not trigger a new model request. No out or callable observe(value) alias exists.
|
|
46
42
|
- state.get(key), state.has(key), state.set(key, value), state.delete(key) access bounded session JSON state. Mutations commit atomically only when the cell succeeds; failed or cancelled cells discard them.
|
|
47
43
|
- catalog.tools() returns a read-only array of the tools callable in this cell, including name, description and inputSchema. It does not discover or authorize additional tools.
|
|
48
44
|
- await cell.sleep(ms) performs a cancellable delay up to ${limits.codeSleepMaxMs} ms.
|
|
@@ -161,7 +161,7 @@ export interface ExecResult {
|
|
|
161
161
|
executionSource?: ExecutionSource;
|
|
162
162
|
status: 'running' | 'completed' | 'cancelled';
|
|
163
163
|
waitOutcome?: import('./wait.js').ToolWaitOutcome;
|
|
164
|
-
reason?: 'steer';
|
|
164
|
+
reason?: 'steer' | 'superseded';
|
|
165
165
|
processId?: string;
|
|
166
166
|
stdout: string;
|
|
167
167
|
stderr: string;
|
|
@@ -12,7 +12,17 @@ export const applyPatchToolDefinition = {
|
|
|
12
12
|
allowedCallers: ['direct', 'programmatic'],
|
|
13
13
|
codeModeExposure: 'both',
|
|
14
14
|
parallelSafety: 'safe',
|
|
15
|
-
description: `
|
|
15
|
+
description: `Apply a patch to one or more files. Group closely related edits when the patch is easy to review. Split long or hard-to-review patches into smaller, valid patches. Oversized patches are rejected.
|
|
16
|
+
|
|
17
|
+
Start with *** Begin Patch and end with *** End Patch, each on its own line. Use *** Add File: <path>, *** Update File: <path>, or *** Delete File: <path> as the file header. To move a file, put *** Move to: <new path> immediately after the Update File header. A move without content changes needs no hunks.
|
|
18
|
+
|
|
19
|
+
Prefix each Add File content line with +, including blank lines. Start each update hunk with @@ or @@ <change context>, not a unified diff line-number range. In the hunk body, prefix unchanged lines with one space, deletions with -, and additions with +. An insertion-only hunk needs at least one unchanged line in its body.
|
|
20
|
+
|
|
21
|
+
Add and Move may overwrite existing regular files. Duplicate operations on the same resolved path are invalid. A patch must change or move at least one file.
|
|
22
|
+
|
|
23
|
+
Changes commit in order by file unit, not as one transaction. A move covers both paths in one unit. Syntax errors report line and column. Hunk conflicts identify the path and hunk; a conflict in the first unit leaves files unchanged. MAR_AGENT_PATCH_PARTIAL identifies applied, failed, and pending paths. Do not replay already applied units.
|
|
24
|
+
|
|
25
|
+
On success, data.files lists file operations and line counts, and data.totals contains the totals.`,
|
|
16
26
|
inputMode: 'freeform',
|
|
17
27
|
outputSchema: {
|
|
18
28
|
type: 'object',
|
|
@@ -55,7 +65,7 @@ export const applyPatchToolDefinition = {
|
|
|
55
65
|
properties: {
|
|
56
66
|
input: {
|
|
57
67
|
type: 'string',
|
|
58
|
-
description: 'Complete patch text, including the
|
|
68
|
+
description: 'Complete patch text, including the opening and closing markers.'
|
|
59
69
|
}
|
|
60
70
|
},
|
|
61
71
|
required: ['input'],
|
package/dist/tools/local/exec.js
CHANGED
|
@@ -34,7 +34,7 @@ export const execToolDefinition = {
|
|
|
34
34
|
allowedCallers: ['direct', 'programmatic'],
|
|
35
35
|
codeModeExposure: 'both',
|
|
36
36
|
parallelSafety: 'safe',
|
|
37
|
-
description: 'Start a platform-native command, script, or program in workspace/default cwd. Returns a stable processId (p_ plus 12 lowercase hex characters), status, bounded stdout/stderr, cumulative byte counts, dropped-byte counts, exitCode and truncated. A completed status does not imply exitCode 0; inspect stderr/exitCode. For subsequent waiting, stdin writes or cancellation, use exec_wait with processId, not exec. Truncation does not stop the process. Cancelling the initial wait does not terminate the process. waitOutcome distinguishes completion from a wait timeout. A direct foreground call may return interrupted with reason=steer.
|
|
37
|
+
description: 'Start a platform-native command, script, or program in workspace/default cwd. Returns a stable processId (p_ plus 12 lowercase hex characters), status, bounded stdout/stderr, cumulative byte counts, dropped-byte counts, exitCode and truncated. A completed status does not imply exitCode 0; inspect stderr/exitCode. For subsequent waiting, stdin writes or cancellation, use exec_wait with processId, not exec. Truncation does not stop the process. Cancelling the initial wait does not terminate the process. waitOutcome distinguishes completion from a wait timeout. A direct foreground call may return interrupted with reason=steer. For tools.exec, steer interrupts only the foreground cell wait, not the initial process wait. In either case the process keeps running.',
|
|
38
38
|
outputSchema: {
|
|
39
39
|
type: 'object',
|
|
40
40
|
required: ['content', 'data'],
|
|
@@ -55,7 +55,7 @@ export const execToolDefinition = {
|
|
|
55
55
|
properties: {
|
|
56
56
|
status: { enum: ['running', 'completed', 'cancelled'] },
|
|
57
57
|
waitOutcome: { enum: ['snapshot', 'completion', 'timeout', 'yield', 'interrupted'] },
|
|
58
|
-
reason: { enum: ['steer'] },
|
|
58
|
+
reason: { enum: ['steer', 'superseded'] },
|
|
59
59
|
processId: { type: 'string' },
|
|
60
60
|
stdout: { type: 'string' },
|
|
61
61
|
stderr: { type: 'string' },
|
|
@@ -109,7 +109,7 @@ export const execWaitToolDefinition = {
|
|
|
109
109
|
allowedCallers: ['direct', 'programmatic'],
|
|
110
110
|
codeModeExposure: 'both',
|
|
111
111
|
parallelSafety: 'safe',
|
|
112
|
-
description: 'Wait for or control a managed process by processId. action defaults to poll: collect output until termination or the wait window ends
|
|
112
|
+
description: 'Wait for or control a managed process by processId. action defaults to poll: collect output until termination or the wait window ends. New output does not end the wait. A new active poll takes over an older poll of the same process. The older poll returns normally with waitOutcome=interrupted and reason=superseded without consuming pending stdout/stderr or terminating the process. Both entry points share the same buffer of incremental stdout/stderr. write sends data to stdin; cancel terminates the process or removes its cached result. After the terminal result is collected, later polls can replay a bounded snapshot marked cached for up to five minutes. Cancelling a wait does not terminate the process. Uses the same Session-owned processes as exec; cannot start a process or extend its timeout. Inspect stderr/exitCode; completed does not imply success. Interrupted with reason=steer ends only a foreground wait, never the process.',
|
|
113
113
|
outputSchema: execToolDefinition.outputSchema,
|
|
114
114
|
inputSchema: {
|
|
115
115
|
type: 'object',
|
|
@@ -125,7 +125,7 @@ export const execWaitToolDefinition = {
|
|
|
125
125
|
minimum: 0,
|
|
126
126
|
maximum: TOOL_EXECUTION_LIMITS.execMaxYieldMs,
|
|
127
127
|
default: TOOL_EXECUTION_LIMITS.execDefaultPollYieldMs,
|
|
128
|
-
description: `Poll wait window in milliseconds
|
|
128
|
+
description: `Poll wait window in milliseconds. Values below ${TOOL_EXECUTION_LIMITS.execMinYieldMs} are treated as ${TOOL_EXECUTION_LIMITS.execMinYieldMs}.`
|
|
129
129
|
},
|
|
130
130
|
data: { type: 'string', description: 'Required stdin data for write.' }
|
|
131
131
|
},
|
package/dist/tools/local/read.js
CHANGED
|
@@ -51,7 +51,9 @@ export const readToolDefinition = {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
},
|
|
54
|
-
description: `Read
|
|
54
|
+
description: `Read text files or line ranges by path. Supports strict UTF-8 (BOM optional) and BOM-marked UTF-16LE/BE. When exec is available, the built-in rg can list paths (rg --files) or locate matching lines (rg -n).
|
|
55
|
+
|
|
56
|
+
Results follow input order; items fail independently. data.results[].text contains the decoded source for the returned range; the numbered preview may show less. To continue, use nextOffset, when present, from the preview or the structured item you are reading. A long line may have a head/tail preview without a cursor, or return an item error if it exceeds the read limit.`,
|
|
55
57
|
inputSchema: {
|
|
56
58
|
type: 'object',
|
|
57
59
|
properties: {
|
|
@@ -59,21 +61,21 @@ export const readToolDefinition = {
|
|
|
59
61
|
type: 'array',
|
|
60
62
|
minItems: 1,
|
|
61
63
|
maxItems: TOOL_EXECUTION_LIMITS.readMaxBatchItems,
|
|
62
|
-
description: '
|
|
64
|
+
description: 'Files or line ranges to read.',
|
|
63
65
|
items: {
|
|
64
66
|
type: 'object',
|
|
65
67
|
properties: {
|
|
66
|
-
path: { type: 'string', description: '
|
|
68
|
+
path: { type: 'string', description: 'Workspace-relative or absolute path.' },
|
|
67
69
|
offset: {
|
|
68
70
|
type: 'integer',
|
|
69
71
|
minimum: 1,
|
|
70
|
-
description: 'First 1-based
|
|
72
|
+
description: 'First line (1-based; default: 1).'
|
|
71
73
|
},
|
|
72
74
|
limit: {
|
|
73
75
|
type: 'integer',
|
|
74
76
|
minimum: 1,
|
|
75
77
|
maximum: TOOL_EXECUTION_LIMITS.readMaxLines,
|
|
76
|
-
description: `Maximum lines
|
|
78
|
+
description: `Maximum lines (default: ${TOOL_EXECUTION_LIMITS.readDefaultLines}).`
|
|
77
79
|
}
|
|
78
80
|
},
|
|
79
81
|
required: ['path'],
|
|
@@ -8,7 +8,7 @@ export const viewImageToolDefinition = {
|
|
|
8
8
|
name: 'view_image',
|
|
9
9
|
allowedCallers: ['direct', 'programmatic'],
|
|
10
10
|
parallelSafety: 'safe',
|
|
11
|
-
description: 'View a PNG, JPEG, or WebP image by path or Session resourceId.
|
|
11
|
+
description: 'View a PNG, JPEG, or WebP image by workspace-relative or absolute path, or by Session resourceId. Specify exactly one source. Returns the image and its dimensions; optional cropping and resizing affect only the returned image.',
|
|
12
12
|
inputSchema: {
|
|
13
13
|
type: 'object',
|
|
14
14
|
properties: {
|
|
@@ -1,14 +1,10 @@
|
|
|
1
|
-
import type { ClientToolDefinition } from '../contracts.js';
|
|
2
|
-
import type { McpCatalogTool, McpToolCatalog, ToolExecutionResult } from '../contracts.js';
|
|
1
|
+
import type { ClientToolDefinition, McpCatalogTool, McpToolCatalog, ToolExecutionResult } from '../contracts.js';
|
|
3
2
|
import type { ToolRuntimeContext } from '../runtime-context.js';
|
|
4
3
|
export declare const TOOL_SEARCH_LIMITS: Readonly<{
|
|
5
4
|
defaultLimit: 5;
|
|
6
5
|
maximumLimit: 20;
|
|
7
6
|
queryBytes: 4096;
|
|
8
7
|
catalogBytes: number;
|
|
9
|
-
maximumDefinitionTokens: 16384;
|
|
10
|
-
definitionWindowFraction: 0.25;
|
|
11
|
-
minimumContinuationTokens: 1024;
|
|
12
8
|
}>;
|
|
13
9
|
export declare const toolSearchToolDefinition: ClientToolDefinition;
|
|
14
10
|
export declare function parseToolSearchInput(input: unknown): {
|
|
@@ -35,12 +31,8 @@ export declare class DeferredMcpRegistry {
|
|
|
35
31
|
search(query: string, limit: number): McpCatalogTool[];
|
|
36
32
|
expose(input: unknown, context: {
|
|
37
33
|
signal: AbortSignal;
|
|
38
|
-
base: readonly ClientToolDefinition[];
|
|
39
|
-
window: number;
|
|
40
|
-
system: string;
|
|
41
34
|
publish?: (names: readonly string[]) => Promise<void>;
|
|
42
35
|
}): Promise<ToolExecutionResult>;
|
|
43
|
-
assertBudget(base: readonly ClientToolDefinition[], window: number, system: string, selection?: readonly string[], executionSelection?: ReadonlySet<string>): void;
|
|
44
36
|
navigation(): string | undefined;
|
|
45
37
|
}
|
|
46
38
|
export declare function executeToolSearch(input: unknown, context: ToolRuntimeContext): Promise<ToolExecutionResult>;
|
|
@@ -1,20 +1,15 @@
|
|
|
1
1
|
import { AgentError } from '../../error.js';
|
|
2
|
-
import { countModelTokens } from '../../runtime/token-budget.js';
|
|
3
|
-
import { projectCodeModeSearchResult, projectCodeModeTools } from '../code-mode/index.js';
|
|
4
2
|
import { assertMcpToolCatalog } from './catalog.js';
|
|
5
3
|
import { orderToolDefinitions, stableToolDefinition } from '../definition-projection.js';
|
|
6
4
|
export const TOOL_SEARCH_LIMITS = Object.freeze({
|
|
7
5
|
defaultLimit: 5,
|
|
8
6
|
maximumLimit: 20,
|
|
9
7
|
queryBytes: 4096,
|
|
10
|
-
catalogBytes: 16 * 1024
|
|
11
|
-
maximumDefinitionTokens: 16384,
|
|
12
|
-
definitionWindowFraction: 0.25,
|
|
13
|
-
minimumContinuationTokens: 1024
|
|
8
|
+
catalogBytes: 16 * 1024
|
|
14
9
|
});
|
|
15
10
|
export const toolSearchToolDefinition = {
|
|
16
11
|
name: 'tool_search',
|
|
17
|
-
description: 'Search and load deferred MCP tools for the next model request.
|
|
12
|
+
description: 'Search and load deferred MCP tools for the next model request. Returns matching names, or an empty list; definitions are supplied separately. Does not execute the discovered tools.',
|
|
18
13
|
inputSchema: {
|
|
19
14
|
type: 'object',
|
|
20
15
|
properties: {
|
|
@@ -199,8 +194,6 @@ export class DeferredMcpRegistry {
|
|
|
199
194
|
selection.push(name);
|
|
200
195
|
}
|
|
201
196
|
}
|
|
202
|
-
this.assertBudget(context.base, context.window, context.system, selection, executionSelection);
|
|
203
|
-
context.signal.throwIfAborted();
|
|
204
197
|
const data = { tools: matches.map((tool) => tool.definition.name) };
|
|
205
198
|
if (context.publish && data.tools.length)
|
|
206
199
|
await context.publish(data.tools);
|
|
@@ -212,22 +205,6 @@ export class DeferredMcpRegistry {
|
|
|
212
205
|
...(context.publish ? {} : { toolSearchTools: matches.map((tool) => tool.definition) })
|
|
213
206
|
};
|
|
214
207
|
}
|
|
215
|
-
assertBudget(base, window, system, selection = this.#selected, executionSelection = this.#executionSelected) {
|
|
216
|
-
const resident = this.projectDirect(base);
|
|
217
|
-
const active = this.project(base, selection, new Set(executionSelection));
|
|
218
|
-
const tools = projectCodeModeTools(active, resident);
|
|
219
|
-
const direct = projectCodeModeTools(resident);
|
|
220
|
-
const residentNames = new Set(resident.map((tool) => tool.name));
|
|
221
|
-
const definitions = active.filter((tool) => !residentNames.has(tool.name));
|
|
222
|
-
const searchResult = projectCodeModeSearchResult({ role: 'tool', content: '', toolSearchTools: definitions }, base.some((tool) => tool.name === 'code_exec'));
|
|
223
|
-
// Search-result definitions still consume context even when Only mode hides direct tools.
|
|
224
|
-
const estimated = countModelTokens(searchResult.content || JSON.stringify(searchResult.toolSearchTools));
|
|
225
|
-
const full = Math.max(countModelTokens(JSON.stringify(tools)), countModelTokens(JSON.stringify(direct)) + estimated);
|
|
226
|
-
const maximum = Math.min(TOOL_SEARCH_LIMITS.maximumDefinitionTokens, Math.floor(window * TOOL_SEARCH_LIMITS.definitionWindowFraction));
|
|
227
|
-
if (estimated > maximum ||
|
|
228
|
-
full + countModelTokens(system) + TOOL_SEARCH_LIMITS.minimumContinuationTokens > window)
|
|
229
|
-
throw new AgentError('MAR_AGENT_TOOL_EXPOSURE_LIMIT', 'The selected MCP definitions cannot fit within the exposure budget.', { details: { estimatedTokens: estimated, maximumTokens: maximum } });
|
|
230
|
-
}
|
|
231
208
|
navigation() {
|
|
232
209
|
if (!this.hasDeferred)
|
|
233
210
|
return undefined;
|