@c9up/polaris 0.1.0 → 0.1.1
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 +614 -10
- package/dist/Polaris.d.ts +6 -2
- package/dist/Polaris.d.ts.map +1 -1
- package/dist/Polaris.js +14 -0
- package/dist/Polaris.js.map +1 -1
- package/dist/PolarisClient.d.ts +51 -3
- package/dist/PolarisClient.d.ts.map +1 -1
- package/dist/PolarisClient.js +213 -45
- package/dist/PolarisClient.js.map +1 -1
- package/dist/PolarisProvider.d.ts +7 -2
- package/dist/PolarisProvider.d.ts.map +1 -1
- package/dist/PolarisProvider.js +34 -2
- package/dist/PolarisProvider.js.map +1 -1
- package/dist/augmentations.d.ts +4 -1
- package/dist/augmentations.d.ts.map +1 -1
- package/dist/augmentations.js +1 -1
- package/dist/budget.d.ts +39 -6
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +79 -12
- package/dist/budget.js.map +1 -1
- package/dist/catalog/catalog.d.ts +37 -0
- package/dist/catalog/catalog.d.ts.map +1 -0
- package/dist/catalog/catalog.js +145 -0
- package/dist/catalog/catalog.js.map +1 -0
- package/dist/catalog/discover.d.ts +64 -0
- package/dist/catalog/discover.d.ts.map +1 -0
- package/dist/catalog/discover.js +148 -0
- package/dist/catalog/discover.js.map +1 -0
- package/dist/catalog/index.d.ts +8 -0
- package/dist/catalog/index.d.ts.map +1 -0
- package/dist/catalog/index.js +8 -0
- package/dist/catalog/index.js.map +1 -0
- package/dist/commands/index.d.ts +82 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +278 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/cost.d.ts +3 -1
- package/dist/cost.d.ts.map +1 -1
- package/dist/cost.js +8 -3
- package/dist/cost.js.map +1 -1
- package/dist/drivers/anthropic.d.ts +6 -1
- package/dist/drivers/anthropic.d.ts.map +1 -1
- package/dist/drivers/anthropic.js +166 -21
- package/dist/drivers/anthropic.js.map +1 -1
- package/dist/drivers/openai-compatible.d.ts +1 -1
- package/dist/drivers/openai-compatible.d.ts.map +1 -1
- package/dist/drivers/openai-compatible.js +106 -70
- package/dist/drivers/openai-compatible.js.map +1 -1
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/json-schema.d.ts +33 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +508 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +3 -1
- package/dist/log.js.map +1 -1
- package/dist/mcp/client.d.ts +81 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +401 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/endpoint.d.ts +54 -0
- package/dist/mcp/endpoint.d.ts.map +1 -0
- package/dist/mcp/endpoint.js +158 -0
- package/dist/mcp/endpoint.js.map +1 -0
- package/dist/mcp/host.d.ts +42 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +111 -0
- package/dist/mcp/host.js.map +1 -0
- package/dist/mcp/http.d.ts +32 -0
- package/dist/mcp/http.d.ts.map +1 -0
- package/dist/mcp/http.js +190 -0
- package/dist/mcp/http.js.map +1 -0
- package/dist/mcp/index.d.ts +23 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +21 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manifest.d.ts +36 -0
- package/dist/mcp/manifest.d.ts.map +1 -0
- package/dist/mcp/manifest.js +40 -0
- package/dist/mcp/manifest.js.map +1 -0
- package/dist/mcp/rpc.d.ts +39 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +149 -0
- package/dist/mcp/rpc.js.map +1 -0
- package/dist/mcp/stdio.d.ts +24 -0
- package/dist/mcp/stdio.d.ts.map +1 -0
- package/dist/mcp/stdio.js +157 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/worker-main.d.ts +6 -0
- package/dist/mcp/worker-main.d.ts.map +1 -0
- package/dist/mcp/worker-main.js +17 -0
- package/dist/mcp/worker-main.js.map +1 -0
- package/dist/mcp/worker.d.ts +54 -0
- package/dist/mcp/worker.d.ts.map +1 -0
- package/dist/mcp/worker.js +166 -0
- package/dist/mcp/worker.js.map +1 -0
- package/dist/meter.d.ts +6 -0
- package/dist/meter.d.ts.map +1 -1
- package/dist/meter.js +6 -3
- package/dist/meter.js.map +1 -1
- package/dist/redact.d.ts +4 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +5 -4
- package/dist/redact.js.map +1 -1
- package/dist/redis-budget.d.ts +45 -0
- package/dist/redis-budget.d.ts.map +1 -0
- package/dist/redis-budget.js +56 -0
- package/dist/redis-budget.js.map +1 -0
- package/dist/response.d.ts +21 -3
- package/dist/response.d.ts.map +1 -1
- package/dist/response.js +71 -7
- package/dist/response.js.map +1 -1
- package/dist/server-sent.d.ts +9 -0
- package/dist/server-sent.d.ts.map +1 -0
- package/dist/server-sent.js +74 -0
- package/dist/server-sent.js.map +1 -0
- package/dist/server-tools.d.ts +12 -0
- package/dist/server-tools.d.ts.map +1 -0
- package/dist/server-tools.js +71 -0
- package/dist/server-tools.js.map +1 -0
- package/dist/services/catalog.d.ts +19 -0
- package/dist/services/catalog.d.ts.map +1 -0
- package/dist/services/catalog.js +37 -0
- package/dist/services/catalog.js.map +1 -0
- package/dist/skills/folder.d.ts +32 -0
- package/dist/skills/folder.d.ts.map +1 -0
- package/dist/skills/folder.js +170 -0
- package/dist/skills/folder.js.map +1 -0
- package/dist/skills/frontmatter.d.ts +15 -0
- package/dist/skills/frontmatter.d.ts.map +1 -0
- package/dist/skills/frontmatter.js +92 -0
- package/dist/skills/frontmatter.js.map +1 -0
- package/dist/skills/index.d.ts +18 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +18 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/skills/kit.d.ts +39 -0
- package/dist/skills/kit.d.ts.map +1 -0
- package/dist/skills/kit.js +124 -0
- package/dist/skills/kit.js.map +1 -0
- package/dist/skills/skill.d.ts +67 -0
- package/dist/skills/skill.d.ts.map +1 -0
- package/dist/skills/skill.js +114 -0
- package/dist/skills/skill.js.map +1 -0
- package/dist/sse.d.ts +43 -6
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +44 -18
- package/dist/sse.js.map +1 -1
- package/dist/testing/FakeProvider.d.ts.map +1 -1
- package/dist/testing/FakeProvider.js +1 -0
- package/dist/testing/FakeProvider.js.map +1 -1
- package/dist/tool-modules.d.ts +17 -0
- package/dist/tool-modules.d.ts.map +1 -0
- package/dist/tool-modules.js +43 -0
- package/dist/tool-modules.js.map +1 -0
- package/dist/tools.d.ts +69 -5
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +174 -31
- package/dist/tools.js.map +1 -1
- package/dist/transport.d.ts +8 -3
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +19 -4
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +106 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +22 -1
- package/src/Polaris.ts +25 -1
- package/src/PolarisClient.ts +288 -51
- package/src/PolarisProvider.ts +40 -2
- package/src/augmentations.ts +4 -1
- package/src/budget.ts +115 -15
- package/src/catalog/catalog.ts +180 -0
- package/src/catalog/discover.ts +234 -0
- package/src/catalog/index.ts +19 -0
- package/src/commands/index.ts +412 -0
- package/src/cost.ts +9 -3
- package/src/drivers/anthropic.ts +203 -20
- package/src/drivers/openai-compatible.ts +143 -76
- package/src/errors.ts +41 -0
- package/src/index.ts +16 -0
- package/src/json-schema.ts +597 -0
- package/src/log.ts +3 -1
- package/src/mcp/client.ts +532 -0
- package/src/mcp/endpoint.ts +229 -0
- package/src/mcp/host.ts +140 -0
- package/src/mcp/http.ts +276 -0
- package/src/mcp/index.ts +51 -0
- package/src/mcp/manifest.ts +73 -0
- package/src/mcp/rpc.ts +197 -0
- package/src/mcp/stdio.ts +190 -0
- package/src/mcp/worker-main.ts +18 -0
- package/src/mcp/worker.ts +212 -0
- package/src/meter.ts +13 -2
- package/src/redact.ts +6 -3
- package/src/redis-budget.ts +85 -0
- package/src/response.ts +86 -8
- package/src/server-sent.ts +70 -0
- package/src/server-tools.ts +77 -0
- package/src/services/catalog.ts +43 -0
- package/src/skills/folder.ts +231 -0
- package/src/skills/frontmatter.ts +92 -0
- package/src/skills/index.ts +38 -0
- package/src/skills/kit.ts +163 -0
- package/src/skills/skill.ts +171 -0
- package/src/sse.ts +88 -22
- package/src/testing/FakeProvider.ts +1 -0
- package/src/tool-modules.ts +49 -0
- package/src/tools.ts +260 -27
- package/src/transport.ts +25 -3
- package/src/types.ts +108 -2
package/src/sse.ts
CHANGED
|
@@ -10,7 +10,13 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { codeOf } from "./log.js";
|
|
13
|
-
import type {
|
|
13
|
+
import type { RunEvent, RunResult } from "./PolarisClient.js";
|
|
14
|
+
import type {
|
|
15
|
+
ChatResponse,
|
|
16
|
+
StreamEvent,
|
|
17
|
+
ToolCallPart,
|
|
18
|
+
Usage,
|
|
19
|
+
} from "./types.js";
|
|
14
20
|
|
|
15
21
|
/**
|
|
16
22
|
* What polaris needs of an SSE stream: ream's `SseStream` fits as it is, and
|
|
@@ -28,6 +34,15 @@ export interface SseSink {
|
|
|
28
34
|
/** How a streamed reply ended. */
|
|
29
35
|
export type StreamToResult =
|
|
30
36
|
| { readonly status: "done"; readonly response: ChatResponse }
|
|
37
|
+
| SseFailure;
|
|
38
|
+
|
|
39
|
+
/** How a streamed tool run ended. */
|
|
40
|
+
export type StreamRunToResult =
|
|
41
|
+
| { readonly status: "done"; readonly result: RunResult }
|
|
42
|
+
| SseFailure;
|
|
43
|
+
|
|
44
|
+
/** The ways a stream to the browser ends without its last event. */
|
|
45
|
+
export type SseFailure =
|
|
31
46
|
/** The client went away; the provider request was cancelled. */
|
|
32
47
|
| { readonly status: "client_left" }
|
|
33
48
|
/** The call failed; the client was sent an `error` event with its code. */
|
|
@@ -43,6 +58,21 @@ export interface DoneEventData {
|
|
|
43
58
|
readonly usage: Usage;
|
|
44
59
|
}
|
|
45
60
|
|
|
61
|
+
/** The `done` event's data at the end of a run: its last reply, with the run's steps and tokens. */
|
|
62
|
+
export interface RunDoneEventData extends DoneEventData {
|
|
63
|
+
readonly steps: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The `tool_result` event's data. The result itself stays on the server: it
|
|
68
|
+
* is the application's data, read by the model, not meant for the page.
|
|
69
|
+
*/
|
|
70
|
+
export interface ToolResultEventData {
|
|
71
|
+
readonly id: string;
|
|
72
|
+
readonly name: string;
|
|
73
|
+
readonly isError: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
46
76
|
/** Why polaris cancelled the provider request: the client closed the stream. */
|
|
47
77
|
export class ClientLeft extends Error {
|
|
48
78
|
constructor() {
|
|
@@ -52,28 +82,31 @@ export class ClientLeft extends Error {
|
|
|
52
82
|
}
|
|
53
83
|
|
|
54
84
|
/**
|
|
55
|
-
* Forward `events` to `sink` as named
|
|
56
|
-
* `tool_call`, `done
|
|
57
|
-
*
|
|
85
|
+
* Forward `events` to `sink` as events named by their type after `prefix`
|
|
86
|
+
* (`text`, `tool_call`, `done`…, and `error` on a failure), and end the stream
|
|
87
|
+
* after the last one. `leave` is aborted when the client closes the stream.
|
|
88
|
+
* `encode` gives an event's data, and the result when it is the last one.
|
|
58
89
|
* Never rejects: every outcome is in the result.
|
|
59
90
|
*/
|
|
60
|
-
export async function pipeToSse(
|
|
61
|
-
events: AsyncIterable<
|
|
91
|
+
export async function pipeToSse<E extends { readonly type: string }, R>(
|
|
92
|
+
events: AsyncIterable<E>,
|
|
62
93
|
sink: SseSink,
|
|
63
94
|
leave: AbortController,
|
|
64
95
|
prefix: string,
|
|
65
|
-
):
|
|
96
|
+
encode: (event: E) => { readonly data: unknown; readonly last?: R },
|
|
97
|
+
): Promise<R | SseFailure> {
|
|
66
98
|
try {
|
|
67
99
|
for await (const event of events) {
|
|
68
100
|
if (leave.signal.aborted) break;
|
|
69
|
-
const
|
|
101
|
+
const { data, last } = encode(event);
|
|
102
|
+
const sent = await sink.send(`${prefix}${event.type}`, data);
|
|
70
103
|
if (!sent) {
|
|
71
104
|
leave.abort(new ClientLeft());
|
|
72
105
|
break;
|
|
73
106
|
}
|
|
74
|
-
if (
|
|
107
|
+
if (last !== undefined) {
|
|
75
108
|
await settle(() => sink.end());
|
|
76
|
-
return
|
|
109
|
+
return last;
|
|
77
110
|
}
|
|
78
111
|
}
|
|
79
112
|
// Leaving the loop early cancels the provider request.
|
|
@@ -101,28 +134,61 @@ async function settle(step: () => unknown): Promise<void> {
|
|
|
101
134
|
}
|
|
102
135
|
}
|
|
103
136
|
|
|
104
|
-
|
|
137
|
+
/** A streamed reply's event, as `streamTo()` sends it. */
|
|
138
|
+
export function encodeStreamEvent(event: StreamEvent): {
|
|
139
|
+
readonly data: unknown;
|
|
140
|
+
readonly last?: StreamToResult;
|
|
141
|
+
} {
|
|
105
142
|
switch (event.type) {
|
|
106
143
|
case "text":
|
|
107
144
|
case "reasoning":
|
|
108
|
-
return { text: event.text };
|
|
145
|
+
return { data: { text: event.text } };
|
|
109
146
|
case "tool_call":
|
|
147
|
+
return { data: toolCallData(event.call) };
|
|
148
|
+
case "done":
|
|
110
149
|
return {
|
|
150
|
+
data: doneData(event.response),
|
|
151
|
+
last: { status: "done", response: event.response },
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A streamed run's event, as `streamRunTo()` sends it. */
|
|
157
|
+
export function encodeRunEvent(event: RunEvent): {
|
|
158
|
+
readonly data: unknown;
|
|
159
|
+
readonly last?: StreamRunToResult;
|
|
160
|
+
} {
|
|
161
|
+
switch (event.type) {
|
|
162
|
+
case "text":
|
|
163
|
+
case "reasoning":
|
|
164
|
+
return { data: { text: event.text } };
|
|
165
|
+
case "tool_call":
|
|
166
|
+
return { data: toolCallData(event.call) };
|
|
167
|
+
case "tool_result": {
|
|
168
|
+
const data: ToolResultEventData = {
|
|
111
169
|
id: event.call.id,
|
|
112
170
|
name: event.call.name,
|
|
113
|
-
|
|
171
|
+
isError: event.result.isError === true,
|
|
114
172
|
};
|
|
173
|
+
return { data };
|
|
174
|
+
}
|
|
115
175
|
case "done": {
|
|
116
|
-
const {
|
|
117
|
-
const data:
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
text,
|
|
122
|
-
stopReason,
|
|
123
|
-
usage,
|
|
176
|
+
const { result } = event;
|
|
177
|
+
const data: RunDoneEventData = {
|
|
178
|
+
...doneData(result.response),
|
|
179
|
+
usage: result.usage,
|
|
180
|
+
steps: result.steps,
|
|
124
181
|
};
|
|
125
|
-
return data;
|
|
182
|
+
return { data, last: { status: "done", result } };
|
|
126
183
|
}
|
|
127
184
|
}
|
|
128
185
|
}
|
|
186
|
+
|
|
187
|
+
function toolCallData(call: ToolCallPart): unknown {
|
|
188
|
+
return { id: call.id, name: call.name, input: call.input };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function doneData(response: ChatResponse): DoneEventData {
|
|
192
|
+
const { id, provider, model, text, stopReason, usage } = response;
|
|
193
|
+
return { id, provider, model, text, stopReason, usage };
|
|
194
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool modules: the files a skill's `tools/` folder and the application's
|
|
3
|
+
* tool folders hold. Each exports a tool, a list of tools, or a function
|
|
4
|
+
* (sync or async) returning one, as `default` or `tools`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { extname } from "node:path";
|
|
8
|
+
import { isTool, type PolarisTool } from "./tools.js";
|
|
9
|
+
|
|
10
|
+
const EXTENSIONS = new Set([".js", ".mjs", ".ts", ".mts"]);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Is `file` (a base name) a tool module? A file whose name starts with `_` or
|
|
14
|
+
* `.`, a declaration file and a test are not: shared code goes in `_x.ts`.
|
|
15
|
+
*/
|
|
16
|
+
export function isToolModuleFile(file: string): boolean {
|
|
17
|
+
return (
|
|
18
|
+
EXTENSIONS.has(extname(file)) &&
|
|
19
|
+
!/^[._]/.test(file) &&
|
|
20
|
+
!/\.d\.[mc]?ts$|\.(test|spec)\.[mc]?[jt]s$/.test(file)
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The tools a module exports, or why it has none: `failed to load: ...` or
|
|
26
|
+
* `must export a tool...`. A function that is not itself a tool is called.
|
|
27
|
+
*/
|
|
28
|
+
export async function importToolModule(
|
|
29
|
+
url: string,
|
|
30
|
+
): Promise<PolarisTool[] | string> {
|
|
31
|
+
let exported: unknown;
|
|
32
|
+
try {
|
|
33
|
+
const module: unknown = await import(url);
|
|
34
|
+
exported =
|
|
35
|
+
typeof module === "object" && module !== null
|
|
36
|
+
? (Reflect.get(module, "default") ?? Reflect.get(module, "tools"))
|
|
37
|
+
: undefined;
|
|
38
|
+
if (typeof exported === "function" && !isTool(exported)) {
|
|
39
|
+
exported = await exported();
|
|
40
|
+
}
|
|
41
|
+
} catch (error) {
|
|
42
|
+
return `failed to load: ${error instanceof Error ? error.message : String(error)}`;
|
|
43
|
+
}
|
|
44
|
+
const list: unknown[] = Array.isArray(exported) ? exported : [exported];
|
|
45
|
+
if (list.length === 0 || !list.every(isTool)) {
|
|
46
|
+
return "must export a tool, a list of tools, or a function returning one, as `default` or `tools`";
|
|
47
|
+
}
|
|
48
|
+
return list;
|
|
49
|
+
}
|
package/src/tools.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Tools the model may call, and the loop that runs them.
|
|
3
3
|
*
|
|
4
|
-
* A tool's input is described by a {@link StandardSchema}
|
|
5
|
-
*
|
|
4
|
+
* A tool's input is described by a {@link StandardSchema} (a rune schema,
|
|
5
|
+
* `rune.create({...})`, is one), or by a plain JSON Schema (`inputSchema`).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import {
|
|
9
9
|
E_POLARIS_INVALID_REQUEST,
|
|
10
10
|
E_POLARIS_TOO_MANY_STEPS,
|
|
11
|
+
E_POLARIS_TOO_MANY_TOOL_CALLS,
|
|
11
12
|
} from "./errors.js";
|
|
13
|
+
import { jsonSchema } from "./json-schema.js";
|
|
12
14
|
import {
|
|
13
15
|
describeIssues,
|
|
14
16
|
objectJsonSchema,
|
|
@@ -16,7 +18,12 @@ import {
|
|
|
16
18
|
type SchemaResult,
|
|
17
19
|
type StandardSchema,
|
|
18
20
|
} from "./schema.js";
|
|
19
|
-
import type {
|
|
21
|
+
import type {
|
|
22
|
+
JsonSchema,
|
|
23
|
+
ToolCallPart,
|
|
24
|
+
ToolDefinition,
|
|
25
|
+
ToolResultPart,
|
|
26
|
+
} from "./types.js";
|
|
20
27
|
|
|
21
28
|
/** What a tool's handler is given besides its input. */
|
|
22
29
|
export interface ToolContext {
|
|
@@ -24,6 +31,23 @@ export interface ToolContext {
|
|
|
24
31
|
readonly toolCallId: string;
|
|
25
32
|
/** Aborted when the run is cancelled or runs out of time. */
|
|
26
33
|
readonly signal: AbortSignal;
|
|
34
|
+
/**
|
|
35
|
+
* Add tools to the run: the model can call them from the run's next
|
|
36
|
+
* request. A tool already in the run is left as it is; one of the run's
|
|
37
|
+
* `inactiveTools` becomes callable. Another tool under a name the run
|
|
38
|
+
* already has, or more than {@link MAX_RUN_TOOLS} tools in all, is refused
|
|
39
|
+
* with a {@link ToolError}, which the model reads. Outside a run (a tool
|
|
40
|
+
* executed by hand), it throws that error too.
|
|
41
|
+
*/
|
|
42
|
+
addTools(tools: readonly PolarisTool[]): void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What `execute` is given: a run passes `addTools`, a caller may leave it out. */
|
|
46
|
+
export type ExecuteContext = Omit<ToolContext, "addTools"> &
|
|
47
|
+
Partial<Pick<ToolContext, "addTools">>;
|
|
48
|
+
|
|
49
|
+
function outsideRun(): never {
|
|
50
|
+
throw new ToolError("Tools can only be added during a run.");
|
|
27
51
|
}
|
|
28
52
|
|
|
29
53
|
/**
|
|
@@ -45,7 +69,7 @@ export interface PolarisTool {
|
|
|
45
69
|
/** What is sent to the model. */
|
|
46
70
|
readonly definition: ToolDefinition;
|
|
47
71
|
/** Validate the model's input, then run the handler. Never throws. */
|
|
48
|
-
execute(call: ToolCallPart, context:
|
|
72
|
+
execute(call: ToolCallPart, context: ExecuteContext): Promise<ToolOutcome>;
|
|
49
73
|
}
|
|
50
74
|
|
|
51
75
|
/** How one tool call went. */
|
|
@@ -69,7 +93,22 @@ export interface ToolSpec<S extends StandardSchema> {
|
|
|
69
93
|
run(input: SchemaOutput<S>, context: ToolContext): unknown;
|
|
70
94
|
}
|
|
71
95
|
|
|
96
|
+
/**
|
|
97
|
+
* A tool whose input is described by a plain JSON Schema, checked by polaris
|
|
98
|
+
* (see {@link jsonSchema} for the keywords it checks). `I` is what the input
|
|
99
|
+
* is typed as.
|
|
100
|
+
*/
|
|
101
|
+
export interface JsonSchemaToolSpec<I = Record<string, unknown>> {
|
|
102
|
+
readonly name: string;
|
|
103
|
+
readonly description: string;
|
|
104
|
+
/** An object schema: `{ type: 'object', properties: {...}, required: [...] }`. */
|
|
105
|
+
readonly inputSchema: JsonSchema;
|
|
106
|
+
run(input: I, context: ToolContext): unknown;
|
|
107
|
+
}
|
|
108
|
+
|
|
72
109
|
const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
110
|
+
/** The most tools one run holds, active and inactive. */
|
|
111
|
+
export const MAX_RUN_TOOLS = 128;
|
|
73
112
|
const FAILED = "The tool failed.";
|
|
74
113
|
|
|
75
114
|
/**
|
|
@@ -81,23 +120,51 @@ const FAILED = "The tool failed.";
|
|
|
81
120
|
* schema: rune.create({ canton: rune.string() }),
|
|
82
121
|
* run: async ({ canton }) => rules.find(canton),
|
|
83
122
|
* })
|
|
123
|
+
*
|
|
124
|
+
* or by a plain JSON Schema, as an MCP server or a skill gives it:
|
|
125
|
+
*
|
|
126
|
+
* defineTool({
|
|
127
|
+
* name: 'canton_rule',
|
|
128
|
+
* description: 'Look up a tax rule for a Swiss canton',
|
|
129
|
+
* inputSchema: { type: 'object', properties: { canton: { type: 'string' } }, required: ['canton'] },
|
|
130
|
+
* run: async ({ canton }) => rules.find(String(canton)),
|
|
131
|
+
* })
|
|
84
132
|
*/
|
|
85
133
|
export function defineTool<S extends StandardSchema>(
|
|
86
134
|
spec: ToolSpec<S>,
|
|
135
|
+
): PolarisTool;
|
|
136
|
+
export function defineTool<I = Record<string, unknown>>(
|
|
137
|
+
spec: JsonSchemaToolSpec<I>,
|
|
138
|
+
): PolarisTool;
|
|
139
|
+
export function defineTool(
|
|
140
|
+
spec: ToolSpec<StandardSchema> | JsonSchemaToolSpec<unknown>,
|
|
87
141
|
): PolarisTool {
|
|
88
142
|
if (!TOOL_NAME.test(spec.name)) {
|
|
89
143
|
throw new E_POLARIS_INVALID_REQUEST([
|
|
90
144
|
`a tool name is 1 to 64 letters, digits, '_' or '-'; '${spec.name}' is not`,
|
|
91
145
|
]);
|
|
92
146
|
}
|
|
93
|
-
const
|
|
94
|
-
const
|
|
147
|
+
const label = `tool '${spec.name}'`;
|
|
148
|
+
const hasSchema = "schema" in spec && spec.schema !== undefined;
|
|
149
|
+
const hasInputSchema =
|
|
150
|
+
"inputSchema" in spec && spec.inputSchema !== undefined;
|
|
151
|
+
if (hasSchema === hasInputSchema) {
|
|
152
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
153
|
+
`${label} takes one of \`schema\` (a Standard Schema) and \`inputSchema\` (a JSON Schema)`,
|
|
154
|
+
]);
|
|
155
|
+
}
|
|
156
|
+
const schema: StandardSchema = hasSchema
|
|
157
|
+
? (spec as ToolSpec<StandardSchema>).schema
|
|
158
|
+
: jsonSchema((spec as JsonSchemaToolSpec<unknown>).inputSchema, label);
|
|
159
|
+
const standard = schema["~standard"];
|
|
160
|
+
const inputSchema = objectJsonSchema(schema, label);
|
|
161
|
+
const run = spec.run as (input: unknown, context: ToolContext) => unknown;
|
|
95
162
|
|
|
96
163
|
return {
|
|
97
164
|
name: spec.name,
|
|
98
165
|
definition: { name: spec.name, description: spec.description, inputSchema },
|
|
99
166
|
async execute(call, context) {
|
|
100
|
-
let result: SchemaResult<
|
|
167
|
+
let result: SchemaResult<unknown>;
|
|
101
168
|
try {
|
|
102
169
|
result = await standard.validate(call.input);
|
|
103
170
|
} catch (error) {
|
|
@@ -110,10 +177,15 @@ export function defineTool<S extends StandardSchema>(
|
|
|
110
177
|
error: result.issues,
|
|
111
178
|
};
|
|
112
179
|
}
|
|
180
|
+
const handed: ToolContext = {
|
|
181
|
+
toolCallId: context.toolCallId,
|
|
182
|
+
signal: context.signal,
|
|
183
|
+
addTools: context.addTools ?? outsideRun,
|
|
184
|
+
};
|
|
113
185
|
try {
|
|
114
186
|
return {
|
|
115
187
|
ok: true,
|
|
116
|
-
content: toContent(await
|
|
188
|
+
content: toContent(await run(result.value, handed)),
|
|
117
189
|
};
|
|
118
190
|
} catch (error) {
|
|
119
191
|
return {
|
|
@@ -132,31 +204,182 @@ function toContent(value: unknown): string {
|
|
|
132
204
|
return JSON.stringify(value);
|
|
133
205
|
}
|
|
134
206
|
|
|
135
|
-
/**
|
|
136
|
-
export
|
|
137
|
-
|
|
138
|
-
|
|
207
|
+
/** Called with every failed tool call, and the error the model does not see. */
|
|
208
|
+
export type OnToolError = (error: unknown, call: ToolCallPart) => void;
|
|
209
|
+
|
|
210
|
+
/** Whether `value` is a tool built by {@link defineTool}. */
|
|
211
|
+
export function isTool(value: unknown): value is PolarisTool {
|
|
212
|
+
return (
|
|
213
|
+
typeof value === "object" &&
|
|
214
|
+
value !== null &&
|
|
215
|
+
typeof Reflect.get(value, "name") === "string" &&
|
|
216
|
+
typeof Reflect.get(value, "execute") === "function" &&
|
|
217
|
+
typeof Reflect.get(value, "definition") === "object"
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The tools of one run: those the model may call, those sent but not
|
|
223
|
+
* callable yet (`inactiveTools`), and those added during the current turn,
|
|
224
|
+
* which join the run once the turn is answered, so the calls of one turn all
|
|
225
|
+
* see the same tools.
|
|
226
|
+
*/
|
|
227
|
+
export class RunTools {
|
|
228
|
+
/** Every tool sent to the model, in the order it is sent. */
|
|
229
|
+
readonly #sent: PolarisTool[] = [];
|
|
230
|
+
readonly #active = new Map<string, PolarisTool>();
|
|
231
|
+
readonly #inactive = new Map<string, PolarisTool>();
|
|
232
|
+
/** Added during the current turn: new tools, and inactive ones made callable. */
|
|
233
|
+
readonly #added = new Map<string, PolarisTool>();
|
|
234
|
+
readonly #activated = new Set<string>();
|
|
235
|
+
|
|
236
|
+
constructor(
|
|
237
|
+
active: readonly PolarisTool[],
|
|
238
|
+
inactive: readonly PolarisTool[] = [],
|
|
239
|
+
) {
|
|
240
|
+
for (const [list, into] of [
|
|
241
|
+
[active, this.#active],
|
|
242
|
+
[inactive, this.#inactive],
|
|
243
|
+
] as const) {
|
|
244
|
+
for (const tool of list) {
|
|
245
|
+
if (!isTool(tool)) {
|
|
246
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
247
|
+
"a run's tools must be built by `defineTool()`",
|
|
248
|
+
]);
|
|
249
|
+
}
|
|
250
|
+
if (this.#has(tool.name)) {
|
|
251
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
252
|
+
`two tools are named '${tool.name}'`,
|
|
253
|
+
]);
|
|
254
|
+
}
|
|
255
|
+
into.set(tool.name, tool);
|
|
256
|
+
this.#sent.push(tool);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (this.#sent.length > MAX_RUN_TOOLS) {
|
|
260
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
261
|
+
`a run holds at most ${MAX_RUN_TOOLS} tools`,
|
|
262
|
+
]);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
#has(name: string): boolean {
|
|
267
|
+
return this.#active.has(name) || this.#inactive.has(name);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** What the next request sends. */
|
|
271
|
+
definitions(): ToolDefinition[] {
|
|
272
|
+
return this.#sent.map((tool) => tool.definition);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The tool a call names, `inactive` when it is not callable yet. */
|
|
276
|
+
find(name: string): PolarisTool | "inactive" | undefined {
|
|
277
|
+
return (
|
|
278
|
+
this.#active.get(name) ??
|
|
279
|
+
(this.#inactive.has(name) ? "inactive" : undefined)
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Take tools a handler added: they join the run at {@link commit}, once
|
|
285
|
+
* the turn is answered. All of them or none.
|
|
286
|
+
*/
|
|
287
|
+
stage(tools: readonly PolarisTool[]): void {
|
|
288
|
+
if (!Array.isArray(tools) || !tools.every(isTool)) {
|
|
289
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
290
|
+
"`addTools` takes tools built by `defineTool()`",
|
|
291
|
+
]);
|
|
292
|
+
}
|
|
293
|
+
const added = new Map<string, PolarisTool>();
|
|
294
|
+
const activated = new Set<string>();
|
|
295
|
+
for (const tool of tools) {
|
|
296
|
+
if (this.#inactive.get(tool.name) === tool) {
|
|
297
|
+
activated.add(tool.name);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const known =
|
|
301
|
+
this.#active.get(tool.name) ??
|
|
302
|
+
this.#inactive.get(tool.name) ??
|
|
303
|
+
this.#added.get(tool.name) ??
|
|
304
|
+
added.get(tool.name);
|
|
305
|
+
if (known === tool) continue;
|
|
306
|
+
if (known !== undefined) {
|
|
307
|
+
throw new ToolError(
|
|
308
|
+
`A tool named '${tool.name}' is already in this run; nothing was added.`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
added.set(tool.name, tool);
|
|
312
|
+
}
|
|
313
|
+
if (this.#sent.length + this.#added.size + added.size > MAX_RUN_TOOLS) {
|
|
314
|
+
throw new ToolError(
|
|
315
|
+
`This run cannot hold more than ${MAX_RUN_TOOLS} tools; nothing was added.`,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
for (const [name, tool] of added) this.#added.set(name, tool);
|
|
319
|
+
for (const name of activated) this.#activated.add(name);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Let the tools added during the turn into the run. */
|
|
323
|
+
commit(): void {
|
|
324
|
+
for (const name of this.#activated) {
|
|
325
|
+
// Only an inactive tool is activated, and only here does it leave.
|
|
326
|
+
const tool = this.#inactive.get(name) as PolarisTool;
|
|
327
|
+
this.#inactive.delete(name);
|
|
328
|
+
this.#active.set(name, tool);
|
|
329
|
+
}
|
|
330
|
+
for (const [name, tool] of this.#added) {
|
|
331
|
+
this.#active.set(name, tool);
|
|
332
|
+
this.#sent.push(tool);
|
|
333
|
+
}
|
|
334
|
+
this.#activated.clear();
|
|
335
|
+
this.#added.clear();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Run one call, and answer it. Never rejects. */
|
|
340
|
+
export async function runToolCall(
|
|
341
|
+
call: ToolCallPart,
|
|
342
|
+
tools: RunTools,
|
|
139
343
|
signal: AbortSignal,
|
|
140
|
-
onToolError:
|
|
141
|
-
): Promise<ToolResultPart
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
344
|
+
onToolError: OnToolError | undefined,
|
|
345
|
+
): Promise<ToolResultPart> {
|
|
346
|
+
const tool = tools.find(call.name);
|
|
347
|
+
const outcome: ToolOutcome =
|
|
348
|
+
tool === "inactive"
|
|
349
|
+
? {
|
|
350
|
+
ok: false,
|
|
351
|
+
content: `The tool '${call.name}' is not available yet.`,
|
|
352
|
+
error: new Error(`inactive tool '${call.name}'`),
|
|
353
|
+
}
|
|
354
|
+
: tool
|
|
355
|
+
? await tool.execute(call, {
|
|
356
|
+
toolCallId: call.id,
|
|
357
|
+
signal,
|
|
358
|
+
addTools: (added) => tools.stage(added),
|
|
359
|
+
})
|
|
147
360
|
: {
|
|
148
361
|
ok: false,
|
|
149
362
|
content: `There is no tool named '${call.name}'.`,
|
|
150
363
|
error: new Error(`unknown tool '${call.name}'`),
|
|
151
364
|
};
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
365
|
+
if (!outcome.ok) onToolError?.(outcome.error, call);
|
|
366
|
+
return {
|
|
367
|
+
type: "tool_result",
|
|
368
|
+
toolCallId: call.id,
|
|
369
|
+
content: outcome.content,
|
|
370
|
+
...(outcome.ok ? {} : { isError: true }),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Run every call of one turn, at once, and answer them in one message. */
|
|
375
|
+
export function runToolCalls(
|
|
376
|
+
calls: readonly ToolCallPart[],
|
|
377
|
+
tools: RunTools,
|
|
378
|
+
signal: AbortSignal,
|
|
379
|
+
onToolError: OnToolError | undefined,
|
|
380
|
+
): Promise<ToolResultPart[]> {
|
|
381
|
+
return Promise.all(
|
|
382
|
+
calls.map((call) => runToolCall(call, tools, signal, onToolError)),
|
|
160
383
|
);
|
|
161
384
|
}
|
|
162
385
|
|
|
@@ -164,3 +387,13 @@ export async function runToolCalls(
|
|
|
164
387
|
export function tooManySteps(maxSteps: number): Error {
|
|
165
388
|
return new E_POLARIS_TOO_MANY_STEPS([maxSteps]);
|
|
166
389
|
}
|
|
390
|
+
|
|
391
|
+
/** Refuse a reply that calls more tools than `maxToolCalls`, before any runs. */
|
|
392
|
+
export function checkToolCalls(
|
|
393
|
+
calls: readonly unknown[],
|
|
394
|
+
maxToolCalls: number,
|
|
395
|
+
): void {
|
|
396
|
+
if (calls.length > maxToolCalls) {
|
|
397
|
+
throw new E_POLARIS_TOO_MANY_TOOL_CALLS([calls.length, maxToolCalls]);
|
|
398
|
+
}
|
|
399
|
+
}
|
package/src/transport.ts
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
E_POLARIS_PROVIDER_REJECTED,
|
|
3
|
+
E_POLARIS_RESPONSE_TOO_LARGE,
|
|
4
|
+
} from "./errors.js";
|
|
2
5
|
import type { Transport } from "./types.js";
|
|
3
6
|
|
|
4
7
|
/** Statuses whose response has no body by definition. */
|
|
5
8
|
const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
|
-
* Wrap `base` so every request it sends carries `signal`,
|
|
9
|
-
* longer than `maxBytes
|
|
11
|
+
* Wrap `base` so every request it sends carries `signal`, follows no redirect,
|
|
12
|
+
* and reads no response body longer than `maxBytes`.
|
|
13
|
+
*
|
|
14
|
+
* A redirect is refused, never followed: on another origin, `fetch` would
|
|
15
|
+
* drop `Authorization` but send every other header (`api-key`,
|
|
16
|
+
* `x-goog-api-key`...) and, on a 307 or 308, the whole prompt again. The
|
|
17
|
+
* provider is the configured origin and nothing else.
|
|
10
18
|
*
|
|
11
19
|
* The size is counted on the bytes as they arrive, not taken from
|
|
12
20
|
* `Content-Length` alone: a compressed or chunked body announces nothing true
|
|
@@ -17,14 +25,28 @@ export function boundFetch(
|
|
|
17
25
|
base: Transport,
|
|
18
26
|
signal: AbortSignal,
|
|
19
27
|
maxBytes: number,
|
|
28
|
+
provider: string,
|
|
20
29
|
): Transport {
|
|
21
30
|
return async (input, init) => {
|
|
22
31
|
const own = init?.signal;
|
|
23
32
|
const response = await base(input, {
|
|
24
33
|
...init,
|
|
34
|
+
redirect: "manual",
|
|
25
35
|
signal: own ? AbortSignal.any([signal, own]) : signal,
|
|
26
36
|
});
|
|
27
37
|
|
|
38
|
+
// A browser answers a manual redirect with an opaque response, status 0.
|
|
39
|
+
if (
|
|
40
|
+
response.type === "opaqueredirect" ||
|
|
41
|
+
(response.status >= 300 && response.status < 400)
|
|
42
|
+
) {
|
|
43
|
+
await response.body?.cancel().catch(() => undefined);
|
|
44
|
+
throw new E_POLARIS_PROVIDER_REJECTED([
|
|
45
|
+
provider,
|
|
46
|
+
`it answered with a redirect (HTTP ${response.status}), which polaris does not follow`,
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
|
|
28
50
|
const declared = Number(response.headers.get("content-length"));
|
|
29
51
|
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
30
52
|
await response.body?.cancel().catch(() => undefined);
|