jackline 0.0.0-stage → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * MCP servers as Jackline tools (spec G3).
3
+ *
4
+ * Each MCP tool becomes a Jackline tool whose manifest (name, description,
5
+ * input schema) is pinned when granted. If the server later changes it,
6
+ * calls are refused with `ManifestChanged` until the tool is granted again.
7
+ * Output is untrusted by default, like any tool.
8
+ *
9
+ * Works with a `Client` from the official `@modelcontextprotocol/sdk`, or any
10
+ * object with the same `listTools()` and `callTool()` methods.
11
+ */
12
+ import { Tool } from "./run.js";
13
+ /** A connected MCP server. Use `server.tool(name)` to get a Jackline tool. */
14
+ export class Server {
15
+ session;
16
+ name;
17
+ manifests = new Map();
18
+ constructor(session, name) {
19
+ this.session = session;
20
+ this.name = name;
21
+ }
22
+ /**
23
+ * Re-read the server's tool list (for example after a
24
+ * `notifications/tools/list_changed` message).
25
+ */
26
+ async refresh() {
27
+ const listed = await this.session.listTools();
28
+ this.manifests = new Map(listed.tools.map((t) => [
29
+ t.name,
30
+ { name: t.name, description: t.description ?? "", input_schema: t.inputSchema ?? {} },
31
+ ]));
32
+ }
33
+ /** A Jackline tool that calls `name` on this server. */
34
+ tool(name, options = {}) {
35
+ const pinned = this.manifests.get(name);
36
+ if (!pinned)
37
+ throw new Error(`MCP server \`${this.name}\` has no tool \`${name}\``);
38
+ return new Tool({
39
+ name: `mcp:${this.name}/${name}`,
40
+ description: pinned.description,
41
+ effect: options.effect ?? "irreversible",
42
+ output: options.output,
43
+ // A tool that disappeared can never match its pinned manifest.
44
+ manifest: () => this.manifests.get(name) ?? { name, removed: true },
45
+ }, async (args) => {
46
+ const result = await this.session.callTool({ name, arguments: args });
47
+ const text = (result.content ?? [])
48
+ .map((c) => c.text)
49
+ .filter((t) => t !== undefined)
50
+ .join("\n");
51
+ if (result.isError)
52
+ throw new Error(text || `MCP tool \`${name}\` failed`);
53
+ return result.structuredContent ?? text;
54
+ });
55
+ }
56
+ get toolNames() {
57
+ return [...this.manifests.keys()].sort();
58
+ }
59
+ }
60
+ /** Wrap an initialized MCP client and read its tool list. */
61
+ export async function connect(session, name) {
62
+ const server = new Server(session, name);
63
+ await server.refresh();
64
+ return server;
65
+ }
66
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,IAAI,EAAoB,MAAM,UAAU,CAAC;AAoBlD,8EAA8E;AAC9E,MAAM,OAAO,MAAM;IAIN;IACA;IAJH,SAAS,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEhD,YACW,OAAmB,EACnB,IAAY;QADZ,YAAO,GAAP,OAAO,CAAY;QACnB,SAAI,GAAJ,IAAI,CAAQ;IACpB,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,OAAO;QACX,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QAC9C,IAAI,CAAC,SAAS,GAAG,IAAI,GAAG,CACtB,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;YACtB,CAAC,CAAC,IAAI;YACN,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,IAAI,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC,WAAW,IAAI,EAAE,EAAE;SACtF,CAAC,CACH,CAAC;IACJ,CAAC;IAED,wDAAwD;IACxD,IAAI,CAAC,IAAY,EAAE,UAAwD,EAAE;QAC3E,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,IAAI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IAAI,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACzC,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACvB,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/dist/mock.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Test doubles. Mocked effects pass through the kernel and are journaled like
3
+ * real ones, marked as mocked (spec G7).
4
+ */
5
+ import { Model, type ModelResult, type Usage } from "./run.js";
6
+ type Json = Record<string, unknown>;
7
+ /** A scripted response: the reply text, a full result, or an error to throw. */
8
+ export type MockResponse = string | Partial<ModelResult> | Error;
9
+ export interface MockOptions {
10
+ name?: string;
11
+ /**
12
+ * Make the mock cost money as if it were this model (for example
13
+ * `"claude-opus-5-5"`), so budget behaviour can be tested without an API key.
14
+ */
15
+ priceAs?: string | null;
16
+ maxTokens?: number;
17
+ }
18
+ /**
19
+ * A model that answers from a script.
20
+ *
21
+ * Without `usage` in a response, usage is simulated: about four bytes per
22
+ * input token and four characters per output token. `calls` records every
23
+ * request it received.
24
+ */
25
+ export declare class MockModel extends Model {
26
+ mocked: boolean;
27
+ readonly calls: Json[];
28
+ private readonly responses;
29
+ constructor(responses: Iterable<MockResponse>, options?: MockOptions);
30
+ execute(request: Json): Promise<ModelResult>;
31
+ private answer;
32
+ usage(result: ModelResult): Usage | null;
33
+ }
34
+ /** A model that answers from a script. */
35
+ export declare function model(responses: Iterable<MockResponse>, options?: MockOptions): MockModel;
36
+ /** A scripted reply in which the model calls one tool. */
37
+ export declare function toolCall(name: string, input?: Json, text?: string): Partial<ModelResult>;
38
+ export {};
package/dist/mock.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Test doubles. Mocked effects pass through the kernel and are journaled like
3
+ * real ones, marked as mocked (spec G7).
4
+ */
5
+ import { Model, usageFromApi } from "./run.js";
6
+ /**
7
+ * A model that answers from a script.
8
+ *
9
+ * Without `usage` in a response, usage is simulated: about four bytes per
10
+ * input token and four characters per output token. `calls` records every
11
+ * request it received.
12
+ */
13
+ export class MockModel extends Model {
14
+ mocked = true;
15
+ calls = [];
16
+ responses;
17
+ constructor(responses, options = {}) {
18
+ super();
19
+ this.responses = [...responses];
20
+ this.target = `mock:${options.name ?? "mock"}`;
21
+ this.priceKey = options.priceAs ?? null;
22
+ this.defaultMaxTokens = options.maxTokens ?? 1024;
23
+ }
24
+ execute(request) {
25
+ return Promise.resolve().then(() => this.answer(request));
26
+ }
27
+ answer(request) {
28
+ this.calls.push(request);
29
+ if (this.responses.length === 0) {
30
+ throw new Error(`${this.target} received more calls than scripted responses`);
31
+ }
32
+ const next = this.responses.shift();
33
+ if (next instanceof Error)
34
+ throw next;
35
+ const response = typeof next === "string" ? { text: next, stop_reason: "end_turn" } : { ...next };
36
+ const calls = response.tool_calls ?? [];
37
+ response.tool_calls ??= calls;
38
+ response.content ??= [
39
+ ...(response.text ? [{ type: "text", text: response.text }] : []),
40
+ ...calls.map((c) => ({ type: "tool_use", id: c.id, name: c.name, input: c.input ?? {} })),
41
+ ];
42
+ response.stop_reason ??= calls.length ? "tool_use" : "end_turn";
43
+ response.text ??= "";
44
+ response.model ??= this.priceKey ?? this.target;
45
+ response.raw ??= null;
46
+ if (!("usage" in response)) {
47
+ const promptBytes = Buffer.byteLength(JSON.stringify(request.messages ?? []), "utf8");
48
+ response.usage = {
49
+ input_tokens: Math.floor(promptBytes / 4) + 1,
50
+ output_tokens: Math.min(Math.floor(String(response.text).length / 4) + 1, Math.trunc(Number(request.max_tokens ?? this.defaultMaxTokens))),
51
+ };
52
+ }
53
+ return response;
54
+ }
55
+ usage(result) {
56
+ return usageFromApi(result.usage, this.priceKey);
57
+ }
58
+ }
59
+ /** A model that answers from a script. */
60
+ export function model(responses, options = {}) {
61
+ return new MockModel(responses, options);
62
+ }
63
+ let ids = 0;
64
+ /** A scripted reply in which the model calls one tool. */
65
+ export function toolCall(name, input = {}, text = "") {
66
+ ids += 1;
67
+ return { text, tool_calls: [{ id: `toolu_mock_${ids}`, name, input }] };
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AC,CAAC,GAAG,CAAC;gBAC7C,aAAa,EAAE,IAAI,CAAC,GAAG,CACrB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,EAChD,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,IAAI,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAChE;aACF,CAAC;QACJ,CAAC;QACD,OAAO,QAAuB,CAAC;IACjC,CAAC;IAEQ,KAAK,CAAC,MAAmB;QAChC,OAAO,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnD,CAAC;CACF;AAED,0CAA0C;AAC1C,MAAM,UAAU,KAAK,CAAC,SAAiC,EAAE,UAAuB,EAAE;IAChF,OAAO,IAAI,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAC3C,CAAC;AAED,IAAI,GAAG,GAAG,CAAC,CAAC;AAEZ,0DAA0D;AAC1D,MAAM,UAAU,QAAQ,CAAC,IAAY,EAAE,QAAc,EAAE,EAAE,IAAI,GAAG,EAAE;IAChE,GAAG,IAAI,CAAC,CAAC;IACT,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,EAAE,EAAE,EAAE,cAAc,GAAG,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAC1E,CAAC"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Model adapters.
3
+ *
4
+ * Jackline wraps the official provider SDKs rather than reimplementing them.
5
+ * An adapter turns messages into the plain data that gets recorded and
6
+ * hashed, and sends it with the developer's own client.
7
+ */
8
+ import { Model, type CostBound, type ModelResult, type Usage } from "./run.js";
9
+ export { Model };
10
+ type Json = Record<string, unknown>;
11
+ /**
12
+ * The parts of an `@anthropic-ai/sdk` client the adapter uses. Pass a real
13
+ * `new Anthropic()` client; tests can pass a fake with the same shape.
14
+ */
15
+ export interface AnthropicClient {
16
+ messages: {
17
+ create(params: any): Promise<unknown>;
18
+ countTokens?(params: any): Promise<{
19
+ input_tokens: number;
20
+ }>;
21
+ };
22
+ beta: {
23
+ messages: {
24
+ create(params: any): Promise<unknown>;
25
+ };
26
+ };
27
+ }
28
+ /** The model declined the request (`stop_reason === "refusal"`). */
29
+ export declare class ModelRefused extends Error {
30
+ constructor(message: string);
31
+ }
32
+ export interface AnthropicOptions {
33
+ /** Default `claude-opus-5-5`. */
34
+ model?: string;
35
+ /** Default 16,000. */
36
+ maxTokens?: number;
37
+ /**
38
+ * Server-side refusal fallbacks: `"default"` (the default, for models that
39
+ * support them) or `null` to turn them off.
40
+ */
41
+ fallbacks?: unknown;
42
+ /**
43
+ * Bound input with the API's token-counting endpoint instead of one token
44
+ * per byte: tighter, at the cost of an extra request per call.
45
+ */
46
+ countTokens?: boolean;
47
+ }
48
+ /**
49
+ * Calls Claude through the official `@anthropic-ai/sdk`.
50
+ *
51
+ * Pass your own client, so credentials, retries and timeouts stay under your
52
+ * control. Server-side refusal fallbacks are on by default for models that
53
+ * support them: if the model declines, the API retries on a fallback model
54
+ * inside the same call. Pass `fallbacks: null` to turn it off. Prices,
55
+ * including the fallback ceiling, are computed by the kernel.
56
+ */
57
+ export declare class Anthropic extends Model {
58
+ readonly client: AnthropicClient;
59
+ readonly model: string;
60
+ readonly maxTokens: number;
61
+ readonly fallbacks: unknown;
62
+ readonly countTokens: boolean;
63
+ constructor(client: AnthropicClient, options?: AnthropicOptions);
64
+ /**
65
+ * Worst-case cost. By default the input bound is a safe overestimate (one
66
+ * token per byte). With `countTokens` it uses the API's token-counting
67
+ * endpoint. With fallbacks on, the count gets a 35% margin, since a
68
+ * fallback model may tokenize differently.
69
+ */
70
+ costRequest(request: Json): CostBound | Promise<CostBound>;
71
+ usage(result: ModelResult): Usage | null;
72
+ request(messages: unknown[], options: Json): Json;
73
+ execute(request: Json): Promise<ModelResult>;
74
+ }
75
+ /** Shorthand for `new Anthropic(client, options)`. */
76
+ export declare function anthropic(client: AnthropicClient, options?: AnthropicOptions): Anthropic;
package/dist/models.js ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Model adapters.
3
+ *
4
+ * Jackline wraps the official provider SDKs rather than reimplementing them.
5
+ * An adapter turns messages into the plain data that gets recorded and
6
+ * hashed, and sends it with the developer's own client.
7
+ */
8
+ import { Model, usageFromApi } from "./run.js";
9
+ export { Model };
10
+ /** Models that accept server-side refusal fallbacks (`fallbacks: "default"`). */
11
+ const FALLBACK_MODELS = new Set([
12
+ "claude-fable-5-2",
13
+ "claude-fable-5-1",
14
+ "claude-opus-5-5",
15
+ "claude-opus-5",
16
+ "claude-sonnet-5-5",
17
+ ]);
18
+ const FALLBACK_BETA = "server-side-fallback-2026-07-01";
19
+ /* eslint-enable @typescript-eslint/no-explicit-any */
20
+ /** Tool results must be text for the Messages API. */
21
+ function apiMessage(m) {
22
+ const msg = m;
23
+ if (!Array.isArray(msg.content))
24
+ return m;
25
+ const blocks = msg.content.map((b) => {
26
+ const block = b;
27
+ if (block && typeof block === "object" && block.type === "tool_result" && typeof block.content !== "string") {
28
+ return { ...block, content: JSON.stringify(block.content) };
29
+ }
30
+ return b;
31
+ });
32
+ return { ...msg, content: blocks };
33
+ }
34
+ function withoutNulls(v) {
35
+ if (Array.isArray(v))
36
+ return v.map(withoutNulls);
37
+ if (v && typeof v === "object") {
38
+ return Object.fromEntries(Object.entries(v)
39
+ .filter(([, x]) => x !== null && x !== undefined)
40
+ .map(([k, x]) => [k, withoutNulls(x)]));
41
+ }
42
+ return v;
43
+ }
44
+ /** The model declined the request (`stop_reason === "refusal"`). */
45
+ export class ModelRefused extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = "ModelRefused";
49
+ }
50
+ }
51
+ /**
52
+ * Calls Claude through the official `@anthropic-ai/sdk`.
53
+ *
54
+ * Pass your own client, so credentials, retries and timeouts stay under your
55
+ * control. Server-side refusal fallbacks are on by default for models that
56
+ * support them: if the model declines, the API retries on a fallback model
57
+ * inside the same call. Pass `fallbacks: null` to turn it off. Prices,
58
+ * including the fallback ceiling, are computed by the kernel.
59
+ */
60
+ export class Anthropic extends Model {
61
+ client;
62
+ model;
63
+ maxTokens;
64
+ fallbacks;
65
+ countTokens;
66
+ constructor(client, options = {}) {
67
+ super();
68
+ this.client = client;
69
+ this.model = options.model ?? "claude-opus-5-5";
70
+ this.maxTokens = options.maxTokens ?? 16_000;
71
+ const fallbacks = options.fallbacks === undefined ? "default" : options.fallbacks;
72
+ this.fallbacks = FALLBACK_MODELS.has(this.model) ? fallbacks : null;
73
+ this.countTokens = options.countTokens ?? false;
74
+ this.target = `anthropic:${this.model}`;
75
+ this.priceKey = this.model;
76
+ }
77
+ /**
78
+ * Worst-case cost. By default the input bound is a safe overestimate (one
79
+ * token per byte). With `countTokens` it uses the API's token-counting
80
+ * endpoint. With fallbacks on, the count gets a 35% margin, since a
81
+ * fallback model may tokenize differently.
82
+ */
83
+ costRequest(request) {
84
+ const bound = super.costRequest(request);
85
+ if (!this.countTokens)
86
+ return bound;
87
+ return (async () => {
88
+ const params = {};
89
+ for (const k of ["model", "messages", "system"])
90
+ if (k in request)
91
+ params[k] = request[k];
92
+ if (!this.client.messages.countTokens)
93
+ throw new TypeError("this client can't count tokens");
94
+ const counted = (await this.client.messages.countTokens(params)).input_tokens;
95
+ return {
96
+ ...bound,
97
+ inputTokens: this.fallbacks !== null ? Math.trunc(counted * 1.35) + 1 : counted,
98
+ };
99
+ })();
100
+ }
101
+ usage(result) {
102
+ const u = result.usage;
103
+ if (!u || Object.keys(u).length === 0)
104
+ return null;
105
+ // A server-side fallback may have answered: price what actually ran.
106
+ return usageFromApi(u, result.model ?? null);
107
+ }
108
+ request(messages, options) {
109
+ // Leading system messages become the top-level `system` parameter.
110
+ const systemParts = [];
111
+ const rest = [...messages];
112
+ while (rest.length && rest[0].role === "system")
113
+ systemParts.push(String(rest.shift().content));
114
+ const { max_tokens, output_schema, ...other } = options;
115
+ const req = {
116
+ model: this.model,
117
+ max_tokens: max_tokens ?? this.maxTokens,
118
+ messages: rest.map(apiMessage),
119
+ };
120
+ if (systemParts.length)
121
+ req.system = systemParts.join("\n\n");
122
+ if (this.fallbacks !== null)
123
+ req.fallbacks = this.fallbacks;
124
+ if (output_schema !== undefined) {
125
+ // Structured outputs: the model must return JSON matching the schema.
126
+ req.output_config = { format: { type: "json_schema", schema: output_schema } };
127
+ }
128
+ return { ...req, ...other };
129
+ }
130
+ async execute(request) {
131
+ const { fallbacks, ...params } = request;
132
+ const response = fallbacks !== undefined && fallbacks !== null
133
+ ? await this.client.beta.messages.create({ ...params, betas: [FALLBACK_BETA], fallbacks })
134
+ : await this.client.messages.create(params);
135
+ // Plain data only: SDK responses may carry extra non-JSON properties.
136
+ const raw = JSON.parse(JSON.stringify(response));
137
+ if (raw.stop_reason === "refusal")
138
+ throw new ModelRefused(`${String(raw.model)} declined the request`);
139
+ // Passed back unchanged on the next turn, thinking blocks included.
140
+ const content = withoutNulls(raw.content ?? []);
141
+ const text = content
142
+ .filter((b) => b.type === "text")
143
+ .map((b) => String(b.text))
144
+ .join("");
145
+ const toolCalls = content
146
+ .filter((b) => b.type === "tool_use")
147
+ .map((b) => ({ id: b.id, name: b.name, input: b.input }));
148
+ return {
149
+ text,
150
+ stop_reason: raw.stop_reason,
151
+ model: raw.model,
152
+ usage: raw.usage ?? null,
153
+ content,
154
+ tool_calls: toolCalls,
155
+ raw,
156
+ };
157
+ }
158
+ }
159
+ /** Shorthand for `new Anthropic(client, options)`. */
160
+ export function anthropic(client, options = {}) {
161
+ return new Anthropic(client, options);
162
+ }
163
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,KAAK,EAAE,YAAY,EAAgD,MAAM,UAAU,CAAC;AAE7F,OAAO,EAAE,KAAK,EAAE,CAAC;AAI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AAC;CACF;AAED,sDAAsD;AACtD,MAAM,UAAU,SAAS,CAAC,MAAuB,EAAE,UAA4B,EAAE;IAC/E,OAAO,IAAI,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The native kernel, loaded by napi-rs's generated loader, with its errors
3
+ * turned into typed Jackline errors.
4
+ */
5
+ import * as binding from "../native/index.js";
6
+ export type NativeKernel = binding.Kernel;
7
+ export declare function openKernel(path: string): NativeKernel;
8
+ export declare function memoryKernel(): NativeKernel;
9
+ export declare function manifestDigest(manifest: unknown): string;
10
+ /** What a model is told when a call with this refusal code is refused. */
11
+ export declare function modelMessage(code: string): string;
12
+ /** The hex canonical CBOR encoding of a value, as the kernel hashes it. */
13
+ export declare function canonicalHex(value: unknown): string;
14
+ /** The kernel's version: the workspace version in the root Cargo.toml. */
15
+ export declare const kernelVersion: string;
16
+ /** The version of the built-in price table. */
17
+ export declare const PRICE_TABLE_VERSION: string;
package/dist/native.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The native kernel, loaded by napi-rs's generated loader, with its errors
3
+ * turned into typed Jackline errors.
4
+ */
5
+ import * as binding from "../native/index.js";
6
+ import { fromNative } from "./errors.js";
7
+ /** Every method call on the kernel throws typed Jackline errors. */
8
+ function wrap(kernel) {
9
+ return new Proxy(kernel, {
10
+ get(target, prop, receiver) {
11
+ const value = Reflect.get(target, prop, receiver);
12
+ if (typeof value !== "function")
13
+ return value;
14
+ return (...args) => {
15
+ try {
16
+ return value.apply(target, args);
17
+ }
18
+ catch (err) {
19
+ throw fromNative(err);
20
+ }
21
+ };
22
+ },
23
+ });
24
+ }
25
+ export function openKernel(path) {
26
+ try {
27
+ return wrap(binding.Kernel.open(path));
28
+ }
29
+ catch (err) {
30
+ throw fromNative(err);
31
+ }
32
+ }
33
+ export function memoryKernel() {
34
+ return wrap(binding.Kernel.memory());
35
+ }
36
+ export function manifestDigest(manifest) {
37
+ try {
38
+ return binding.manifestDigest(manifest);
39
+ }
40
+ catch (err) {
41
+ throw fromNative(err);
42
+ }
43
+ }
44
+ /** What a model is told when a call with this refusal code is refused. */
45
+ export function modelMessage(code) {
46
+ return binding.modelMessage(code);
47
+ }
48
+ /** The hex canonical CBOR encoding of a value, as the kernel hashes it. */
49
+ export function canonicalHex(value) {
50
+ try {
51
+ return binding.canonicalHex(value);
52
+ }
53
+ catch (err) {
54
+ throw fromNative(err);
55
+ }
56
+ }
57
+ /** The kernel's version: the workspace version in the root Cargo.toml. */
58
+ export const kernelVersion = binding.VERSION;
59
+ /** The version of the built-in price table. */
60
+ export const PRICE_TABLE_VERSION = binding.PRICE_TABLE_VERSION;
61
+ //# sourceMappingURL=native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native.js","sourceRoot":"","sources":["../src/native.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,oEAAoE;AACpE,SAAS,IAAI,CAAC,MAAsB;IAClC,OAAO,IAAI,KAAK,CAAC,MAAM,EAAE;QACvB,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ;YACxB,MAAM,KAAK,GAAY,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;YAC3D,IAAI,OAAO,KAAK,KAAK,UAAU;gBAAE,OAAO,KAAK,CAAC;YAC9C,OAAO,CAAC,GAAG,IAAe,EAAE,EAAE;gBAC5B,IAAI,CAAC;oBACH,OAAQ,KAAsC,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;gBACrE,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC;gBACxB,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,YAAY;IAC1B,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,QAAiB;IAC9C,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,OAAO,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;AACpC,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAW,OAAO,CAAC,OAAO,CAAC;AAErD,+CAA+C;AAC/C,MAAM,CAAC,MAAM,mBAAmB,GAAW,OAAO,CAAC,mBAAmB,CAAC"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Labels, policies and capability constraints (spec G3, G4).
3
+ *
4
+ * Everything here builds plain data that the Rust kernel enforces. Policies
5
+ * are declarative, so they can be exported for review and loaded back
6
+ * identically.
7
+ */
8
+ /** Who may receive a value. */
9
+ export type Readers = {
10
+ kind: "public";
11
+ } | {
12
+ kind: "only";
13
+ principals: string[];
14
+ };
15
+ /** A value's label, as the kernel reports it. */
16
+ export interface Label {
17
+ integrity: "trusted" | "untrusted";
18
+ readers: Readers;
19
+ tags: string[];
20
+ sources: string[];
21
+ }
22
+ export declare const readers: {
23
+ /** Anyone may read it. */
24
+ public: Readers;
25
+ /** Nobody outside this run may read it. */
26
+ private: Readers;
27
+ /** Only these principals may read it. */
28
+ only(...principals: string[]): Readers;
29
+ };
30
+ interface KernelLabel {
31
+ integrity: "trusted" | "untrusted";
32
+ readers: Readers;
33
+ tags: string[];
34
+ sources: string[];
35
+ }
36
+ /** What a tool declares about its output. Trusted configuration (spec N10). */
37
+ export declare class LabelSpec {
38
+ readonly base: KernelLabel;
39
+ readonly fields: Record<string, KernelLabel>;
40
+ readonly independentOfArgs: boolean;
41
+ constructor(base: KernelLabel, fields?: Record<string, KernelLabel>, independentOfArgs?: boolean);
42
+ /** The kernel's form. */
43
+ toKernel(): {
44
+ base: KernelLabel;
45
+ fields: Record<string, KernelLabel>;
46
+ independent_of_args: boolean;
47
+ };
48
+ }
49
+ export interface TrustedOptions {
50
+ readers?: Readers;
51
+ tags?: Iterable<string>;
52
+ /**
53
+ * Only for tools whose answer is reliable whatever input they get, such as
54
+ * a check that an order belongs to a customer.
55
+ */
56
+ independentOfArgs?: boolean;
57
+ }
58
+ /**
59
+ * Output the agent may act on: from your own systems, or a verifier.
60
+ *
61
+ * A result is never more trusted than the call that produced it: if the tool
62
+ * is called with untrusted arguments, its result is untrusted too, unless
63
+ * `independentOfArgs` is set.
64
+ */
65
+ export declare function trusted(options?: TrustedOptions): LabelSpec;
66
+ /** Output from the outside world. The default for every tool. */
67
+ export declare function untrusted(options?: {
68
+ readers?: Readers;
69
+ tags?: Iterable<string>;
70
+ }): LabelSpec;
71
+ /**
72
+ * Different labels for different top-level fields of a structured result,
73
+ * e.g. `fields({ customer_id: trusted(), body: untrusted() })`.
74
+ */
75
+ export declare function fields(perField: Record<string, LabelSpec>, options?: {
76
+ default?: LabelSpec;
77
+ }): LabelSpec;
78
+ /** One policy rule, in the kernel's form. */
79
+ export type Rule = Record<string, unknown> & {
80
+ rule: string;
81
+ };
82
+ /**
83
+ * These tools may only be called from a trusted context. With `args`, those
84
+ * arguments must come from trusted data instead.
85
+ *
86
+ * `otherwise: "approve"` asks a human instead of refusing. Tool names may use
87
+ * `*` wildcards.
88
+ */
89
+ export declare function requiresTrusted(tools: string | string[], options?: {
90
+ args?: string[];
91
+ otherwise?: "refuse" | "approve";
92
+ }): Rule;
93
+ /**
94
+ * Values tagged `tags` (wildcards allowed, e.g. `secret:*`) may not flow into
95
+ * these `tool.arg` selectors, unless the value of the `destination` argument
96
+ * is one of the value's permitted readers.
97
+ */
98
+ export declare function noFlow(tags: string, options: {
99
+ into: string[];
100
+ destination?: string;
101
+ }): Rule;
102
+ /** Calls to these tools from an untrusted context need a human's approval. */
103
+ export declare function approveIfUntrusted(...tools: string[]): Rule;
104
+ /**
105
+ * A list of rules, evaluated by the kernel on every tool call.
106
+ *
107
+ * Every rule is checked and the strictest outcome wins: refuse, then ask for
108
+ * approval, then allow.
109
+ */
110
+ export declare class Policy {
111
+ readonly rules: Rule[];
112
+ constructor(rules?: Rule[]);
113
+ /** The kernel's form. */
114
+ toJSON(): {
115
+ rules: Rule[];
116
+ };
117
+ /** Write the policy for review, as JSON (which is also valid YAML). */
118
+ export(path: string): void;
119
+ /** Load a policy written by `export` (here or in Python, as JSON). */
120
+ static load(path: string): Policy;
121
+ }
122
+ /** A constraint on one argument of a capability. */
123
+ export type Constraint = {
124
+ op: "at_most";
125
+ value: number;
126
+ } | {
127
+ op: "at_least";
128
+ value: number;
129
+ } | {
130
+ op: "one_of";
131
+ values: unknown[];
132
+ } | {
133
+ op: "equals";
134
+ value: unknown;
135
+ } | {
136
+ op: "prefix";
137
+ value: string;
138
+ };
139
+ export declare function atMost(value: number): Constraint;
140
+ export declare function atLeast(value: number): Constraint;
141
+ export declare function oneOf(values: Iterable<unknown>): Constraint;
142
+ export declare function equals(value: unknown): Constraint;
143
+ export declare function prefix(value: string): Constraint;
144
+ export {};