@bitbaum/ai-kit 1.2.0 → 1.4.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.
@@ -0,0 +1,52 @@
1
+ /**
2
+ * ai-kit/capability — what a model can do, observed rather than declared.
3
+ *
4
+ * Replaces the list every app writes and every app gets wrong:
5
+ *
6
+ * const TOOL_CAPABLE_PROVIDERS = ['groq', 'openrouter'];
7
+ *
8
+ * That line is wrong the moment a user brings a model nobody on the team has
9
+ * heard of, which is every day. It is also wrong in the other direction: it
10
+ * cannot express that five of nine free models answer tools only in prose, so
11
+ * a native-only client silently loses most of its chain while believing it is
12
+ * fine.
13
+ *
14
+ * The replacement is not a better list. It is three rules:
15
+ *
16
+ * 1. The first real call IS the probe. Send tools, read what comes back,
17
+ * write down what it proved. Every model a user brings classifies itself
18
+ * on its first message, at no extra cost and with no release from us.
19
+ * 2. A positive is cheap and a negative is expensive. One `tool_calls`
20
+ * proves capability. A 400 proves nothing unless the vendor SAYS it is
21
+ * about tools — otherwise a context-length overflow permanently cripples
22
+ * a capable model and nothing explains why.
23
+ * 3. "Never asked" is its own answer. Optimistic on the wire, because asking
24
+ * is how we learn; pessimistic in the prompt and the UI, because
25
+ * announcing an unproven capability is a promise the model may not keep.
26
+ *
27
+ * Storage stays with the app — a table, a KV, a file. This package owns the
28
+ * shape and the rules, which is the part everyone gets wrong; it does not own
29
+ * where rows live, which is the part where apps legitimately differ.
30
+ */
31
+ export type {
32
+ ToolVerdict,
33
+ CapabilityKind,
34
+ Provenance,
35
+ CapabilityRecord,
36
+ CapabilityStore,
37
+ Classification,
38
+ } from "./types.js";
39
+
40
+ export { classifyToolAttempt, saysToolsUnsupported, type ToolAttempt } from "./classify.js";
41
+
42
+ export {
43
+ planToolAttempt,
44
+ claimableVerdict,
45
+ currentVerdict,
46
+ isStale,
47
+ makeRecord,
48
+ scopeKey,
49
+ shouldReplace,
50
+ DEFAULT_TTL_MS,
51
+ type ToolPlan,
52
+ } from "./decide.js";
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What a model can actually do, as OBSERVED rather than as claimed.
3
+ *
4
+ * The problem this exists for: capability is not a property of a model name.
5
+ * It is a property of a model, on a provider, through a particular deployment,
6
+ * reached with a particular credential. A quantized local build drops tool
7
+ * support the upstream weights have. A proxy strips `tool_calls`. An org's key
8
+ * has vision disabled. A vendor updates a model in place behind an alias. None
9
+ * of that is knowable from a name, and every one of it is knowable by asking
10
+ * once.
11
+ *
12
+ * So this module holds no list of models. It holds the shape of an observation,
13
+ * the rules for turning a real call into one, and the decision of what to send
14
+ * next time. The list every app is tempted to write — "these providers support
15
+ * tools" — is the thing being replaced: it was wrong the day a user brought a
16
+ * model nobody had heard of, which is every day.
17
+ */
18
+
19
+ /**
20
+ * How a model answers a request carrying tool definitions.
21
+ *
22
+ * Four values, and the fourth is the one that matters. `unobserved` is not a
23
+ * synonym for `none`: it means nobody has ever asked, and a system that treats
24
+ * it as `none` silently disables tools for every model it has not met yet,
25
+ * while a system that treats it as `native` promises a capability it cannot
26
+ * demonstrate. It has to stay its own answer all the way to the user.
27
+ */
28
+ export type ToolVerdict = "native" | "text" | "none" | "unobserved";
29
+
30
+ /** What a single capability question is asked about. */
31
+ export type CapabilityKind = "tools" | "vision";
32
+
33
+ /** How we came to believe something, ordered weakest to strongest. */
34
+ export type Provenance =
35
+ /** The vendor's docs or a hand-maintained registry. A prior, never a fact. */
36
+ | "declared"
37
+ /** A deliberate probe request made to answer this question. */
38
+ | "probe"
39
+ /** Real traffic the user asked for, which answered it for free. */
40
+ | "live";
41
+
42
+ export type CapabilityRecord = {
43
+ provider: string;
44
+ model: string;
45
+ /**
46
+ * Which credential this was observed through — a HASH, never the key.
47
+ * Capability differs per key (an org with vision disabled, a proxy that
48
+ * strips tool calls), so an observation made with one credential is not
49
+ * evidence about another.
50
+ */
51
+ scope: string;
52
+ capability: CapabilityKind;
53
+ verdict: ToolVerdict;
54
+ /** ISO 8601. Used for staleness; models change under their own names. */
55
+ observedAt: string;
56
+ via: Provenance;
57
+ /** Short, human-readable reason. Goes in logs and in the UI. */
58
+ evidence?: string;
59
+ };
60
+
61
+ /**
62
+ * Storage is the app's problem — a table, a KV, a file. This package owns the
63
+ * shape and the rules, because those are what every app gets wrong; it does not
64
+ * own where the rows live, because that is the one part where apps legitimately
65
+ * differ.
66
+ */
67
+ export type CapabilityStore = {
68
+ get(key: {
69
+ provider: string;
70
+ model: string;
71
+ scope: string;
72
+ capability: CapabilityKind;
73
+ }): Promise<CapabilityRecord | null>;
74
+ put(record: CapabilityRecord): Promise<void>;
75
+ };
76
+
77
+ /** The outcome of reading one real response for what it says about capability. */
78
+ export type Classification = {
79
+ verdict: ToolVerdict;
80
+ /**
81
+ * Whether this is worth WRITING DOWN. A response can be uninformative —
82
+ * a 429, a 500, a timeout, a 400 about something other than tools — and
83
+ * recording those is how a model gets wrongly marked incapable forever.
84
+ */
85
+ record: boolean;
86
+ evidence: string;
87
+ };
package/src/complete.ts CHANGED
@@ -61,6 +61,7 @@ import { ChainExhaustedError, type ChainAttemptFailure } from "./attempt.js";
61
61
  import type { HealthTracker } from "./health.js";
