@myagentroam/agent 0.15.47 → 0.15.49
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/extensions/session-tools.d.ts +2 -2
- package/dist/extensions/session-tools.js +35 -20
- package/dist/extensions/session.d.ts +1 -1
- package/dist/extensions/session.js +2 -2
- package/dist/model/responses-request.js +25 -25
- package/dist/runtime/context/restore.d.ts +3 -2
- package/dist/runtime/context/restore.js +52 -0
- package/dist/runtime/execution.d.ts +5 -2
- package/dist/runtime/execution.js +133 -48
- package/dist/runtime/tool-round-contract.d.ts +7 -0
- package/dist/sdk/execution-model-lifecycle.d.ts +1 -1
- package/dist/sdk/execution-model-lifecycle.js +6 -2
- package/dist/sdk/execution-tool-scope.d.ts +1 -1
- package/dist/sdk/execution-tool-scope.js +24 -1
- package/dist/sdk/session-execution-factory.js +14 -2
- package/dist/tools/execution.d.ts +4 -1
- package/dist/tools/execution.js +89 -8
- package/dist/tools/permissions.d.ts +4 -0
- package/dist/tools/permissions.js +25 -0
- package/dist/tools/runtime-context.d.ts +2 -0
- package/package.json +1 -1
|
@@ -18,7 +18,7 @@ export declare class ExtensionSessionTools {
|
|
|
18
18
|
private readonly scheduleTool;
|
|
19
19
|
private readonly assertLive;
|
|
20
20
|
private readonly isRetired;
|
|
21
|
-
constructor(toolRuntime: ExtensionToolRuntime, operations: Pick<ExtensionOperations, 'callback' | 'continue'>, hooks: Pick<ExtensionHooks<DomainToolOperations, DomainToolFacts>, 'invoke' | 'emit'>, baseTools: (context?: ExtensionOperationContext) => readonly ExtensionToolBinding[], allowTool: (name: string, definition?: ExtensionToolBinding['definition']) => boolean, scheduleTool: <T>(definition: ExtensionToolBinding['definition'], run: () => Promise<T>) => Promise<T>, assertLive: () => void, isRetired: () => boolean);
|
|
21
|
+
constructor(toolRuntime: ExtensionToolRuntime, operations: Pick<ExtensionOperations, 'callback' | 'continue'>, hooks: Pick<ExtensionHooks<DomainToolOperations, DomainToolFacts>, 'invoke' | 'emit' | 'hasInterceptors'>, baseTools: (context?: ExtensionOperationContext) => readonly ExtensionToolBinding[], allowTool: (name: string, definition?: ExtensionToolBinding['definition']) => boolean, scheduleTool: <T>(definition: ExtensionToolBinding['definition'], run: () => Promise<T>) => Promise<T>, assertLive: () => void, isRetired: () => boolean);
|
|
22
22
|
readonly tools: ExtensionTools;
|
|
23
23
|
private get toolFrame();
|
|
24
24
|
/** Release propagation only after the Session owner has joined all scoped tool work. */
|
|
@@ -29,7 +29,7 @@ export declare class ExtensionSessionTools {
|
|
|
29
29
|
bind(scope: ExtensionResourceScope, extensionId: string, run: ExtensionOperationRunner, current: () => ExtensionOperationContext | undefined): ExtensionToolsApi;
|
|
30
30
|
toolRef(binding: ExtensionToolBinding): ExtensionToolRef;
|
|
31
31
|
capture(context?: ExtensionOperationContext, includeStaged?: boolean, base?: readonly ExtensionToolBinding[]): ReadonlyMap<string, ExtensionToolBinding>;
|
|
32
|
-
invoke(call: ToolCall, context: ExtensionOperationContext, snapshot?: ReadonlyMap<string, ExtensionToolBinding>): Promise<ToolExecutionResult>;
|
|
32
|
+
invoke(call: ToolCall, context: ExtensionOperationContext, snapshot?: ReadonlyMap<string, ExtensionToolBinding>, admitEarlyHandler?: (eligible: boolean) => Promise<void>): Promise<ToolExecutionResult>;
|
|
33
33
|
private assertToolAvailable;
|
|
34
34
|
private toolAttempt;
|
|
35
35
|
check(call: ExtensionToolInvocation, context: ExtensionOperationContext): ExtensionToolCheck;
|
|
@@ -123,7 +123,7 @@ export class ExtensionSessionTools {
|
|
|
123
123
|
const tools = this.tools.capture(base ?? this.baseTools(context), includeStaged || ExtensionResourceScope.initializing);
|
|
124
124
|
return new Map([...tools].filter(([name, binding]) => this.allowTool(name, binding.definition)));
|
|
125
125
|
}
|
|
126
|
-
async invoke(call, context, snapshot = this.capture(context)) {
|
|
126
|
+
async invoke(call, context, snapshot = this.capture(context), admitEarlyHandler) {
|
|
127
127
|
this.assertLive();
|
|
128
128
|
const permissionPolicy = this.toolRuntime.currentPermissions(context);
|
|
129
129
|
let approved;
|
|
@@ -148,25 +148,40 @@ export class ExtensionSessionTools {
|
|
|
148
148
|
: {}),
|
|
149
149
|
...(call.callId === undefined ? {} : { toolCallId: call.callId })
|
|
150
150
|
});
|
|
151
|
-
return this.operations.continue(effective, () => this.toolAttempt(call, effective, 'result',
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
151
|
+
return this.operations.continue(effective, () => this.toolAttempt(call, effective, 'result', async () => {
|
|
152
|
+
if (admitEarlyHandler && this.hooks.hasInterceptors('tool.invoke'))
|
|
153
|
+
throw new AgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool interception changed during early dispatch.');
|
|
154
|
+
return this.hooks.invoke('tool.invoke', call, effective, async (target, effective) => {
|
|
155
|
+
const binding = snapshot.get(target.name);
|
|
156
|
+
if (!binding)
|
|
157
|
+
throw new AgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Tool source is unavailable.');
|
|
158
|
+
this.assertToolAvailable(binding, effective);
|
|
159
|
+
permissionPolicy?.assertDispatch();
|
|
160
|
+
const normalized = this.toolRuntime.normalizeInput(target.arguments, binding.definition.inputSchema);
|
|
161
|
+
const explicitlyApproved = approved?.name === target.name &&
|
|
162
|
+
isDeepStrictEqual(normalized, this.toolRuntime.normalizeInput(approved.arguments, binding.definition.inputSchema));
|
|
163
|
+
if (admitEarlyHandler) {
|
|
164
|
+
// Only the validated terminal binding can leave an irreversible admission record.
|
|
165
|
+
await admitEarlyHandler(context.entry === 'direct' &&
|
|
166
|
+
call.name === 'exec' &&
|
|
167
|
+
target.name === call.name &&
|
|
168
|
+
target.callId === call.callId &&
|
|
169
|
+
binding.source.kind === 'builtin' &&
|
|
170
|
+
approved === undefined);
|
|
171
|
+
effective.signal?.throwIfAborted();
|
|
172
|
+
permissionPolicy?.assertDispatch();
|
|
173
|
+
}
|
|
174
|
+
return binding.invoke({
|
|
175
|
+
...target,
|
|
176
|
+
arguments: normalized
|
|
177
|
+
}, explicitlyApproved
|
|
178
|
+
? Object.freeze({
|
|
179
|
+
...effective,
|
|
180
|
+
permission: Object.freeze({ decision: 'approved' })
|
|
181
|
+
})
|
|
182
|
+
: effective);
|
|
183
|
+
});
|
|
184
|
+
}));
|
|
170
185
|
}
|
|
171
186
|
assertToolAvailable(binding, call) {
|
|
172
187
|
this.assertLive();
|
|
@@ -45,7 +45,7 @@ export declare class ExtensionSession {
|
|
|
45
45
|
context(extension: AgentExtension, scope: ExtensionResourceScope): SessionExtensionContext;
|
|
46
46
|
withTools<T>(bindings: ReadonlyMap<string, ExtensionToolBinding>, schedule: <Value>(definition: ExtensionToolBinding['definition'], run: () => Promise<Value>) => Promise<Value>, run: () => T): T;
|
|
47
47
|
capture(context?: ExtensionOperationContext, includeStaged?: boolean, base?: readonly ExtensionToolBinding[]): ReadonlyMap<string, ExtensionToolBinding>;
|
|
48
|
-
invoke(call: ToolCall, context: ExtensionOperationContext, snapshot?: ReadonlyMap<string, ExtensionToolBinding>): Promise<ToolExecutionResult>;
|
|
48
|
+
invoke(call: ToolCall, context: ExtensionOperationContext, snapshot?: ReadonlyMap<string, ExtensionToolBinding>, admitEarlyHandler?: (eligible: boolean) => Promise<void>): Promise<ToolExecutionResult>;
|
|
49
49
|
modelEvent(event: ExtensionModelEvent, call: ExtensionOperationContext): Promise<ExtensionModelEvent | undefined>;
|
|
50
50
|
composeModelSystem(system: string | ExtensionPromptComposition, call: ExtensionOperationContext): Promise<{
|
|
51
51
|
text: string;
|
|
@@ -220,8 +220,8 @@ export class ExtensionSession {
|
|
|
220
220
|
capture(context, includeStaged = false, base) {
|
|
221
221
|
return this.#toolDomain.capture(context, includeStaged, base);
|
|
222
222
|
}
|
|
223
|
-
invoke(call, context, snapshot) {
|
|
224
|
-
return this.#toolDomain.invoke(call, context, snapshot);
|
|
223
|
+
invoke(call, context, snapshot, admitEarlyHandler) {
|
|
224
|
+
return this.#toolDomain.invoke(call, context, snapshot, admitEarlyHandler);
|
|
225
225
|
}
|
|
226
226
|
async modelEvent(event, call) {
|
|
227
227
|
await this.hooks.emit('model.event', event, call);
|
|
@@ -216,32 +216,26 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
216
216
|
const customCallIds = new Set();
|
|
217
217
|
const searchCallIds = new Set();
|
|
218
218
|
const providerMessageTexts = new Set();
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
if (
|
|
228
|
-
|
|
229
|
-
|
|
219
|
+
const rememberProviderCall = (item) => {
|
|
220
|
+
const ids = item.type === 'function_call'
|
|
221
|
+
? functionCallIds
|
|
222
|
+
: nativeTools && item.type === 'custom_tool_call'
|
|
223
|
+
? customCallIds
|
|
224
|
+
: nativeTools && item.type === 'tool_search_call'
|
|
225
|
+
? searchCallIds
|
|
226
|
+
: undefined;
|
|
227
|
+
if (!ids || typeof item.call_id !== 'string')
|
|
228
|
+
return;
|
|
229
|
+
ids.add(item.call_id);
|
|
230
|
+
providerCallIds.add(item.call_id);
|
|
231
|
+
};
|
|
232
|
+
// The logical suffix can include a generic call already held by the WebSocket response.
|
|
233
|
+
for (const item of previousOutputItems)
|
|
234
|
+
rememberProviderCall(item);
|
|
230
235
|
for (const message of compatibleMessages) {
|
|
231
236
|
if (message.role !== 'provider' || !message.item)
|
|
232
237
|
continue;
|
|
233
|
-
|
|
234
|
-
providerCallIds.add(message.item.call_id);
|
|
235
|
-
functionCallIds.add(message.item.call_id);
|
|
236
|
-
}
|
|
237
|
-
if (message.item.type === 'tool_search_call' && typeof message.item.call_id === 'string') {
|
|
238
|
-
providerCallIds.add(message.item.call_id);
|
|
239
|
-
searchCallIds.add(message.item.call_id);
|
|
240
|
-
}
|
|
241
|
-
if (message.item.type === 'custom_tool_call' && typeof message.item.call_id === 'string') {
|
|
242
|
-
providerCallIds.add(message.item.call_id);
|
|
243
|
-
customCallIds.add(message.item.call_id);
|
|
244
|
-
}
|
|
238
|
+
rememberProviderCall(message.item);
|
|
245
239
|
if (message.item.type === 'message') {
|
|
246
240
|
const content = Array.isArray(message.item.content) ? message.item.content : [];
|
|
247
241
|
const value = content
|
|
@@ -255,7 +249,12 @@ export function openAiInput(messages, images, modelId, requireEncryptedReasoning
|
|
|
255
249
|
}
|
|
256
250
|
}
|
|
257
251
|
for (const message of compatibleMessages) {
|
|
258
|
-
|
|
252
|
+
// Only reconstructed calls contribute type information; skipped generic calls cannot
|
|
253
|
+
// change the result family of a retained native call.
|
|
254
|
+
if (!nativeTools ||
|
|
255
|
+
message.role !== 'tool_call' ||
|
|
256
|
+
!message.callId ||
|
|
257
|
+
providerCallIds.has(message.callId))
|
|
259
258
|
continue;
|
|
260
259
|
if (message.inputMode === 'freeform')
|
|
261
260
|
customCallIds.add(message.callId);
|
|
@@ -343,7 +342,8 @@ function openAiInputItem(message, images, customCallIds = new Set(), functionCal
|
|
|
343
342
|
if (message.role === 'tool' &&
|
|
344
343
|
nativeTools &&
|
|
345
344
|
message.toolSearchTools &&
|
|
346
|
-
!functionCallIds.has(message.callId ?? '')
|
|
345
|
+
!functionCallIds.has(message.callId ?? '') &&
|
|
346
|
+
!customCallIds.has(message.callId ?? '')) {
|
|
347
347
|
const placeholders = deferredPlaceholders ? new Map() : undefined;
|
|
348
348
|
const projectedTools = message.toolSearchTools.map((tool) => responsesFunctionTool(tool, true, placeholders));
|
|
349
349
|
if (placeholders && message.callId)
|
|
@@ -4,9 +4,10 @@ import type { ModelImage } from '../../model/image.js';
|
|
|
4
4
|
import type { CompactUserInput } from '../../session/record-contract.js';
|
|
5
5
|
import type { EnvironmentContextState } from './contracts.js';
|
|
6
6
|
import { type ContextProjection } from './projection.js';
|
|
7
|
+
import type { SessionRecord } from '../../session/record-contract.js';
|
|
7
8
|
type RestoreStore = Pick<SessionStore, 'readResource' | 'readInputImages'>;
|
|
8
9
|
export declare function readResourceImages(store: Pick<SessionStore, 'readResource'>, sessionId: string, images: readonly ModelImage[]): Promise<ModelImage[]>;
|
|
9
|
-
export declare function restoreMessages(store: RestoreStore, sessionId: string, records: readonly
|
|
10
|
+
export declare function restoreMessages(store: RestoreStore, sessionId: string, records: readonly SessionRecord[], options: {
|
|
10
11
|
includeImages: boolean;
|
|
11
12
|
strictImages?: boolean;
|
|
12
13
|
currentTurnId?: string;
|
|
@@ -17,7 +18,7 @@ export declare function restoreMessages(store: RestoreStore, sessionId: string,
|
|
|
17
18
|
isError: boolean;
|
|
18
19
|
result?: unknown;
|
|
19
20
|
}>;
|
|
20
|
-
pendingInputs: Map<string,
|
|
21
|
+
pendingInputs: Map<string, SessionRecord>;
|
|
21
22
|
environmentState: EnvironmentContextState | undefined;
|
|
22
23
|
userMessages: CompactUserInput[];
|
|
23
24
|
messages: ModelMessage[];
|
|
@@ -25,11 +25,13 @@ export async function restoreMessages(store, sessionId, records, options) {
|
|
|
25
25
|
let currentTurnUserIndex;
|
|
26
26
|
let environmentState;
|
|
27
27
|
const pendingInputs = pendingDeferredInputs(records);
|
|
28
|
+
const unresolved = unresolvedEarlyDispatches(records);
|
|
28
29
|
for (const record of records) {
|
|
29
30
|
const messageStart = messages.length;
|
|
30
31
|
const applied = appliedInputRecord(record);
|
|
31
32
|
const inputRecord = applied ?? record;
|
|
32
33
|
const payload = inputRecord.payload;
|
|
34
|
+
const unresolvedDispatch = unresolved.get(record.recordId);
|
|
33
35
|
if ((record.type === 'tool.completed' || record.type === 'tool.failed') &&
|
|
34
36
|
typeof payload.callId === 'string') {
|
|
35
37
|
const result = record.type === 'tool.failed' ? payload.message : payload.data;
|
|
@@ -145,6 +147,18 @@ export async function restoreMessages(store, sessionId, records, options) {
|
|
|
145
147
|
environmentState = current;
|
|
146
148
|
}
|
|
147
149
|
}
|
|
150
|
+
else if (unresolvedDispatch) {
|
|
151
|
+
// The provider may never have sent the native call item. Do not synthesize a protocol item.
|
|
152
|
+
const call = JSON.stringify(unresolvedDispatch.callId);
|
|
153
|
+
const location = unresolvedDispatch.startedSequence === undefined
|
|
154
|
+
? `tool.early_admitted session record #${unresolvedDispatch.admittedSequence}`
|
|
155
|
+
: `tool.started session record #${unresolvedDispatch.startedSequence}`;
|
|
156
|
+
messages.push({
|
|
157
|
+
role: 'user',
|
|
158
|
+
contextKind: 'contextual',
|
|
159
|
+
content: `A previously admitted exec (call ID ${call}; ${location}) may have run, but no tool result was committed. Verify its effects before attempting the operation again.`
|
|
160
|
+
});
|
|
161
|
+
}
|
|
148
162
|
else if (record.type === 'model.context') {
|
|
149
163
|
const message = modelProjection.get(record.recordId);
|
|
150
164
|
if (message) {
|
|
@@ -184,3 +198,41 @@ export async function restoreMessages(store, sessionId, records, options) {
|
|
|
184
198
|
currentTurnUserIndex
|
|
185
199
|
};
|
|
186
200
|
}
|
|
201
|
+
/** Locate unresolved admissions using existing record identities, never event input or command text. */
|
|
202
|
+
function unresolvedEarlyDispatches(records) {
|
|
203
|
+
const pending = new Map();
|
|
204
|
+
for (const record of records) {
|
|
205
|
+
if (record.type !== 'tool.early_admitted' && record.type !== 'model.context')
|
|
206
|
+
continue;
|
|
207
|
+
const payload = record.payload;
|
|
208
|
+
if (typeof payload.callId !== 'string')
|
|
209
|
+
continue;
|
|
210
|
+
const key = JSON.stringify([record.executionId, payload.callId]);
|
|
211
|
+
if (record.type === 'tool.early_admitted')
|
|
212
|
+
pending.set(key, { record, callId: payload.callId });
|
|
213
|
+
else if (payload.role === 'tool')
|
|
214
|
+
pending.delete(key);
|
|
215
|
+
}
|
|
216
|
+
const unresolved = new Map([...pending].slice(-16));
|
|
217
|
+
if (unresolved.size > 0)
|
|
218
|
+
for (const record of records) {
|
|
219
|
+
if (record.type !== 'tool.started')
|
|
220
|
+
continue;
|
|
221
|
+
const payload = record.payload;
|
|
222
|
+
if (payload.toolName !== 'exec' ||
|
|
223
|
+
typeof payload.callId !== 'string' ||
|
|
224
|
+
payload.parentCallId !== undefined)
|
|
225
|
+
continue;
|
|
226
|
+
const dispatch = unresolved.get(JSON.stringify([record.executionId, payload.callId]));
|
|
227
|
+
if (dispatch && record.sequence < dispatch.record.sequence)
|
|
228
|
+
dispatch.startedSequence = record.sequence;
|
|
229
|
+
}
|
|
230
|
+
return new Map([...unresolved.values()].map(({ record, callId, startedSequence }) => [
|
|
231
|
+
record.recordId,
|
|
232
|
+
{
|
|
233
|
+
callId: callId.length > 128 ? `${callId.slice(0, 128)}…` : callId,
|
|
234
|
+
admittedSequence: record.sequence,
|
|
235
|
+
startedSequence
|
|
236
|
+
}
|
|
237
|
+
]));
|
|
238
|
+
}
|
|
@@ -2,7 +2,7 @@ import type { SessionModelMessage as ModelMessage } from '../session/model-reque
|
|
|
2
2
|
import type { SessionModelRequest as ModelRequest } from '../session/model-request.js';
|
|
3
3
|
import type { AgentModelConfiguration } from '../model/configuration.js';
|
|
4
4
|
import type { ModelEvent, ModelUsage } from '../model/contracts.js';
|
|
5
|
-
import type { ClientToolCall, ExecutedToolCall } from './tool-round-contract.js';
|
|
5
|
+
import type { ClientToolCall, ExecutedToolCall, StreamingToolRound } from './tool-round-contract.js';
|
|
6
6
|
import type { AuthoritativeModelUsage } from './context/usage.js';
|
|
7
7
|
import type { ExecutionMode } from './contracts.js';
|
|
8
8
|
import type { EventPayload } from './events.js';
|
|
@@ -26,13 +26,14 @@ export interface ExecutionLoopInput<TScope = unknown> {
|
|
|
26
26
|
readonly appendContext: (message: ModelMessage) => Promise<void>;
|
|
27
27
|
readonly prepareRound: () => Promise<PreparedExecutionRound<TScope>>;
|
|
28
28
|
readonly runTools: (calls: readonly ClientToolCall[], scope: TScope) => Promise<ExecutedToolCall[]>;
|
|
29
|
+
readonly openToolRound?: (scope: TScope) => StreamingToolRound;
|
|
29
30
|
readonly startModel: (request: ModelRequest) => AsyncIterable<ModelEvent>;
|
|
30
31
|
readonly recoverySignal: () => AbortSignal;
|
|
31
32
|
readonly compactContext: () => Promise<boolean>;
|
|
32
33
|
readonly compactionFallback?: (() => boolean) | undefined;
|
|
33
34
|
readonly observeUsage: (usage: Omit<AuthoritativeModelUsage, 'historyMessages'> | undefined) => void;
|
|
34
35
|
readonly observeContextTokens: (tokens: number) => void;
|
|
35
|
-
readonly afterModel?: (closedPrefixLength: number, acceptedRequest?: ModelRequest) => Promise<void>;
|
|
36
|
+
readonly afterModel?: (continuing: boolean, closedPrefixLength: number, acceptedRequest?: ModelRequest) => Promise<void>;
|
|
36
37
|
readonly checkpoint: (round: PreparedExecutionRound<TScope>, usage: ModelUsage | undefined, thoughtCallIds: readonly string[]) => Promise<void>;
|
|
37
38
|
readonly mailbox: {
|
|
38
39
|
hasPending(): boolean;
|
|
@@ -52,4 +53,6 @@ export declare class ExecutionLoop<TScope = unknown> {
|
|
|
52
53
|
finalAnswer: string;
|
|
53
54
|
usage?: ModelUsage;
|
|
54
55
|
}>;
|
|
56
|
+
private runRounds;
|
|
57
|
+
private persistToolResult;
|
|
55
58
|
}
|
|
@@ -21,6 +21,19 @@ export class ExecutionLoop {
|
|
|
21
21
|
this.input = input;
|
|
22
22
|
}
|
|
23
23
|
async run() {
|
|
24
|
+
let drain;
|
|
25
|
+
try {
|
|
26
|
+
return await this.runRounds((next) => {
|
|
27
|
+
drain = next;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
// Preserve the original failure even if the writer is no longer usable.
|
|
32
|
+
await drain?.().catch(() => undefined);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async runRounds(setDrain) {
|
|
24
37
|
const input = this.input;
|
|
25
38
|
const { mode, messages } = input;
|
|
26
39
|
let recoveringFromContextOverflow = false;
|
|
@@ -33,7 +46,12 @@ export class ExecutionLoop {
|
|
|
33
46
|
let roundServerUsage;
|
|
34
47
|
const pendingTools = [];
|
|
35
48
|
let incompleteToolCall = false;
|
|
49
|
+
let discardedToolResults;
|
|
36
50
|
const round = await input.prepareRound();
|
|
51
|
+
const streaming = mode === 'run' ? input.openToolRound?.(round.toolScope) : undefined;
|
|
52
|
+
const callIds = streaming ? new Set() : undefined;
|
|
53
|
+
const recordedCalls = new Set();
|
|
54
|
+
const recordedResults = new Set();
|
|
37
55
|
const reasoningScope = randomUUID();
|
|
38
56
|
const publishedReasoning = new Set();
|
|
39
57
|
const startedMessages = new Set();
|
|
@@ -77,6 +95,8 @@ export class ExecutionLoop {
|
|
|
77
95
|
};
|
|
78
96
|
const persistToolCalls = async (calls) => {
|
|
79
97
|
for (const call of calls) {
|
|
98
|
+
if (recordedCalls.has(call))
|
|
99
|
+
continue;
|
|
80
100
|
const message = {
|
|
81
101
|
role: 'tool_call',
|
|
82
102
|
callId: call.callId,
|
|
@@ -85,10 +105,31 @@ export class ExecutionLoop {
|
|
|
85
105
|
...(call.inputMode ? { inputMode: call.inputMode } : {}),
|
|
86
106
|
content: ''
|
|
87
107
|
};
|
|
88
|
-
messages.push(message);
|
|
89
108
|
await input.appendContext(message);
|
|
109
|
+
messages.push(message);
|
|
110
|
+
recordedCalls.add(call);
|
|
90
111
|
}
|
|
91
112
|
};
|
|
113
|
+
const persistToolResults = async (results) => {
|
|
114
|
+
const byCall = new Map(results.map((result) => [result.call, result]));
|
|
115
|
+
// A committed streaming batch can be interrupted before every entry starts.
|
|
116
|
+
// Close its journal slots in model order without publishing synthetic tool events.
|
|
117
|
+
for (const call of streaming ? recordedCalls : byCall.keys()) {
|
|
118
|
+
if (recordedResults.has(call))
|
|
119
|
+
continue;
|
|
120
|
+
const result = byCall.get(call) ?? missingToolResult(call);
|
|
121
|
+
await this.persistToolResult(result);
|
|
122
|
+
recordedResults.add(call);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const stopTools = streaming === undefined
|
|
126
|
+
? undefined
|
|
127
|
+
: async (cancelInFlight) => {
|
|
128
|
+
const results = await streaming.stop(cancelInFlight);
|
|
129
|
+
await persistToolCalls(results.map(({ call }) => call));
|
|
130
|
+
await persistToolResults(results);
|
|
131
|
+
};
|
|
132
|
+
setDrain(stopTools);
|
|
92
133
|
const requestStartedAt = performance.now();
|
|
93
134
|
const tpsStartedAt = retryTpsStartedAt ?? requestStartedAt;
|
|
94
135
|
retryTpsStartedAt = undefined;
|
|
@@ -98,6 +139,8 @@ export class ExecutionLoop {
|
|
|
98
139
|
retryState: modelRetryState
|
|
99
140
|
})) {
|
|
100
141
|
if (event.type === 'output.reset') {
|
|
142
|
+
if (streaming && pendingTools.length)
|
|
143
|
+
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model reset after emitting a complete tool call.');
|
|
101
144
|
generation = new ModelGenerationTiming();
|
|
102
145
|
requestCompletedAt = undefined;
|
|
103
146
|
requestOutputTokens = undefined;
|
|
@@ -272,38 +315,56 @@ export class ExecutionLoop {
|
|
|
272
315
|
if (mode === 'compact')
|
|
273
316
|
throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Compaction returned a tool call while tools were disabled.');
|
|
274
317
|
sawTool = true;
|
|
318
|
+
if (callIds?.has(event.callId))
|
|
319
|
+
continue;
|
|
320
|
+
callIds?.add(event.callId);
|
|
275
321
|
pendingTools.push(event);
|
|
322
|
+
streaming?.enqueue(event);
|
|
276
323
|
}
|
|
277
324
|
else if (event.type === 'completed') {
|
|
278
325
|
stop = event.reason;
|
|
279
326
|
requestCompletedAt = observedAt;
|
|
327
|
+
// An adapter can still await cleanup after yielding its terminal event.
|
|
328
|
+
if (stop === 'cancelled')
|
|
329
|
+
discardedToolResults = streaming?.stop();
|
|
330
|
+
else if (stop === 'max_output' &&
|
|
331
|
+
pendingTools.some((call) => call.argumentError !== undefined))
|
|
332
|
+
discardedToolResults = streaming?.stop(false);
|
|
280
333
|
}
|
|
281
334
|
if (isFirstModelResponse)
|
|
282
335
|
await emitLatency();
|
|
283
336
|
}
|
|
337
|
+
incompleteToolCall = pendingTools.some((call) => call.argumentError !== undefined);
|
|
338
|
+
if (stop === 'max_output' && incompleteToolCall)
|
|
339
|
+
pendingTools.length = 0;
|
|
284
340
|
if (mode !== 'compact' &&
|
|
285
341
|
stop !== 'cancelled' &&
|
|
286
342
|
!input.signal.aborted &&
|
|
287
343
|
requestCompletedAt !== undefined)
|
|
288
344
|
await emitFinalPerformance(requestCompletedAt);
|
|
289
|
-
|
|
290
|
-
if (!(stop === 'max_output' && incompleteToolCall)) {
|
|
345
|
+
if (!streaming)
|
|
291
346
|
await persistToolCalls(pendingTools);
|
|
292
|
-
}
|
|
293
|
-
else
|
|
294
|
-
pendingTools.splice(0, pendingTools.length);
|
|
295
347
|
}
|
|
296
348
|
catch (error) {
|
|
297
349
|
this.planOutputPrefixes.clear();
|
|
350
|
+
const mixedBatch = pendingTools.some((call) => call.argumentError !== undefined);
|
|
351
|
+
// A queued exec must not become an admitted side effect while model recovery is backing off.
|
|
352
|
+
const discardedOnDisconnect = mixedBatch ? streaming?.stop(false) : undefined;
|
|
298
353
|
if (await recoverModelStream(error, modelRetryState, input.recoverySignal())) {
|
|
299
354
|
this.finalAnswer = '';
|
|
300
355
|
if (mode === 'compact')
|
|
301
356
|
messages.splice(roundMessageCount);
|
|
302
|
-
if (
|
|
357
|
+
if (mixedBatch) {
|
|
358
|
+
await discardedOnDisconnect;
|
|
359
|
+
// The outer failure drain preserves any already admitted results without replaying.
|
|
360
|
+
if (streaming?.hasAdmitted())
|
|
361
|
+
throw error;
|
|
303
362
|
pendingTools.splice(0, pendingTools.length);
|
|
304
|
-
|
|
363
|
+
}
|
|
364
|
+
else if (!streaming && pendingTools.length > 0)
|
|
305
365
|
await persistToolCalls(pendingTools);
|
|
306
366
|
if (pendingTools.length === 0) {
|
|
367
|
+
await stopTools?.();
|
|
307
368
|
// Runtime recovery continues the same logical request unless it runs a tool.
|
|
308
369
|
retryTpsStartedAt = tpsStartedAt;
|
|
309
370
|
continue;
|
|
@@ -334,49 +395,26 @@ export class ExecutionLoop {
|
|
|
334
395
|
const outputLimitReached = mode !== 'compact' && stop === 'max_output';
|
|
335
396
|
if (outputLimitReached)
|
|
336
397
|
this.finalAnswer = '';
|
|
398
|
+
if (streaming && (stop === 'cancelled' || input.signal.aborted))
|
|
399
|
+
throw new AgentError('MAR_AGENT_EXECUTION_CANCELLED', 'Execution cancelled.');
|
|
337
400
|
input.observeUsage(roundServerUsage);
|
|
338
401
|
const emptyCompletion = stop === 'completed' && !sawTool && !this.finalAnswer.trim();
|
|
339
|
-
await input.afterModel?.(pendingTools.length ? roundMessageCount : messages.length, emptyCompletion || stop === 'cancelled' ? undefined : round.request);
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
input.toolImages.push(...result.sourceImages
|
|
344
|
-
.filter((image) => image.dataBase64 !== undefined)
|
|
345
|
-
.map((image) => ({
|
|
346
|
-
mimeType: image.mimeType,
|
|
347
|
-
data: Buffer.from(image.dataBase64, 'base64')
|
|
348
|
-
})));
|
|
349
|
-
const toolSearchTools = result.call.name === 'tool_search' && !result.failed
|
|
350
|
-
? result.output.toolSearchTools
|
|
351
|
-
: undefined;
|
|
352
|
-
const message = {
|
|
353
|
-
role: 'tool',
|
|
354
|
-
callId: result.call.callId,
|
|
355
|
-
name: result.call.name,
|
|
356
|
-
isError: result.failed,
|
|
357
|
-
content: result.content,
|
|
358
|
-
...(result.calls ? { calls: result.calls } : {}),
|
|
359
|
-
...(result.observations ? { observations: result.observations } : {}),
|
|
360
|
-
...(toolSearchTools === undefined ? {} : { toolSearchTools }),
|
|
361
|
-
...('images' in result && result.images?.length ? { images: result.images } : {})
|
|
362
|
-
};
|
|
363
|
-
messages.push(message);
|
|
364
|
-
await input.appendContext({
|
|
365
|
-
role: message.role,
|
|
366
|
-
callId: result.call.callId,
|
|
367
|
-
name: result.call.name,
|
|
368
|
-
isError: result.failed,
|
|
369
|
-
content: message.content,
|
|
370
|
-
...(message.calls ? { calls: message.calls } : {}),
|
|
371
|
-
...(message.observations ? { observations: message.observations } : {}),
|
|
372
|
-
...(message.images?.length
|
|
373
|
-
? { images: message.images.map(({ dataBase64: _bytes, ...image }) => image) }
|
|
374
|
-
: {}),
|
|
375
|
-
...(message.toolSearchTools === undefined
|
|
376
|
-
? {}
|
|
377
|
-
: { toolSearchTools: message.toolSearchTools })
|
|
378
|
-
});
|
|
402
|
+
await input.afterModel?.(stop !== 'cancelled' && (pendingTools.length > 0 || stop === 'pause'), pendingTools.length || discardedToolResults ? roundMessageCount : messages.length, emptyCompletion || stop === 'cancelled' || discardedToolResults ? undefined : round.request);
|
|
403
|
+
if (streaming && pendingTools.length) {
|
|
404
|
+
input.signal.throwIfAborted();
|
|
405
|
+
await persistToolCalls(pendingTools);
|
|
379
406
|
}
|
|
407
|
+
const toolResults = discardedToolResults
|
|
408
|
+
? await discardedToolResults
|
|
409
|
+
: streaming
|
|
410
|
+
? pendingTools.length
|
|
411
|
+
? await streaming.finish()
|
|
412
|
+
: []
|
|
413
|
+
: await input.runTools(pendingTools, round.toolScope);
|
|
414
|
+
if (discardedToolResults)
|
|
415
|
+
await persistToolCalls(toolResults.map(({ call }) => call));
|
|
416
|
+
await persistToolResults(toolResults);
|
|
417
|
+
setDrain();
|
|
380
418
|
if (sawTool) {
|
|
381
419
|
modelRetryState.attempts = 0;
|
|
382
420
|
if (input.sourceType === 'subagent')
|
|
@@ -439,6 +477,53 @@ export class ExecutionLoop {
|
|
|
439
477
|
modelRetryState.attempts = 0;
|
|
440
478
|
}
|
|
441
479
|
}
|
|
480
|
+
async persistToolResult(result) {
|
|
481
|
+
const input = this.input;
|
|
482
|
+
if ('sourceImages' in result && result.sourceImages?.length)
|
|
483
|
+
input.toolImages.push(...result.sourceImages
|
|
484
|
+
.filter((image) => image.dataBase64 !== undefined)
|
|
485
|
+
.map((image) => ({
|
|
486
|
+
mimeType: image.mimeType,
|
|
487
|
+
data: Buffer.from(image.dataBase64, 'base64')
|
|
488
|
+
})));
|
|
489
|
+
const toolSearchTools = result.call.name === 'tool_search' && !result.failed
|
|
490
|
+
? result.output.toolSearchTools
|
|
491
|
+
: undefined;
|
|
492
|
+
const message = {
|
|
493
|
+
role: 'tool',
|
|
494
|
+
callId: result.call.callId,
|
|
495
|
+
name: result.call.name,
|
|
496
|
+
isError: result.failed,
|
|
497
|
+
content: result.content,
|
|
498
|
+
...(result.calls ? { calls: result.calls } : {}),
|
|
499
|
+
...(result.observations ? { observations: result.observations } : {}),
|
|
500
|
+
...(toolSearchTools === undefined ? {} : { toolSearchTools }),
|
|
501
|
+
...('images' in result && result.images?.length ? { images: result.images } : {})
|
|
502
|
+
};
|
|
503
|
+
await input.appendContext({
|
|
504
|
+
role: message.role,
|
|
505
|
+
callId: result.call.callId,
|
|
506
|
+
name: result.call.name,
|
|
507
|
+
isError: result.failed,
|
|
508
|
+
content: message.content,
|
|
509
|
+
...(message.calls ? { calls: message.calls } : {}),
|
|
510
|
+
...(message.observations ? { observations: message.observations } : {}),
|
|
511
|
+
...(message.images?.length
|
|
512
|
+
? { images: message.images.map(({ dataBase64: _bytes, ...image }) => image) }
|
|
513
|
+
: {}),
|
|
514
|
+
...(message.toolSearchTools === undefined ? {} : { toolSearchTools: message.toolSearchTools })
|
|
515
|
+
});
|
|
516
|
+
input.messages.push(message);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
function missingToolResult(call) {
|
|
520
|
+
const error = new AgentError('MAR_AGENT_TOOL_RESULT_UNAVAILABLE', 'The tool round ended without a recorded result for this call.');
|
|
521
|
+
return {
|
|
522
|
+
call,
|
|
523
|
+
failed: true,
|
|
524
|
+
error,
|
|
525
|
+
content: JSON.stringify({ error: error.code, message: error.message })
|
|
526
|
+
};
|
|
442
527
|
}
|
|
443
528
|
function isModelResponseEvent(event) {
|
|
444
529
|
if (event.type === 'text.delta')
|
|
@@ -3,6 +3,13 @@ import type { ToolExecutionResult } from '../tools/contracts.js';
|
|
|
3
3
|
export type ClientToolCall = Extract<ModelEvent, {
|
|
4
4
|
type: 'client_tool.call';
|
|
5
5
|
}>;
|
|
6
|
+
/** Dispatch may overlap streaming; only the ExecutionLoop commits results to model history. */
|
|
7
|
+
export interface StreamingToolRound {
|
|
8
|
+
enqueue(call: ClientToolCall): void;
|
|
9
|
+
finish(): Promise<ExecutedToolCall[]>;
|
|
10
|
+
stop(cancelInFlight?: boolean): Promise<ExecutedToolCall[]>;
|
|
11
|
+
hasAdmitted(): boolean;
|
|
12
|
+
}
|
|
6
13
|
export type ExecutedToolCall = {
|
|
7
14
|
call: ClientToolCall;
|
|
8
15
|
content: string;
|
|
@@ -33,7 +33,7 @@ export declare class ExecutionModelLifecycle {
|
|
|
33
33
|
resetSmart(): void;
|
|
34
34
|
invalidate(): void;
|
|
35
35
|
start(request: SessionModelRequest, onCompleted?: () => Promise<void>): AsyncIterable<ModelEvent>;
|
|
36
|
-
afterModel(closedPrefixLength: number, request: SessionModelRequest | undefined): Promise<void>;
|
|
36
|
+
afterModel(continuing: boolean, closedPrefixLength: number, request: SessionModelRequest | undefined): Promise<void>;
|
|
37
37
|
observeTokens(tokens: number): void;
|
|
38
38
|
observeUsage(usage: Omit<AuthoritativeModelUsage, 'historyMessages'> | undefined): void;
|
|
39
39
|
}
|
|
@@ -48,13 +48,17 @@ export class ExecutionModelLifecycle {
|
|
|
48
48
|
}
|
|
49
49
|
}, ports.signal);
|
|
50
50
|
}
|
|
51
|
-
async afterModel(closedPrefixLength, request) {
|
|
51
|
+
async afterModel(continuing, closedPrefixLength, request) {
|
|
52
52
|
this.ports.turn.commitContinuationInput?.(this.dispatchedInputs + this.ports.messages.length - this.dispatchedLocal);
|
|
53
53
|
if (request && this.completedMedia.has(request.messages)) {
|
|
54
54
|
await this.ports.resources.complete(request);
|
|
55
55
|
this.ports.updateBoundary(closedPrefixLength);
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
// Overlap generation with in-flight work, not with a final answer. Any
|
|
58
|
+
// new input will use the next request's budget preflight instead.
|
|
59
|
+
if (continuing &&
|
|
60
|
+
!this.ports.signal.aborted &&
|
|
61
|
+
this.contextTokens !== undefined &&
|
|
58
62
|
(this.contextTokens * 100) / this.ports.contextWindowTokens >=
|
|
59
63
|
AGENT_EXECUTION_POLICY.backgroundCompactionPercent &&
|
|
60
64
|
!this.ports.compactPending())
|
|
@@ -33,7 +33,7 @@ export declare function createExecutionToolScope(input: {
|
|
|
33
33
|
readonly publishSkillContext: NonNullable<ToolRuntimeContext['publishSkillContext']>;
|
|
34
34
|
withRecordProjection<T>(action: () => Promise<T>): Promise<T>;
|
|
35
35
|
publishMcpDiscovery(names: readonly string[], signal: AbortSignal): Promise<void>;
|
|
36
|
-
readonly coreExtensions: Pick<ExtensionSession, 'epoch' | 'withTools' | 'invoke' | 'assertLive' | 'pin' | 'diagnose' | 'composeModelSystem' | 'services'>;
|
|
36
|
+
readonly coreExtensions: Pick<ExtensionSession, 'epoch' | 'withTools' | 'invoke' | 'assertLive' | 'pin' | 'diagnose' | 'composeModelSystem' | 'services' | 'hooks'>;
|
|
37
37
|
readonly operations: Pick<ExtensionOperations, 'enter'>;
|
|
38
38
|
readonly scheduleTool: SessionRuntime['scheduleTool'];
|
|
39
39
|
readonly sources: Pick<ExecutionToolSources, 'withFrame' | 'assertActive'>;
|
|
@@ -2,6 +2,7 @@ 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
4
|
import { withToolPermissions } from '../tools/permissions.js';
|
|
5
|
+
import { parseExecInput } from '../tools/local/exec.js';
|
|
5
6
|
import { SESSION_CONTEXT_PROVIDER } from '../extensions/session-context.js';
|
|
6
7
|
/** Capture immutable round tool identities, parent scope and resource capabilities. */
|
|
7
8
|
export function createExecutionToolScope(input) {
|
|
@@ -93,7 +94,9 @@ export function createExecutionToolScope(input) {
|
|
|
93
94
|
}
|
|
94
95
|
}),
|
|
95
96
|
signal: context.signal
|
|
96
|
-
}, (operation) => coreExtensions.invoke(call, operation, roundBindings
|
|
97
|
+
}, (operation) => coreExtensions.invoke(call, operation, roundBindings, caller === 'direct' && context.parentCallId === undefined
|
|
98
|
+
? context.admitEarlyHandler
|
|
99
|
+
: undefined))));
|
|
97
100
|
try {
|
|
98
101
|
return await sources.withFrame(context, invoke);
|
|
99
102
|
}
|
|
@@ -119,6 +122,26 @@ export function createExecutionToolScope(input) {
|
|
|
119
122
|
const toolScope = {
|
|
120
123
|
context: toolContext,
|
|
121
124
|
tools: roundTools,
|
|
125
|
+
canDispatchEarly: (call) => {
|
|
126
|
+
if (call.name !== 'exec' ||
|
|
127
|
+
call.argumentError !== undefined ||
|
|
128
|
+
!call.callId ||
|
|
129
|
+
call.callId === 'unknown' ||
|
|
130
|
+
roundBindings.get('exec')?.source.kind !== 'builtin' ||
|
|
131
|
+
coreExtensions.hooks.hasInterceptors('tool.invoke') ||
|
|
132
|
+
!call.arguments ||
|
|
133
|
+
typeof call.arguments !== 'object' ||
|
|
134
|
+
Array.isArray(call.arguments))
|
|
135
|
+
return false;
|
|
136
|
+
if (!permissionPolicy.canDispatchWhileStreaming(call.arguments))
|
|
137
|
+
return false;
|
|
138
|
+
try {
|
|
139
|
+
return 'command' in parseExecInput(call.arguments);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
},
|
|
122
145
|
expectations: roundMcpExpectations,
|
|
123
146
|
extensionToolNames: new Set([...roundBindings.values()]
|
|
124
147
|
.filter((binding) => binding.source.kind === 'host' || binding.source.kind === 'extension')
|
|
@@ -3,7 +3,7 @@ import { latestModelUsage, reasoningEffortBaseline } from '../runtime/context/us
|
|
|
3
3
|
import { publicModelUsage } from '../runtime/event-projection.js';
|
|
4
4
|
import { truncateModelText } from '../runtime/token-budget.js';
|
|
5
5
|
import { MCP_DISCOVERY_DELIVERED } from '../session/mcp-discovery.js';
|
|
6
|
-
import { executeRoundTools } from '../tools/execution.js';
|
|
6
|
+
import { createStreamingToolRound, executeRoundTools } from '../tools/execution.js';
|
|
7
7
|
import { pairedMcpToolNames } from '../tools/mcp/history.js';
|
|
8
8
|
import { ExecutionToolPermissions, projectPermissionTool, resolvePermissionMode, withToolPermissions } from '../tools/permissions.js';
|
|
9
9
|
import { createToolWaitInterrupt } from '../tools/wait.js';
|
|
@@ -831,6 +831,18 @@ export function createSessionExecutionFactory(ports) {
|
|
|
831
831
|
}),
|
|
832
832
|
prepareRound,
|
|
833
833
|
runTools: executeRoundTools,
|
|
834
|
+
...(mode === 'run' && process.env.MAR_AGENT_EARLY_EXEC !== '0'
|
|
835
|
+
? {
|
|
836
|
+
openToolRound: (scope) => createStreamingToolRound(scope, async (call) => {
|
|
837
|
+
await withRecordProjection(() => store.append(sessionId, {
|
|
838
|
+
type: 'tool.early_admitted',
|
|
839
|
+
payload: { callId: call.callId },
|
|
840
|
+
executionId,
|
|
841
|
+
turnId
|
|
842
|
+
}));
|
|
843
|
+
})
|
|
844
|
+
}
|
|
845
|
+
: {}),
|
|
834
846
|
startModel: async function* (request) {
|
|
835
847
|
let contextAcknowledgementFailed = false;
|
|
836
848
|
yield* modelLifecycle.start(request, async () => {
|
|
@@ -865,7 +877,7 @@ export function createSessionExecutionFactory(ports) {
|
|
|
865
877
|
},
|
|
866
878
|
recoverySignal: () => controller.signal,
|
|
867
879
|
compactContext,
|
|
868
|
-
afterModel: (closedPrefixLength, request) => modelLifecycle.afterModel(closedPrefixLength, request),
|
|
880
|
+
afterModel: (continuing, closedPrefixLength, request) => modelLifecycle.afterModel(continuing, closedPrefixLength, request),
|
|
869
881
|
observeContextTokens: (tokens) => modelLifecycle.observeTokens(tokens),
|
|
870
882
|
observeUsage: (usage) => modelLifecycle.observeUsage(usage),
|
|
871
883
|
checkpoint: (round, latestUsage, thoughtCallIds) => contextCoordinator.checkpoint(round, latestUsage, thoughtCallIds),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ClientToolCall, ExecutedToolCall } from '../runtime/tool-round-contract.js';
|
|
1
|
+
import type { ClientToolCall, ExecutedToolCall, StreamingToolRound } from '../runtime/tool-round-contract.js';
|
|
2
2
|
export type { ClientToolCall, ExecutedToolCall } from '../runtime/tool-round-contract.js';
|
|
3
3
|
import type { EventPayload } from '../runtime/events.js';
|
|
4
4
|
import type { ClientToolDefinition, McpToolCallContext, ToolExecutionContext } from './contracts.js';
|
|
@@ -9,6 +9,7 @@ import type { ToolCall } from './contracts.js';
|
|
|
9
9
|
export interface RoundToolScope {
|
|
10
10
|
readonly context: Omit<ToolRuntimeContext, 'codeMode' | 'expectedMcpTool' | 'searchMcpTools' | 'recentImages'>;
|
|
11
11
|
readonly tools: readonly ClientToolDefinition[];
|
|
12
|
+
readonly canDispatchEarly?: (call: ClientToolCall) => boolean;
|
|
12
13
|
readonly expectations: ReadonlyMap<string, McpToolCallContext['expectedTool']>;
|
|
13
14
|
readonly extensionToolNames: ReadonlySet<string>;
|
|
14
15
|
readonly schedule: ReturnType<typeof createSessionToolScheduler>;
|
|
@@ -28,3 +29,5 @@ export declare function createRoundToolRuntimeContext(scope: RoundToolScope, cal
|
|
|
28
29
|
}, signal: AbortSignal): Promise<ToolRuntimeContext>;
|
|
29
30
|
/** Complete every call in model order even if individual execution fails. */
|
|
30
31
|
export declare function executeRoundTools(calls: readonly ClientToolCall[], scope: RoundToolScope): Promise<ExecutedToolCall[]>;
|
|
32
|
+
/** A deferred entry occupies its round barrier immediately, but not the Session tool lock. */
|
|
33
|
+
export declare function createStreamingToolRound(scope: RoundToolScope, admit: (call: ClientToolCall) => Promise<void>): StreamingToolRound;
|
package/dist/tools/execution.js
CHANGED
|
@@ -9,7 +9,7 @@ import { publishModelResources } from '../runtime/resource-publication.js';
|
|
|
9
9
|
import { executeRegisteredTool } from './runtime.js';
|
|
10
10
|
import { failedToolResultExtensions } from './result-extensions.js';
|
|
11
11
|
import { permissionStopFromError } from './permissions.js';
|
|
12
|
-
import { scheduleToolCallBatch } from './scheduler.js';
|
|
12
|
+
import { createToolCallScheduler, scheduleToolCallBatch } from './scheduler.js';
|
|
13
13
|
import { readThoughtInput, thoughtToolDefinition } from './agent/thought.js';
|
|
14
14
|
/** Shared raw context construction for physical tools and native calls in a real model round. */
|
|
15
15
|
export async function createRoundToolRuntimeContext(scope, call, signal) {
|
|
@@ -88,9 +88,9 @@ export async function createRoundToolRuntimeContext(scope, call, signal) {
|
|
|
88
88
|
: {})
|
|
89
89
|
};
|
|
90
90
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
91
|
+
function createRoundToolExecutor(scope) {
|
|
92
|
+
const run = async (call, signal = scope.context.signal, admitEarlyHandler) => {
|
|
93
|
+
const caller = 'direct';
|
|
94
94
|
const inputFields = call.name === THOUGHT_TOOL_NAME
|
|
95
95
|
? thoughtToolDefinition.eventInputFields
|
|
96
96
|
: scope.tools.find((tool) => tool.name === call.name)?.eventInputFields;
|
|
@@ -101,7 +101,6 @@ export async function executeRoundTools(calls, scope) {
|
|
|
101
101
|
type: 'tool.started',
|
|
102
102
|
toolName: call.name,
|
|
103
103
|
callId: call.callId,
|
|
104
|
-
...(parentCallId === undefined ? {} : { parentCallId }),
|
|
105
104
|
input: publicInput
|
|
106
105
|
});
|
|
107
106
|
try {
|
|
@@ -116,6 +115,8 @@ export async function executeRoundTools(calls, scope) {
|
|
|
116
115
|
arguments_ = structuredClone(arguments_);
|
|
117
116
|
}
|
|
118
117
|
const context = await createRoundToolRuntimeContext(scope, call, signal);
|
|
118
|
+
if (admitEarlyHandler)
|
|
119
|
+
context.admitEarlyHandler = admitEarlyHandler;
|
|
119
120
|
const runTool = () => {
|
|
120
121
|
signal.throwIfAborted();
|
|
121
122
|
return executeRegisteredTool(call.name, arguments_, call.callId, context);
|
|
@@ -156,7 +157,6 @@ export async function executeRoundTools(calls, scope) {
|
|
|
156
157
|
...(output.resultExtensions ? { resultExtensions: output.resultExtensions } : {}),
|
|
157
158
|
toolName: call.name,
|
|
158
159
|
callId: call.callId,
|
|
159
|
-
...(parentCallId === undefined ? {} : { parentCallId }),
|
|
160
160
|
summary: eventSummary.summary,
|
|
161
161
|
truncated: output.truncated === true || modelOutput.truncated,
|
|
162
162
|
...(eventSummary.truncated ? { summaryTruncated: true } : {}),
|
|
@@ -197,7 +197,6 @@ export async function executeRoundTools(calls, scope) {
|
|
|
197
197
|
: {}),
|
|
198
198
|
toolName: call.name,
|
|
199
199
|
callId: call.callId,
|
|
200
|
-
...(parentCallId === undefined ? {} : { parentCallId }),
|
|
201
200
|
code: diagnostic.code,
|
|
202
201
|
message: diagnostic.message,
|
|
203
202
|
...(permissionStopFromError(error)
|
|
@@ -230,5 +229,87 @@ export async function executeRoundTools(calls, scope) {
|
|
|
230
229
|
};
|
|
231
230
|
}
|
|
232
231
|
};
|
|
233
|
-
return
|
|
232
|
+
return run;
|
|
233
|
+
}
|
|
234
|
+
/** Complete every call in model order even if individual execution fails. */
|
|
235
|
+
export function executeRoundTools(calls, scope) {
|
|
236
|
+
return scheduleToolCallBatch(calls, scope.tools, createRoundToolExecutor(scope));
|
|
237
|
+
}
|
|
238
|
+
/** A deferred entry occupies its round barrier immediately, but not the Session tool lock. */
|
|
239
|
+
export function createStreamingToolRound(scope, admit) {
|
|
240
|
+
const execute = createRoundToolExecutor(scope);
|
|
241
|
+
const gate = Promise.withResolvers();
|
|
242
|
+
const controller = new AbortController();
|
|
243
|
+
const signal = AbortSignal.any([scope.context.signal, controller.signal]);
|
|
244
|
+
let released = false;
|
|
245
|
+
let stopped = false;
|
|
246
|
+
let admitted = false;
|
|
247
|
+
let approvalBoundaryQueued = false;
|
|
248
|
+
const stop = (cancelInFlight = true) => {
|
|
249
|
+
stopped = true;
|
|
250
|
+
if (cancelInFlight)
|
|
251
|
+
controller.abort();
|
|
252
|
+
gate.resolve();
|
|
253
|
+
};
|
|
254
|
+
const schedule = createToolCallScheduler(scope.tools, async (entry) => {
|
|
255
|
+
const early = !released && !entry.blockedByApproval && scope.canDispatchEarly?.(entry.call) === true;
|
|
256
|
+
if (!early)
|
|
257
|
+
await gate.promise;
|
|
258
|
+
if (stopped || signal.aborted)
|
|
259
|
+
return undefined;
|
|
260
|
+
return execute(entry.call, signal, early
|
|
261
|
+
? async (eligible) => {
|
|
262
|
+
signal.throwIfAborted();
|
|
263
|
+
if (stopped)
|
|
264
|
+
throw new AgentError('MAR_AGENT_CANCELLED', 'Tool round is closed.');
|
|
265
|
+
if (!eligible)
|
|
266
|
+
throw new AgentError('MAR_AGENT_TOOL_NOT_AVAILABLE', 'Early tool binding is no longer eligible.');
|
|
267
|
+
if (!released) {
|
|
268
|
+
await admit(entry.call);
|
|
269
|
+
entry.admitted = admitted = true;
|
|
270
|
+
if (stopped)
|
|
271
|
+
throw new AgentError('MAR_AGENT_CANCELLED', 'Tool round is closed.');
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
: undefined);
|
|
275
|
+
});
|
|
276
|
+
const entries = [];
|
|
277
|
+
return {
|
|
278
|
+
enqueue(call) {
|
|
279
|
+
const entry = {
|
|
280
|
+
name: call.name,
|
|
281
|
+
call,
|
|
282
|
+
admitted: false,
|
|
283
|
+
blockedByApproval: approvalBoundaryQueued
|
|
284
|
+
};
|
|
285
|
+
if (scope.context.permissionPolicy?.canStopAtApprovalBoundary(call.arguments))
|
|
286
|
+
approvalBoundaryQueued = true;
|
|
287
|
+
entries.push({
|
|
288
|
+
entry,
|
|
289
|
+
result: schedule(entry).then((value) => ({ status: 'fulfilled', value }), (reason) => {
|
|
290
|
+
stop();
|
|
291
|
+
return { status: 'rejected', reason };
|
|
292
|
+
})
|
|
293
|
+
});
|
|
294
|
+
},
|
|
295
|
+
hasAdmitted: () => admitted,
|
|
296
|
+
async finish() {
|
|
297
|
+
released = true;
|
|
298
|
+
gate.resolve();
|
|
299
|
+
const settled = await Promise.all(entries.map(({ result }) => result));
|
|
300
|
+
const failure = settled.find((result) => result.status === 'rejected');
|
|
301
|
+
if (failure)
|
|
302
|
+
throw failure.reason;
|
|
303
|
+
return settled.flatMap((result) => result.status === 'fulfilled' && result.value ? [result.value] : []);
|
|
304
|
+
},
|
|
305
|
+
async stop(cancelInFlight) {
|
|
306
|
+
stop(cancelInFlight);
|
|
307
|
+
const settled = await Promise.all(entries.map(({ result }) => result));
|
|
308
|
+
return settled.flatMap((result, index) => result.status === 'fulfilled' &&
|
|
309
|
+
result.value &&
|
|
310
|
+
(released || entries[index].entry.admitted)
|
|
311
|
+
? [result.value]
|
|
312
|
+
: []);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
234
315
|
}
|
|
@@ -47,6 +47,10 @@ export declare class ExecutionToolPermissions {
|
|
|
47
47
|
readonly signal: AbortSignal;
|
|
48
48
|
} | undefined);
|
|
49
49
|
get stop(): PermissionStop | undefined;
|
|
50
|
+
/** Preview only; never ask for approval or alter the permission-stop state here. */
|
|
51
|
+
canDispatchWhileStreaming(args: Record<string, unknown>): boolean;
|
|
52
|
+
/** An unhandled ask stops the Execution; later calls must not run ahead of that decision. */
|
|
53
|
+
canStopAtApprovalBoundary(args: unknown): boolean;
|
|
50
54
|
assertDispatch(): void;
|
|
51
55
|
prepare(call: ToolCall, context: InvocationContext, tool: ClientToolDefinition): ToolCall;
|
|
52
56
|
authorize(call: ToolCall, context: InvocationContext, publicInputFields?: readonly string[]): Promise<ToolCall>;
|
|
@@ -103,6 +103,31 @@ export class ExecutionToolPermissions {
|
|
|
103
103
|
get stop() {
|
|
104
104
|
return this.#stop;
|
|
105
105
|
}
|
|
106
|
+
/** Preview only; never ask for approval or alter the permission-stop state here. */
|
|
107
|
+
canDispatchWhileStreaming(args) {
|
|
108
|
+
if (this.#stop)
|
|
109
|
+
return false;
|
|
110
|
+
if (this.mode !== 'auto')
|
|
111
|
+
return args.permission == null;
|
|
112
|
+
try {
|
|
113
|
+
const permission = parsePermission(args.permission);
|
|
114
|
+
return permission === undefined || permission.action === 'allow';
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** An unhandled ask stops the Execution; later calls must not run ahead of that decision. */
|
|
121
|
+
canStopAtApprovalBoundary(args) {
|
|
122
|
+
if (this.mode !== 'auto' || this.approval || !record(args))
|
|
123
|
+
return false;
|
|
124
|
+
try {
|
|
125
|
+
return parsePermission(args.permission)?.action === 'ask';
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
106
131
|
assertDispatch() {
|
|
107
132
|
if (this.#stop)
|
|
108
133
|
throw new AgentError('MAR_AGENT_TOOL_SKIPPED_PERMISSION_STOP', 'Tool was not executed because this execution stopped for permission.');
|
|
@@ -74,6 +74,8 @@ export interface ToolRuntimeContext {
|
|
|
74
74
|
recentImages?: readonly ToolRuntimeImage[];
|
|
75
75
|
searchMcpTools?: (input: unknown, signal: AbortSignal, caller?: import('./contracts.js').ToolCaller) => Promise<import('./contracts.js').ToolExecutionResult>;
|
|
76
76
|
expectedMcpTool?: import('./contracts.js').McpToolCallContext['expectedTool'];
|
|
77
|
+
/** Durably admit an early invocation after permission and before its physical handler. */
|
|
78
|
+
admitEarlyHandler?: (eligible: boolean) => Promise<void>;
|
|
77
79
|
invokeTool?: (call: import('./contracts.js').ToolCall, context: ToolRuntimeContext, caller: import('./contracts.js').ToolCaller) => Promise<import('./contracts.js').ToolExecutionResult>;
|
|
78
80
|
emit(event: ToolRuntimeEvent): Promise<void>;
|
|
79
81
|
}
|