@ouispec/agent-worker 0.32.2 → 0.32.4
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/README.md +30 -3
- package/dist/approvals/client.d.ts +3 -2
- package/dist/approvals/client.d.ts.map +1 -1
- package/dist/approvals/client.js +6 -4
- package/dist/approvals/client.js.map +1 -1
- package/dist/attachments/content.d.ts +6 -8
- package/dist/attachments/content.d.ts.map +1 -1
- package/dist/attachments/content.js +29 -13
- package/dist/attachments/content.js.map +1 -1
- package/dist/capture/capture-tools.d.ts +2 -3
- package/dist/capture/capture-tools.d.ts.map +1 -1
- package/dist/capture/capture-tools.js +2 -3
- package/dist/capture/capture-tools.js.map +1 -1
- package/dist/conversations/client.d.ts +3 -2
- package/dist/conversations/client.d.ts.map +1 -1
- package/dist/conversations/client.js +6 -4
- package/dist/conversations/client.js.map +1 -1
- package/dist/emit/http-adapter.d.ts +4 -2
- package/dist/emit/http-adapter.d.ts.map +1 -1
- package/dist/emit/http-adapter.js +9 -6
- package/dist/emit/http-adapter.js.map +1 -1
- package/dist/events/http-waiter.d.ts +3 -2
- package/dist/events/http-waiter.d.ts.map +1 -1
- package/dist/events/http-waiter.js +4 -2
- package/dist/events/http-waiter.js.map +1 -1
- package/dist/handoff/handoff-tool.d.ts +2 -1
- package/dist/handoff/handoff-tool.d.ts.map +1 -1
- package/dist/handoff/handoff-tool.js +2 -1
- package/dist/handoff/handoff-tool.js.map +1 -1
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -4
- package/dist/index.js.map +1 -1
- package/dist/orchestrator.d.ts +24 -2
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +243 -84
- package/dist/orchestrator.js.map +1 -1
- package/dist/prompt/builder.d.ts +10 -0
- package/dist/prompt/builder.d.ts.map +1 -1
- package/dist/prompt/builder.js +14 -2
- package/dist/prompt/builder.js.map +1 -1
- package/dist/prompt/capture.d.ts +9 -3
- package/dist/prompt/capture.d.ts.map +1 -1
- package/dist/prompt/capture.js +32 -11
- package/dist/prompt/capture.js.map +1 -1
- package/dist/prompt/handoff.d.ts +5 -2
- package/dist/prompt/handoff.d.ts.map +1 -1
- package/dist/prompt/handoff.js +13 -5
- package/dist/prompt/handoff.js.map +1 -1
- package/dist/prompt/index.d.ts +1 -1
- package/dist/prompt/index.d.ts.map +1 -1
- package/dist/prompt/index.js +1 -1
- package/dist/prompt/index.js.map +1 -1
- package/dist/prompt/rules/tool-strategy.d.ts +5 -5
- package/dist/prompt/rules/tool-strategy.d.ts.map +1 -1
- package/dist/prompt/rules/tool-strategy.js +27 -6
- package/dist/prompt/rules/tool-strategy.js.map +1 -1
- package/dist/prompt/rules/ui-control.d.ts +5 -9
- package/dist/prompt/rules/ui-control.d.ts.map +1 -1
- package/dist/prompt/rules/ui-control.js +49 -14
- package/dist/prompt/rules/ui-control.js.map +1 -1
- package/dist/prompt/step-tools.d.ts +68 -0
- package/dist/prompt/step-tools.d.ts.map +1 -0
- package/dist/prompt/step-tools.js +72 -0
- package/dist/prompt/step-tools.js.map +1 -0
- package/dist/prompt/vision.d.ts +4 -2
- package/dist/prompt/vision.d.ts.map +1 -1
- package/dist/prompt/vision.js +17 -4
- package/dist/prompt/vision.js.map +1 -1
- package/dist/realtime/api-key.d.ts +65 -0
- package/dist/realtime/api-key.d.ts.map +1 -0
- package/dist/realtime/api-key.js +120 -0
- package/dist/realtime/api-key.js.map +1 -0
- package/dist/realtime/long-poll.d.ts +6 -2
- package/dist/realtime/long-poll.d.ts.map +1 -1
- package/dist/realtime/long-poll.js +20 -1
- package/dist/realtime/long-poll.js.map +1 -1
- package/dist/runtime/config.d.ts.map +1 -1
- package/dist/runtime/config.js +2 -1
- package/dist/runtime/config.js.map +1 -1
- package/dist/runtime/turn-runner.d.ts.map +1 -1
- package/dist/runtime/turn-runner.js +10 -4
- package/dist/runtime/turn-runner.js.map +1 -1
- package/dist/runtime/types.d.ts +13 -1
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/step-messages.d.ts +8 -0
- package/dist/step-messages.d.ts.map +1 -1
- package/dist/step-messages.js +24 -0
- package/dist/step-messages.js.map +1 -1
- package/dist/stop/turn-stop.d.ts +3 -2
- package/dist/stop/turn-stop.d.ts.map +1 -1
- package/dist/stop/turn-stop.js +9 -3
- package/dist/stop/turn-stop.js.map +1 -1
- package/dist/time-hand-back.d.ts +6 -2
- package/dist/time-hand-back.d.ts.map +1 -1
- package/dist/time-hand-back.js +13 -3
- package/dist/time-hand-back.js.map +1 -1
- package/dist/tools/builtin-tools.d.ts +2 -0
- package/dist/tools/builtin-tools.d.ts.map +1 -1
- package/dist/tools/builtin-tools.js +3 -1
- package/dist/tools/builtin-tools.js.map +1 -1
- package/dist/tools/sdk-tool-names.d.ts +27 -0
- package/dist/tools/sdk-tool-names.d.ts.map +1 -0
- package/dist/tools/sdk-tool-names.js +27 -0
- package/dist/tools/sdk-tool-names.js.map +1 -0
- package/dist/turn-policy.d.ts +9 -1
- package/dist/turn-policy.d.ts.map +1 -1
- package/dist/turn-policy.js.map +1 -1
- package/dist/ui/channel.d.ts +3 -2
- package/dist/ui/channel.d.ts.map +1 -1
- package/dist/ui/channel.js +14 -11
- package/dist/ui/channel.js.map +1 -1
- package/dist/ui/knowledge.d.ts +8 -5
- package/dist/ui/knowledge.d.ts.map +1 -1
- package/dist/ui/knowledge.js +17 -9
- package/dist/ui/knowledge.js.map +1 -1
- package/dist/vision/look-tool.d.ts +2 -1
- package/dist/vision/look-tool.d.ts.map +1 -1
- package/dist/vision/look-tool.js +2 -1
- package/dist/vision/look-tool.js.map +1 -1
- package/package.json +2 -2
package/dist/orchestrator.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* - ApiSurface binding for tool execution
|
|
19
19
|
* - Configurable TurnPolicy for product-specific step control
|
|
20
20
|
*/
|
|
21
|
-
import { streamText, dynamicTool, jsonSchema, isStepCount, wrapLanguageModel } from 'ai';
|
|
21
|
+
import { streamText, dynamicTool, jsonSchema, isStepCount, wrapLanguageModel, NoSuchToolError } from 'ai';
|
|
22
22
|
import { AGENT_SOCKET_EVENTS, argsHash, approvalReceiptAudience, canonicalJson, isTurnEndReason, staffMessageNote, takeoverNote, turnStoppedNote, } from '@ouispec/agent-core';
|
|
23
23
|
import { DEFAULT_STOP_GRACE_MS, TurnStopped, stopOf, watchTurnStop } from './stop/turn-stop.js';
|
|
24
24
|
import { stoppedTurnMessages } from './stop/partial.js';
|
|
@@ -32,7 +32,10 @@ import { jsonBytes } from 'oui-spec/spec';
|
|
|
32
32
|
import { CLIENT_SNAPSHOT_KEY, readClientPage, withoutClientUI } from './ui/snapshot.js';
|
|
33
33
|
import { KNOWLEDGE_TOOL, knowledgeTool, readClientKnowledge, withClientKnowledge } from './ui/knowledge.js';
|
|
34
34
|
import { answerWithoutState, withStatesAtEnd } from './ui/page-state-at-end.js';
|
|
35
|
-
import { readTurnContextPlacement, stepMessages as forStep, STEP_NOTE_CLOSE, STEP_NOTE_OPEN } from './step-messages.js';
|
|
35
|
+
import { readTurnContextPlacement, stepMessages as forStep, STEP_NOTE_CLOSE, STEP_NOTE_OPEN, withCallResults } from './step-messages.js';
|
|
36
|
+
import { EVERY_TOOL, offeredTools, renderRule } from './prompt/step-tools.js';
|
|
37
|
+
import { systemPromptForTools } from './prompt/builder.js';
|
|
38
|
+
import { PRESENT_OPTIONS_TOOL } from './tools/sdk-tool-names.js';
|
|
36
39
|
import { clockText, readClientTimeZone } from './prompt/clock.js';
|
|
37
40
|
import { readClientMessageInput, spokenInputText } from './prompt/spoken-input.js';
|
|
38
41
|
import { readClientReplyOutput, spokenReplyText } from './prompt/spoken-reply.js';
|
|
@@ -43,7 +46,7 @@ import { captureTools } from './capture/capture-tools.js';
|
|
|
43
46
|
import { handoffText } from './prompt/handoff.js';
|
|
44
47
|
import { handoffTool } from './handoff/handoff-tool.js';
|
|
45
48
|
import { AttachmentGuard } from './attachments/guard.js';
|
|
46
|
-
import {
|
|
49
|
+
import { attachmentDataNote, turnAttachmentParts, withReferenceLines, withTurnAttachments, withoutLeftOut } from './attachments/content.js';
|
|
47
50
|
import { attachmentTools } from './attachments/tools.js';
|
|
48
51
|
import { acceptsMediaType, attachmentIdsIn, attachmentNameForModel, misplacedAttachmentInputs } from '@ouispec/agent-core';
|
|
49
52
|
const ATTACHMENT_LIST_HINT = 'attachment_list lists the files that can.';
|
|
@@ -92,10 +95,44 @@ const UI_TOOL_NAMES = new Set([UI_ACT_TOOL, UI_DESCRIBE_TOOL, UI_READ_TOOL, UI_W
|
|
|
92
95
|
*/
|
|
93
96
|
export const USER_INPUT_TOOLS = ['present_options', 'confirm_action', 'request_user_decision'];
|
|
94
97
|
/** The choice built-in, which `requireReplyBeforeChoice` holds to a reply. */
|
|
95
|
-
export
|
|
98
|
+
export { PRESENT_OPTIONS_TOOL };
|
|
99
|
+
/**
|
|
100
|
+
* What the model is told of a call to a tool its step does not offer (or one
|
|
101
|
+
* that does not exist): it did not run, nothing reached the user, and the
|
|
102
|
+
* step goes on. `ai` answers such a call with its own error (`AI_NoSuchToolError`)
|
|
103
|
+
* and runs nothing; this is the result the model reads in its place.
|
|
104
|
+
*/
|
|
105
|
+
export function unavailableToolError(toolName) {
|
|
106
|
+
return (`"${toolName}" is not one of the tools you can use now, so the call did not run and nothing was shown to the user. ` +
|
|
107
|
+
'Carry on with the tools you have, or answer in words.');
|
|
108
|
+
}
|
|
96
109
|
/** What the model is told when `requireReplyBeforeChoice` sends a choice back. */
|
|
97
110
|
export const REPLY_BEFORE_CHOICE_ERROR = 'Not shown. Your reply is the plain text you write outside any tool call, and you have written none: the card, its context included, is not the reply. ' +
|
|
98
111
|
'Write one or two sentences now, as text (what you found or did), then call present_options again.';
|
|
112
|
+
/**
|
|
113
|
+
* How the page's index says its actions are run. The tools that work the page
|
|
114
|
+
* are named only to a step that offers them (prompt/step-tools.ts).
|
|
115
|
+
*/
|
|
116
|
+
const RUN_AN_ACTION = {
|
|
117
|
+
tools: [UI_ACT_TOOL],
|
|
118
|
+
text: ` Run an action with ${UI_ACT_TOOL}`,
|
|
119
|
+
within: [{ tools: [UI_DESCRIBE_TOOL], text: `; ${UI_DESCRIBE_TOOL} says what one takes` }, '.'],
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* The tools a step offers the model, by the names it calls them, from the
|
|
123
|
+
* turn's tools and what the step is held to: none with `toolChoice: 'none'`,
|
|
124
|
+
* the one it must call with a forced choice, else its active tools (all the
|
|
125
|
+
* turn's when none are named). Everything that writes the step's prompt is
|
|
126
|
+
* told this one value.
|
|
127
|
+
*/
|
|
128
|
+
export function stepOfferedTools(turnTools, held) {
|
|
129
|
+
const { toolChoice, activeTools } = held;
|
|
130
|
+
if (toolChoice === 'none')
|
|
131
|
+
return offeredTools([]);
|
|
132
|
+
if (typeof toolChoice === 'object')
|
|
133
|
+
return offeredTools(turnTools.filter((name) => name === toolChoice.toolName));
|
|
134
|
+
return offeredTools(activeTools ? turnTools.filter((name) => activeTools.includes(name)) : turnTools);
|
|
135
|
+
}
|
|
99
136
|
function log(level, ns, message, data) {
|
|
100
137
|
const entry = { level, ns, message, timestamp: new Date().toISOString(), ...data };
|
|
101
138
|
if (level === 'error')
|
|
@@ -261,9 +298,18 @@ export async function runAgentTurn(config, input) {
|
|
|
261
298
|
const hostPrompt = typeof config.systemPrompt === 'function'
|
|
262
299
|
? config.systemPrompt({ userId: input.userId, accountId: input.accountId, context: withoutClientUI(input.context) })
|
|
263
300
|
: config.systemPrompt;
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
301
|
+
/**
|
|
302
|
+
* The system prompt as a step offering `offered` is told it: the host's,
|
|
303
|
+
* whose SDK rules name only the tools the step offers (prompt/step-tools.ts),
|
|
304
|
+
* then, with a file area, that a file's name and content are data, never
|
|
305
|
+
* instructions, then the client's knowledge. Every SDK word in it about a
|
|
306
|
+
* tool is said only to a step that offers the tool.
|
|
307
|
+
*/
|
|
308
|
+
const systemPromptFor = (offered) => {
|
|
309
|
+
const host = systemPromptForTools(hostPrompt, offered);
|
|
310
|
+
return withClientKnowledge(fileArea ? `${host}\n\n${attachmentDataNote(offered)}` : host, input.context, offered);
|
|
311
|
+
};
|
|
312
|
+
log('debug', 'agent:prompt', 'System prompt built', { turnId, promptLength: systemPromptFor(EVERY_TOOL).length, hostPromptLength: hostPrompt.length });
|
|
267
313
|
// Wall-clock deadline: abort the entire streamText call if it exceeds turnDeadlineMs.
|
|
268
314
|
const turnStartedAt = Date.now();
|
|
269
315
|
// A UI tool waiting on work it started stops in time for the model to answer.
|
|
@@ -356,8 +402,33 @@ export async function runAgentTurn(config, input) {
|
|
|
356
402
|
* as it is coalesced, and can trail a tool call the model makes after it.
|
|
357
403
|
*/
|
|
358
404
|
let replyText = '';
|
|
359
|
-
/**
|
|
360
|
-
|
|
405
|
+
/**
|
|
406
|
+
* The calls of this turn that did not run, by call id, with why: refused,
|
|
407
|
+
* invalid, denied, or a call to a tool its step did not offer. Every check
|
|
408
|
+
* that ends a turn because of a call reads the calls that ran: a choice that
|
|
409
|
+
* did not run asked the user nothing, and ends no turn.
|
|
410
|
+
*/
|
|
411
|
+
const callsNotRun = new Map();
|
|
412
|
+
/**
|
|
413
|
+
* The result the model reads for a call `ai` answered with its own error,
|
|
414
|
+
* because no tool of the step could run it (`callNoToolRan`): put in place
|
|
415
|
+
* of that error in every step's messages, and stored as the call's result.
|
|
416
|
+
*/
|
|
417
|
+
const resultsOfCallsNoToolRan = new Map();
|
|
418
|
+
/** Why a call that did not run did not, from the result the model was given. */
|
|
419
|
+
const notRunReason = (text) => {
|
|
420
|
+
try {
|
|
421
|
+
const parsed = JSON.parse(text);
|
|
422
|
+
if (typeof parsed.error === 'string')
|
|
423
|
+
return parsed.error;
|
|
424
|
+
if (typeof parsed.message === 'string')
|
|
425
|
+
return parsed.message;
|
|
426
|
+
}
|
|
427
|
+
catch {
|
|
428
|
+
// A result that is not JSON is said as it is.
|
|
429
|
+
}
|
|
430
|
+
return text;
|
|
431
|
+
};
|
|
361
432
|
/** Whether `requireReplyBeforeChoice` has already sent a choice back this turn: it does so once. */
|
|
362
433
|
let choiceSentBackForReply = false;
|
|
363
434
|
/** The reply a choice's card said, by call, when it was offered twice with none (`requireReplyBeforeChoice`). */
|
|
@@ -460,6 +531,62 @@ export async function runAgentTurn(config, input) {
|
|
|
460
531
|
}
|
|
461
532
|
return v;
|
|
462
533
|
};
|
|
534
|
+
/**
|
|
535
|
+
* A call refused before any tool ran, as the client is told of it: a call
|
|
536
|
+
* that started and failed, so a session's record holds every call the model
|
|
537
|
+
* made with its arguments.
|
|
538
|
+
*/
|
|
539
|
+
const emitRefusedCall = async (toolUseId, name, input, error) => {
|
|
540
|
+
const now = Date.now();
|
|
541
|
+
await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, { turnId, toolUseId, name, input, timestamp: now });
|
|
542
|
+
await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
|
|
543
|
+
turnId,
|
|
544
|
+
toolUseId,
|
|
545
|
+
name,
|
|
546
|
+
result: { error, refused: true },
|
|
547
|
+
success: false,
|
|
548
|
+
durationMs: 0,
|
|
549
|
+
timestamp: now,
|
|
550
|
+
});
|
|
551
|
+
};
|
|
552
|
+
/**
|
|
553
|
+
* A call no tool of its step could run, which `ai` answers with an error of
|
|
554
|
+
* its own and never executes: the model named a tool the step does not
|
|
555
|
+
* offer, or none of the turn's (`AI_NoSuchToolError`), or wrote input that
|
|
556
|
+
* could not be read (an invalid tool call). Nova, 2026-11-19: a step held to
|
|
557
|
+
* one tool still called `present_options` beside it; the call never ran, but
|
|
558
|
+
* the turn counted it as a question to the user and ended with no reply.
|
|
559
|
+
*
|
|
560
|
+
* It did not run, so it goes into `callsNotRun`: it asks the user nothing and
|
|
561
|
+
* ends no turn. The model reads, as its result, that the tool is not one it
|
|
562
|
+
* can use now (`unavailableToolError`), in place of `ai`'s error, so it
|
|
563
|
+
* answers in words in the same turn; the turn's record and the stored
|
|
564
|
+
* conversation hold the same result, and the client hears of a refused call.
|
|
565
|
+
*/
|
|
566
|
+
const callNoToolRan = async (call) => {
|
|
567
|
+
if (callsNotRun.has(call.toolCallId))
|
|
568
|
+
return;
|
|
569
|
+
const unavailable = NoSuchToolError.isInstance(call.error);
|
|
570
|
+
const error = unavailable
|
|
571
|
+
? unavailableToolError(call.toolName)
|
|
572
|
+
: call.error instanceof Error
|
|
573
|
+
? call.error.message
|
|
574
|
+
: `The call to "${call.toolName}" could not be read, so it did not run.`;
|
|
575
|
+
const text = JSON.stringify({ success: false, notRun: true, ...(unavailable ? { unavailable: true } : { invalidInput: true }), error });
|
|
576
|
+
callsNotRun.set(call.toolCallId, error);
|
|
577
|
+
resultsOfCallsNoToolRan.set(call.toolCallId, text);
|
|
578
|
+
executedToolResults.push({ toolCallId: call.toolCallId, toolName: call.toolName, result: text });
|
|
579
|
+
recordedCalls.set(call.toolCallId, { toolCallId: call.toolCallId, toolName: call.toolName, input: call.input, text, settled: Promise.resolve() });
|
|
580
|
+
ledger.record({ tool: call.toolName, ok: false, error });
|
|
581
|
+
log('warn', 'agent:tool', unavailable ? 'Tool call not run: its step does not offer that tool' : 'Tool call not run: its input could not be read', {
|
|
582
|
+
turnId,
|
|
583
|
+
toolName: call.toolName,
|
|
584
|
+
toolCallId: call.toolCallId,
|
|
585
|
+
});
|
|
586
|
+
// A tool whose input speaks of the person is said to have been called, and no more.
|
|
587
|
+
const known = callableTools().find((t) => t.name === call.toolName);
|
|
588
|
+
await emitRefusedCall(call.toolCallId, call.toolName, known?.inputPrivate ? {} : call.input, error);
|
|
589
|
+
};
|
|
463
590
|
/**
|
|
464
591
|
* Runs one call of a tool: validation, quota, policy, approval, then the
|
|
465
592
|
* tool. `approved` is set only for the call a redeemed approval token names,
|
|
@@ -481,23 +608,7 @@ export async function runAgentTurn(config, input) {
|
|
|
481
608
|
*/
|
|
482
609
|
const refused = async (payload, given) => {
|
|
483
610
|
ledger.record({ tool: t.name, ok: false, error: payload.error });
|
|
484
|
-
|
|
485
|
-
await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
|
|
486
|
-
turnId,
|
|
487
|
-
toolUseId,
|
|
488
|
-
name: t.name,
|
|
489
|
-
input: shownInput(given),
|
|
490
|
-
timestamp: now,
|
|
491
|
-
});
|
|
492
|
-
await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
|
|
493
|
-
turnId,
|
|
494
|
-
toolUseId,
|
|
495
|
-
name: t.name,
|
|
496
|
-
result: { error: payload.error, refused: true },
|
|
497
|
-
success: false,
|
|
498
|
-
durationMs: 0,
|
|
499
|
-
timestamp: now,
|
|
500
|
-
});
|
|
611
|
+
await emitRefusedCall(toolUseId, t.name, shownInput(given), payload.error);
|
|
501
612
|
return notRun({ success: false, ...payload });
|
|
502
613
|
};
|
|
503
614
|
// A UI tool waits for the client's answer, which has its own deadline, and
|
|
@@ -1021,7 +1132,7 @@ export async function runAgentTurn(config, input) {
|
|
|
1021
1132
|
return tracked(toolUseId, t.name, rawArgs, async () => {
|
|
1022
1133
|
const { text, ran } = await executeCall(t, rawArgs, toolUseId, uiSlot).finally(() => uiSlot?.release());
|
|
1023
1134
|
if (!ran)
|
|
1024
|
-
callsNotRun.
|
|
1135
|
+
callsNotRun.set(toolUseId, notRunReason(text));
|
|
1025
1136
|
executedToolResults.push({ toolCallId: toolUseId, toolName: t.name, result: text });
|
|
1026
1137
|
return text;
|
|
1027
1138
|
});
|
|
@@ -1144,6 +1255,7 @@ export async function runAgentTurn(config, input) {
|
|
|
1144
1255
|
uiSlot.release();
|
|
1145
1256
|
ledger.record({ tool: typeof action === 'string' && action ? action : UI_ACT_TOOL, ok: false, error });
|
|
1146
1257
|
const text = JSON.stringify({ success: false, notRun: true, error });
|
|
1258
|
+
callsNotRun.set(toolUseId, error);
|
|
1147
1259
|
executedToolResults.push({ toolCallId: toolUseId, toolName: UI_ACT_TOOL, result: text });
|
|
1148
1260
|
return text;
|
|
1149
1261
|
};
|
|
@@ -1164,7 +1276,9 @@ export async function runAgentTurn(config, input) {
|
|
|
1164
1276
|
return notAnAction(`"${action}" is not an action of the page as it is now.` +
|
|
1165
1277
|
(near.length ? ` Did you mean: ${near.join(', ')}?` : ' Read the page’s index for what it offers; an action is named by its id there.'));
|
|
1166
1278
|
}
|
|
1167
|
-
const { text } = await executeCall(tool, actionInput ?? {}, toolUseId, uiSlot).finally(() => uiSlot.release());
|
|
1279
|
+
const { text, ran } = await executeCall(tool, actionInput ?? {}, toolUseId, uiSlot).finally(() => uiSlot.release());
|
|
1280
|
+
if (!ran)
|
|
1281
|
+
callsNotRun.set(toolUseId, notRunReason(text));
|
|
1168
1282
|
executedToolResults.push({ toolCallId: toolUseId, toolName: UI_ACT_TOOL, result: text });
|
|
1169
1283
|
return text;
|
|
1170
1284
|
}
|
|
@@ -1655,29 +1769,46 @@ export async function runAgentTurn(config, input) {
|
|
|
1655
1769
|
// `instructions` takes `string | SystemModelMessage | SystemModelMessage[]`,
|
|
1656
1770
|
// and the message form carries `providerOptions`, so the breakpoint travels
|
|
1657
1771
|
// with it. (`system` is the deprecated alias for the same type.)
|
|
1658
|
-
const systemMessage = {
|
|
1659
|
-
role: 'system',
|
|
1660
|
-
content: systemPrompt,
|
|
1661
|
-
...(cachePoint ? { providerOptions: cachePoint } : {}),
|
|
1662
|
-
};
|
|
1663
1772
|
// What the page offers, after the system prompt with a breakpoint of its own:
|
|
1664
1773
|
// it is the same for every step and every turn on the same page, so it is
|
|
1665
1774
|
// read from the cache, and when the page changes only it and what follows are
|
|
1666
1775
|
// written again. A change during the turn reaches the model in the answer
|
|
1667
1776
|
// that made it (ui-tools.ts `forModel`).
|
|
1668
|
-
const
|
|
1669
|
-
|
|
1777
|
+
const pageIndexText = client && client.page.length > 0 ? indexText(client.page, config.ui?.maxIndexChars ?? DEFAULT_INDEX_CHARS) : null;
|
|
1778
|
+
/**
|
|
1779
|
+
* What a step is told before the conversation, for the tools it offers: the
|
|
1780
|
+
* system prompt and the page's index. Steps told the same words are given
|
|
1781
|
+
* the same instructions, so the cache reads one from the other.
|
|
1782
|
+
*/
|
|
1783
|
+
const instructionsByTools = new Map();
|
|
1784
|
+
const instructionsByWords = new Map();
|
|
1785
|
+
const instructionsFor = (offered) => {
|
|
1786
|
+
const held = instructionsByTools.get(offered.key);
|
|
1787
|
+
if (held)
|
|
1788
|
+
return held;
|
|
1789
|
+
const systemMessage = {
|
|
1670
1790
|
role: 'system',
|
|
1671
|
-
content:
|
|
1672
|
-
'<page_index>',
|
|
1673
|
-
`The user's screen offers these surfaces and actions. In brackets after an action: what it takes ("?" marks an optional one, and a name alone takes text) and what calling it involves; no brackets means it takes nothing. Run an action with ${UI_ACT_TOOL}; ${UI_DESCRIBE_TOOL} says what one takes.`,
|
|
1674
|
-
indexText(client.page, config.ui?.maxIndexChars ?? DEFAULT_INDEX_CHARS),
|
|
1675
|
-
'</page_index>',
|
|
1676
|
-
].join('\n'),
|
|
1791
|
+
content: systemPromptFor(offered),
|
|
1677
1792
|
...(cachePoint ? { providerOptions: cachePoint } : {}),
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
|
|
1793
|
+
};
|
|
1794
|
+
const pageIndex = pageIndexText !== null
|
|
1795
|
+
? {
|
|
1796
|
+
role: 'system',
|
|
1797
|
+
content: [
|
|
1798
|
+
'<page_index>',
|
|
1799
|
+
`The user's screen offers these surfaces and actions. In brackets after an action: what it takes ("?" marks an optional one, and a name alone takes text) and what calling it involves; no brackets means it takes nothing.${renderRule(RUN_AN_ACTION, offered)}`,
|
|
1800
|
+
pageIndexText,
|
|
1801
|
+
'</page_index>',
|
|
1802
|
+
].join('\n'),
|
|
1803
|
+
...(cachePoint ? { providerOptions: cachePoint } : {}),
|
|
1804
|
+
}
|
|
1805
|
+
: null;
|
|
1806
|
+
const words = [systemMessage.content, pageIndex?.content ?? ''].join('\u0000');
|
|
1807
|
+
const made = instructionsByWords.get(words) ?? (pageIndex ? [systemMessage, pageIndex] : systemMessage);
|
|
1808
|
+
instructionsByWords.set(words, made);
|
|
1809
|
+
instructionsByTools.set(offered.key, made);
|
|
1810
|
+
return made;
|
|
1811
|
+
};
|
|
1681
1812
|
// ─── What is true now: with the turn's message, and after the conversation (step-messages.ts) ───
|
|
1682
1813
|
// The turn's own message: answers after it are this turn's, and only those
|
|
1683
1814
|
// are newer than the page the turn began on.
|
|
@@ -1686,12 +1817,6 @@ export async function runAgentTurn(config, input) {
|
|
|
1686
1817
|
const turnSpoken = input.approval || input.resume ? null : readClientMessageInput(input.context ?? null);
|
|
1687
1818
|
// The reply is spoken on every turn of a call, the turn an approval continues included.
|
|
1688
1819
|
const turnSpokenReply = readClientReplyOutput(input.context ?? null);
|
|
1689
|
-
// Whether the model may look at the person, and how, or why it cannot (prompt/vision.ts): a line of the turn's context.
|
|
1690
|
-
const turnVisionText = visionText(input.vision);
|
|
1691
|
-
// When to offer each photo plan, where a running capture stands, and an update that rode this turn (prompt/capture.ts).
|
|
1692
|
-
const turnCaptureText = captureText(input.capture);
|
|
1693
|
-
// When to move the call to the caller's phone, which device it is on, and an update that rode this turn (prompt/handoff.ts).
|
|
1694
|
-
const turnHandoffText = handoffText(input.handoff);
|
|
1695
1820
|
const turnPageValues = client && client.page.length > 0
|
|
1696
1821
|
? [
|
|
1697
1822
|
observationsText(client.observations, config.ui?.maxObservationChars ?? DEFAULT_PAGE_STATE_CHARS, {
|
|
@@ -1702,31 +1827,41 @@ export async function runAgentTurn(config, input) {
|
|
|
1702
1827
|
: null;
|
|
1703
1828
|
/**
|
|
1704
1829
|
* What is true for the whole turn, sent with the turn's own message on every
|
|
1705
|
-
* step
|
|
1706
|
-
*
|
|
1830
|
+
* step (step-messages.ts): never after a tool result, where the model reads
|
|
1831
|
+
* it as the person's newest message and drops the result. Its lines about
|
|
1832
|
+
* tools (looking, photos, moving the call) are written for the tools the step
|
|
1833
|
+
* offers, so steps that offer the same tools are told the same words.
|
|
1707
1834
|
*/
|
|
1708
|
-
const
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
//
|
|
1712
|
-
|
|
1713
|
-
//
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1835
|
+
const turnContextFor = (offered) => {
|
|
1836
|
+
// Whether the model may look at the person, and how, or why it cannot (prompt/vision.ts).
|
|
1837
|
+
const turnVisionText = visionText(input.vision, offered);
|
|
1838
|
+
// When to offer each photo plan, where a running capture stands, and an update that rode this turn (prompt/capture.ts).
|
|
1839
|
+
const turnCaptureText = captureText(input.capture, offered);
|
|
1840
|
+
// When to move the call to the caller's phone, which device it is on, and an update that rode this turn (prompt/handoff.ts).
|
|
1841
|
+
const turnHandoffText = handoffText(input.handoff, offered);
|
|
1842
|
+
return [
|
|
1843
|
+
turnClock,
|
|
1844
|
+
// A message the person spoke may hold a mis-heard word (prompt/spoken-input.ts). A click on an
|
|
1845
|
+
// approval card, and a resume after work, are not messages, so they say nothing.
|
|
1846
|
+
...(turnSpoken ? [spokenInputText(turnSpoken)] : []),
|
|
1847
|
+
// A reply a voice will read out is written for the ear (prompt/spoken-reply.ts).
|
|
1848
|
+
...(turnSpokenReply ? [spokenReplyText(turnSpokenReply)] : []),
|
|
1849
|
+
// When the model may look at the person, or that it cannot see them and why.
|
|
1850
|
+
...(turnVisionText ? [turnVisionText] : []),
|
|
1851
|
+
// When the model may ask for photos, and what has happened in a capture.
|
|
1852
|
+
...(turnCaptureText ? [turnCaptureText] : []),
|
|
1853
|
+
// When the model may move the call to the caller's phone, and what has happened to their devices.
|
|
1854
|
+
...(turnHandoffText ? [turnHandoffText] : []),
|
|
1855
|
+
...(expired.outcomes.length > 0 ? [expiredNote(expired)] : []),
|
|
1856
|
+
...(input.stepContext?.trim() ? [input.stepContext.trim()] : []),
|
|
1857
|
+
];
|
|
1858
|
+
};
|
|
1724
1859
|
/** The page's state from this turn's newest answer that carried one; until then, as the user's screen sent it. */
|
|
1725
1860
|
let newestAnswerState;
|
|
1726
1861
|
// Where it goes: with the turn's message (the default), or after the conversation, as 0.30 sent it.
|
|
1727
1862
|
const turnContextPlacement = readTurnContextPlacement(config.turnContextPlacement);
|
|
1728
1863
|
/** What is true for this step only, after the conversation: the page's state, and the step's notes. */
|
|
1729
|
-
const stepTail = (notes) => [
|
|
1864
|
+
const stepTail = (notes, turnContext) => [
|
|
1730
1865
|
...(turnPageValues
|
|
1731
1866
|
? [
|
|
1732
1867
|
[
|
|
@@ -1768,6 +1903,8 @@ export async function runAgentTurn(config, input) {
|
|
|
1768
1903
|
while (modelCalled) {
|
|
1769
1904
|
segments++;
|
|
1770
1905
|
const aiTools = assembleTools();
|
|
1906
|
+
// The turn's tools, as the model calls them: what a step offers when nothing holds it to fewer.
|
|
1907
|
+
const turnTools = Object.keys(aiTools);
|
|
1771
1908
|
const previousSteps = [...allSteps];
|
|
1772
1909
|
log('info', 'agent:llm', 'Messages prepared', {
|
|
1773
1910
|
turnId,
|
|
@@ -1777,7 +1914,7 @@ export async function runAgentTurn(config, input) {
|
|
|
1777
1914
|
});
|
|
1778
1915
|
const result = streamText({
|
|
1779
1916
|
model: replyRecorder,
|
|
1780
|
-
instructions,
|
|
1917
|
+
instructions: instructionsFor(offeredTools(turnTools)),
|
|
1781
1918
|
messages: withCachePoint(conversation),
|
|
1782
1919
|
tools: aiTools,
|
|
1783
1920
|
maxOutputTokens: maxTokens,
|
|
@@ -1785,11 +1922,17 @@ export async function runAgentTurn(config, input) {
|
|
|
1785
1922
|
abortSignal: abortController.signal,
|
|
1786
1923
|
// The host's, the same for every call (a thinking setting that changes invalidates the cache).
|
|
1787
1924
|
...(config.modelProviderOptions ? { providerOptions: config.modelProviderOptions } : {}),
|
|
1788
|
-
onChunk: ({ chunk }) => {
|
|
1925
|
+
onChunk: async ({ chunk }) => {
|
|
1789
1926
|
// A model named by its id is not wrapped: its text is recorded here instead.
|
|
1790
1927
|
if (typeof config.model === 'string')
|
|
1791
1928
|
recordReply(chunk);
|
|
1792
1929
|
reasoningRelay.onPart(chunk);
|
|
1930
|
+
// A call no tool of the step can run (a tool the step does not offer, input that would not parse) never
|
|
1931
|
+
// reaches `execute`: it is known here, as it arrives, before the step ends or the turn decides to.
|
|
1932
|
+
if (chunk.type === 'tool-call' && chunk.invalid) {
|
|
1933
|
+
const call = chunk;
|
|
1934
|
+
await callNoToolRan({ toolCallId: call.toolCallId, toolName: call.toolName, input: call.input, error: call.error });
|
|
1935
|
+
}
|
|
1793
1936
|
},
|
|
1794
1937
|
// An action of the page called as a tool of its own is the `ui_act` call it
|
|
1795
1938
|
// means, run once (ui/action-as-tool.ts): never refused, then called again.
|
|
@@ -1832,20 +1975,27 @@ export async function runAgentTurn(config, input) {
|
|
|
1832
1975
|
});
|
|
1833
1976
|
}
|
|
1834
1977
|
handedBackForTime ||= timing.handBack;
|
|
1835
|
-
const canOfferChoices =
|
|
1978
|
+
const canOfferChoices = PRESENT_OPTIONS_TOOL in aiTools;
|
|
1836
1979
|
const stepPolicy = handedBackForTime
|
|
1837
1980
|
? {
|
|
1838
|
-
|
|
1839
|
-
|
|
1981
|
+
// The hand-back step is held to the choice, or to no tool: it is told of exactly that.
|
|
1982
|
+
note: timeHandBackNote(offeredTools(canOfferChoices ? [PRESENT_OPTIONS_TOOL] : [])),
|
|
1983
|
+
toolChoice: canOfferChoices ? { type: 'tool', toolName: PRESENT_OPTIONS_TOOL } : 'none',
|
|
1840
1984
|
}
|
|
1841
1985
|
: await turnPolicy.prepareStep({
|
|
1842
|
-
// The policy counts steps across the whole turn, not per segment.
|
|
1986
|
+
// The policy counts steps across the whole turn, not per segment. Each call says whether it
|
|
1987
|
+
// ran: one that did not (refused, invalid, a tool the step did not offer) did nothing.
|
|
1843
1988
|
steps: [...previousSteps, ...steps].map((step) => ({
|
|
1844
|
-
toolCalls: step.toolCalls?.map((tc) =>
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
: tc.toolName
|
|
1848
|
-
|
|
1989
|
+
toolCalls: step.toolCalls?.map((tc) => {
|
|
1990
|
+
const notRun = callsNotRun.get(tc.toolCallId);
|
|
1991
|
+
return {
|
|
1992
|
+
toolName: tc.toolName === UI_ACT_TOOL && typeof tc.input?.action === 'string'
|
|
1993
|
+
? tc.input.action
|
|
1994
|
+
: tc.toolName,
|
|
1995
|
+
ran: notRun === undefined,
|
|
1996
|
+
...(notRun !== undefined ? { notRun } : {}),
|
|
1997
|
+
};
|
|
1998
|
+
}),
|
|
1849
1999
|
text: typeof step.text === 'string' ? step.text : '',
|
|
1850
2000
|
})),
|
|
1851
2001
|
turnClass,
|
|
@@ -1901,8 +2051,13 @@ export async function runAgentTurn(config, input) {
|
|
|
1901
2051
|
: 'This step: call a tool.'
|
|
1902
2052
|
: null;
|
|
1903
2053
|
const notes = [note, stepCall, ledger.note(), outputLimitNote].filter((n) => !!n);
|
|
2054
|
+
// What this step offers the model: everything the SDK tells it about a tool names only these.
|
|
2055
|
+
const offered = stepOfferedTools(turnTools, constraints);
|
|
2056
|
+
const turnContext = turnContextFor(offered);
|
|
2057
|
+
// A call no tool ran reads the SDK's result for it, never `ai`'s error (callNoToolRan).
|
|
2058
|
+
const answered = messages && resultsOfCallsNoToolRan.size > 0 ? withCallResults(messages, resultsOfCallsNoToolRan) : messages;
|
|
1904
2059
|
// Every answer gives its page state up the same way; the newest of this turn's is read at the end.
|
|
1905
|
-
const trimmed =
|
|
2060
|
+
const trimmed = answered ? withStatesAtEnd(answered, turnMessageAt) : null;
|
|
1906
2061
|
if (trimmed) {
|
|
1907
2062
|
pageStatesMoved += trimmed.moved;
|
|
1908
2063
|
if (trimmed.newest !== undefined)
|
|
@@ -1917,11 +2072,15 @@ export async function runAgentTurn(config, input) {
|
|
|
1917
2072
|
});
|
|
1918
2073
|
}
|
|
1919
2074
|
const leftOut = fileGuard.leftOutParts();
|
|
1920
|
-
const stepMessages = leftOut.length > 0 &&
|
|
2075
|
+
const stepMessages = leftOut.length > 0 && answered ? withoutLeftOut(trimmed?.messages ?? answered, leftOut) : trimmed?.messages ?? answered;
|
|
1921
2076
|
return {
|
|
1922
2077
|
...constraints,
|
|
1923
|
-
...(stepMessages
|
|
1924
|
-
|
|
2078
|
+
...(stepMessages
|
|
2079
|
+
? {
|
|
2080
|
+
messages: forStep(stepMessages, { turnContext: turnContextPlacement === 'with-message' ? turnContext : [], tail: stepTail(notes, turnContext) }, cachePoint),
|
|
2081
|
+
}
|
|
2082
|
+
: {}),
|
|
2083
|
+
instructions: instructionsFor(offered),
|
|
1925
2084
|
};
|
|
1926
2085
|
},
|
|
1927
2086
|
onStepEnd: async ({ text, toolCalls, usage: stepUsage, finishReason }) => {
|