@ultimat3/ai 31.47.1 → 31.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +2 -2
- package/README.md +14 -7
- package/package.json +11 -11
- package/src/agent-compact-request.ts +5 -2
- package/src/agent-compact.ts +92 -10
- package/src/agent-tools.ts +49 -21
- package/src/agent-transcript.ts +33 -2
- package/src/agent.ts +8 -1
- package/src/anthropic-provider.ts +5 -1
- package/src/anthropic-strict.ts +104 -0
- package/src/budget.ts +19 -2
- package/src/eval-baseline.ts +5 -1
- package/src/eval-errors.ts +1 -1
- package/src/evals.ts +10 -2
- package/src/gateway-settle.ts +1 -0
- package/src/llm.ts +2 -2
- package/src/openai-body.ts +3 -1
- package/src/openai-messages.ts +6 -3
- package/src/pg-vector-sql.ts +20 -4
- package/src/provider.ts +6 -0
- package/src/rag.ts +6 -8
- package/src/tools.ts +3 -3
- package/src/wire.ts +2 -2
package/CLAUDE.md
CHANGED
|
@@ -21,7 +21,7 @@ Keep `policy` dev-only: tests and `*-fixture.ts` harnesses import `allow`. The
|
|
|
21
21
|
| `model-resolve.ts` | `resolveModel` / `modelForCall` — declaration → prompt → gateway `defaultModel`, none is `X_AI_MODEL_UNRESOLVED` naming all three; `describedModel` for a published fact |
|
|
22
22
|
| `model-fixture.ts` | the rows this package's own suites register (`useFixtureModels()`). Not shipped |
|
|
23
23
|
| `provider.ts` | `Provider` interface, the request half; re-exports the Anthropic names |
|
|
24
|
-
| `anthropic-provider.ts` | `anthropicProvider()`,
|
|
24
|
+
| `anthropic-provider.ts` / `-strict.ts` | `anthropicProvider()`, `requiresStreaming`, message parse; which tools keep `strict` |
|
|
25
25
|
| `echo-provider.ts` | `echoProvider()`, the deterministic double. A fixture that needs a tool call uses `scriptedProvider`, never a hand-rolled `Provider` |
|
|
26
26
|
| `scripted-provider.ts` | `scriptedProvider()`, the scripted double that calls tools, and `X_AI_SCRIPT_EXHAUSTED`: one call past the script is refused, never answered with the last turn again |
|
|
27
27
|
| `content-blocks.ts` | the `image` / `document` block shapes, the screen every request runs them through, their token estimate |
|
|
@@ -69,7 +69,7 @@ Keep `policy` dev-only: tests and `*-fixture.ts` harnesses import `allow`. The
|
|
|
69
69
|
| `prompt-cache.ts` / `-rows.ts` | PROVIDER prompt caching, `PROMPT_CACHE_RULES` (sources in its header); the provider-rows screen |
|
|
70
70
|
| `prompt-cache-blocks.ts` | the Anthropic wire's marks (chat-completions': `openai-messages.ts`) |
|
|
71
71
|
| `agent-per-run.ts` / `agent-run-limits.ts` | one run's `offerTools()`/`model()`/`limits()`, narrow only; `costPerRun` |
|
|
72
|
-
| `agent-compact{,-def,-measure,-request,-text}.ts` | trigger, cut;
|
|
72
|
+
| `agent-compact{,-def,-measure,-request,-text}.ts` | trigger, cut; option, event; head; ratio; summary request, text if long |
|
|
73
73
|
| `agent-send.ts` / `context-overflow.ts` / `agent-checkpoint.ts` | a turn sent, an overflow compacted once; `X_AI_CONTEXT_OVERFLOW`'s phrases; `onCheckpoint` |
|
|
74
74
|
| `agent-continue.ts` / `agent-session.ts` / `agent-turn.ts` | the transcript handle and its screen; `.run()` / `.continue()` and their session; one turn's report and refusals |
|
|
75
75
|
| `agent-transcript.ts` | what one turn leaves in the transcript: the assistant replay, the tool results, the correction |
|
package/README.md
CHANGED
|
@@ -362,7 +362,7 @@ under-reported.
|
|
|
362
362
|
|---|---|
|
|
363
363
|
| **Structured output is the `respond` tool**, never `response_format` | `llm()` already projects `output` into one tool and reads the answer out of the tool call; `json_schema` + `strict` would be a second structured-output path (axiom 1) and is the one feature most OpenAI-*compatible* servers do not implement |
|
|
364
364
|
| `tool_choice` is forced when the request offers **exactly one** tool | one tool is nothing to choose between, and that is precisely `llm()`'s shape. A tool loop (`agent()`) is never forced — that would decide the model's next step for it |
|
|
365
|
-
| `strict: true` is claimed only when the schema **can keep the promise** | on this wire `strict` is checked by the server: one optional field and the request is a 400. The flag is derived from the projected schema, never forwarded |
|
|
365
|
+
| `strict: true` is claimed only when the schema **can keep the promise** | on this wire `strict` is checked by the server: one optional field — under `properties`, `items` or any `anyOf` branch — and the request is a 400. The flag is derived from the projected schema, never forwarded. The Messages wire derives its own (`anthropic-provider.ts`): there a length, numeric or array bound, a `pattern`, an object not closed with `additionalProperties: false`, or a request past 20 strict tools / 24 optional parameters / 16 union parameters is the 400, so such a tool is sent without the flag and validated on the way back |
|
|
366
366
|
| `max_completion_tokens`, never `max_tokens` | the old field is rejected outright by every current reasoning model |
|
|
367
367
|
| `stream_options: { include_usage: true }` on every streamed call | without it the final chunk carries no `usage`, and the budget reconciles a real call against nothing |
|
|
368
368
|
| Usage absent anyway → **estimated**, never zero — output counts the text AND every tool call's arguments | a compatible server that ignores `stream_options` would otherwise refund the whole reservation, and an `llm()` answer is one `respond` call with no text |
|
|
@@ -536,7 +536,7 @@ so `billedOf(error)` reads it. A meter, not a ledger: it refuses nothing.
|
|
|
536
536
|
|
|
537
537
|
### Continuing a run
|
|
538
538
|
|
|
539
|
-
`agent()` returns an `AgentAction`: the action, plus `.run(input, opts)` → `{ output, transcript, turns, usage }` and `.continue(input, { transcript, user }, opts)`, which appends one user turn to a stored transcript and resumes the loop. The transcript is re-sent byte for byte (the provider's prompt cache reads it back; no tool re-runs); `maxTurns` and `budget.tokensPerRun` are cumulative; the handle is signed, bound to the agent, model, tools and tenant, and screened (`X_AGENT_TRANSCRIPT_INVALID`); a failed call leaves an updated one on the error (`transcriptOf(error)`), which is the one a job stores. Full contract: [Agents → Continuing a run](https://github.com/developerz-ai/ultimate/wiki/Agents#continuing-a-run-run--continue).
|
|
539
|
+
`agent()` returns an `AgentAction`: the action, plus `.run(input, opts)` → `{ output, transcript, turns, usage }` and `.continue(input, { transcript, user }, opts)`, which appends one user turn to a stored transcript and resumes the loop. The transcript is re-sent byte for byte (the provider's prompt cache reads it back; no tool re-runs); `maxTurns` and `budget.tokensPerRun` are cumulative; the handle is signed, bound to the agent, model, tools and tenant, and screened (`X_AGENT_TRANSCRIPT_INVALID`); a failed call leaves an updated one on the error (`transcriptOf(error)`), which is the one a job stores — it holds every tool result the failed turn completed, a call cut off in flight answered `Interrupted: … outcome is unknown` and one never started `Not run`, so a continuation does not run a finished tool (a charge) a second time. Full contract: [Agents → Continuing a run](https://github.com/developerz-ai/ultimate/wiki/Agents#continuing-a-run-run--continue).
|
|
540
540
|
|
|
541
541
|
`onCheckpoint(event, { input, ctx })` hands the app the same signed handle **between** turns — after a
|
|
542
542
|
turn's tool results (or its correction) land, before the next turn is bought, never after the answer
|
|
@@ -598,7 +598,11 @@ export const researcher = agent({
|
|
|
598
598
|
Before each turn, the gateway's estimate of that turn's request — scaled by what the provider
|
|
599
599
|
reported for the last one — is compared with the model row's `contextWindow` less `maxTokens`. Over `at` of it, ONE model call summarises every turn older than
|
|
600
600
|
the last `keepTurns`; the summary joins the first user message (after the prompt, verbatim, marked
|
|
601
|
-
`[compacted: …]`), the kept turns follow byte for byte, and the turn is sent.
|
|
601
|
+
`[compacted: …]`), the kept turns follow byte for byte, and the turn is sent. What the **user**
|
|
602
|
+
said in the summarised turns — a `.continue()` instruction — is carried into that first message
|
|
603
|
+
verbatim, newest first up to `KEPT_USER_CHARS` (8,000 characters) **in total** — what earlier
|
|
604
|
+
compactions carried is charged against the same allowance, so a long chat's head stays bounded —
|
|
605
|
+
and beyond it left to the summary.
|
|
602
606
|
|
|
603
607
|
| Rule | Why |
|
|
604
608
|
|---|---|
|
|
@@ -620,7 +624,7 @@ the last `keepTurns`; the summary joins the first user message (after the prompt
|
|
|
620
624
|
|---|---|
|
|
621
625
|
| the estimate | ~4 characters a token until the first turn reports, which is why `at` defaults below 1 |
|
|
622
626
|
| the forced compaction | its summary call is the refused request less the kept turns: with a tiny `keepTurns` it may not fit either — `compact.model` with a larger window is the way out |
|
|
623
|
-
| `tools: []` on the chat-completions wire |
|
|
627
|
+
| `tools: []` on the chat-completions wire | the summary call carries `toolChoice: 'auto'` (`GenerateRequest`), so the one `respond` tool is offered but not forced and the summary is prose — until 2026-11 it was forced, answered no text and never compacted |
|
|
624
628
|
| per run | `compact` is the declaration's; `limits()` does not take it, `describeAgents()` does not publish it |
|
|
625
629
|
|
|
626
630
|
### Provider prompt caching
|
|
@@ -1008,7 +1012,8 @@ test('summarize holds its recorded scores', async () => {
|
|
|
1008
1012
|
```
|
|
1009
1013
|
|
|
1010
1014
|
`ULTIMATE_EVAL_RECORD=1 x test eval` writes the baselines instead of gating on them, so
|
|
1011
|
-
accepting a new number is a reviewable diff
|
|
1015
|
+
accepting a new number is a reviewable diff (`0`, `false`, `no`, `off` and empty are off: they gate).
|
|
1016
|
+
`tolerance` is screened at declaration — finite and 0 or more, else `X_INVARIANT`. An eval that has never been recorded fails with
|
|
1012
1017
|
`X_EVAL_BASELINE_MISSING` — gating on nothing is not passing — and `x verify` asks that question
|
|
1013
1018
|
itself, so an eval no test happens to assert is still red.
|
|
1014
1019
|
|
|
@@ -1161,8 +1166,10 @@ search loses on exactly the queries users type: error codes, SKUs, identifiers,
|
|
|
1161
1166
|
RRF fuses by *rank*, so the two score scales never have to be reconciled.
|
|
1162
1167
|
|
|
1163
1168
|
`postgresVectorStore()` is the production path: pgvector cosine (`<=>`, HNSW) and Postgres FTS
|
|
1164
|
-
(
|
|
1165
|
-
|
|
1169
|
+
(any word of the query matches — one `phraseto_tsquery` per word, OR-ed — ranked by `ts_rank_cd`,
|
|
1170
|
+
GIN) in **the same Postgres**, fused by `1/(k+rank)` in one statement. The query is text, never
|
|
1171
|
+
syntax: quotes, `-` and `or` are not operators (until 2026-11 it was `websearch_to_tsquery`, which
|
|
1172
|
+
ANDs every word, so a whole question matched no chunk and hybrid ranked on the vector alone). `memoryVectorStore()` is the dev twin — BM25 instead of `ts_rank_cd`, the same RRF,
|
|
1166
1173
|
the same envelope, the same cosine (magnitude never ranks; a zero-norm row scores `NaN` and sorts
|
|
1167
1174
|
last, as float8 does), and fusion on the same `(tenant, id)` key, so an unscoped hybrid keeps two
|
|
1168
1175
|
tenants' same-id rows apart.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/ai",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.49.0",
|
|
4
4
|
"description": "LLM gateway, versioned prompts, evals as tests, embeddings, hybrid vector search, RAG",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,17 +45,17 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/action": "31.
|
|
49
|
-
"@ultimat3/cache": "31.
|
|
50
|
-
"@ultimat3/core": "31.
|
|
51
|
-
"@ultimat3/db": "31.
|
|
52
|
-
"@ultimat3/http": "31.
|
|
53
|
-
"@ultimat3/jobs": "31.
|
|
54
|
-
"@ultimat3/money": "31.
|
|
55
|
-
"@ultimat3/schema": "31.
|
|
56
|
-
"@ultimat3/time": "31.
|
|
48
|
+
"@ultimat3/action": "31.49.0",
|
|
49
|
+
"@ultimat3/cache": "31.49.0",
|
|
50
|
+
"@ultimat3/core": "31.49.0",
|
|
51
|
+
"@ultimat3/db": "31.49.0",
|
|
52
|
+
"@ultimat3/http": "31.49.0",
|
|
53
|
+
"@ultimat3/jobs": "31.49.0",
|
|
54
|
+
"@ultimat3/money": "31.49.0",
|
|
55
|
+
"@ultimat3/schema": "31.49.0",
|
|
56
|
+
"@ultimat3/time": "31.49.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@ultimat3/policy": "31.
|
|
59
|
+
"@ultimat3/policy": "31.49.0"
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -66,10 +66,13 @@ function writerRequest(
|
|
|
66
66
|
maxTokens: number,
|
|
67
67
|
messages: readonly AiMessage[],
|
|
68
68
|
): GenerateRequest {
|
|
69
|
-
|
|
69
|
+
// `toolChoice: 'auto'`: the summary is prose. A run offering `respond` alone would otherwise be
|
|
70
|
+
// FORCED through it on the chat-completions wire, answer no text, and never compact.
|
|
71
|
+
const prose = { messages, maxTokens, toolChoice: 'auto' as const };
|
|
72
|
+
if (writer === base.model) return { ...base, ...prose };
|
|
70
73
|
// Nor the run model's fallback chain: a separate writer is its own choice, and may be in it.
|
|
71
74
|
const { effort: _effort, thinking: _thinking, fallbackModels: _chain, ...rest } = base;
|
|
72
|
-
return { ...rest, model: writer,
|
|
75
|
+
return { ...rest, model: writer, ...prose };
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
/** Roles must alternate, and the older turns end on a user message: the instruction joins it. */
|
package/src/agent-compact.ts
CHANGED
|
@@ -21,11 +21,18 @@ import type { SummaryInput, SummarySplit } from './agent-compact-request';
|
|
|
21
21
|
import { blocksOf, COMPACTED_MARK, summaryCall } from './agent-compact-request';
|
|
22
22
|
import { AgentContextExhaustedError } from './agent-errors';
|
|
23
23
|
import type { RunDeadline } from './agent-guards';
|
|
24
|
+
import { isRepairText } from './agent-transcript';
|
|
24
25
|
import type { Gateway } from './gateway';
|
|
25
26
|
import { reportedCall } from './llm-instrument';
|
|
26
27
|
import type { ModelId } from './models';
|
|
27
28
|
import { modelSpec } from './models';
|
|
28
|
-
import type {
|
|
29
|
+
import type {
|
|
30
|
+
AiContentBlock,
|
|
31
|
+
AiMessage,
|
|
32
|
+
GenerateRequest,
|
|
33
|
+
GenerateResult,
|
|
34
|
+
TokenUsage,
|
|
35
|
+
} from './provider';
|
|
29
36
|
import { estimateInputTokens, estimateTextTokens, isTruncated } from './provider';
|
|
30
37
|
import { runMeter } from './run-meter';
|
|
31
38
|
|
|
@@ -217,7 +224,7 @@ export function compactor(input: CompactorInput): Compactor {
|
|
|
217
224
|
);
|
|
218
225
|
}
|
|
219
226
|
if (summary === '') return failed('the summary call answered no text', summarised, result);
|
|
220
|
-
const compacted = [compactedHead(split.head, summarised, summary), ...split.kept];
|
|
227
|
+
const compacted = [compactedHead(split.head, split.older, summarised, summary), ...split.kept];
|
|
221
228
|
const after = measured({ ...base, messages: compacted });
|
|
222
229
|
if (after >= before) {
|
|
223
230
|
return failed('the summary was no shorter than the turns it replaced', summarised, result);
|
|
@@ -273,15 +280,90 @@ function splitTurns(messages: readonly AiMessage[], keepTurns: number): Split |
|
|
|
273
280
|
}
|
|
274
281
|
|
|
275
282
|
/**
|
|
276
|
-
* The
|
|
277
|
-
*
|
|
283
|
+
* The most user text a compacted head carries out of summarised turns, in characters (~2,000
|
|
284
|
+
* tokens), IN TOTAL: what earlier compactions carried is charged too, newest kept first. Past it the
|
|
285
|
+
* older text is the summary's to cover, as all of it was — a pasted document, or a long
|
|
286
|
+
* `.continue()` chat, must not make a transcript no compaction can shorten.
|
|
278
287
|
*/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
288
|
+
export const KEPT_USER_CHARS = 8_000;
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* How the summary block this file writes OPENS. The whole phrase, not `[compacted:` alone: a
|
|
292
|
+
* prompt whose template opens with a slot can start with anything, and a block that merely looks
|
|
293
|
+
* marked was deleted as an old summary.
|
|
294
|
+
*/
|
|
295
|
+
const SUMMARY_NOTE = /^\[compacted: \d+ earlier turns? of this run were summarised to fit /;
|
|
296
|
+
|
|
297
|
+
/** The clause naming how many blocks before the note are carried user text, not the prompt. */
|
|
298
|
+
const CARRIED_NOTE =
|
|
299
|
+
/^\[compacted: \d+ earlier turns? of this run were summarised to fit the context window, the last (\d+) text blocks? above kept as the user wrote them\./;
|
|
300
|
+
|
|
301
|
+
const isSummary = (block: AiContentBlock): boolean =>
|
|
302
|
+
block.type === 'text' && SUMMARY_NOTE.test(block.text);
|
|
303
|
+
|
|
304
|
+
/** How many blocks an earlier compaction carried, read off its note; 0 for a note without the count. */
|
|
305
|
+
function carriedCount(blocks: readonly AiContentBlock[]): number {
|
|
306
|
+
for (const block of blocks) {
|
|
307
|
+
if (block.type !== 'text' || !isSummary(block)) continue;
|
|
308
|
+
const count = CARRIED_NOTE.exec(block.text)?.[1];
|
|
309
|
+
return count === undefined ? 0 : Number.parseInt(count, 10);
|
|
310
|
+
}
|
|
311
|
+
return 0;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `head` rebuilt for `turns` summarised turns (`older`): its prompt less an earlier summary — the
|
|
316
|
+
* new one covers it — then the user's text out of what earlier compactions carried and `older`,
|
|
317
|
+
* within one `KEPT_USER_CHARS`, then the summary. The model reads the summary as its own notes,
|
|
318
|
+
* said to be so; the note counts the carried blocks so the next compaction can charge them.
|
|
319
|
+
*/
|
|
320
|
+
export function compactedHead(
|
|
321
|
+
head: AiMessage,
|
|
322
|
+
older: readonly AiMessage[],
|
|
323
|
+
turns: number,
|
|
324
|
+
summary: string,
|
|
325
|
+
): AiMessage {
|
|
326
|
+
const blocks = blocksOf(head);
|
|
327
|
+
const own = blocks.filter((block) => !isSummary(block));
|
|
328
|
+
const from = Math.max(0, own.length - carriedCount(blocks));
|
|
329
|
+
const kept = userTexts([...textsOf(own.slice(from)), ...older.flatMap(saidIn)]);
|
|
330
|
+
const carried =
|
|
331
|
+
kept.length === 0
|
|
332
|
+
? ''
|
|
333
|
+
: `, the last ${kept.length} text block${kept.length === 1 ? '' : 's'} above kept as the user wrote them`;
|
|
334
|
+
const note = `${COMPACTED_MARK} ${turns} earlier turn${turns === 1 ? '' : 's'} of this run were summarised to fit the context window${carried}. Your summary of everything after the task above:]\n\n${summary}`;
|
|
335
|
+
return {
|
|
336
|
+
role: 'user',
|
|
337
|
+
content: [
|
|
338
|
+
...own.slice(0, from),
|
|
339
|
+
...kept.map((text): AiContentBlock => ({ type: 'text', text })),
|
|
340
|
+
{ type: 'text', text: note },
|
|
341
|
+
],
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const textsOf = (blocks: readonly AiContentBlock[]): readonly string[] =>
|
|
346
|
+
blocks.flatMap((block) => (block.type === 'text' ? [block.text] : []));
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* What the user wrote in one message. A user message holds tool results and framework text too:
|
|
350
|
+
* results are never text blocks, and the loop's own correction is recognised by `isRepairText`.
|
|
351
|
+
*/
|
|
352
|
+
const saidIn = (message: AiMessage): readonly string[] =>
|
|
353
|
+
message.role !== 'user'
|
|
354
|
+
? []
|
|
355
|
+
: textsOf(blocksOf(message)).filter((text) => text.trim() !== '' && !isRepairText(text));
|
|
356
|
+
|
|
357
|
+
/** `said`, oldest first, cut to the newest that fit `KEPT_USER_CHARS` together. */
|
|
358
|
+
function userTexts(said: readonly string[]): readonly string[] {
|
|
359
|
+
const kept: string[] = [];
|
|
360
|
+
let room = KEPT_USER_CHARS;
|
|
361
|
+
for (const text of [...said].reverse()) {
|
|
362
|
+
if (text.length > room) break;
|
|
363
|
+
room -= text.length;
|
|
364
|
+
kept.unshift(text);
|
|
365
|
+
}
|
|
366
|
+
return kept;
|
|
285
367
|
}
|
|
286
368
|
|
|
287
369
|
/** The event's facts about the summary call's input: its form, and how far text was shortened. */
|
package/src/agent-tools.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { Actor, Ctx } from '@ultimat3/core';
|
|
|
8
8
|
import { throwIfAborted } from '@ultimat3/core';
|
|
9
9
|
import type { RunDeadline } from './agent-guards';
|
|
10
10
|
import type { EmitChunk } from './agent-stream';
|
|
11
|
-
import { assistantTurn, toolResultTurn } from './agent-transcript';
|
|
11
|
+
import { assistantTurn, settledResults, toolResultTurn } from './agent-transcript';
|
|
12
12
|
import type { AiMessage, GenerateResult } from './provider';
|
|
13
13
|
import type { LlmToolCall, LlmToolResult, ProjectableAction } from './tools';
|
|
14
14
|
import { runLlmToolCall } from './tools';
|
|
@@ -25,6 +25,14 @@ export interface ToolBatchOptions {
|
|
|
25
25
|
readonly discloseErrors?: boolean;
|
|
26
26
|
/** Asked before EACH call starts — the run's abort and deadline checks: a throw starts nothing more. */
|
|
27
27
|
readonly beforeCall?: () => void;
|
|
28
|
+
/** Written as the batch runs, so a caller whose batch THREW can still read how far it got. */
|
|
29
|
+
readonly progress?: ToolBatchProgress;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One batch, by call index: which calls started, and the result of each that completed. */
|
|
33
|
+
export interface ToolBatchProgress {
|
|
34
|
+
readonly started: boolean[];
|
|
35
|
+
readonly results: (LlmToolResult | undefined)[];
|
|
28
36
|
}
|
|
29
37
|
|
|
30
38
|
/**
|
|
@@ -50,7 +58,10 @@ export async function runToolBatch(
|
|
|
50
58
|
const call = calls[index];
|
|
51
59
|
if (call === undefined) continue;
|
|
52
60
|
options.beforeCall?.();
|
|
53
|
-
|
|
61
|
+
if (options.progress !== undefined) options.progress.started[index] = true;
|
|
62
|
+
const done = await runLlmToolCall(tools, call, actor, disclosure);
|
|
63
|
+
results[index] = done;
|
|
64
|
+
if (options.progress !== undefined) options.progress.results[index] = done;
|
|
54
65
|
}
|
|
55
66
|
};
|
|
56
67
|
const width = Math.max(1, Math.min(options.concurrency, calls.length));
|
|
@@ -72,6 +83,12 @@ export interface ToolRun {
|
|
|
72
83
|
readonly chars: number;
|
|
73
84
|
readonly redact: (text: string) => string;
|
|
74
85
|
readonly repeated: (calls: readonly LlmToolCall[], results: readonly LlmToolResult[]) => void;
|
|
86
|
+
/**
|
|
87
|
+
* Handed the transcript of a tool turn that THREW after a tool started — the abort, the deadline,
|
|
88
|
+
* `X_AGENT_TOOL_LOOP` — so the failed run's handle holds every result that completed. Without
|
|
89
|
+
* it a continuation resumes from before the turn and runs the same tools (a charge) again.
|
|
90
|
+
*/
|
|
91
|
+
readonly interrupted?: (messages: readonly AiMessage[]) => void;
|
|
75
92
|
}
|
|
76
93
|
|
|
77
94
|
/**
|
|
@@ -93,25 +110,8 @@ export async function toolTurn(
|
|
|
93
110
|
};
|
|
94
111
|
stop();
|
|
95
112
|
for (const call of requested) emit({ type: 'tool_call', turn, id: call.id, name: call.name });
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
deadline.scope(() =>
|
|
99
|
-
runToolBatch(run.tools, requested, run.actor, {
|
|
100
|
-
concurrency: run.concurrency,
|
|
101
|
-
discloseErrors: run.discloseErrors,
|
|
102
|
-
beforeCall: stop,
|
|
103
|
-
}),
|
|
104
|
-
),
|
|
105
|
-
);
|
|
106
|
-
results.forEach((done, index) => {
|
|
107
|
-
const name = requested[index]?.name ?? '';
|
|
108
|
-
emit({ type: 'tool_result', turn, id: done.toolUseId, name, isError: done.isError === true });
|
|
109
|
-
});
|
|
110
|
-
emit({ type: 'turn', turn, maxTurns: run.maxTurns });
|
|
111
|
-
// Before the next turn is bought: the same calls with the same results cannot lead anywhere a
|
|
112
|
-
// further turn would not also lead.
|
|
113
|
-
run.repeated(requested, results);
|
|
114
|
-
return [
|
|
113
|
+
const progress: ToolBatchProgress = { started: [], results: [] };
|
|
114
|
+
const transcript = (results: readonly LlmToolResult[]): readonly AiMessage[] => [
|
|
115
115
|
...messages,
|
|
116
116
|
assistantTurn(result),
|
|
117
117
|
// Parallel tool use — one turn asking for a tool AND answering — is normal, and the answer is
|
|
@@ -120,4 +120,32 @@ export async function toolTurn(
|
|
|
120
120
|
// block with no `tool_result` is a 400 and the whole run becomes `X_AI_PROVIDER_UNAVAILABLE`.
|
|
121
121
|
toolResultTurn(results, run.chars, answers, run.redact),
|
|
122
122
|
];
|
|
123
|
+
try {
|
|
124
|
+
const results = await deadline.guard(
|
|
125
|
+
// Inside the deadline's scope, so each tool's own `ctx.signal` carries it.
|
|
126
|
+
deadline.scope(() =>
|
|
127
|
+
runToolBatch(run.tools, requested, run.actor, {
|
|
128
|
+
concurrency: run.concurrency,
|
|
129
|
+
discloseErrors: run.discloseErrors,
|
|
130
|
+
beforeCall: stop,
|
|
131
|
+
progress,
|
|
132
|
+
}),
|
|
133
|
+
),
|
|
134
|
+
);
|
|
135
|
+
results.forEach((done, index) => {
|
|
136
|
+
const name = requested[index]?.name ?? '';
|
|
137
|
+
emit({ type: 'tool_result', turn, id: done.toolUseId, name, isError: done.isError === true });
|
|
138
|
+
});
|
|
139
|
+
emit({ type: 'turn', turn, maxTurns: run.maxTurns });
|
|
140
|
+
// Before the next turn is bought: the same calls with the same results cannot lead anywhere a
|
|
141
|
+
// further turn would not also lead.
|
|
142
|
+
run.repeated(requested, results);
|
|
143
|
+
return transcript(results);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
// Nothing started is nothing to remember: the handle stays at the request the turn answered.
|
|
146
|
+
if (progress.started.some(Boolean)) {
|
|
147
|
+
run.interrupted?.(transcript(settledResults(requested, progress.started, progress.results)));
|
|
148
|
+
}
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
123
151
|
}
|
package/src/agent-transcript.ts
CHANGED
|
@@ -16,7 +16,8 @@ import type { LlmToolCall, LlmToolResult } from './tools';
|
|
|
16
16
|
*/
|
|
17
17
|
export function assistantTurn(result: GenerateResult): AiMessage {
|
|
18
18
|
const blocks: AiContentBlock[] = [];
|
|
19
|
-
|
|
19
|
+
// Whitespace-only counts as empty: the Messages API refuses a blank text block either way.
|
|
20
|
+
if (result.text.trim() !== '') blocks.push({ type: 'text', text: result.text });
|
|
20
21
|
for (const call of result.toolCalls) {
|
|
21
22
|
blocks.push({ type: 'tool_use', id: call.id, name: call.name, input: call.input });
|
|
22
23
|
}
|
|
@@ -70,6 +71,36 @@ export function toolResultTurn(
|
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
73
|
|
|
74
|
+
/** A call the run stopped before starting: safe to ask for again. */
|
|
75
|
+
const NOT_RUN = 'Not run: the run stopped before this call started.';
|
|
76
|
+
/** A call in flight when the run stopped. Never "not run": a model told that buys the effect twice. */
|
|
77
|
+
const INTERRUPTED =
|
|
78
|
+
'Interrupted: this call had started when the run stopped, and its outcome is unknown. Check whether it took effect before calling it again.';
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* One result per call of a turn that did not finish, in call order: the real result where the tool
|
|
82
|
+
* completed, and an error result saying WHICH of the two other things happened where it did not.
|
|
83
|
+
*/
|
|
84
|
+
export function settledResults(
|
|
85
|
+
calls: readonly LlmToolCall[],
|
|
86
|
+
started: readonly (boolean | undefined)[],
|
|
87
|
+
results: readonly (LlmToolResult | undefined)[],
|
|
88
|
+
): readonly LlmToolResult[] {
|
|
89
|
+
return calls.map(
|
|
90
|
+
(call, index) =>
|
|
91
|
+
results[index] ?? {
|
|
92
|
+
toolUseId: call.id,
|
|
93
|
+
content: started[index] === true ? INTERRUPTED : NOT_RUN,
|
|
94
|
+
isError: true,
|
|
95
|
+
},
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const REPAIR_OPENS = 'That answer failed its schema: ';
|
|
100
|
+
|
|
101
|
+
/** Whether a user message's text is the loop's own correction (`repairTurn`), not the user's. */
|
|
102
|
+
export const isRepairText = (text: string): boolean => text.startsWith(REPAIR_OPENS);
|
|
103
|
+
|
|
73
104
|
/**
|
|
74
105
|
* The correction after an answer that failed its schema, in whichever shape the turn it corrects
|
|
75
106
|
* demands: a `tool_result` when the answer came through `respond` (the dominant path, and a
|
|
@@ -77,7 +108,7 @@ export function toolResultTurn(
|
|
|
77
108
|
* prose and there is no id to name. Framework text, so never truncated by `maxToolResultChars`.
|
|
78
109
|
*/
|
|
79
110
|
export function repairTurn(unaccepted: readonly LlmToolCall[], issues: string): AiMessage {
|
|
80
|
-
const text =
|
|
111
|
+
const text = `${REPAIR_OPENS}${issues}. Call the "${RESPOND}" tool with a value that satisfies it. Answer only through the tool.`;
|
|
81
112
|
return unaccepted.length === 0
|
|
82
113
|
? { role: 'user', content: text }
|
|
83
114
|
: { role: 'user', content: rejections(unaccepted, text) };
|
package/src/agent.ts
CHANGED
|
@@ -337,6 +337,9 @@ async function run<
|
|
|
337
337
|
chars,
|
|
338
338
|
redact,
|
|
339
339
|
repeated,
|
|
340
|
+
interrupted: (partial) => {
|
|
341
|
+
at.messages = partial;
|
|
342
|
+
},
|
|
340
343
|
};
|
|
341
344
|
let messages: readonly AiMessage[] =
|
|
342
345
|
prior === undefined ? [{ role: 'user', content: rendered }] : continued(prior, rendered);
|
|
@@ -391,6 +394,8 @@ async function run<
|
|
|
391
394
|
|
|
392
395
|
if (requested.length > 0) {
|
|
393
396
|
messages = await toolTurn(tools, turn, result, requested, answers, messages);
|
|
397
|
+
// Before anything else can throw (`onCheckpoint`): a failed run's handle holds these results.
|
|
398
|
+
at.messages = messages;
|
|
394
399
|
calls += requested.length;
|
|
395
400
|
rejected = undefined;
|
|
396
401
|
await landed(turn, messages, result.model);
|
|
@@ -421,6 +426,7 @@ async function run<
|
|
|
421
426
|
rejected = formatIssues(parsed.issues);
|
|
422
427
|
issues = rejected.join('; ');
|
|
423
428
|
messages = [...messages, assistantTurn(result), repairTurn(answers, issues)];
|
|
429
|
+
at.messages = messages;
|
|
424
430
|
await landed(turn, messages, result.model);
|
|
425
431
|
}
|
|
426
432
|
|
|
@@ -443,7 +449,8 @@ async function run<
|
|
|
443
449
|
.catch((error: unknown) => {
|
|
444
450
|
const failed = meter.fail(error);
|
|
445
451
|
// A failed `.run()` / `.continue()` leaves a handle too: the transcript up to the request
|
|
446
|
-
// the failed turn was answering
|
|
452
|
+
// the failed turn was answering — plus every tool result that turn completed, so a
|
|
453
|
+
// continuation never runs a tool twice — with `turns` and `usage` counting what this call was
|
|
447
454
|
// billed. Without it a retry resumes from the OLD handle, which never heard of that spend
|
|
448
455
|
// — six truncated continuations billed six times against a ceiling that saw none of them.
|
|
449
456
|
if (session !== undefined && at.messages.length > 0) {
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// ./provider's; ./models owns the per-model rules and ./wire the streamed response half.
|
|
4
4
|
|
|
5
5
|
import { readAnswerBody } from './answer-body';
|
|
6
|
+
import { anthropicTools } from './anthropic-strict';
|
|
6
7
|
import { billedCall } from './billed';
|
|
7
8
|
import { assertMediaContent } from './content-blocks';
|
|
8
9
|
import { providerFailure } from './context-overflow';
|
|
@@ -210,7 +211,10 @@ export class AnthropicProvider implements Provider {
|
|
|
210
211
|
...providerOptionsBody('anthropic', request.providerOptions),
|
|
211
212
|
};
|
|
212
213
|
if (prompt.system !== undefined) body['system'] = prompt.system;
|
|
213
|
-
if (request.tools !== undefined && request.tools.length > 0)
|
|
214
|
+
if (request.tools !== undefined && request.tools.length > 0) {
|
|
215
|
+
// `strict` is derived for this wire, never forwarded: outside the subset it is a 400.
|
|
216
|
+
body['tools'] = anthropicTools(request.tools);
|
|
217
|
+
}
|
|
214
218
|
if (request.stopSequences !== undefined) body['stop_sequences'] = request.stopSequences;
|
|
215
219
|
return body;
|
|
216
220
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Which tools of one Anthropic request may carry `strict: true`. On this wire the flag is a promise
|
|
2
|
+
// the server checks — a schema outside the documented strict subset, or a request past one of three
|
|
3
|
+
// caps, is a 400 — so it is derived per request, never forwarded. Source (read 2026-11-19):
|
|
4
|
+
// platform.claude.com/docs/en/build-with-claude/structured-outputs.
|
|
5
|
+
|
|
6
|
+
import type { JsonSchema, LlmTool } from './tools';
|
|
7
|
+
|
|
8
|
+
/** "Strict tools per request: 20". A tool sent without the flag does not count. */
|
|
9
|
+
export const MAX_STRICT_TOOLS = 20;
|
|
10
|
+
/** "Optional parameters: 24" — keys not in `required`, summed over every strict schema. */
|
|
11
|
+
export const MAX_STRICT_OPTIONAL = 24;
|
|
12
|
+
/** "Parameters with union types: 16" — `anyOf`, summed over every strict schema. */
|
|
13
|
+
export const MAX_STRICT_UNIONS = 16;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The keywords the strict subset accepts as this package emits them. An ALLOW-list: a keyword the
|
|
17
|
+
* projection grows later is outside it until someone reads the provider's page again. `pattern` is
|
|
18
|
+
* left out on purpose — only "simple" patterns compile, and which those are is not ours to guess.
|
|
19
|
+
*/
|
|
20
|
+
const ACCEPTED: ReadonlySet<string> = new Set([
|
|
21
|
+
'type',
|
|
22
|
+
'title',
|
|
23
|
+
'description',
|
|
24
|
+
'properties',
|
|
25
|
+
'required',
|
|
26
|
+
'additionalProperties',
|
|
27
|
+
'items',
|
|
28
|
+
'minItems',
|
|
29
|
+
'enum',
|
|
30
|
+
'const',
|
|
31
|
+
'default',
|
|
32
|
+
'anyOf',
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
/** What one schema costs against the request's caps. */
|
|
36
|
+
export interface StrictWeight {
|
|
37
|
+
readonly optional: number;
|
|
38
|
+
readonly unions: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `schema`'s weight when it is inside the strict subset, `undefined` when it is not: a length,
|
|
43
|
+
* numeric or array bound (`minItems` 0 and 1 excepted), an object not closed with
|
|
44
|
+
* `additionalProperties: false`, or `anyOf` beside `type` / `properties`.
|
|
45
|
+
*/
|
|
46
|
+
export function strictSubset(schema: JsonSchema): StrictWeight | undefined {
|
|
47
|
+
for (const key of Object.keys(schema)) if (!ACCEPTED.has(key)) return undefined;
|
|
48
|
+
if (schema.minItems !== undefined && schema.minItems !== 0 && schema.minItems !== 1) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
let optional = 0;
|
|
52
|
+
let unions = 0;
|
|
53
|
+
const children: JsonSchema[] = [];
|
|
54
|
+
if (schema.anyOf !== undefined) {
|
|
55
|
+
if (schema.type !== undefined || schema.properties !== undefined) return undefined;
|
|
56
|
+
unions += 1;
|
|
57
|
+
children.push(...schema.anyOf);
|
|
58
|
+
}
|
|
59
|
+
if (schema.items !== undefined) children.push(schema.items);
|
|
60
|
+
if (schema.type === 'object' || schema.properties !== undefined) {
|
|
61
|
+
if (schema.additionalProperties !== false) return undefined;
|
|
62
|
+
const required = new Set(schema.required ?? []);
|
|
63
|
+
for (const [key, child] of Object.entries(schema.properties ?? {})) {
|
|
64
|
+
if (!required.has(key)) optional += 1;
|
|
65
|
+
children.push(child);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
for (const child of children) {
|
|
69
|
+
const weight = strictSubset(child);
|
|
70
|
+
if (weight === undefined) return undefined;
|
|
71
|
+
optional += weight.optional;
|
|
72
|
+
unions += weight.unions;
|
|
73
|
+
}
|
|
74
|
+
return { optional, unions };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The request's tools as this wire takes them: `strict` kept where the tool asked for it, its
|
|
79
|
+
* schema is inside the subset, and the request stays under all three caps — granted in request
|
|
80
|
+
* order, so the same tools always get the same flags (the tools are a cached prefix). A tool
|
|
81
|
+
* without the flag is sent whole and validated by its own schema on the way back, as every tool
|
|
82
|
+
* call already is.
|
|
83
|
+
*/
|
|
84
|
+
export function anthropicTools(tools: readonly LlmTool[]): readonly LlmTool[] {
|
|
85
|
+
let strict = 0;
|
|
86
|
+
let optional = 0;
|
|
87
|
+
let unions = 0;
|
|
88
|
+
return tools.map((tool) => {
|
|
89
|
+
const { strict: asked, ...rest } = tool;
|
|
90
|
+
const weight = asked === true ? strictSubset(tool.input_schema) : undefined;
|
|
91
|
+
if (
|
|
92
|
+
weight === undefined ||
|
|
93
|
+
strict + 1 > MAX_STRICT_TOOLS ||
|
|
94
|
+
optional + weight.optional > MAX_STRICT_OPTIONAL ||
|
|
95
|
+
unions + weight.unions > MAX_STRICT_UNIONS
|
|
96
|
+
) {
|
|
97
|
+
return rest;
|
|
98
|
+
}
|
|
99
|
+
strict += 1;
|
|
100
|
+
optional += weight.optional;
|
|
101
|
+
unions += weight.unions;
|
|
102
|
+
return tool;
|
|
103
|
+
});
|
|
104
|
+
}
|
package/src/budget.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// `node:async_hooks` to `{}`, and took every importer of `@ultimat3/ai` with it.
|
|
12
12
|
|
|
13
13
|
import type { Actor } from '@ultimat3/core';
|
|
14
|
-
import { assert, asyncContext, finiteCount } from '@ultimat3/core';
|
|
14
|
+
import { assert, asyncContext, finiteCount, logger } from '@ultimat3/core';
|
|
15
15
|
import type { Money } from '@ultimat3/money';
|
|
16
16
|
import { assertSameCurrency, commonScale, exponentOf, minorAt } from '@ultimat3/money';
|
|
17
17
|
import type { BudgetStore } from './budget-store';
|
|
@@ -281,7 +281,7 @@ export class BudgetLedger {
|
|
|
281
281
|
for (let l: BudgetLedger | undefined = this; l !== undefined; l = l.parent) {
|
|
282
282
|
l.costMicro += micro;
|
|
283
283
|
}
|
|
284
|
-
await this.debit(
|
|
284
|
+
await this.debit(countedTokens(usage, reservation) - (reservation?.tokens ?? 0));
|
|
285
285
|
}
|
|
286
286
|
|
|
287
287
|
/**
|
|
@@ -447,3 +447,20 @@ export function withBudget<T>(ledger: BudgetLedger, fn: () => Promise<T>): Promi
|
|
|
447
447
|
export function currentBudget(): BudgetLedger | undefined {
|
|
448
448
|
return storage.get();
|
|
449
449
|
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* What `usage` adds up to — or, when any counter is not a count, what was reserved. The built-in
|
|
453
|
+
* wires clamp their counters; an app-written `Provider` may answer a `NaN`, and one `NaN` debit made
|
|
454
|
+
* the actor's counter `NaN` for the life of the process: every later `reserve` threw, and the
|
|
455
|
+
* ledger's own ceiling compared false. Each counter is screened, not the sum: `-1000 + 1000` sums
|
|
456
|
+
* to a count and refunded the reservation. The estimate over-counts: the safe side of unknown.
|
|
457
|
+
*/
|
|
458
|
+
function countedTokens(usage: TokenUsage, reservation: BudgetReservation | undefined): number {
|
|
459
|
+
const total = totalTokens(usage);
|
|
460
|
+
const { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens } = usage;
|
|
461
|
+
const counters = [inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens];
|
|
462
|
+
if (counters.every((n) => Number.isFinite(n) && n >= 0)) return total;
|
|
463
|
+
const assumed = reservation?.tokens ?? 0;
|
|
464
|
+
logger.warn('ai.budget.usage_invalid', { received: String(total), assumed });
|
|
465
|
+
return assumed;
|
|
466
|
+
}
|
package/src/eval-baseline.ts
CHANGED
|
@@ -36,7 +36,11 @@ export const OVERALL = 'overall';
|
|
|
36
36
|
/** Set to re-record every baseline instead of gating on it: `ULTIMATE_EVAL_RECORD=1 x test eval`. */
|
|
37
37
|
export const RECORD_ENV = 'ULTIMATE_EVAL_RECORD';
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
/** The spellings of "off". A CI that sets the variable to `0` to be explicit is gating. */
|
|
40
|
+
const RECORD_OFF: ReadonlySet<string> = new Set(['', '0', 'false', 'no', 'off']);
|
|
41
|
+
|
|
42
|
+
export const recordingBaselines = (): boolean =>
|
|
43
|
+
!RECORD_OFF.has((Bun.env[RECORD_ENV] ?? '').trim().toLowerCase());
|
|
40
44
|
|
|
41
45
|
/**
|
|
42
46
|
* Where the baseline lives. Declarations write `import.meta.resolve('./x.baseline.json')`, which
|
package/src/eval-errors.ts
CHANGED
|
@@ -119,7 +119,7 @@ export class EvalRecordingError extends UltimateError {
|
|
|
119
119
|
super({
|
|
120
120
|
code: 'X_EVAL_RECORDING',
|
|
121
121
|
cause: `${input.env} is set, so every eval would re-record its baseline instead of gating on it`,
|
|
122
|
-
fix: `env -u ${input.env} x verify`,
|
|
122
|
+
fix: `env -u ${input.env} x verify --only eval`,
|
|
123
123
|
});
|
|
124
124
|
}
|
|
125
125
|
}
|
package/src/evals.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// Every result is filed against a prompt's content hash, so a score is always attributable
|
|
12
12
|
// to an exact prompt rather than "whatever was in main that day".
|
|
13
13
|
|
|
14
|
-
import { finiteCount } from '@ultimat3/core';
|
|
14
|
+
import { assert, finiteCount, finiteOption } from '@ultimat3/core';
|
|
15
15
|
import type { AgentEvalInput, CaseOutcome } from './eval-agent';
|
|
16
16
|
import { agentPrompt, runAgentCase } from './eval-agent';
|
|
17
17
|
import type { EvalBaseline, Regression } from './eval-baseline';
|
|
@@ -132,6 +132,14 @@ const registry = new Map<string, Eval>();
|
|
|
132
132
|
export function defineEval<V extends PromptVars>(input: PromptEvalInput<V>): Eval<V>;
|
|
133
133
|
export function defineEval<I>(input: AgentEvalInput<I>): Eval;
|
|
134
134
|
export function defineEval(input: DefineEvalInput): Eval {
|
|
135
|
+
// `drop > NaN` is false for every drop, so an unscreened `Number(env.X)` is a gate that cannot
|
|
136
|
+
// fail; below zero it fails a run that scored exactly its baseline.
|
|
137
|
+
const tolerance = finiteOption('defineEval', 'tolerance', input.tolerance);
|
|
138
|
+
assert(
|
|
139
|
+
tolerance >= 0,
|
|
140
|
+
`defineEval "${input.name}" tolerance is ${tolerance}, and a drop is never below zero: the gate would fail a run that scored exactly its baseline`,
|
|
141
|
+
'tolerance: 0 # the largest drop from the baseline the gate allows, 0 or more',
|
|
142
|
+
);
|
|
135
143
|
const prompt = 'prompt' in input ? input.prompt : agentPrompt(input.agent, input.name);
|
|
136
144
|
const evaluation: Eval = {
|
|
137
145
|
name: input.name,
|
|
@@ -144,7 +152,7 @@ export function defineEval(input: DefineEvalInput): Eval {
|
|
|
144
152
|
},
|
|
145
153
|
}
|
|
146
154
|
: {}),
|
|
147
|
-
tolerance
|
|
155
|
+
tolerance,
|
|
148
156
|
baseline: input.baseline,
|
|
149
157
|
run: (gateway) => runEval(input, prompt, gateway),
|
|
150
158
|
assert: (gateway) => assertEval(input, prompt, gateway),
|
package/src/gateway-settle.ts
CHANGED
|
@@ -73,6 +73,7 @@ export function promptCacheKey(request: GenerateRequest): string {
|
|
|
73
73
|
// Only when asked for: an absent knob must leave every key written before it existed as it was.
|
|
74
74
|
...(request.temperature === undefined ? {} : { temperature: request.temperature }),
|
|
75
75
|
...(request.seed === undefined ? {} : { seed: request.seed }),
|
|
76
|
+
...(request.toolChoice === undefined ? {} : { toolChoice: request.toolChoice }),
|
|
76
77
|
// A wire parameter changes the answer; absent leaves every older key as it was.
|
|
77
78
|
...(request.providerOptions === undefined ? {} : { providerOptions: request.providerOptions }),
|
|
78
79
|
});
|
package/src/llm.ts
CHANGED
|
@@ -380,7 +380,7 @@ function limitsOf(budget: LlmBudget | undefined): BudgetLimits {
|
|
|
380
380
|
/**
|
|
381
381
|
* What the model answered, as text the Messages API will accept — or nothing.
|
|
382
382
|
*
|
|
383
|
-
* `result.text` is the EMPTY STRING whenever the answer came through the `respond` tool, which
|
|
383
|
+
* `result.text` is the EMPTY STRING (or, from some models, bare whitespace) whenever the answer came through the `respond` tool, which
|
|
384
384
|
* is the dominant path: an empty text block is a 400 (`text content blocks must be non-empty`),
|
|
385
385
|
* so the repair turn came back as `X_AI_PROVIDER_UNAVAILABLE` and the caller never saw the
|
|
386
386
|
* `X_LLM_OUTPUT_INVALID` this loop exists to raise. The tool call's own arguments ARE the answer
|
|
@@ -389,7 +389,7 @@ function limitsOf(budget: LlmBudget | undefined): BudgetLimits {
|
|
|
389
389
|
* replaying it as text avoids the `tool_result` the API would then demand of the next message.
|
|
390
390
|
*/
|
|
391
391
|
function assistantEcho(result: GenerateResult): string | undefined {
|
|
392
|
-
if (result.text !== '') return result.text;
|
|
392
|
+
if (result.text.trim() !== '') return result.text;
|
|
393
393
|
const call = result.toolCalls.find((c) => c.name === RESPOND) ?? result.toolCalls[0];
|
|
394
394
|
if (call === undefined) return undefined;
|
|
395
395
|
const replayed = JSON.stringify(call.input);
|
package/src/openai-body.ts
CHANGED
|
@@ -59,7 +59,9 @@ export function chatCompletionBody(input: ChatCompletionBodyInput): Record<strin
|
|
|
59
59
|
if (request.tools !== undefined && request.tools.length > 0) {
|
|
60
60
|
body['tools'] = toOpenAiTools(request.tools);
|
|
61
61
|
// Forced unless the row says this model rejects a forced choice (`forcedToolChoice: false`).
|
|
62
|
-
|
|
62
|
+
// Nor when the request says prose is a legal answer (`toolChoice: 'auto'`, a summary call).
|
|
63
|
+
const unforced = spec.forcedToolChoice === false || request.toolChoice === 'auto';
|
|
64
|
+
const choice = unforced ? undefined : toolChoiceFor(request.tools);
|
|
63
65
|
if (choice !== undefined) body['tool_choice'] = choice;
|
|
64
66
|
}
|
|
65
67
|
if (request.stopSequences !== undefined && request.stopSequences.length > 0) {
|
package/src/openai-messages.ts
CHANGED
|
@@ -249,7 +249,8 @@ function mediaPart(block: AiMediaBlock, at: string, target: MediaTarget): OpenAi
|
|
|
249
249
|
* a promise the server checks: a schema with an optional field — one key in `properties` and not in
|
|
250
250
|
* `required` — is a 400 (`Invalid schema for function …`) rather than a looser check. So the flag
|
|
251
251
|
* is derived from the schema, never forwarded, and a schema that cannot keep the promise is sent
|
|
252
|
-
* without it and validated by the output schema on the way back
|
|
252
|
+
* without it and validated by the output schema on the way back. The Anthropic wire derives its
|
|
253
|
+
* own flag from its own, different subset (`anthropic-provider.ts`).
|
|
253
254
|
*/
|
|
254
255
|
export function toOpenAiTools(tools: readonly LlmTool[]): readonly OpenAiFunctionTool[] {
|
|
255
256
|
return tools.map((tool) => ({
|
|
@@ -265,11 +266,13 @@ export function toOpenAiTools(tools: readonly LlmTool[]): readonly OpenAiFunctio
|
|
|
265
266
|
|
|
266
267
|
/**
|
|
267
268
|
* Whether a schema keeps OpenAI's strict-mode promise: every object closed with
|
|
268
|
-
* `additionalProperties: false`, and every one of its keys listed in `required`. Recursive
|
|
269
|
-
* the server checks it
|
|
269
|
+
* `additionalProperties: false`, and every one of its keys listed in `required`. Recursive —
|
|
270
|
+
* through `properties`, `items` and every `anyOf` branch — because the server checks it so.
|
|
270
271
|
*/
|
|
271
272
|
export function satisfiesStrictMode(schema: JsonSchema): boolean {
|
|
272
273
|
if (schema.items !== undefined && !satisfiesStrictMode(schema.items)) return false;
|
|
274
|
+
// A nullable object is `anyOf: [object, null]`: the server checks every branch.
|
|
275
|
+
if (schema.anyOf !== undefined && !schema.anyOf.every(satisfiesStrictMode)) return false;
|
|
273
276
|
if (schema.type !== 'object' && schema.properties === undefined) return true;
|
|
274
277
|
if (schema.additionalProperties !== false) return false;
|
|
275
278
|
const properties = schema.properties ?? {};
|
package/src/pg-vector-sql.ts
CHANGED
|
@@ -162,9 +162,24 @@ from (
|
|
|
162
162
|
order by distance, "id" asc`;
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
+
/**
|
|
166
|
+
* The lexical query: ANY word of `query` matches, and `ts_rank_cd` orders — what the memory
|
|
167
|
+
* store's BM25 does. `websearch_to_tsquery` ANDs every word, so a whole question ("how do I reset
|
|
168
|
+
* my password after the billing migration") matched no chunk at all and hybrid fused the dense
|
|
169
|
+
* ranking alone. Each whitespace-separated word is its own `phraseto_tsquery` — an identifier the
|
|
170
|
+
* parser splits (`x_vector_drift`) still has to match as one — and the words are OR-ed. A word
|
|
171
|
+
* with no lexeme (a stop word, bare punctuation) is skipped; none at all is the empty query,
|
|
172
|
+
* which matches nothing. Nothing a caller typed is query syntax: `phraseto_tsquery` has none.
|
|
173
|
+
*/
|
|
174
|
+
function anyWordSql(target: PgVectorTable, query: string): SqlFragment {
|
|
175
|
+
return sql`(select coalesce(string_agg('(' || phraseto_tsquery(c.cfg, word)::text || ')', ' | '), '')::tsquery as q
|
|
176
|
+
from (select ${target.language}::regconfig as cfg) c, regexp_split_to_table(${query}, '[[:space:]]+') word
|
|
177
|
+
where length(to_tsvector(c.cfg, word)) > 0) terms`;
|
|
178
|
+
}
|
|
179
|
+
|
|
165
180
|
export function textSql(target: PgVectorTable, query: string, args: PgSearchArgs): SqlFragment {
|
|
166
181
|
return sql`select "id", "content", "metadata", ts_rank_cd("tsv", q) as score
|
|
167
|
-
from ${identifier(target.table)},
|
|
182
|
+
from ${identifier(target.table)}, ${anyWordSql(target, query)}
|
|
168
183
|
where "tsv" @@ q and ${conditionsSql(args.scope, args.filter)}
|
|
169
184
|
order by score desc, "id" asc
|
|
170
185
|
limit ${args.k}`;
|
|
@@ -177,8 +192,9 @@ export interface PgHybridArgs extends PgSearchArgs {
|
|
|
177
192
|
|
|
178
193
|
/**
|
|
179
194
|
* Reciprocal-rank fusion, done in SQL. Two candidate sets are ranked independently and fused by
|
|
180
|
-
* `1 / (rrfK + rank)` — identical to `fuse()` in `vector.ts
|
|
181
|
-
*
|
|
195
|
+
* `1 / (rrfK + rank)` — identical to `fuse()` in `vector.ts`. The lexical half matches on ANY
|
|
196
|
+
* word (`anyWordSql`), as the memory store's does; the two RANK by different formulas
|
|
197
|
+
* (`ts_rank_cd` here, BM25 there), so which chunks qualify agrees and their order may not. Both CTEs carry the SAME scope conditions: fusing an unfiltered lexical ranking
|
|
182
198
|
* into a filtered dense one would leak the other tenant's rows through the back door. A rank is a
|
|
183
199
|
* position, so each window breaks a tie by `"id"` as `vector.ts` does; the dense candidate scan
|
|
184
200
|
* keeps its bare `order by distance`, the shape HNSW answers.
|
|
@@ -204,7 +220,7 @@ export function hybridSql(
|
|
|
204
220
|
select "tenant", "id", row_number() over (order by relevance desc, "id" asc) as rank
|
|
205
221
|
from (
|
|
206
222
|
select "tenant", "id", ts_rank_cd("tsv", q) as relevance
|
|
207
|
-
from ${table},
|
|
223
|
+
from ${table}, ${anyWordSql(target, query)}
|
|
208
224
|
where "tsv" @@ q and ${where}
|
|
209
225
|
order by relevance desc, "id" asc
|
|
210
226
|
limit ${args.candidates}
|
package/src/provider.ts
CHANGED
|
@@ -82,6 +82,12 @@ export interface GenerateRequest {
|
|
|
82
82
|
readonly effort?: Effort;
|
|
83
83
|
readonly thinking?: ThinkingMode;
|
|
84
84
|
readonly tools?: readonly LlmTool[];
|
|
85
|
+
/**
|
|
86
|
+
* `'auto'`: the model may answer in prose even when exactly ONE tool is offered — the shape the
|
|
87
|
+
* chat-completions wire otherwise forces (`toolChoiceFor`). A compaction's summary call sets it:
|
|
88
|
+
* it keeps the run's tools for the cached prefix and wants text. Absent is each wire's default.
|
|
89
|
+
*/
|
|
90
|
+
readonly toolChoice?: 'auto';
|
|
85
91
|
readonly stopSequences?: readonly string[];
|
|
86
92
|
/** Sent only to a model whose row takes it (`ModelSpec.sampling`, `./sampling`). 0 to 2. */
|
|
87
93
|
readonly temperature?: number;
|
package/src/rag.ts
CHANGED
|
@@ -47,7 +47,10 @@ export function chunkDocument(input: ChunkInput): readonly Chunk[] {
|
|
|
47
47
|
const units = splitUnits(input.text, size);
|
|
48
48
|
const chunks: Chunk[] = [];
|
|
49
49
|
let buffer: string[] = [];
|
|
50
|
-
|
|
50
|
+
// Measured on the JOINED text, the string a chunk is: units are joined by a space, and forty
|
|
51
|
+
// one-token sentences summed to 8 are a ten-token chunk.
|
|
52
|
+
const over = (unit: string): boolean =>
|
|
53
|
+
buffer.length > 0 && estimateChunkTokens([...buffer, unit].join(' ')) > size;
|
|
51
54
|
|
|
52
55
|
const flush = (): void => {
|
|
53
56
|
if (buffer.length === 0) return;
|
|
@@ -75,19 +78,14 @@ export function chunkDocument(input: ChunkInput): readonly Chunk[] {
|
|
|
75
78
|
carriedTokens += estimateChunkTokens(unit);
|
|
76
79
|
}
|
|
77
80
|
buffer = carried;
|
|
78
|
-
tokens = carriedTokens;
|
|
79
81
|
};
|
|
80
82
|
|
|
81
83
|
for (const unit of units) {
|
|
82
|
-
|
|
83
|
-
if (tokens + unitTokens > size && buffer.length > 0) flush();
|
|
84
|
+
if (over(unit)) flush();
|
|
84
85
|
// The carried overlap yields to the unit, oldest first: a carry the unit does not fit beside
|
|
85
86
|
// made a chunk past `size` — the one promise this function makes.
|
|
86
|
-
while (buffer.
|
|
87
|
-
tokens -= estimateChunkTokens(buffer.shift() ?? '');
|
|
88
|
-
}
|
|
87
|
+
while (over(unit)) buffer.shift();
|
|
89
88
|
buffer.push(unit);
|
|
90
|
-
tokens += unitTokens;
|
|
91
89
|
}
|
|
92
90
|
flush();
|
|
93
91
|
// The final flush leaves the overlap tail in the buffer; it is already covered.
|
package/src/tools.ts
CHANGED
|
@@ -54,9 +54,9 @@ export interface LlmTool {
|
|
|
54
54
|
readonly description: string;
|
|
55
55
|
readonly input_schema: JsonSchema;
|
|
56
56
|
/**
|
|
57
|
-
* Strict mode guarantees the model's `input` validates against the schema exactly.
|
|
58
|
-
*
|
|
59
|
-
*
|
|
57
|
+
* Strict mode guarantees the model's `input` validates against the schema exactly. Every
|
|
58
|
+
* projection ASKS for it; each wire grants it only where its own documented subset and caps
|
|
59
|
+
* allow (`anthropic-provider.ts`, `toOpenAiTools`), because past them the flag is a 400.
|
|
60
60
|
*/
|
|
61
61
|
readonly strict?: boolean;
|
|
62
62
|
}
|
package/src/wire.ts
CHANGED
|
@@ -223,8 +223,8 @@ export class MessageStream {
|
|
|
223
223
|
toolCalls: [...this.toolCalls],
|
|
224
224
|
malformed: [...this.malformed],
|
|
225
225
|
// A refusal detail is a refusal whatever the stop reason says. `parseStopReason` answers
|
|
226
|
-
// `
|
|
227
|
-
// REASON, so the pair would read as a
|
|
226
|
+
// `max_tokens` for a spelling this build has never seen, and every consumer branches on the
|
|
227
|
+
// REASON, so the pair would read as a cut-off answer to continue rather than a refusal.
|
|
228
228
|
stopReason: this.stopDetails === undefined ? this.stopReason : 'refusal',
|
|
229
229
|
stopDetails: this.stopDetails,
|
|
230
230
|
usage: this.usage,
|