graphrt-plugin 0.0.0-stage → 0.2.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 +35 -2
- package/index.d.ts +97 -0
- package/index.mjs +385 -0
- package/package.json +28 -4
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# graphrt-plugin (JavaScript / TypeScript)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Write graphrt node kinds and tools for Node.js 18+. No dependencies; ships ESM
|
|
4
|
+
with TypeScript declarations.
|
|
5
|
+
|
|
6
|
+
```js
|
|
7
|
+
import { Plugin, PluginError, pause } from "graphrt-plugin";
|
|
8
|
+
|
|
9
|
+
const plugin = new Plugin("acme")
|
|
10
|
+
.node("acme.upper", async (ctx, req) => {
|
|
11
|
+
const text = String(req.config.text ?? "");
|
|
12
|
+
ctx.chunk("text", text.toUpperCase());
|
|
13
|
+
return { outputs: { text: text.toUpperCase() } };
|
|
14
|
+
})
|
|
15
|
+
.node("acme.approve", async (ctx, req) => {
|
|
16
|
+
if (!req.resume) return pause("approval", { message: "Publish?" }, { draft: req.config.text });
|
|
17
|
+
return { outputs: { approved: req.resume.input === "yes" }, branch: req.resume.input === "yes" ? "approved" : "rejected" };
|
|
18
|
+
})
|
|
19
|
+
.tool({ name: "shout", description: "Uppercase a text" }, async (args) => String(args.text).toUpperCase());
|
|
20
|
+
|
|
21
|
+
plugin.run();
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Pair it with a `graphrt-plugin.json` manifest; see `docs/plugins.md`.
|
|
25
|
+
|
|
26
|
+
- `req.config`: node config with variables resolved by the host.
|
|
27
|
+
- `req.resume`: `{state, input}` after a pause, else `null`.
|
|
28
|
+
- `ctx.chunk(field, text)`, `ctx.progress(name, data)`, `ctx.log(message)`.
|
|
29
|
+
- `ctx.signal` aborts when the host cancels the request.
|
|
30
|
+
- Never `console.log` (stdout carries the protocol); use `console.error`.
|
|
31
|
+
- Tools can return images for the model:
|
|
32
|
+
`{ text, images: [{ media_type: "image/png", data: pngBuffer }] }` (or
|
|
33
|
+
`data_base64`, or `{ url: "https://..." }`); at most 4, png/jpeg/webp/gif,
|
|
34
|
+
5 MiB each. Hosts without image support get the text plus a note instead.
|
|
35
|
+
|
|
36
|
+
Tests: `npm test` (Node's built-in runner).
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Protocol version implemented by this SDK. */
|
|
2
|
+
export declare const PROTOCOL_VERSION: 1;
|
|
3
|
+
/** Default line limit; the host announces its own in `initialize`. */
|
|
4
|
+
export declare const MAX_MESSAGE_BYTES: number;
|
|
5
|
+
|
|
6
|
+
/** Error reported to the host as a failed node. */
|
|
7
|
+
export declare class PluginError extends Error {
|
|
8
|
+
constructor(message: string, options?: { kind?: string; retryable?: boolean; retryAfterMs?: number });
|
|
9
|
+
kind: string;
|
|
10
|
+
retryable: boolean;
|
|
11
|
+
retryAfterMs?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface Resume {
|
|
15
|
+
/** State returned with `pause(...)`. */
|
|
16
|
+
state: unknown;
|
|
17
|
+
/** Host-supplied input (e.g. a submitted form), or null. */
|
|
18
|
+
input: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RunRequest {
|
|
22
|
+
requestId: string;
|
|
23
|
+
kind: string;
|
|
24
|
+
nodeId: string;
|
|
25
|
+
attempt: number;
|
|
26
|
+
/** Node config with variables resolved by the host. */
|
|
27
|
+
config: Record<string, any>;
|
|
28
|
+
resume: Resume | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface RunResult {
|
|
32
|
+
outputs: Record<string, unknown>;
|
|
33
|
+
branch?: string | null;
|
|
34
|
+
writes?: Array<{ selector: string[] | string; value: unknown }>;
|
|
35
|
+
usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };
|
|
36
|
+
metadata?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PauseResult {
|
|
40
|
+
pause: { kind: string; data: unknown; state: unknown };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export declare function pause(kind: string, data?: unknown, state?: unknown): PauseResult;
|
|
44
|
+
|
|
45
|
+
export declare class RunContext {
|
|
46
|
+
readonly requestId: string;
|
|
47
|
+
/** Stream text for output `field`. */
|
|
48
|
+
chunk(field: string, text: string): void;
|
|
49
|
+
/** Report structured progress. */
|
|
50
|
+
progress(name: string, data?: unknown): void;
|
|
51
|
+
/** Send a log line to the host. */
|
|
52
|
+
log(message: string, level?: "debug" | "info" | "warn" | "error"): void;
|
|
53
|
+
/** Fired when the host cancels this request. */
|
|
54
|
+
readonly signal: AbortSignal;
|
|
55
|
+
readonly cancelled: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ToolSpec {
|
|
59
|
+
name: string;
|
|
60
|
+
description?: string;
|
|
61
|
+
parameters?: Record<string, unknown>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Feature a host lists in `initialize` when tool results may carry `images`. */
|
|
65
|
+
export declare const TOOL_IMAGES_FEATURE: "tool_images";
|
|
66
|
+
export declare const MAX_TOOL_IMAGES: number;
|
|
67
|
+
export declare const MAX_TOOL_IMAGE_BYTES: number;
|
|
68
|
+
export declare const TOOL_IMAGE_MEDIA_TYPES: string[];
|
|
69
|
+
|
|
70
|
+
export type ToolImageMediaType = "image/png" | "image/jpeg" | "image/webp" | "image/gif";
|
|
71
|
+
|
|
72
|
+
/** An image shown to the model with a tool result (at most 4; 5 MiB each). */
|
|
73
|
+
export type ToolImage =
|
|
74
|
+
| { media_type: ToolImageMediaType; data_base64: string }
|
|
75
|
+
| { media_type: ToolImageMediaType; data: Uint8Array }
|
|
76
|
+
| { url: string };
|
|
77
|
+
|
|
78
|
+
export type ToolResult = string | { text: string; data?: unknown; is_error?: boolean; images?: ToolImage[] };
|
|
79
|
+
|
|
80
|
+
/** Normalize a handler result into a `tool.call` result (images dropped with a note for older hosts). */
|
|
81
|
+
export declare function toolResult(
|
|
82
|
+
result: ToolResult | null | undefined,
|
|
83
|
+
options?: { hostSupportsImages?: boolean },
|
|
84
|
+
): { text: string; data?: unknown; is_error: boolean; images?: Array<{ media_type: string; data_base64: string } | { url: string }> };
|
|
85
|
+
|
|
86
|
+
export type NodeHandler = (
|
|
87
|
+
ctx: RunContext,
|
|
88
|
+
req: RunRequest,
|
|
89
|
+
) => RunResult | PauseResult | Record<string, unknown> | void | Promise<RunResult | PauseResult | Record<string, unknown> | void>;
|
|
90
|
+
|
|
91
|
+
export declare class Plugin {
|
|
92
|
+
constructor(name: string);
|
|
93
|
+
readonly name: string;
|
|
94
|
+
node(kind: string, handler: NodeHandler, descriptor?: Record<string, unknown>): this;
|
|
95
|
+
tool(spec: ToolSpec, handler: (args: Record<string, any>) => ToolResult | Promise<ToolResult>): this;
|
|
96
|
+
run(options?: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream }): Promise<void>;
|
|
97
|
+
}
|
package/index.mjs
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// graphrt plugin SDK for JavaScript / TypeScript (Node.js >= 18, no dependencies).
|
|
2
|
+
//
|
|
3
|
+
// The plugin speaks newline-delimited JSON-RPC 2.0 over stdin/stdout.
|
|
4
|
+
// Never write to stdout yourself (console.log); use ctx.log() or console.error().
|
|
5
|
+
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
|
|
8
|
+
export const PROTOCOL_VERSION = 1;
|
|
9
|
+
|
|
10
|
+
/** Error reported to the host as a failed node. */
|
|
11
|
+
export class PluginError extends Error {
|
|
12
|
+
/**
|
|
13
|
+
* @param {string} message
|
|
14
|
+
* @param {{kind?: string, retryable?: boolean, retryAfterMs?: number}} [options]
|
|
15
|
+
*/
|
|
16
|
+
constructor(message, options = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "PluginError";
|
|
19
|
+
this.kind = options.kind ?? "plugin_error";
|
|
20
|
+
this.retryable = options.retryable ?? false;
|
|
21
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Build a result that pauses the run. */
|
|
26
|
+
export function pause(kind, data = null, state = null) {
|
|
27
|
+
return { pause: { kind, data, state } };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const RESULT_KEYS = new Set(["outputs", "branch", "writes", "usage", "metadata", "pause"]);
|
|
31
|
+
|
|
32
|
+
/** Default line limit; the host announces its own in `initialize` (`max_message_bytes`). */
|
|
33
|
+
export const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
/** Feature a host lists in `initialize` when tool results may carry `images`. */
|
|
36
|
+
export const TOOL_IMAGES_FEATURE = "tool_images";
|
|
37
|
+
/** Tool result image limits (the host enforces the same). */
|
|
38
|
+
export const MAX_TOOL_IMAGES = 4;
|
|
39
|
+
export const MAX_TOOL_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
40
|
+
export const TOOL_IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
41
|
+
|
|
42
|
+
const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
43
|
+
|
|
44
|
+
/** One `images` entry as sent on the wire: `{media_type, data_base64}` or `{url}`. */
|
|
45
|
+
function encodeImage(image, index) {
|
|
46
|
+
const fail = (message) => {
|
|
47
|
+
throw new PluginError(`image #${index}: ${message}`, { kind: "invalid_output" });
|
|
48
|
+
};
|
|
49
|
+
if (image === null || typeof image !== "object") fail("must be an object");
|
|
50
|
+
if (image.url !== undefined) {
|
|
51
|
+
if (typeof image.url !== "string" || !/^https:\/\//i.test(image.url)) fail("`url` must start with https://");
|
|
52
|
+
return { url: image.url };
|
|
53
|
+
}
|
|
54
|
+
const mediaType = image.media_type ?? image.mediaType;
|
|
55
|
+
if (!TOOL_IMAGE_MEDIA_TYPES.includes(mediaType)) {
|
|
56
|
+
fail(`media type \`${mediaType}\` is not supported (use ${TOOL_IMAGE_MEDIA_TYPES.join(", ")})`);
|
|
57
|
+
}
|
|
58
|
+
let data = image.data_base64 ?? image.dataBase64;
|
|
59
|
+
let size;
|
|
60
|
+
if (data === undefined && image.data instanceof Uint8Array) {
|
|
61
|
+
size = image.data.byteLength;
|
|
62
|
+
data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength).toString("base64");
|
|
63
|
+
} else if (typeof data === "string" && data.length % 4 !== 1 && BASE64_RE.test(data)) {
|
|
64
|
+
size = Math.floor((data.replace(/=+$/, "").length * 3) / 4);
|
|
65
|
+
} else {
|
|
66
|
+
fail("give `data_base64` (a base64 string) or `data` (a Buffer / Uint8Array)");
|
|
67
|
+
}
|
|
68
|
+
if (size === 0) fail("image data is empty");
|
|
69
|
+
if (size > MAX_TOOL_IMAGE_BYTES) fail(`image is ${size} bytes, above the ${MAX_TOOL_IMAGE_BYTES}-byte limit`);
|
|
70
|
+
return { media_type: mediaType, data_base64: data };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Normalize a tool handler's return value into a `tool.call` result. */
|
|
74
|
+
export function toolResult(result, { hostSupportsImages = true } = {}) {
|
|
75
|
+
if (typeof result === "string") result = { text: result };
|
|
76
|
+
const { images, ...rest } = result ?? {};
|
|
77
|
+
const out = { text: "", is_error: false, ...rest };
|
|
78
|
+
if (images === undefined || images === null) return out;
|
|
79
|
+
if (!Array.isArray(images)) throw new PluginError("`images` must be an array", { kind: "invalid_output" });
|
|
80
|
+
if (images.length > MAX_TOOL_IMAGES) {
|
|
81
|
+
throw new PluginError(`${images.length} images in one tool result, above the limit of ${MAX_TOOL_IMAGES}`, { kind: "invalid_output" });
|
|
82
|
+
}
|
|
83
|
+
if (images.length === 0) return out;
|
|
84
|
+
if (!hostSupportsImages) {
|
|
85
|
+
const note = `[${images.length} image(s) omitted: the graphrt host does not support image tool results]`;
|
|
86
|
+
out.text = out.text ? `${out.text}\n${note}` : note;
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
out.images = images.map(encodeImage);
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Best-effort request id from a line that could not be read. */
|
|
94
|
+
function recoverId(text) {
|
|
95
|
+
const match = /"id"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+)/.exec(text.slice(0, 4096));
|
|
96
|
+
if (!match) return null;
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(match[1]);
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function normalizeResult(result) {
|
|
105
|
+
if (result === undefined || result === null) return { outputs: {} };
|
|
106
|
+
if (typeof result !== "object" || Array.isArray(result)) {
|
|
107
|
+
throw new PluginError("node handlers must return an object", { kind: "plugin_protocol" });
|
|
108
|
+
}
|
|
109
|
+
const keys = Object.keys(result);
|
|
110
|
+
if (keys.length > 0 && keys.every((k) => RESULT_KEYS.has(k))) return result;
|
|
111
|
+
return { outputs: result };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function errorData(e) {
|
|
115
|
+
if (e instanceof PluginError) {
|
|
116
|
+
const data = { kind: e.kind, retryable: e.retryable };
|
|
117
|
+
if (e.retryAfterMs !== undefined) data.retry_after_ms = e.retryAfterMs;
|
|
118
|
+
return data;
|
|
119
|
+
}
|
|
120
|
+
return { kind: "plugin_exception" };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Per-request helpers. */
|
|
124
|
+
export class RunContext {
|
|
125
|
+
constructor(plugin, requestId) {
|
|
126
|
+
this._plugin = plugin;
|
|
127
|
+
this.requestId = requestId;
|
|
128
|
+
this._controller = new AbortController();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Stream text for output `field`. */
|
|
132
|
+
chunk(field, text) {
|
|
133
|
+
this._plugin._notify("node.chunk", { request_id: this.requestId, field, chunk: String(text) });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Report structured progress. */
|
|
137
|
+
progress(name, data = null) {
|
|
138
|
+
this._plugin._notify("node.progress", { request_id: this.requestId, name, data });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Send a log line to the host. */
|
|
142
|
+
log(message, level = "info") {
|
|
143
|
+
this._plugin._notify("log", { level, message: String(message) });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** AbortSignal fired when the host cancels this request (pass it to fetch, timers...). */
|
|
147
|
+
get signal() {
|
|
148
|
+
return this._controller.signal;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
get cancelled() {
|
|
152
|
+
return this._controller.signal.aborted;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A set of node kinds and tools served over the graphrt plugin protocol. */
|
|
157
|
+
export class Plugin {
|
|
158
|
+
/** @param {string} name */
|
|
159
|
+
constructor(name) {
|
|
160
|
+
this.name = name;
|
|
161
|
+
this._nodes = new Map();
|
|
162
|
+
this._descriptors = [];
|
|
163
|
+
this._tools = new Map();
|
|
164
|
+
this._running = new Map();
|
|
165
|
+
this._maxMessageBytes = MAX_MESSAGE_BYTES;
|
|
166
|
+
this._hostFeatures = [];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Register a node handler `async (ctx, req) => result`.
|
|
171
|
+
* The result is `{outputs, branch?, writes?, usage?, metadata?}`, a plain object
|
|
172
|
+
* (taken as the outputs) or `pause(...)`. Throw `PluginError` to fail.
|
|
173
|
+
*/
|
|
174
|
+
node(kind, handler, descriptor) {
|
|
175
|
+
this._nodes.set(kind, handler);
|
|
176
|
+
if (descriptor) this._descriptors.push({ kind, ...descriptor });
|
|
177
|
+
return this;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Register a tool `async (args) => string | {text, data?, is_error?, images?}`.
|
|
182
|
+
* `images` entries are `{media_type, data_base64}`, `{media_type, data: Buffer}`
|
|
183
|
+
* or `{url: "https://..."}`; at most 4, png/jpeg/webp/gif, 5 MiB each.
|
|
184
|
+
*/
|
|
185
|
+
tool(spec, handler) {
|
|
186
|
+
this._tools.set(spec.name, { spec: { description: "", parameters: { type: "object" }, ...spec }, handler });
|
|
187
|
+
return this;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Serve on stdin/stdout until stdin closes or the host sends `shutdown`. */
|
|
191
|
+
run({ input = process.stdin, output = process.stdout } = {}) {
|
|
192
|
+
this._output = output;
|
|
193
|
+
// A stray rejection in user code must not silently kill the plugin process.
|
|
194
|
+
process.on("unhandledRejection", (reason) => {
|
|
195
|
+
console.error(`graphrt plugin ${this.name}: unhandled rejection:`, reason);
|
|
196
|
+
});
|
|
197
|
+
const rl = createInterface({ input, crlfDelay: Infinity, terminal: false });
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
let shutdown = false;
|
|
200
|
+
const finish = () => {
|
|
201
|
+
// `shutdown` stops in-flight work; end of input lets it finish and reply.
|
|
202
|
+
if (shutdown) {
|
|
203
|
+
for (const entry of this._running.values()) {
|
|
204
|
+
entry.cancelled = true;
|
|
205
|
+
entry.ctx._controller.abort();
|
|
206
|
+
}
|
|
207
|
+
this._running.clear();
|
|
208
|
+
}
|
|
209
|
+
resolve();
|
|
210
|
+
};
|
|
211
|
+
rl.on("line", (line) => {
|
|
212
|
+
const text = line.trim();
|
|
213
|
+
if (!text) return;
|
|
214
|
+
if (Buffer.byteLength(text) > this._maxMessageBytes) {
|
|
215
|
+
console.error(`graphrt plugin ${this.name}: dropped a message above ${this._maxMessageBytes} bytes`);
|
|
216
|
+
this._error(recoverId(text), -32600, `message exceeds the ${this._maxMessageBytes}-byte limit`, { kind: "message_too_large" });
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
let msg;
|
|
220
|
+
try {
|
|
221
|
+
msg = JSON.parse(text);
|
|
222
|
+
} catch {
|
|
223
|
+
console.error(`graphrt plugin ${this.name}: unreadable message`);
|
|
224
|
+
this._error(recoverId(text), -32700, "parse error", { kind: "plugin_protocol" });
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (msg === null || typeof msg !== "object" || Array.isArray(msg)) {
|
|
228
|
+
this._error(null, -32600, "message must be a JSON object", { kind: "plugin_protocol" });
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (!this._dispatch(msg)) {
|
|
232
|
+
shutdown = true;
|
|
233
|
+
rl.close();
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
rl.on("close", finish);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
_dispatch(msg) {
|
|
241
|
+
const { id, method } = msg;
|
|
242
|
+
const params = msg.params ?? {};
|
|
243
|
+
if (method === "shutdown") return false;
|
|
244
|
+
if (id === undefined || id === null) {
|
|
245
|
+
if (method === "node.cancel") {
|
|
246
|
+
const entry = this._running.get(params.request_id);
|
|
247
|
+
if (entry) {
|
|
248
|
+
entry.ctx._controller.abort();
|
|
249
|
+
entry.cancelled = true;
|
|
250
|
+
this._running.delete(params.request_id);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return true;
|
|
254
|
+
}
|
|
255
|
+
switch (method) {
|
|
256
|
+
case "initialize": {
|
|
257
|
+
if (Number.isInteger(params.max_message_bytes) && params.max_message_bytes >= 1024) {
|
|
258
|
+
this._maxMessageBytes = params.max_message_bytes;
|
|
259
|
+
}
|
|
260
|
+
this._hostFeatures = Array.isArray(params.features) ? params.features : [];
|
|
261
|
+
const result = { protocol_version: PROTOCOL_VERSION, name: this.name };
|
|
262
|
+
if (this._descriptors.length) result.nodes = this._descriptors;
|
|
263
|
+
if (this._tools.size) result.tools = [...this._tools.values()].map((t) => t.spec);
|
|
264
|
+
this._reply(id, result);
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
case "node.run":
|
|
268
|
+
this._startRun(id, params);
|
|
269
|
+
break;
|
|
270
|
+
case "tool.list":
|
|
271
|
+
this._reply(id, { tools: [...this._tools.values()].map((t) => t.spec) });
|
|
272
|
+
break;
|
|
273
|
+
case "tool.call":
|
|
274
|
+
this._callTool(id, params);
|
|
275
|
+
break;
|
|
276
|
+
default:
|
|
277
|
+
this._error(id, -32601, `method \`${method}\` not found`);
|
|
278
|
+
}
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
_startRun(id, params) {
|
|
283
|
+
const kind = params.kind ?? "";
|
|
284
|
+
const handler = this._nodes.get(kind);
|
|
285
|
+
if (!handler) {
|
|
286
|
+
this._error(id, -32602, `plugin \`${this.name}\` has no node kind \`${kind}\``, { kind: "unknown_kind" });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
const requestId = String(params.request_id ?? id);
|
|
290
|
+
const resume = params.resume && typeof params.resume === "object"
|
|
291
|
+
? { state: params.resume.state ?? null, input: params.resume.input ?? null }
|
|
292
|
+
: null;
|
|
293
|
+
const req = {
|
|
294
|
+
requestId,
|
|
295
|
+
kind,
|
|
296
|
+
nodeId: params.node_id ?? "",
|
|
297
|
+
attempt: params.attempt ?? 1,
|
|
298
|
+
config: params.config ?? {},
|
|
299
|
+
resume,
|
|
300
|
+
};
|
|
301
|
+
const ctx = new RunContext(this, requestId);
|
|
302
|
+
const entry = { ctx, cancelled: false };
|
|
303
|
+
this._running.set(requestId, entry);
|
|
304
|
+
const run = async () => {
|
|
305
|
+
try {
|
|
306
|
+
const result = await handler(ctx, req);
|
|
307
|
+
// normalizeResult and encoding may throw too: handled below, never unhandled.
|
|
308
|
+
if (!entry.cancelled) this._reply(id, normalizeResult(result));
|
|
309
|
+
} catch (e) {
|
|
310
|
+
if (!(e instanceof PluginError)) console.error(e);
|
|
311
|
+
if (!entry.cancelled) this._error(id, -32000, e instanceof Error ? e.message : String(e), errorData(e));
|
|
312
|
+
} finally {
|
|
313
|
+
this._running.delete(requestId);
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
run().catch((e) => this._fatal(id, e));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
_callTool(id, params) {
|
|
320
|
+
const run = async () => {
|
|
321
|
+
const tool = this._tools.get(params.name);
|
|
322
|
+
if (!tool) {
|
|
323
|
+
this._error(id, -32602, `plugin \`${this.name}\` has no tool \`${params.name}\``, { kind: "unknown_tool" });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
try {
|
|
327
|
+
const result = await tool.handler(params.arguments ?? {});
|
|
328
|
+
const hostSupportsImages = this._hostFeatures.includes(TOOL_IMAGES_FEATURE);
|
|
329
|
+
this._reply(id, toolResult(result, { hostSupportsImages }));
|
|
330
|
+
} catch (e) {
|
|
331
|
+
if (!(e instanceof PluginError)) console.error(e);
|
|
332
|
+
this._error(id, -32000, e instanceof Error ? e.message : String(e), errorData(e));
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
run().catch((e) => this._fatal(id, e));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Last resort when even an error reply failed: log and send a minimal error. */
|
|
339
|
+
_fatal(id, e) {
|
|
340
|
+
console.error(e);
|
|
341
|
+
try {
|
|
342
|
+
this._output.write(
|
|
343
|
+
JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32000, message: "plugin failed to encode its reply", data: { kind: "plugin_exception" } } }) + "\n",
|
|
344
|
+
);
|
|
345
|
+
} catch (inner) {
|
|
346
|
+
console.error(inner);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
_send(msg) {
|
|
351
|
+
this._output.write(JSON.stringify(msg) + "\n");
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
_notify(method, params) {
|
|
355
|
+
try {
|
|
356
|
+
this._send({ jsonrpc: "2.0", method, params });
|
|
357
|
+
} catch (e) {
|
|
358
|
+
console.error(`graphrt plugin ${this.name}: dropped \`${method}\` notification:`, e);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
_reply(id, result) {
|
|
363
|
+
let line;
|
|
364
|
+
try {
|
|
365
|
+
line = JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
366
|
+
} catch (e) {
|
|
367
|
+
// BigInt, circular structures...: report instead of crashing the process.
|
|
368
|
+
this._error(id, -32000, `result is not valid JSON: ${e instanceof Error ? e.message : String(e)}`, { kind: "invalid_output" });
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
// A line above the host's limit would break the connection: report it instead.
|
|
372
|
+
const size = Buffer.byteLength(line);
|
|
373
|
+
if (size > this._maxMessageBytes) {
|
|
374
|
+
this._error(id, -32000, `result is ${size} bytes, above the ${this._maxMessageBytes}-byte message limit`, { kind: "message_too_large" });
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
this._output.write(line + "\n");
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
_error(id, code, message, data) {
|
|
381
|
+
const error = { code, message };
|
|
382
|
+
if (data !== undefined) error.data = data;
|
|
383
|
+
this._send({ jsonrpc: "2.0", id, error });
|
|
384
|
+
}
|
|
385
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "graphrt-plugin",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "SDK for writing graphrt plugins in JavaScript / TypeScript (no dependencies)",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./index.mjs",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"import": "./index.mjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"index.mjs",
|
|
17
|
+
"index.d.ts",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "node --test"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/BimaPangestu28/graphrt.git"
|
|
29
|
+
}
|
|
30
|
+
}
|