62
62
  import { classifyRateLimit, retryAfterSeconds, type RateLimitKind } from "./limits.js";
63
63
  import { readQuota, readingFromRefusal, type QuotaReading } from "./meter.js";
64
+ import { parseTextToolCalls, stripToolCallLines, toolNamesFrom } from "./tool-protocol.js";
64
65
 
65
66
  /** One message in the OpenAI chat-completions shape every provider here speaks. */
66
67
  export interface ChatMessage {
@@ -76,9 +77,11 @@ export interface ChatMessage {
76
77
  * actually answer on.
77
78
  *
78
79
  * Both exist in the default chain: of nine free models probed live, four
79
- * answered with native `tool_calls` and five only in text. Callers get the
80
- * native shape here; parsing the text protocol is the caller's business,
81
- * because its convention differs per app.
80
+ * answered with native `tool_calls` and five only in text and three of the
81
+ * seven models shipped in the chain today are in that second group. Since 1.4.0
82
+ * both are read here, so a caller no longer has to know which half of the chain
83
+ * answered. See `toolProtocol` on CompleteOptions, and tool-protocol.ts for why
84
+ * a native-only read is a fabrication path rather than a missing feature.
82
85
  */
83
86
  export interface ToolCall {
84
87
  id: string;
@@ -145,6 +148,23 @@ export interface CompleteOptions {
145
148
  temperature?: number;
146
149
  /** Tool definitions in the OpenAI shape; passed through untouched. */
147
150
  tools?: unknown[];
151
+ /**
152
+ * Which tool-call protocols to READ from the reply. Default `"both"`.
153
+ *
154
+ * `"both"` also parses the `TOOL:` / `ARGS:` line protocol out of ordinary
155
+ * content and strips those lines from `text`. This matters more than it
156
+ * sounds: three of the seven models in the default chain cannot emit a native
157
+ * tool call at all, and a native-only read hands their narration back as a
158
+ * finished answer. The turn then reports a lookup that never happened.
159
+ *
160
+ * Parsing is skipped entirely when no `tools` are supplied — a model does not
161
+ * narrate a call it was never offered — so this is inert for the callers who
162
+ * do not use tools, which today is all of them.
163
+ *
164
+ * Set `"native"` only if you parse the text protocol yourself and would
165
+ * otherwise execute each call twice.
166
+ */
167
+ toolProtocol?: "both" | "native";
148
168
  /** Extra body fields for a vendor-specific parameter. Merged last, so it can override. */
149
169
  extraBody?: Record<string, unknown>;
150
170
  /**
@@ -432,11 +452,31 @@ async function callLink(
432
452
 
433
453
  const choice = (parsed as { choices?: Array<{ message?: Record<string, unknown> }> })
434
454
  ?.choices?.[0];
435
- const content = firstText(choice?.message);
436
- const toolCalls = toolCallsFrom(choice?.message);
455
+ const rawContent = firstText(choice?.message);
456
+ const native = toolCallsFrom(choice?.message);
457
+
458
+ // Read the line protocol out of the prose as well, unless the caller opted
459
+ // out or offered no tools. Native wins on a tie: a model that emits BOTH the
460
+ // real call and a prose echo of it must not run the tool twice — that wastes
461
+ // a round trip and can double-propose an action.
462
+ const wantsText = (options.toolProtocol ?? "both") === "both" && (options.tools?.length ?? 0) > 0;
463
+ const fromText = wantsText
464
+ ? parseTextToolCalls(rawContent, toolNamesFrom(options.tools)).filter((c) => {
465
+ const key = `${c.name}:${c.args}`;
466
+ return !native.some((n) => `${n.name}:${n.args}` === key);
467
+ })
468
+ : [];
469
+
470
+ const toolCalls = [...native, ...fromText];
471
+ // Strip the protocol lines only when they were actually read as calls.
472
+ // Removing them without parsing would delete the evidence and leave a shorter
473
+ // hallucination behind, which is worse than either extreme.
474
+ const content = fromText.length > 0 ? stripToolCallLines(rawContent) : rawContent;
437
475
 
438
476
  // A 200 that carries neither text nor a tool call is an outage wearing a
439
477
  // success code — see the header. Demote, so the chain gets its chance.
478
+ // Note the ordering: a reply that was ONLY a narrated call is now empty text
479
+ // WITH tool calls, which is a valid turn, not an outage.
440
480
  if (content.trim() === "" && toolCalls.length === 0) {
441
481
  throw new LinkFailure(
442
482
  link,
package/src/index.ts CHANGED
@@ -128,6 +128,15 @@ export {
128
128
  answersRemaining,
129
129
  } from "./meter.js";
130
130
 
131
+ export {
132
+ type ParsedToolCall,
133
+ TEXT_TOOL_PROTOCOL_HINT,
134
+ parseTextToolCalls,
135
+ stripToolCallLines,
136
+ safeJsonObject,
137
+ toolNamesFrom,
138
+ } from "./tool-protocol.js";
139
+
131
140
  export {
132
141
  type PoolId,
133
142
  type RungId,
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The other way models ask for a tool: by writing it in the reply.
3
+ *
4
+ * ── WHY A NATIVE-ONLY CLIENT LOSES MOST OF THIS PACKAGE'S OWN CHAIN ──────────
5
+ *
6
+ * `chain.ts` carries a probe table from nine free models called with a real
7
+ * tool. Four answered with native `tool_calls`. Five answered only in TEXT.
8
+ * Of the seven models in the shipped default chain today, three are in that
9
+ * second group:
10
+ *
11
+ * google/gemma-4-26b-a4b-it:free text
12
+ * cohere/north-mini-code:free text
13
+ * openrouter/free text
14
+ *
15
+ * A client that reads only `message.tool_calls` gets ZERO tool calls from those
16
+ * three — and, far worse, gets the model's narration of the call as ordinary
17
+ * content. So a turn that should have looked up a record instead returns a
18
+ * confident sentence describing the lookup it did not perform, and every layer
19
+ * downstream treats it as an answer. That is not a missing feature; it is a
20
+ * fabrication path, and it is open on nearly half the chain this package ships.
21
+ *
22
+ * ── WHY LINE-BASED AND NOT NESTED JSON ───────────────────────────────────────
23
+ *
24
+ * The format is chosen for the WEAKEST model expected to run it, not the
25
+ * strongest. An 8B model reliably reproduces two flat lines:
26
+ *
27
+ * TOOL: search_people
28
+ * ARGS: {"query": "Elena"}
29
+ *
30
+ * The same model routinely breaks nested-JSON escaping. Every leniency in the
31
+ * parser below is a shape a small model actually emitted in production — bolded
32
+ * keys because it was writing markdown, a fenced ARGS block, the parentheses
33
+ * copied from the example, a missing ARGS line for a no-argument tool. Rejecting
34
+ * any of them would fail the turn over formatting, which is the exact failure
35
+ * this protocol exists to avoid.
36
+ */
37
+
38
+ /** The tool-call shape, matching `complete`'s. `args` stays a raw JSON string. */
39
+ export interface ParsedToolCall {
40
+ id: string;
41
+ name: string;
42
+ args: string;
43
+ }
44
+
45
+ /**
46
+ * The convention, as prompt text.
47
+ *
48
+ * Exported so apps stop writing their own wording and drifting from the parser
49
+ * that has to read it back. A prompt and its parser are one contract; keeping
50
+ * them in separate repos is how they diverge.
51
+ *
52
+ * Note what it does NOT say: it never tells the model to use this INSTEAD of
53
+ * native calling. A model with native support should use it, and this is the
54
+ * fallback for one that cannot — offering both costs a few tokens and covers
55
+ * both halves of the chain.
56
+ */
57
+ export const TEXT_TOOL_PROTOCOL_HINT = [
58
+ "If you cannot emit a native tool call, call a tool by writing these two lines in your reply, exactly like this:",
59
+ "",
60
+ "TOOL: tool_name",
61
+ 'ARGS: {"argument": "value"}',
62
+ "",
63
+ "Write nothing else in a reply that calls tools — you will be given the results and asked again.",
64
+ ].join("\n");
65
+
66
+ /** Matches a TOOL: line, tolerating list bullets, markdown bold, and `=`. */
67
+ const TOOL_LINE = /^\s*(?:[-*>]\s*)?(?:\*\*)?TOOL(?:\*\*)?\s*[:=]\s*(.+?)\s*$/i;
68
+ /** Matches an ARGS: line, same tolerances. */
69
+ const ARGS_LINE = /^\s*(?:[-*>]\s*)?(?:\*\*)?ARGS(?:\*\*)?\s*[:=]\s*(.*)$/i;
70
+ /** Either key, for the strip pass. */
71
+ const EITHER_LINE = /^\s*(?:[-*>]\s*)?(?:\*\*)?(?:TOOL|ARGS)(?:\*\*)?\s*[:=]/i;
72
+
73
+ /** How far past a TOOL: line to look for its ARGS:, and how far to join a multi-line object. */
74
+ const ARGS_SEARCH_LINES = 4;
75
+ const ARGS_JOIN_LINES = 8;
76
+
77
+ /**
78
+ * Parse a JSON object, tolerating fences and trailing prose. Null if hopeless.
79
+ *
80
+ * `null` and `{}` must stay distinguishable. Returning `{}` for "nothing
81
+ * parseable here" satisfies a caller's `?? {}` fallback and silently discards
82
+ * arguments the model put on the NEXT line — which is exactly what a model does
83
+ * when it opens a ```json fence after `ARGS:`. That cost a debugging cycle once
84
+ * already; it is a test here now.
85
+ */
86
+ export function safeJsonObject(raw: string): Record<string, unknown> | null {
87
+ const cleaned = raw
88
+ .trim()
89
+ .replace(/^```(?:json)?/i, "")
90
+ .replace(/```$/, "")
91
+ .trim();
92
+ if (!cleaned) return null;
93
+ if (cleaned === "{}") return {};
94
+
95
+ const start = cleaned.indexOf("{");
96
+ if (start === -1) return null;
97
+
98
+ // Walk to the matching brace so trailing commentary does not break the parse.
99
+ // String-aware: a brace inside a quoted value must not change the depth, or
100
+ // an argument like {"q": "a } b"} truncates at the wrong place.
101
+ let depth = 0;
102
+ let inString = false;
103
+ let escaped = false;
104
+ for (let i = start; i < cleaned.length; i++) {
105
+ const ch = cleaned[i];
106
+ if (escaped) {
107
+ escaped = false;
108
+ continue;
109
+ }
110
+ if (ch === "\\") {
111
+ escaped = true;
112
+ continue;
113
+ }
114
+ if (ch === '"') {
115
+ inString = !inString;
116
+ continue;
117
+ }
118
+ if (inString) continue;
119
+ if (ch === "{") depth++;
120
+ else if (ch === "}") {
121
+ depth--;
122
+ if (depth === 0) {
123
+ try {
124
+ const parsed: unknown = JSON.parse(cleaned.slice(start, i + 1));
125
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
126
+ ? (parsed as Record<string, unknown>)
127
+ : null;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * Extract text-protocol calls from a reply.
139
+ *
140
+ * `validNames` is the closed set the model was offered. A line naming anything
141
+ * else is left alone: without that check, a model writing the words "TOOL:
142
+ * whatever" in prose would manufacture a call to a tool that does not exist,
143
+ * and the executor would report a failure the model never asked for.
144
+ */
145
+ export function parseTextToolCalls(text: string, validNames: string[]): ParsedToolCall[] {
146
+ if (!text || validNames.length === 0) return [];
147
+ const calls: ParsedToolCall[] = [];
148
+ const valid = new Set(validNames);
149
+ const lines = text.split(/\r?\n/);
150
+
151
+ for (let i = 0; i < lines.length; i++) {
152
+ const line = lines[i] ?? "";
153
+ const m = TOOL_LINE.exec(line);
154
+ const rawName = m?.[1];
155
+ if (!rawName) continue;
156
+
157
+ // Tolerate `name(...)`, backticks, and trailing punctuation copied from prose.
158
+ const name = rawName
159
+ .replace(/[`*]/g, "")
160
+ .replace(/\(.*$/, "")
161
+ .replace(/[.,;]$/, "")
162
+ .trim();
163
+ if (!valid.has(name)) continue;
164
+
165
+ let args = "{}";
166
+ for (let j = i + 1; j < Math.min(i + ARGS_SEARCH_LINES, lines.length); j++) {
167
+ const next = lines[j] ?? "";
168
+ const a = ARGS_LINE.exec(next);
169
+ if (a) {
170
+ // The object may continue past this line: a model opening a ```json
171
+ // fence puts the brace on the NEXT line, and a pretty-printed object
172
+ // spans several. Join forward and let the brace matcher find the end.
173
+ const rest = lines.slice(j, Math.min(j + ARGS_JOIN_LINES, lines.length)).join("\n");
174
+ const parsed =
175
+ safeJsonObject(a[1] ?? "") ?? safeJsonObject(rest.replace(/^[^:=]*[:=]/, ""));
176
+ if (parsed) args = JSON.stringify(parsed);
177
+ break;
178
+ }
179
+ // A new TOOL line means this call simply had no arguments.
180
+ if (TOOL_LINE.test(next)) break;
181
+ }
182
+
183
+ calls.push({ id: `text_${calls.length}_${name}`, name, args });
184
+ }
185
+ return calls;
186
+ }
187
+
188
+ /**
189
+ * Remove protocol lines from prose.
190
+ *
191
+ * A narrated call must never reach the user as though it were an answer, which
192
+ * is the whole failure this module exists to close. Stripping also means a reply
193
+ * that was ONLY a tool call ends up empty — and an empty reply carrying tool
194
+ * calls is a valid turn, while an empty reply carrying none is an outage. The
195
+ * caller has to keep those apart.
196
+ */
197
+ export function stripToolCallLines(text: string): string {
198
+ return text
199
+ .split(/\r?\n/)
200
+ .filter((l) => !EITHER_LINE.test(l))
201
+ .join("\n")
202
+ .replace(/```(?:json)?\s*```/g, "")
203
+ .replace(/\n{3,}/g, "\n\n")
204
+ .trim();
205
+ }
206
+
207
+ /**
208
+ * The tool names inside an OpenAI-shaped `tools` array.
209
+ *
210
+ * Derived from what the caller already passed rather than asked for separately:
211
+ * two lists that must agree are one list that cannot disagree, and the failure
212
+ * of the split version is silent — a name missing from the second list makes
213
+ * the parser ignore a real call.
214
+ */
215
+ export function toolNamesFrom(tools: unknown[] | undefined): string[] {
216
+ if (!Array.isArray(tools)) return [];
217
+ const names: string[] = [];
218
+ for (const entry of tools) {
219
+ const fn = (entry as { function?: { name?: unknown } } | null)?.function;
220
+ if (fn && typeof fn.name === "string" && fn.name) names.push(fn.name);
221
+ }
222
+ return names;
223
+ }