@loomcycle/client 1.13.0 → 1.16.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 +1 -1
- package/dist/cjs/client-tools.js +119 -0
- package/dist/cjs/client.js +11 -0
- package/dist/cjs/index.js +5 -1
- package/dist/client-tools.d.ts +73 -0
- package/dist/client-tools.js +114 -0
- package/dist/client.d.ts +7 -0
- package/dist/client.js +11 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/types.d.ts +3 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -297,7 +297,7 @@ const forked = (await client.agentDef({
|
|
|
297
297
|
console.log(`forked def_id=${forked.def_id} hash=${forked.content_sha256}`);
|
|
298
298
|
```
|
|
299
299
|
|
|
300
|
-
Operations on AgentDef: `create` / `fork` / `get` / `list` / `promote` / `retire` / **`verify`** (v0.9.x). SkillDef has the same set minus `retire`'s edge cases. See `internal/tools/builtin/agentdef.go` for the canonical input schema; each op enforces the agent's `agent_def_scopes` / `
|
|
300
|
+
Operations on AgentDef: `create` / `fork` / `get` / `list` / `promote` / `retire` / **`verify`** (v0.9.x). SkillDef has the same set minus `retire`'s edge cases. See `internal/tools/builtin/agentdef.go` for the canonical input schema; each op enforces the agent's capability gate from the operator yaml — `agent_def_scopes` for AgentDef, and (RFC BA / v1.14.0) the agent's `skills:` pattern allowlist for SkillDef (the former `skill_def_scopes` gate was removed).
|
|
301
301
|
|
|
302
302
|
Refusals throw `SubstrateToolRefusedError` (a scope deny / empty body / allowed-tools widening); transport failures throw the usual typed errors (`AuthError`, `UnavailableError`, etc.).
|
|
303
303
|
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Client-tool host (RFC BC) — the client side of client-executed tools. Open a
|
|
3
|
+
// persistent WebSocket to loomcycle, register the tools you can run on the
|
|
4
|
+
// user's machine (browser DOM, local FS, shell), and answer the `invoke` frames
|
|
5
|
+
// loomcycle routes to you when an agent of your principal calls one. loomcycle
|
|
6
|
+
// returns your reply to the agent as an ordinary tool result — the agent follows
|
|
7
|
+
// no protocol.
|
|
8
|
+
//
|
|
9
|
+
// Transport note: the adapter is otherwise fetch/SSE-only and takes no WebSocket
|
|
10
|
+
// dependency. connectClientTools uses the global `WebSocket` (browsers, Node
|
|
11
|
+
// 22+); on older Node pass `WebSocketImpl` (e.g. the `ws` package). The bearer
|
|
12
|
+
// rides the `Sec-WebSocket-Protocol` subprotocol (browsers can't set an
|
|
13
|
+
// Authorization header on a WebSocket).
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ClientToolHost = exports.CLIENT_TOOL_SUBPROTOCOL = void 0;
|
|
16
|
+
exports.clientToolsURL = clientToolsURL;
|
|
17
|
+
/** The app-level subprotocol the server negotiates for /v1/client-tools. */
|
|
18
|
+
exports.CLIENT_TOOL_SUBPROTOCOL = "loomcycle.client-tools.v1";
|
|
19
|
+
/**
|
|
20
|
+
* ClientToolHost owns the WebSocket lifecycle: connect → hello → dispatch each
|
|
21
|
+
* invoke to onInvoke → reply with a result, with auto-reconnect. Protocol
|
|
22
|
+
* ping/pong is handled by the WebSocket layer, so there is no app heartbeat.
|
|
23
|
+
* Construct via LoomcycleClient.connectClientTools; call close() to stop.
|
|
24
|
+
*/
|
|
25
|
+
class ClientToolHost {
|
|
26
|
+
url;
|
|
27
|
+
authToken;
|
|
28
|
+
opts;
|
|
29
|
+
ws;
|
|
30
|
+
closed = false;
|
|
31
|
+
constructor(url, authToken, opts) {
|
|
32
|
+
this.url = url;
|
|
33
|
+
this.authToken = authToken;
|
|
34
|
+
this.opts = opts;
|
|
35
|
+
}
|
|
36
|
+
/** Open the connection (called for you by connectClientTools). */
|
|
37
|
+
start() {
|
|
38
|
+
this.connect();
|
|
39
|
+
}
|
|
40
|
+
/** Stop the host + close the socket; suppresses reconnect. */
|
|
41
|
+
close() {
|
|
42
|
+
this.closed = true;
|
|
43
|
+
this.ws?.close(1000, "client closed");
|
|
44
|
+
}
|
|
45
|
+
connect() {
|
|
46
|
+
if (this.closed)
|
|
47
|
+
return;
|
|
48
|
+
const WS = this.opts.WebSocketImpl ?? globalThis.WebSocket;
|
|
49
|
+
if (!WS) {
|
|
50
|
+
throw new Error("connectClientTools: no WebSocket implementation available — pass WebSocketImpl (e.g. the `ws` package) on Node < 22");
|
|
51
|
+
}
|
|
52
|
+
const protocols = [exports.CLIENT_TOOL_SUBPROTOCOL];
|
|
53
|
+
if (this.authToken)
|
|
54
|
+
protocols.push("bearer." + this.authToken);
|
|
55
|
+
this.opts.onStatus?.("connecting");
|
|
56
|
+
const ws = new WS(this.url, protocols);
|
|
57
|
+
this.ws = ws;
|
|
58
|
+
ws.onopen = () => {
|
|
59
|
+
this.opts.onStatus?.("open");
|
|
60
|
+
this.sendJSON({ type: "hello", client: "@loomcycle/client", tools: this.opts.tools });
|
|
61
|
+
};
|
|
62
|
+
ws.onerror = (ev) => this.opts.onError?.(ev);
|
|
63
|
+
ws.onclose = () => {
|
|
64
|
+
this.opts.onStatus?.("closed");
|
|
65
|
+
this.scheduleReconnect();
|
|
66
|
+
};
|
|
67
|
+
ws.onmessage = (ev) => void this.onMessage(ev.data);
|
|
68
|
+
}
|
|
69
|
+
async onMessage(data) {
|
|
70
|
+
let frame;
|
|
71
|
+
try {
|
|
72
|
+
const text = typeof data === "string" ? data : String(data);
|
|
73
|
+
frame = JSON.parse(text);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return; // ignore unparseable frames
|
|
77
|
+
}
|
|
78
|
+
if (frame.type !== "invoke")
|
|
79
|
+
return; // hello_ok / anything else — ignore
|
|
80
|
+
const callId = String(frame.call_id ?? "");
|
|
81
|
+
try {
|
|
82
|
+
const output = await this.opts.onInvoke({
|
|
83
|
+
tool: String(frame.tool ?? ""),
|
|
84
|
+
input: frame.input,
|
|
85
|
+
callId,
|
|
86
|
+
runId: frame.run_id,
|
|
87
|
+
agentId: frame.agent_id,
|
|
88
|
+
});
|
|
89
|
+
this.sendJSON({ type: "result", call_id: callId, ok: true, output });
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
this.sendJSON({
|
|
93
|
+
type: "result",
|
|
94
|
+
call_id: callId,
|
|
95
|
+
ok: false,
|
|
96
|
+
error: e instanceof Error ? e.message : String(e),
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
sendJSON(v) {
|
|
101
|
+
try {
|
|
102
|
+
this.ws?.send(JSON.stringify(v));
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
this.opts.onError?.(e);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
scheduleReconnect() {
|
|
109
|
+
if (this.closed || this.opts.reconnect === false)
|
|
110
|
+
return;
|
|
111
|
+
const delay = this.opts.reconnectDelayMs ?? 2000;
|
|
112
|
+
setTimeout(() => this.connect(), delay);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
exports.ClientToolHost = ClientToolHost;
|
|
116
|
+
/** Build the ws(s):// URL for the client-tool endpoint from an http(s) base. */
|
|
117
|
+
function clientToolsURL(baseUrl) {
|
|
118
|
+
return baseUrl.replace(/\/$/, "").replace(/^http/, "ws") + "/v1/client-tools";
|
|
119
|
+
}
|
package/dist/cjs/client.js
CHANGED
|
@@ -29,6 +29,7 @@ exports.LoomcycleClient = void 0;
|
|
|
29
29
|
const fetch_helpers_js_1 = require("./fetch-helpers.js");
|
|
30
30
|
const stream_js_1 = require("./stream.js");
|
|
31
31
|
const interactive_js_1 = require("./interactive.js");
|
|
32
|
+
const client_tools_js_1 = require("./client-tools.js");
|
|
32
33
|
/** samplingToWire maps the camelCase SamplingOptions to the snake_case wire
|
|
33
34
|
* object, omitting unset fields so they inherit the agent's value. */
|
|
34
35
|
function samplingToWire(s) {
|
|
@@ -467,6 +468,16 @@ class LoomcycleClient {
|
|
|
467
468
|
exportSnapshotURL(snapshotId) {
|
|
468
469
|
return `${this.ctx.baseUrl}/v1/_snapshots/${encodeURIComponent(snapshotId)}/export`;
|
|
469
470
|
}
|
|
471
|
+
/** Open a client-tool host (RFC BC): a persistent WebSocket over which this
|
|
472
|
+
* client registers tools it runs on the user's machine + answers the
|
|
473
|
+
* agent's tool calls. Returns a started {@link ClientToolHost}; call
|
|
474
|
+
* `.close()` to stop. Uses the global WebSocket (browsers, Node 22+); pass
|
|
475
|
+
* `WebSocketImpl` (e.g. the `ws` package) on older Node. */
|
|
476
|
+
connectClientTools(opts) {
|
|
477
|
+
const host = new client_tools_js_1.ClientToolHost((0, client_tools_js_1.clientToolsURL)(this.ctx.baseUrl), this.ctx.authToken, opts);
|
|
478
|
+
host.start();
|
|
479
|
+
return host;
|
|
480
|
+
}
|
|
470
481
|
/** Restore from a same-instance snapshot id OR an inline
|
|
471
482
|
* envelope JSON. Idempotent: ON CONFLICT DO NOTHING per row;
|
|
472
483
|
* the returned counters reflect rows actually written.
|
package/dist/cjs/index.js
CHANGED
|
@@ -92,11 +92,15 @@
|
|
|
92
92
|
* See `adapters/ts/README.md` for usage examples.
|
|
93
93
|
*/
|
|
94
94
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
95
|
-
exports.UnavailableError = exports.SubstrateToolRefusedError = exports.SnapshotVersionError = exports.SnapshotTooLargeError = exports.SnapshotNotFoundError = exports.SessionNotFoundError = exports.SessionBusyError = exports.PerUserQuotaExhaustedError = exports.PauseNotConfiguredError = exports.NotPausedError = exports.LoomcycleError = exports.ChannelCursorRegressionError = exports.InvalidArgumentError = exports.NotFoundError = exports.HookNotFoundError = exports.BackpressureError = exports.AuthError = exports.AlreadyPausingError = exports.AgentNotFoundError = exports.AgentIDInUseError = exports.InteractiveSession = exports.LoomcycleClient = void 0;
|
|
95
|
+
exports.UnavailableError = exports.SubstrateToolRefusedError = exports.SnapshotVersionError = exports.SnapshotTooLargeError = exports.SnapshotNotFoundError = exports.SessionNotFoundError = exports.SessionBusyError = exports.PerUserQuotaExhaustedError = exports.PauseNotConfiguredError = exports.NotPausedError = exports.LoomcycleError = exports.ChannelCursorRegressionError = exports.InvalidArgumentError = exports.NotFoundError = exports.HookNotFoundError = exports.BackpressureError = exports.AuthError = exports.AlreadyPausingError = exports.AgentNotFoundError = exports.AgentIDInUseError = exports.CLIENT_TOOL_SUBPROTOCOL = exports.clientToolsURL = exports.ClientToolHost = exports.InteractiveSession = exports.LoomcycleClient = void 0;
|
|
96
96
|
var client_js_1 = require("./client.js");
|
|
97
97
|
Object.defineProperty(exports, "LoomcycleClient", { enumerable: true, get: function () { return client_js_1.LoomcycleClient; } });
|
|
98
98
|
var interactive_js_1 = require("./interactive.js");
|
|
99
99
|
Object.defineProperty(exports, "InteractiveSession", { enumerable: true, get: function () { return interactive_js_1.InteractiveSession; } });
|
|
100
|
+
var client_tools_js_1 = require("./client-tools.js");
|
|
101
|
+
Object.defineProperty(exports, "ClientToolHost", { enumerable: true, get: function () { return client_tools_js_1.ClientToolHost; } });
|
|
102
|
+
Object.defineProperty(exports, "clientToolsURL", { enumerable: true, get: function () { return client_tools_js_1.clientToolsURL; } });
|
|
103
|
+
Object.defineProperty(exports, "CLIENT_TOOL_SUBPROTOCOL", { enumerable: true, get: function () { return client_tools_js_1.CLIENT_TOOL_SUBPROTOCOL; } });
|
|
100
104
|
var errors_js_1 = require("./errors.js");
|
|
101
105
|
Object.defineProperty(exports, "AgentIDInUseError", { enumerable: true, get: function () { return errors_js_1.AgentIDInUseError; } });
|
|
102
106
|
Object.defineProperty(exports, "AgentNotFoundError", { enumerable: true, get: function () { return errors_js_1.AgentNotFoundError; } });
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** The app-level subprotocol the server negotiates for /v1/client-tools. */
|
|
2
|
+
export declare const CLIENT_TOOL_SUBPROTOCOL = "loomcycle.client-tools.v1";
|
|
3
|
+
/** A tool the client offers to run locally (advertised in the hello frame). */
|
|
4
|
+
export interface ClientToolSchema {
|
|
5
|
+
name: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
/** JSON Schema for the tool input (object). */
|
|
8
|
+
input_schema?: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** An inbound tool call to execute on the user's machine. */
|
|
11
|
+
export interface ClientToolInvocation {
|
|
12
|
+
tool: string;
|
|
13
|
+
input: unknown;
|
|
14
|
+
callId: string;
|
|
15
|
+
runId?: string;
|
|
16
|
+
agentId?: string;
|
|
17
|
+
}
|
|
18
|
+
/** A minimal structural WebSocket type so we don't depend on lib.dom or `ws`. */
|
|
19
|
+
export interface WebSocketLike {
|
|
20
|
+
send(data: string): void;
|
|
21
|
+
close(code?: number, reason?: string): void;
|
|
22
|
+
onopen: ((ev: unknown) => void) | null;
|
|
23
|
+
onclose: ((ev: unknown) => void) | null;
|
|
24
|
+
onerror: ((ev: unknown) => void) | null;
|
|
25
|
+
onmessage: ((ev: {
|
|
26
|
+
data: unknown;
|
|
27
|
+
}) => void) | null;
|
|
28
|
+
}
|
|
29
|
+
export type WebSocketCtor = new (url: string, protocols?: string | string[]) => WebSocketLike;
|
|
30
|
+
export interface ConnectClientToolsOptions {
|
|
31
|
+
/** The tools this client provides. */
|
|
32
|
+
tools: ClientToolSchema[];
|
|
33
|
+
/**
|
|
34
|
+
* Handler for an inbound invoke. Return the tool's output (any JSON value); a
|
|
35
|
+
* thrown error is reported to the agent as a tool error. Confirm mutating /
|
|
36
|
+
* destructive actions with the user before executing — loomcycle cannot.
|
|
37
|
+
*/
|
|
38
|
+
onInvoke: (inv: ClientToolInvocation) => unknown | Promise<unknown>;
|
|
39
|
+
/** WebSocket implementation. Defaults to the global; pass `ws` on Node < 22. */
|
|
40
|
+
WebSocketImpl?: WebSocketCtor;
|
|
41
|
+
/** Auto-reconnect on drop (default true). */
|
|
42
|
+
reconnect?: boolean;
|
|
43
|
+
/** Reconnect backoff in ms (default 2000). */
|
|
44
|
+
reconnectDelayMs?: number;
|
|
45
|
+
/** Called on lifecycle transitions. */
|
|
46
|
+
onStatus?: (status: "connecting" | "open" | "closed") => void;
|
|
47
|
+
/** Called on a transport error (does not stop the host unless you close it). */
|
|
48
|
+
onError?: (err: unknown) => void;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* ClientToolHost owns the WebSocket lifecycle: connect → hello → dispatch each
|
|
52
|
+
* invoke to onInvoke → reply with a result, with auto-reconnect. Protocol
|
|
53
|
+
* ping/pong is handled by the WebSocket layer, so there is no app heartbeat.
|
|
54
|
+
* Construct via LoomcycleClient.connectClientTools; call close() to stop.
|
|
55
|
+
*/
|
|
56
|
+
export declare class ClientToolHost {
|
|
57
|
+
private readonly url;
|
|
58
|
+
private readonly authToken;
|
|
59
|
+
private readonly opts;
|
|
60
|
+
private ws?;
|
|
61
|
+
private closed;
|
|
62
|
+
constructor(url: string, authToken: string | undefined, opts: ConnectClientToolsOptions);
|
|
63
|
+
/** Open the connection (called for you by connectClientTools). */
|
|
64
|
+
start(): void;
|
|
65
|
+
/** Stop the host + close the socket; suppresses reconnect. */
|
|
66
|
+
close(): void;
|
|
67
|
+
private connect;
|
|
68
|
+
private onMessage;
|
|
69
|
+
private sendJSON;
|
|
70
|
+
private scheduleReconnect;
|
|
71
|
+
}
|
|
72
|
+
/** Build the ws(s):// URL for the client-tool endpoint from an http(s) base. */
|
|
73
|
+
export declare function clientToolsURL(baseUrl: string): string;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Client-tool host (RFC BC) — the client side of client-executed tools. Open a
|
|
2
|
+
// persistent WebSocket to loomcycle, register the tools you can run on the
|
|
3
|
+
// user's machine (browser DOM, local FS, shell), and answer the `invoke` frames
|
|
4
|
+
// loomcycle routes to you when an agent of your principal calls one. loomcycle
|
|
5
|
+
// returns your reply to the agent as an ordinary tool result — the agent follows
|
|
6
|
+
// no protocol.
|
|
7
|
+
//
|
|
8
|
+
// Transport note: the adapter is otherwise fetch/SSE-only and takes no WebSocket
|
|
9
|
+
// dependency. connectClientTools uses the global `WebSocket` (browsers, Node
|
|
10
|
+
// 22+); on older Node pass `WebSocketImpl` (e.g. the `ws` package). The bearer
|
|
11
|
+
// rides the `Sec-WebSocket-Protocol` subprotocol (browsers can't set an
|
|
12
|
+
// Authorization header on a WebSocket).
|
|
13
|
+
/** The app-level subprotocol the server negotiates for /v1/client-tools. */
|
|
14
|
+
export const CLIENT_TOOL_SUBPROTOCOL = "loomcycle.client-tools.v1";
|
|
15
|
+
/**
|
|
16
|
+
* ClientToolHost owns the WebSocket lifecycle: connect → hello → dispatch each
|
|
17
|
+
* invoke to onInvoke → reply with a result, with auto-reconnect. Protocol
|
|
18
|
+
* ping/pong is handled by the WebSocket layer, so there is no app heartbeat.
|
|
19
|
+
* Construct via LoomcycleClient.connectClientTools; call close() to stop.
|
|
20
|
+
*/
|
|
21
|
+
export class ClientToolHost {
|
|
22
|
+
url;
|
|
23
|
+
authToken;
|
|
24
|
+
opts;
|
|
25
|
+
ws;
|
|
26
|
+
closed = false;
|
|
27
|
+
constructor(url, authToken, opts) {
|
|
28
|
+
this.url = url;
|
|
29
|
+
this.authToken = authToken;
|
|
30
|
+
this.opts = opts;
|
|
31
|
+
}
|
|
32
|
+
/** Open the connection (called for you by connectClientTools). */
|
|
33
|
+
start() {
|
|
34
|
+
this.connect();
|
|
35
|
+
}
|
|
36
|
+
/** Stop the host + close the socket; suppresses reconnect. */
|
|
37
|
+
close() {
|
|
38
|
+
this.closed = true;
|
|
39
|
+
this.ws?.close(1000, "client closed");
|
|
40
|
+
}
|
|
41
|
+
connect() {
|
|
42
|
+
if (this.closed)
|
|
43
|
+
return;
|
|
44
|
+
const WS = this.opts.WebSocketImpl ?? globalThis.WebSocket;
|
|
45
|
+
if (!WS) {
|
|
46
|
+
throw new Error("connectClientTools: no WebSocket implementation available — pass WebSocketImpl (e.g. the `ws` package) on Node < 22");
|
|
47
|
+
}
|
|
48
|
+
const protocols = [CLIENT_TOOL_SUBPROTOCOL];
|
|
49
|
+
if (this.authToken)
|
|
50
|
+
protocols.push("bearer." + this.authToken);
|
|
51
|
+
this.opts.onStatus?.("connecting");
|
|
52
|
+
const ws = new WS(this.url, protocols);
|
|
53
|
+
this.ws = ws;
|
|
54
|
+
ws.onopen = () => {
|
|
55
|
+
this.opts.onStatus?.("open");
|
|
56
|
+
this.sendJSON({ type: "hello", client: "@loomcycle/client", tools: this.opts.tools });
|
|
57
|
+
};
|
|
58
|
+
ws.onerror = (ev) => this.opts.onError?.(ev);
|
|
59
|
+
ws.onclose = () => {
|
|
60
|
+
this.opts.onStatus?.("closed");
|
|
61
|
+
this.scheduleReconnect();
|
|
62
|
+
};
|
|
63
|
+
ws.onmessage = (ev) => void this.onMessage(ev.data);
|
|
64
|
+
}
|
|
65
|
+
async onMessage(data) {
|
|
66
|
+
let frame;
|
|
67
|
+
try {
|
|
68
|
+
const text = typeof data === "string" ? data : String(data);
|
|
69
|
+
frame = JSON.parse(text);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return; // ignore unparseable frames
|
|
73
|
+
}
|
|
74
|
+
if (frame.type !== "invoke")
|
|
75
|
+
return; // hello_ok / anything else — ignore
|
|
76
|
+
const callId = String(frame.call_id ?? "");
|
|
77
|
+
try {
|
|
78
|
+
const output = await this.opts.onInvoke({
|
|
79
|
+
tool: String(frame.tool ?? ""),
|
|
80
|
+
input: frame.input,
|
|
81
|
+
callId,
|
|
82
|
+
runId: frame.run_id,
|
|
83
|
+
agentId: frame.agent_id,
|
|
84
|
+
});
|
|
85
|
+
this.sendJSON({ type: "result", call_id: callId, ok: true, output });
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
this.sendJSON({
|
|
89
|
+
type: "result",
|
|
90
|
+
call_id: callId,
|
|
91
|
+
ok: false,
|
|
92
|
+
error: e instanceof Error ? e.message : String(e),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
sendJSON(v) {
|
|
97
|
+
try {
|
|
98
|
+
this.ws?.send(JSON.stringify(v));
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
this.opts.onError?.(e);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
scheduleReconnect() {
|
|
105
|
+
if (this.closed || this.opts.reconnect === false)
|
|
106
|
+
return;
|
|
107
|
+
const delay = this.opts.reconnectDelayMs ?? 2000;
|
|
108
|
+
setTimeout(() => this.connect(), delay);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Build the ws(s):// URL for the client-tool endpoint from an http(s) base. */
|
|
112
|
+
export function clientToolsURL(baseUrl) {
|
|
113
|
+
return baseUrl.replace(/\/$/, "").replace(/^http/, "ws") + "/v1/client-tools";
|
|
114
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* full mapping table.
|
|
25
25
|
*/
|
|
26
26
|
import { InteractiveSession } from "./interactive.js";
|
|
27
|
+
import { ClientToolHost, type ConnectClientToolsOptions } from "./client-tools.js";
|
|
27
28
|
import type { Agent, AgentEvent, AgentStatus, CancelAgentResult, ClientOptions, ContinueOptions, CreateSnapshotOptions, EnsureCodeAgentOptions, EnsureCodeAgentResult, EnsureMcpServerOptions, EnsureMcpServerResult, HealthResponse, Hook, InterruptListResponse, InterruptStatus, AckChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAckResult, ChannelAwaitResult, ChannelBroadcastResult, ChannelDescriptor, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelSubscribeResult, CreateChannelOptions, ListChannelsResponse, PeekChannelOptions, PublishChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, SubscribeChannelOptions, UpdateChannelOptions, LibraryAgentDefinition, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, ListUsersResponse, LLMChatOptions, LLMChatResponse, LLMChatStreamItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, MCPServerDefVerifyResult, MemoryEntriesResponse, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopesResponse, PauseResult, PersistentVolumesResponse, EphemeralVolumesResponse, RegisterHookOptions, RegisterHookResponse, ResolveInterruptOptions, ResumeResult, ResolverMatrix, CompactRunResult, RunBatchOptions, RunBatchResult, RunOptions, RunStateStreamItem, RuntimeStateResponse, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotRestoreResponse, StreamUserRunStatesOptions, SubstrateToolInput, SubstrateToolResponse, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, TranscriptResponse, WhoamiResponse, UsageDimension, UsageReportResponse, TokenLimit, TokenLimitsResponse, SetTokenLimitRequest } from "./types.js";
|
|
28
29
|
export declare class LoomcycleClient {
|
|
29
30
|
private ctx;
|
|
@@ -287,6 +288,12 @@ export declare class LoomcycleClient {
|
|
|
287
288
|
* URL (e.g. `curl -H "Authorization: Bearer $TOKEN" ...`).
|
|
288
289
|
* There is no token query-param fallback. */
|
|
289
290
|
exportSnapshotURL(snapshotId: string): string;
|
|
291
|
+
/** Open a client-tool host (RFC BC): a persistent WebSocket over which this
|
|
292
|
+
* client registers tools it runs on the user's machine + answers the
|
|
293
|
+
* agent's tool calls. Returns a started {@link ClientToolHost}; call
|
|
294
|
+
* `.close()` to stop. Uses the global WebSocket (browsers, Node 22+); pass
|
|
295
|
+
* `WebSocketImpl` (e.g. the `ws` package) on older Node. */
|
|
296
|
+
connectClientTools(opts: ConnectClientToolsOptions): ClientToolHost;
|
|
290
297
|
/** Restore from a same-instance snapshot id OR an inline
|
|
291
298
|
* envelope JSON. Idempotent: ON CONFLICT DO NOTHING per row;
|
|
292
299
|
* the returned counters reflect rows actually written.
|
package/dist/client.js
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
import { authHeaders, deleteRequest, jsonFetch, patchJSON, postJSON, putJSON, raiseFromResponse, } from "./fetch-helpers.js";
|
|
27
27
|
import { parseSSE } from "./stream.js";
|
|
28
28
|
import { InteractiveSession } from "./interactive.js";
|
|
29
|
+
import { ClientToolHost, clientToolsURL, } from "./client-tools.js";
|
|
29
30
|
/** samplingToWire maps the camelCase SamplingOptions to the snake_case wire
|
|
30
31
|
* object, omitting unset fields so they inherit the agent's value. */
|
|
31
32
|
function samplingToWire(s) {
|
|
@@ -464,6 +465,16 @@ export class LoomcycleClient {
|
|
|
464
465
|
exportSnapshotURL(snapshotId) {
|
|
465
466
|
return `${this.ctx.baseUrl}/v1/_snapshots/${encodeURIComponent(snapshotId)}/export`;
|
|
466
467
|
}
|
|
468
|
+
/** Open a client-tool host (RFC BC): a persistent WebSocket over which this
|
|
469
|
+
* client registers tools it runs on the user's machine + answers the
|
|
470
|
+
* agent's tool calls. Returns a started {@link ClientToolHost}; call
|
|
471
|
+
* `.close()` to stop. Uses the global WebSocket (browsers, Node 22+); pass
|
|
472
|
+
* `WebSocketImpl` (e.g. the `ws` package) on older Node. */
|
|
473
|
+
connectClientTools(opts) {
|
|
474
|
+
const host = new ClientToolHost(clientToolsURL(this.ctx.baseUrl), this.ctx.authToken, opts);
|
|
475
|
+
host.start();
|
|
476
|
+
return host;
|
|
477
|
+
}
|
|
467
478
|
/** Restore from a same-instance snapshot id OR an inline
|
|
468
479
|
* envelope JSON. Idempotent: ON CONFLICT DO NOTHING per row;
|
|
469
480
|
* the returned counters reflect rows actually written.
|
package/dist/index.d.ts
CHANGED
|
@@ -93,5 +93,7 @@
|
|
|
93
93
|
export { LoomcycleClient } from "./client.js";
|
|
94
94
|
export { InteractiveSession } from "./interactive.js";
|
|
95
95
|
export type { InteractiveSessionOps } from "./interactive.js";
|
|
96
|
+
export { ClientToolHost, clientToolsURL, CLIENT_TOOL_SUBPROTOCOL } from "./client-tools.js";
|
|
97
|
+
export type { ClientToolSchema, ClientToolInvocation, ConnectClientToolsOptions, WebSocketLike, WebSocketCtor, } from "./client-tools.js";
|
|
96
98
|
export type { AgentEvent, ClientOptions, ContinueOptions, EventType, HostWidening, ImageMediaType, ParentContext, PromptContent, PromptSegment, RetryInfo, RunOptions, SamplingOptions, CompactionOptions, ToolUse, Usage, Agent, AgentStatus, AgentUsage, CancelAgentResult, ListAgentsResponse, RunBatchOptions, RunBatchResult, SpawnRunResult, CompactRunResult, TranscriptEvent, TranscriptResponse, HealthResponse, ListUsersResponse, UserSummary, WhoamiResponse, PauseResult, ResumeResult, RuntimeStateResponse, RuntimeStateStatus, ResolverMatrix, ResolverModelStatus, ResolverProviderAvailability, CreateSnapshotOptions, SnapshotCreateResponse, SnapshotDescriptor, SnapshotEnvelope, SnapshotListResponse, SnapshotRestoreResponse, MemoryEntriesResponse, MemoryEntry, MemoryEntryResponse, MemoryScopeIDsResponse, MemoryScopeIDSummary, MemoryScopeKind, MemoryScopesResponse, InterruptListResponse, InterruptRow, InterruptStatus, ResolveInterruptOptions, Hook, HookFailMode, HookPhase, HookToolCall, HookToolResult, ListHooksResponse, PostHookCall, PostHookResult, PreHookCall, PreHookResult, RegisterHookOptions, RegisterHookResponse, SubstrateToolInput, SubstrateToolResponse, PathToolInput, PathToolResponse, DocumentToolInput, DocumentToolResponse, VolumeMode, PersistentVolumeEntry, PersistentVolumesResponse, EphemeralVolumeEntry, EphemeralVolumesResponse, SystemPromptPayload, UserInputPayload, ChannelDescriptor, ListChannelsResponse, RunStateEvent, RunStateStreamClose, RunStateStreamItem, RunStateStreamOpen, StreamUserRunStatesOptions, AckChannelOptions, ChannelAckResult, ChannelMessageItem, ChannelPeekResult, ChannelPublishResult, ChannelPurgeResult, ChannelScope, ChannelSubscribeResult, PeekChannelOptions, PublishChannelOptions, SubscribeChannelOptions, AwaitChannelsOptions, BroadcastChannelsOptions, ChannelAwaitEntry, ChannelAwaitMode, ChannelAwaitResult, ChannelBroadcastEntry, ChannelBroadcastResult, CreateChannelOptions, UpdateChannelOptions, SetMemoryEntryOptions, SetMemoryEntryResponse, AgentDefRowResponse, AgentDefVerifyResult, SkillDefVerifyResult, EnsureMcpServerOptions, EnsureMcpServerResult, MCPServerDefRowResponse, MCPServerDefVerifyResult, AgentDefOverlay, EnsureCodeAgentOptions, EnsureCodeAgentResult, LibraryAgentDefinition, LibraryEntry, LibraryListResponse, LibraryMcpServerDefinition, LibrarySkillDefinition, LLMChatContent, LLMChatMessage, LLMChatOptions, LLMChatResponse, LLMChatStreamDelta, LLMChatStreamItem, LLMChatToolCall, LLMChatUsage, LLMTool, LLMEmbeddingItem, LLMEmbeddingsOptions, LLMEmbeddingsResponse, LLMEmbeddingsUsage, UsageDimension, UsageAggregate, UsageReportResponse, LimitInfo, TokenLimit, TokenLimitsResponse, SetTokenLimitRequest, } from "./types.js";
|
|
97
99
|
export { AgentIDInUseError, AgentNotFoundError, AlreadyPausingError, AuthError, BackpressureError, HookNotFoundError, NotFoundError, InvalidArgumentError, ChannelCursorRegressionError, LoomcycleError, NotPausedError, PauseNotConfiguredError, PerUserQuotaExhaustedError, SessionBusyError, SessionNotFoundError, SnapshotNotFoundError, SnapshotTooLargeError, SnapshotVersionError, SubstrateToolRefusedError, UnavailableError, } from "./errors.js";
|
package/dist/index.js
CHANGED
|
@@ -92,4 +92,5 @@
|
|
|
92
92
|
*/
|
|
93
93
|
export { LoomcycleClient } from "./client.js";
|
|
94
94
|
export { InteractiveSession } from "./interactive.js";
|
|
95
|
+
export { ClientToolHost, clientToolsURL, CLIENT_TOOL_SUBPROTOCOL } from "./client-tools.js";
|
|
95
96
|
export { AgentIDInUseError, AgentNotFoundError, AlreadyPausingError, AuthError, BackpressureError, HookNotFoundError, NotFoundError, InvalidArgumentError, ChannelCursorRegressionError, LoomcycleError, NotPausedError, PauseNotConfiguredError, PerUserQuotaExhaustedError, SessionBusyError, SessionNotFoundError, SnapshotNotFoundError, SnapshotTooLargeError, SnapshotVersionError, SubstrateToolRefusedError, UnavailableError, } from "./errors.js";
|
package/dist/types.d.ts
CHANGED
|
@@ -1448,6 +1448,9 @@ export interface LibraryAgentDefinition {
|
|
|
1448
1448
|
tools?: string[];
|
|
1449
1449
|
skills?: string[];
|
|
1450
1450
|
providers?: string[];
|
|
1451
|
+
/** RFC BB: per-agent web-search fallback list — the ordered providers the
|
|
1452
|
+
* WebSearch tool tries (empty = the global search_priority default). */
|
|
1453
|
+
search_providers?: string[];
|
|
1451
1454
|
/** Per-tier candidate list. Server-side opaque shape — kept as
|
|
1452
1455
|
* Record<string, unknown> for forward-compat. */
|
|
1453
1456
|
models?: Record<string, unknown>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loomcycle/client",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "TypeScript client for the loomcycle sidecar (HTTP+SSE).
|
|
3
|
+
"version": "1.16.0",
|
|
4
|
+
"description": "TypeScript client for the loomcycle sidecar (HTTP+SSE). 64 methods covering run streaming, agent metadata, pause/resume/state, resolver re-probe (resolveProbe — issue #88 operator escape hatch), operator-token admin (operatorTokenDef — RFC L OSS multi-tenant auth) + whoami (RFC L authoritative principal, v0.17.0) + tenant-scoped listUsers / listUserAgents, dynamic MCP registration (mcpServerDef + v0.18.0 typed mcpServerDefVerify + ensureMcpServer idempotent register-if-changed), snapshot lifecycle, memory admin (incl. v0.9.0 Vector Memory embed_stats + reembed AND v0.11.5 setMemoryEntry + deleteMemoryEntry), interruption resolve, hook management, v0.8.22 substrate admin (agentDef + skillDef), v0.9.x n8n Phase 0 (listChannels + streamUserRunStates), v0.9.x Channel CRUD (publishChannel + subscribeChannel + peekChannel + ackChannel), v0.11.5 Channel admin CRUD (createChannel + updateChannel + deleteChannel — runtime substrate; yaml channels refuse mutation with HTTP 409), v0.9.x content_sha256 verify, v0.9.1 transcript first-cycle, v0.9.x dynamic MCP server registration (mcpServerDef + MCPServerDefVerifyResult), v0.10.3 Library v2 enumeration (listLibraryAgents + listLibrarySkills + listLibraryMcpServers), and v0.11.0 LLM Gateway (llmChat + llmStream — direct provider routing without agent overhead; primary target is n8n's LoomCycleChatModel AI Agent sub-node and any LangChain-compatible consumer). v0.10.1 — dual ESM + CommonJS distribution (additive — ESM consumers unchanged; CJS consumers like n8n's community-node loader now work). v0.19.0 — typed inline code-js agent ingestion (AgentDefOverlay.code_body + ensureCodeAgent — register a deterministic code agent through the substrate with no host filesystem bind; RFC J). v0.20.0 — ensureMcpServer surfaces discoveredToolCount straight from create (loomcycle now auto-discovers MCP tools at ingestion); rediscover is now an explicit force-refresh. v0.21.0 — run/continue accept optional non-secret `metadata` (repo name, review policy, …) passed to the agent, symmetric with the WebHook/Schedule trigger paths. v0.22.0 — version-aligned lockstep release; no client-surface change (RFC N tenant isolation of the agent/skill/MCP/Schedule/Webhook definition plane + real op-schemas on the builtin MCP meta-tools are both server-side). v0.23.0 — version-aligned lockstep release; no client-surface change (RFCs O/P/R MCP-server hardening + thin client and the RFC Q DeepSeek tool-content fix are all server-side / MCP-transport-side). v0.24.0 — purgeChannel clears a channel's buffered messages without deleting its definition (allowed on yaml-declared channels too, unlike deleteChannel — F20); AgentDefOverlay gains channels / evaluation_scopes / interruption so a COMPLETE interactive/multi-agent agent round-trips over the substrate (F14). (Consolidates the interim 0.24/0.25 package bumps, which were never tag-published, back into lockstep with the loomcycle v0.24.0 tag.) v0.25.0 — adds the RFC S channel fan-in/fan-out client twins: awaitChannels() (wait for any/all/at_least N messages across channels, or a timeout — non-committing) + broadcastChannels() (publish one payload to N channels in one atomic-pre-flight call), the client-facing counterparts of the in-band Channel.await / Channel.broadcast tool ops (the rest of v0.25.0 — the manual-management Web UI console + Context op=time + max_fires self-retiring schedules — is server-side / in-band, no client-surface change). v0.29.1 — Usage gains optional `max_context_tokens` (the serving model's context-window ceiling, stamped by the loop from Provider.Capabilities() on each usage event) so a consumer can render a 'context used / max' gauge without a hard-coded per-model table; additive + optional, no behavior change. (Lockstep catch-up: the field landed in loomcycle v0.29.0 but the adapter publish skipped on a version mismatch; v0.29.1 realigns the package version with the release tag so it publishes.) v0.33.0 — gRPC + TS client parity for the RFC Y external fan-out and the compaction surface: spawnRunBatch() (POST /v1/runs:batch — spawn up to 32 fresh runs concurrently in one call, combined index-aligned envelope, per-child failures in-envelope) + compactRun(runId) (POST /v1/runs/{run_id}/compact — summarize a parked run's context); plus per-run sampling + compaction overrides now accepted on runStreaming / continueSession (an explicit temperature 0 is preserved as deterministic, not dropped as falsy). (The gRPC half adds the matching SpawnRunBatch / CompactRun RPCs + the sampling/compaction fields on RunRequest/ContinueRequest — server-side.) v0.34.0 — version-aligned lockstep release; no client-surface change (context-transform plugins / RFC Z Phase 1a are server-side config; the exp7 hardening pass is server-side; the R2 cross-provider thinking-model downgrade surfaces a new `model_downgraded` SSE event the generic stream passes through unchanged). v0.35.0 — RFC AH dynamic filesystem volumes: volumeDef() (POST /v1/_volumedef — op-discriminated create/get/list/delete/purge; a Volume is flat, so delete unmaps + purge RemoveAll's, no retire/promote/fork) + listVolumes() / listEphemeralVolumes() (GET /v1/_volumes[/ephemeral] — tenant-scoped; host paths redacted for non-operator callers). Tenant-confined; the runtime derives the path inside an operator-blessed dynamic_root, so callers pass name + mode, never a host path. v1.1.1 — RFC AI interactive agentic sessions: an `interactive: true` flag on runStreaming/continueSession (a run that parks at end_turn for steering) + sendRunInput(runId, text) (POST /v1/runs/{id}/input — steer a live run) + streamRunByID(runId, {fromSeq}) (GET /v1/runs/{id}/stream — re-attach by run_id; the operator's prior turns replay as `steer` events so a cold client reconstructs the whole conversation) + a high-level InteractiveSession driver (client.interactiveSession / attachInteractiveSession — events()/send()/cancel(), the adapter port of the Web UI run terminal). The AgentEvent union gains awaiting_input/steer/context_compaction frames. Version-aligned with the loomcycle v1.1.x line so the v1.1.1 tag publishes it (also carrying the previously-unpublished v0.35.0 volume surface). v1.4.0 — RFC AL Path VFS + RFC AK Document on the wire: path(input) (POST /v1/_path — a Unix-like filesystem over Memory/Volumes/Documents; resolve/ls/stat/mkdir/mv/rm) + document(input) (POST /v1/_document — chunked-graph documents; 13 ops, needs SQL Memory on the sidecar). Scope (agent/user/tenant) + tenant are resolved server-side from the authenticated principal, never the wire; an off-run scope:'user' op keys on the principal subject so it interoperates with that user's agent runs. New PathToolInput / DocumentToolInput types; responses are op-varying (unknown — narrow as needed). v1.7.0 — RFC AT image/vision input: the PromptContent union gains an `image` variant ({ type:'image'; media_type: ImageMediaType; data: base64-no-prefix }) accepted in a user segment by runStreaming / continueSession (segments pass through unchanged — no method change). The model must be vision-capable or the run errors before the call. New ImageMediaType type (image/png|jpeg|gif|webp). v1.12.1 — Path/Document browse-by-subject + the full Document op set (RFC AS/AK): path(input, opts) / document(input, opts) accept optional scopeId / tenant browse overrides sent as ?scope_id= / ?tenant= query params (server reads them from the URL, re-checks authorization; omit both to browse your own subject — byte-identical to the pre-RFC-AS request), and DocumentToolInput.op now covers all 16 backend ops (adds set_path, export_md, import_md) with the matching include_metadata / markdown fields. Additive — existing path() / document() callers are unchanged. v1.16.0 — RFC BC client-executed tools (local tool host): connectClientTools({tools,onInvoke}) opens a persistent WebSocket to /v1/client-tools, registers tools this client runs on the user's machine (browser DOM / files / shell), and answers the invoke frames loomcycle routes when an agent of your principal calls a client:<tool> — returning your reply as an ordinary tool result. Returns a ClientToolHost driver (.close() to stop; auto-reconnect); dependency-free (global WebSocket in browsers / Node 22+, or an injected WebSocketImpl like the ws package on older Node); the bearer rides the Sec-WebSocket-Protocol subprotocol (browsers can't set an Authorization header on a WebSocket). The runtime's first WebSocket surface.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|