@staal/node 0.24.1 → 0.25.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/README.md CHANGED
@@ -31,6 +31,38 @@ in `index.d.ts`: `done` with a `result`, `failed` with a `failure`, `stopped` (a
31
31
  action in doubt: `resolve` it, then `resume`), `invalid` with located check errors,
32
32
  or `error`. Pass `{ engine: 'native' }` to run pure code as machine code.
33
33
 
34
+ **As a tool.** `staal.Tool.open` makes a program a tool an agent can call many times,
35
+ with quotas across calls, `once` (the same operation called again is the same run),
36
+ and recovery of a run a crash interrupted when the journal directory is next opened.
37
+ Grants are fixed, or computed by your app for each call from a context it passes:
38
+
39
+ ```js
40
+ const refund = await staal.Tool.open('refund.staal', {
41
+ name: 'refund_order',
42
+ description: 'Refund part of an order.',
43
+ grants: (customer) => ({ pay: { cap: 'payments.refund', uses: 1, each: { amount: LIMITS[customer.tier], currency: 'USD' } } }),
44
+ journals: 'runs',
45
+ quota: { window: '1h', money: { amount: '1000.00', currency: 'USD' } },
46
+ });
47
+ const r = await refund.call({ order: '4417', amount: { amount: '35.00', currency: 'USD' } }, { context: customer });
48
+ // r.status: 'done', 'failed', 'stopped', 'in_progress' or 'not_run'; r.text, r.value, r.run
49
+ ```
50
+
51
+ A grant is never an argument, and the model never sees one. An app serving several
52
+ tenants or users from one directory also gives `scope: (customer) => customer.tenantId`,
53
+ from its own records: `once` keys are then held per scope, and a run's status is given
54
+ only in its scope (`refund.status(run, { context: customer })`). One process uses a
55
+ journal directory at a time, so give each worker its own directory (whose quotas are
56
+ then its own), or send the calls through one process.
57
+
58
+ **Agent frameworks.** `functionTool` from `@staal/node/openai-agents` gives an OpenAI
59
+ Agents SDK tool (grants from the run's `context`), and `structuredTool` from
60
+ `@staal/node/langgraph` a LangChain tool for LangGraph (context from
61
+ `config.configurable.staal_context`). The frameworks are optional peer dependencies.
62
+ Both are tested through the framework's own agent loop (@openai/agents 0.20.0,
63
+ @langchain/langgraph 1.5.1); the examples are in
64
+ [examples/frameworks](https://github.com/laurells/staal/tree/main/examples/frameworks).
65
+
34
66
  **Platforms.** Node 18 or newer, on Linux (x86_64 and arm64, glibc 2.28 or newer) and
35
67
  macOS (Apple Silicon, macOS 11 or newer; Intel, macOS 10.12 or newer). Elsewhere,
36
68
  build `node/` from the repository.
Binary file
Binary file
Binary file
Binary file
package/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export type FailureKind =
30
30
  | 'provider'
31
31
  | 'step_limit'
32
32
  | 'depth_limit'
33
+ | 'deadline'
33
34
  | 'internal'
34
35
  | 'journal'
35
36
  | 'in_doubt';
@@ -39,8 +40,17 @@ export interface Failure {
39
40
  message: string;
40
41
  }
41
42
 
43
+ /** What one granted capability used over a run (RUNTIME.md section 6). */
44
+ export interface GrantUsage {
45
+ capability: string;
46
+ uses: number;
47
+ charged: { amount: string; currency: string }[];
48
+ }
49
+
42
50
  interface Ran {
43
51
  log: LogEvent[];
52
+ /** For each capability parameter of the entry function, by name. */
53
+ usage: { [parameter: string]: GrantUsage };
44
54
  /** Present when the run loaded C code, which Staal cannot check (RUNTIME.md section 19). */
45
55
  unchecked?: Json[];
46
56
  }
@@ -75,3 +85,92 @@ export function check(program: string): Promise<CheckResult>;
75
85
  export function run(program: string, config: RunConfig, options?: RunOptions): Promise<RunResult>;
76
86
  export function resume(program: string, config: RunConfig, journal: string, options?: Pick<RunOptions, 'engine'>): Promise<RunResult>;
77
87
  export function resolve(journal: string, resolution: Resolution): Promise<ResolveResult>;
88
+
89
+ /** A host or tool could not be opened, or a call was malformed: nothing ran. */
90
+ export class StaalError extends Error {}
91
+
92
+ export interface HostOptions {
93
+ /** Days a settled run's files are kept (default 90), or "forever". */
94
+ keep?: number | 'forever';
95
+ max_concurrent_runs?: number;
96
+ notify?: string[];
97
+ notify_env?: string[];
98
+ }
99
+
100
+ /** Where tools keep their runs: one journal directory, its ledger and its quotas. */
101
+ export class Host {
102
+ static open(journals: string, options?: HostOptions): Promise<Host>;
103
+ readonly journals: string;
104
+ /** What happened to a run, by its id. Changes nothing. */
105
+ /** A run made in a scope is described only when the same scope is given. */
106
+ status(run: string, options?: { scope?: string }): Promise<RunStatus>;
107
+ close(): Promise<void>;
108
+ }
109
+
110
+ export type RunStatus = {
111
+ run: string;
112
+ status: 'running' | 'waiting_for_operator' | 'done' | 'failed' | 'not_started' | 'expired' | 'unknown';
113
+ observed_at: string;
114
+ result?: Json;
115
+ failure?: { kind: string; message: string };
116
+ reason?: string;
117
+ };
118
+
119
+ export interface ToolOptions<Context = unknown> {
120
+ name: string;
121
+ description: string;
122
+ /** The same grants for every call, or a function of the call's context giving that call's. */
123
+ grants?: { [name: string]: Json } | ((context: Context) => { [name: string]: Json } | Promise<{ [name: string]: Json }>);
124
+ /**
125
+ * The call's trusted scope (a tenant's or a user's id, from the app's own records,
126
+ * never from the arguments), from its context: `once` keys are held within a scope,
127
+ * and a run's status is given only in its scope.
128
+ */
129
+ scope?: (context: Context) => string | Promise<string>;
130
+ /** A journal directory, or an open host: one is required. */
131
+ journals?: string;
132
+ host?: Host;
133
+ title?: string;
134
+ entry?: string;
135
+ quota?: { window: string; calls?: number; money?: { amount: string; currency: string } };
136
+ once?: { by: string[]; keep?: string };
137
+ deadline?: string;
138
+ max_concurrent_runs?: number;
139
+ engine?: 'interpreter' | 'native';
140
+ model?: Json;
141
+ secrets?: Json;
142
+ net?: Json;
143
+ fs?: Json;
144
+ adapters?: Json;
145
+ limits?: Json;
146
+ }
147
+
148
+ export interface ToolResult {
149
+ status: 'done' | 'failed' | 'stopped' | 'in_progress' | 'not_run';
150
+ isError: boolean;
151
+ /** What to show a model. */
152
+ text: string;
153
+ structured?: { result: Json } | { status: 'waiting_for_operator'; run: string };
154
+ run?: string;
155
+ /** The program's result, when done. */
156
+ value?: Json;
157
+ }
158
+
159
+ /** A program's entry function as a tool, with quotas, once and recovery across calls. */
160
+ export class Tool<Context = unknown> {
161
+ static open<Context = unknown>(program: string, options: ToolOptions<Context>): Promise<Tool<Context>>;
162
+ readonly name: string;
163
+ readonly title?: string;
164
+ readonly description: string;
165
+ /** The JSON Schema of its arguments. */
166
+ readonly schema: Json;
167
+ readonly outputSchema: Json;
168
+ readonly annotations: { readOnlyHint: boolean; destructiveHint: boolean; idempotentHint: boolean; openWorldHint: boolean; title?: string };
169
+ readonly warnings: string[];
170
+ readonly perCallGrants: boolean;
171
+ readonly host: Host;
172
+ call(args?: { [name: string]: Json }, options?: { context?: Context }): Promise<ToolResult>;
173
+ /** A run's status, in the scope the tool's scope function gives for the context. */
174
+ status(run: string, options?: { context?: Context }): Promise<RunStatus>;
175
+ close(): Promise<void>;
176
+ }
package/index.js CHANGED
@@ -77,4 +77,154 @@ async function resolve(journal, resolution) {
77
77
  return parse(await addon.resolve(str(journal, 'journal'), JSON.stringify(resolution)));
78
78
  }
79
79
 
80
- module.exports = { version, check, run, resume, resolve };
80
+ class StaalError extends Error {}
81
+
82
+ function ok(out) {
83
+ if (out.status === 'error') throw new StaalError(out.error);
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Where tools keep their runs: one journal directory, its ledger and its quotas.
89
+ * Opening it resumes or settles whatever an earlier process left there. One process
90
+ * uses a directory at a time; opening it again in this process gives the same host.
91
+ */
92
+ class Host {
93
+ constructor(handle, journals) {
94
+ this._handle = handle;
95
+ this.journals = journals;
96
+ }
97
+
98
+ static async open(journals, options = {}) {
99
+ const settings = { journals: str(journals, 'journals'), keep: 90, max_concurrent_runs: 8, ...options };
100
+ const out = ok(parse(await addon.hostOpen(JSON.stringify(settings))));
101
+ return new Host(out.host, journals);
102
+ }
103
+
104
+ /**
105
+ * What happened to a run, by its id. Changes nothing. A run made in a scope is
106
+ * described only when `options.scope` is that scope; otherwise it is unknown.
107
+ */
108
+ async status(run, options = {}) {
109
+ return ok(parse(await addon.runStatus(this._handle, str(run, 'run'), scopeOf(options.scope))));
110
+ }
111
+
112
+ async close() {
113
+ if (this._handle !== null) {
114
+ const h = this._handle;
115
+ this._handle = null;
116
+ ok(parse(await addon.hostClose(h)));
117
+ }
118
+ }
119
+ }
120
+
121
+ function scopeOf(scope) {
122
+ if (scope === undefined || scope === null) return undefined;
123
+ if (typeof scope !== 'string') throw new TypeError("staal: a scope must be a string (a tenant's or a user's id, from the app's own records)");
124
+ return scope;
125
+ }
126
+
127
+ const SPEC_KEYS = ['title', 'entry', 'quota', 'once', 'deadline', 'max_concurrent_runs', 'engine',
128
+ 'model', 'secrets', 'net', 'fs', 'adapters', 'limits'];
129
+
130
+ /**
131
+ * A program's entry function as a tool. `grants` is an object, the same for every
132
+ * call, or a function of the call's context that returns that call's grants, so the
133
+ * app's policy decides each call's limits. `scope`, if given, is a function of the
134
+ * same context returning the call's trusted scope as a string (a tenant's or a user's
135
+ * id, from the app's own records, never from the arguments): a `once` key is held
136
+ * within its scope, and a run's status is given only in its scope. An app serving more
137
+ * than one tenant or user from one journal directory gives a scope. Give `journals`
138
+ * (a directory) or `host`.
139
+ */
140
+ class Tool {
141
+ static async open(program, options) {
142
+ const { name, description, grants, scope, journals, host, ...spec } = options || {};
143
+ if (scope !== undefined && typeof scope !== 'function') throw new TypeError("staal: Tool: scope is a function of the call's context");
144
+ for (const k of Object.keys(spec)) {
145
+ if (!SPEC_KEYS.includes(k)) throw new TypeError(`staal: Tool: unknown option '${k}'`);
146
+ }
147
+ if ((journals === undefined) === (host === undefined)) {
148
+ throw new TypeError('staal: Tool: give journals (a directory) or host, not both and not neither');
149
+ }
150
+ const ownHost = host === undefined;
151
+ const h = ownHost ? await Host.open(journals) : host;
152
+ const body = { name, description, program: str(program, 'program') };
153
+ if (grants !== undefined && typeof grants !== 'function') body.grants = grants;
154
+ for (const [k, v] of Object.entries(spec)) if (v !== undefined && v !== null) body[k] = v;
155
+ let out;
156
+ try {
157
+ out = ok(parse(await addon.toolOpen(h._handle, JSON.stringify(body))));
158
+ } catch (e) {
159
+ if (ownHost) await h.close();
160
+ throw e;
161
+ }
162
+ const t = new Tool(out, h, ownHost, typeof grants === 'function' ? grants : null, scope || null);
163
+ if (t.perCallGrants && t._grants === null) {
164
+ await t.close();
165
+ throw new TypeError('staal: Tool: the program needs grants; give grants (an object or a function of the context)');
166
+ }
167
+ if (!t.perCallGrants && t._grants !== null) {
168
+ await t.close();
169
+ throw new TypeError("staal: Tool: the program's entry function takes no capabilities, so it takes no grants");
170
+ }
171
+ return t;
172
+ }
173
+
174
+ constructor(out, host, ownHost, grants, scope) {
175
+ this._handle = out.tool;
176
+ this._scope = scope;
177
+ this.host = host;
178
+ this._ownHost = ownHost;
179
+ this._grants = grants;
180
+ this.name = out.name;
181
+ this.title = out.title;
182
+ this.description = out.description;
183
+ this.schema = out.input_schema;
184
+ this.outputSchema = out.output_schema;
185
+ this.annotations = out.annotations;
186
+ this.warnings = out.warnings;
187
+ this.perCallGrants = out.grants === 'per_call';
188
+ }
189
+
190
+ /**
191
+ * One call. Resolves to { status, isError, text, structured, run, value }: status is
192
+ * "done", "failed", "stopped" (waiting for an operator), "in_progress" or "not_run";
193
+ * a refusal is a result too, so a model can be told why.
194
+ */
195
+ async call(args = {}, options = {}) {
196
+ let grants;
197
+ if (this.perCallGrants) {
198
+ const g = await this._grants(options.context);
199
+ if (g === null || typeof g !== 'object' || Array.isArray(g)) throw new TypeError('staal: the grants function must return an object');
200
+ grants = JSON.stringify(g);
201
+ }
202
+ const scope = this._scope ? scopeOf(await this._scope(options.context)) : undefined;
203
+ const out = ok(parse(await addon.toolCall(this._handle, JSON.stringify(args), grants, scope)));
204
+ return {
205
+ status: out.status,
206
+ isError: out.is_error,
207
+ text: out.text,
208
+ structured: out.structured,
209
+ run: out.run,
210
+ value: out.status === 'done' && out.structured ? out.structured.result : undefined,
211
+ };
212
+ }
213
+
214
+ /** A run's status, in the scope the tool's scope function gives for `options.context`. */
215
+ async status(run, options = {}) {
216
+ const scope = this._scope ? scopeOf(await this._scope(options.context)) : undefined;
217
+ return this.host.status(run, { scope });
218
+ }
219
+
220
+ async close() {
221
+ if (this._handle !== null) {
222
+ const t = this._handle;
223
+ this._handle = null;
224
+ ok(parse(await addon.toolClose(t)));
225
+ }
226
+ if (this._ownHost) await this.host.close();
227
+ }
228
+ }
229
+
230
+ module.exports = { version, check, run, resume, resolve, Host, Tool, StaalError };
package/langgraph.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { Tool } from './index';
2
+ /** A staal Tool as a @langchain/core tool; `context` maps the call's config to the tool's context. */
3
+ export function structuredTool(staalTool: Tool<any>, options?: { context?: (config: any) => unknown }): any;
package/langgraph.js ADDED
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ // A staal Tool as a LangChain tool, for LangGraph's ToolNode and agents (@langchain/core
3
+ // and @langchain/langgraph, which the app installs; @staal/node does not depend on them).
4
+ //
5
+ // const { ToolNode } = require('@langchain/langgraph/prebuilt');
6
+ // const { structuredTool } = require('@staal/node/langgraph');
7
+ // const tools = new ToolNode([structuredTool(refund)]);
8
+ // await graph.invoke(state, { configurable: { staal_context: customer } });
9
+ //
10
+ // Each call runs the Staal program with the grants the app's policy gives for the call's
11
+ // context: by default `config.configurable.staal_context`, or whatever `context` returns
12
+ // for the call's config. A refusal or a failure is given to the model as the tool's
13
+ // output, the broker's message included, so the model can correct itself.
14
+
15
+ const { tool } = require('@langchain/core/tools');
16
+
17
+ /** `staalTool` (from Tool.open) as a @langchain/core tool. */
18
+ function structuredTool(staalTool, options = {}) {
19
+ const pick = options.context || ((config) => (config && config.configurable ? config.configurable.staal_context : undefined));
20
+ const schema = { ...staalTool.schema };
21
+ delete schema.$schema;
22
+ return tool(
23
+ async (input, config) => {
24
+ const result = await staalTool.call(input || {}, { context: pick(config) });
25
+ return result.text;
26
+ },
27
+ { name: staalTool.name, description: staalTool.description, schema },
28
+ );
29
+ }
30
+
31
+ module.exports = { structuredTool };
@@ -0,0 +1,3 @@
1
+ import type { Tool } from './index';
2
+ /** A staal Tool as an @openai/agents function tool; `context` maps the run context to the tool's context. */
3
+ export function functionTool(staalTool: Tool<any>, options?: { context?: (runContext: any) => unknown }): any;
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+ // A staal Tool as a tool of the OpenAI Agents SDK for JavaScript (@openai/agents, which
3
+ // the app installs; @staal/node does not depend on it).
4
+ //
5
+ // const { Agent } = require('@openai/agents');
6
+ // const { functionTool } = require('@staal/node/openai-agents');
7
+ // const agent = new Agent({ name: 'Support', tools: [functionTool(refund)] });
8
+ //
9
+ // Each call runs the Staal program with the grants the app's policy gives for the run's
10
+ // context (the `context` passed to run(), unless `context` says otherwise). A refusal
11
+ // or a failure is given to the model as the tool's output, the broker's message
12
+ // included, so the model can correct itself.
13
+
14
+ const { tool } = require('@openai/agents');
15
+
16
+ /** `staalTool` (from Tool.open) as an @openai/agents function tool. */
17
+ function functionTool(staalTool, options = {}) {
18
+ const pick = options.context || ((runContext) => (runContext ? runContext.context : undefined));
19
+ const parameters = { ...staalTool.schema };
20
+ delete parameters.$schema;
21
+ return tool({
22
+ name: staalTool.name,
23
+ description: staalTool.description,
24
+ parameters,
25
+ // Staal's own check of the arguments is the one that decides; the schema is given
26
+ // as it is rather than rewritten into the API's strict subset.
27
+ strict: false,
28
+ execute: async (input, runContext) => {
29
+ const result = await staalTool.call(input || {}, { context: pick(runContext) });
30
+ return result.text;
31
+ },
32
+ });
33
+ }
34
+
35
+ module.exports = { functionTool };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staal/node",
3
- "version": "0.24.1",
3
+ "version": "0.25.0",
4
4
  "description": "Staal, the programming language for agents, for Node.js: the staalc compiler and runtime, through its C interface",
5
5
  "keywords": [
6
6
  "staal",
@@ -27,7 +27,11 @@
27
27
  "README.md",
28
28
  "LICENSE",
29
29
  "NOTICE",
30
- "LICENSE-THIRD-PARTY.txt"
30
+ "LICENSE-THIRD-PARTY.txt",
31
+ "openai-agents.js",
32
+ "openai-agents.d.ts",
33
+ "langgraph.js",
34
+ "langgraph.d.ts"
31
35
  ],
32
36
  "publishConfig": {
33
37
  "access": "public"
@@ -50,5 +54,32 @@
50
54
  "devDependencies": {
51
55
  "@types/node": "22.10.2",
52
56
  "typescript": "5.7.2"
57
+ },
58
+ "exports": {
59
+ ".": {
60
+ "types": "./index.d.ts",
61
+ "default": "./index.js"
62
+ },
63
+ "./openai-agents": {
64
+ "types": "./openai-agents.d.ts",
65
+ "default": "./openai-agents.js"
66
+ },
67
+ "./langgraph": {
68
+ "types": "./langgraph.d.ts",
69
+ "default": "./langgraph.js"
70
+ },
71
+ "./package.json": "./package.json"
72
+ },
73
+ "peerDependencies": {
74
+ "@openai/agents": ">=0.20.0",
75
+ "@langchain/core": ">=1.2.18"
76
+ },
77
+ "peerDependenciesMeta": {
78
+ "@openai/agents": {
79
+ "optional": true
80
+ },
81
+ "@langchain/core": {
82
+ "optional": true
83
+ }
53
84
  }
54
85
  }