lampson 0.2.10 → 0.4.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/sdk/index.js ADDED
@@ -0,0 +1,250 @@
1
+ // sdk/index.js — the Lampson SDK for JavaScript/TypeScript (Node 18+, no dependencies).
2
+ //
3
+ // const { Lampson } = require("lampson"); // or: import { Lampson } from "lampson";
4
+ //
5
+ // Two ways to reach Lampson, the same methods for both:
6
+ //
7
+ // SERVER new Lampson({ url: "https://my-lampson.com/w/<workspace>", key: "lk_..." })
8
+ // talks to a running Lampson (the hub, a VPS, Docker) over its HTTP API /v1. Messages go through each
9
+ // conversation's mailbox (queue, quiet window, mid-turn messages), exactly like a channel.
10
+ // LOCAL new Lampson({ local: { workspace: "./my-project" } })
11
+ // starts Lampson ITSELF as a child process on this machine (`lampson run --stdio`): no hub, no port, no
12
+ // key. Lampson inside your program, like SQLite. Different conversations run in parallel; two messages of
13
+ // the same conversation (agent + thread) are answered in order.
14
+ //
15
+ // await lampson.ask({ agent: "shop", thread: "customer-42", text: "do you have whole-wheat bread?" })
16
+ // → { agent, thread, session, text, steps, usage, stopped } (throws LampsonError if the turn failed)
17
+ // for await (const ev of lampson.stream({ ... })) { ... } the agent's steps live, last one kind "done"
18
+ // await lampson.agents() [{ id, description }]
19
+ // await lampson.close() local mode: stops the child process
20
+ // Lampson.verifySignature(rawBody, req.headers["x-lampson-signature"], secret) for callbacks / webhooks
21
+ //
22
+ // Contracts behind it: spec/engine.md (envelope, events), lib/api.syn (HTTP), run.syn (--stdio).
23
+ 'use strict';
24
+ const { spawn } = require('child_process');
25
+ const crypto = require('crypto');
26
+ const path = require('path');
27
+ const readline = require('readline');
28
+
29
+ class LampsonError extends Error {
30
+ constructor(message, details) {
31
+ super(message);
32
+ this.name = 'LampsonError';
33
+ Object.assign(this, details || {});
34
+ }
35
+ }
36
+
37
+ // a message, in the envelope Lampson speaks (spec/engine.md): `agent` is an alias of `to`, `sentAt` of `sent_at`
38
+ function envelope(msg) {
39
+ if (msg == null || typeof msg !== 'object') throw new TypeError('ask/stream take an object: { agent, thread, text }');
40
+ if (typeof msg.text !== 'string' || msg.text.trim() === '') throw new TypeError('text is required');
41
+ const env = { text: msg.text };
42
+ const to = msg.agent || msg.to;
43
+ if (to) env.to = to;
44
+ for (const k of ['thread', 'session', 'images', 'meta', 'from', 'callback', 'mode']) if (msg[k] != null) env[k] = msg[k];
45
+ if (msg.sentAt != null) env.sent_at = msg.sentAt;
46
+ return env;
47
+ }
48
+
49
+ function failed(result) {
50
+ return typeof result.stopped === 'string' && result.stopped.startsWith('error');
51
+ }
52
+
53
+ // ---------- server mode: HTTP API /v1 ----------
54
+
55
+ class HttpTransport {
56
+ constructor({ url, key, fetch: fetchImpl, timeout }) {
57
+ if (!url) throw new TypeError('url is required (e.g. "http://127.0.0.1:8080/w/<workspace>")');
58
+ if (!key) throw new TypeError('key is required (create one with `lampson key add`)');
59
+ this.base = String(url).replace(/\/+$/, '').replace(/\/v1$/, '');
60
+ this.key = key;
61
+ this.fetch = fetchImpl || globalThis.fetch;
62
+ if (!this.fetch) throw new Error('this Node has no fetch: use Node 18+ or pass { fetch }');
63
+ this.timeout = timeout || 15 * 60 * 1000;
64
+ }
65
+ headers(extra) {
66
+ return Object.assign({ Authorization: 'Bearer ' + this.key, 'Content-Type': 'application/json' }, extra || {});
67
+ }
68
+ async request(method, p, body, extraHeaders) {
69
+ const res = await this.fetch(this.base + '/v1' + p, {
70
+ method, headers: this.headers(extraHeaders), body: body == null ? undefined : JSON.stringify(body),
71
+ signal: AbortSignal.timeout(this.timeout),
72
+ });
73
+ return res;
74
+ }
75
+ async json(method, p, body) {
76
+ const res = await this.request(method, p, body);
77
+ const text = await res.text();
78
+ let data;
79
+ try { data = text ? JSON.parse(text) : {}; } catch { data = { error: text }; }
80
+ if (!res.ok) throw new LampsonError((data && data.error) || ('HTTP ' + res.status), { status: res.status, body: data });
81
+ return data;
82
+ }
83
+ async agents() { return (await this.json('GET', '/agents')).agents; }
84
+ async ask(env) { return this.json('POST', '/messages', env); }
85
+ async job(id) { return this.json('GET', '/jobs/' + encodeURIComponent(id)); }
86
+ async *stream(env) {
87
+ const res = await this.request('POST', '/messages/stream', env, { Accept: 'text/event-stream' });
88
+ if (!res.ok) {
89
+ const text = await res.text();
90
+ let data; try { data = JSON.parse(text); } catch { data = { error: text }; }
91
+ throw new LampsonError(data.error || ('HTTP ' + res.status), { status: res.status, body: data });
92
+ }
93
+ const decoder = new TextDecoder();
94
+ let buf = '';
95
+ for await (const chunk of res.body) {
96
+ buf += decoder.decode(chunk, { stream: true });
97
+ let cut;
98
+ // SSE: events separated by a blank line; the payload is in the "data:" lines
99
+ while ((cut = buf.search(/\r?\n\r?\n/)) !== -1) {
100
+ const block = buf.slice(0, cut);
101
+ buf = buf.slice(cut).replace(/^\r?\n\r?\n/, '');
102
+ const data = block.split(/\r?\n/).filter(l => l.startsWith('data:')).map(l => l.slice(5).trimStart()).join('\n');
103
+ if (!data) continue;
104
+ let ev; try { ev = JSON.parse(data); } catch { continue; }
105
+ yield ev;
106
+ if (ev.kind === 'done') return;
107
+ }
108
+ }
109
+ }
110
+ async close() {}
111
+ }
112
+
113
+ // ---------- local mode: `lampson run --stdio` as a child process ----------
114
+
115
+ class LocalTransport {
116
+ constructor({ workspace, home, env, spawn: spawnSpec }) {
117
+ if (!workspace && !spawnSpec) throw new TypeError('local.workspace is required (the project folder the agents work in)');
118
+ let command, args, cwd;
119
+ if (spawnSpec) {
120
+ // advanced / tests: run an exact command that speaks the --stdio protocol
121
+ ({ command, args = [], cwd } = spawnSpec);
122
+ } else {
123
+ // this package's own launcher: same Lampson the CLI runs (lampson.ps1 / lampson.sh), no PATH needed
124
+ command = process.execPath;
125
+ args = [path.join(__dirname, '..', 'bin', 'lampson.js'), 'run', '--stdio', '--workspace', path.resolve(workspace)];
126
+ cwd = path.resolve(workspace);
127
+ }
128
+ const childEnv = Object.assign({}, process.env, env || {});
129
+ if (home) childEnv.LAMPSON_HOME = home;
130
+ this.child = spawn(command, args, { cwd, env: childEnv, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
131
+ this.pending = new Map(); // id → { onEvent, done }
132
+ this.seq = 0;
133
+ this.stderr = [];
134
+ this.exited = null;
135
+ this.ready = new Promise((resolve, reject) => { this._ready = resolve; this._fail = reject; });
136
+ readline.createInterface({ input: this.child.stdout }).on('line', line => this.onLine(line));
137
+ readline.createInterface({ input: this.child.stderr }).on('line', line => {
138
+ this.stderr.push(line);
139
+ if (this.stderr.length > 40) this.stderr.shift();
140
+ });
141
+ this.child.on('error', err => this.onExit(null, err));
142
+ this.child.on('exit', code => this.onExit(code));
143
+ }
144
+ onLine(line) {
145
+ const t = line.trim();
146
+ if (!t.startsWith('{')) return; // launcher notices ("lampson updated…") are not protocol
147
+ let m; try { m = JSON.parse(t); } catch { return; }
148
+ if (m.kind === 'ready') { this.readyInfo = m.data; this._ready(m.data); return; }
149
+ const p = this.pending.get(m.id);
150
+ if (!p) return;
151
+ p.onEvent(m);
152
+ if (m.kind === 'done' || m.kind === 'agents' || m.kind === 'pong' || m.kind === 'error') {
153
+ this.pending.delete(m.id);
154
+ p.done(m);
155
+ }
156
+ }
157
+ onExit(code, err) {
158
+ this.exited = { code, err };
159
+ const why = new LampsonError('lampson exited' + (code != null ? ' with code ' + code : '') + (err ? ': ' + err.message : '') +
160
+ (this.stderr.length ? '\n' + this.stderr.slice(-8).join('\n') : ''), { code, stderr: this.stderr.slice() });
161
+ this._fail(why);
162
+ for (const p of this.pending.values()) p.done(null, why);
163
+ this.pending.clear();
164
+ }
165
+ async send(req, onEvent) {
166
+ await this.ready;
167
+ if (this.exited) throw new LampsonError('lampson is not running');
168
+ const id = 'r' + (++this.seq);
169
+ return new Promise((resolve, reject) => {
170
+ this.pending.set(id, { onEvent: onEvent || (() => {}), done: (m, err) => err ? reject(err) : resolve(m) });
171
+ this.child.stdin.write(JSON.stringify(Object.assign({ id }, req)) + '\n');
172
+ });
173
+ }
174
+ async agents() { return (await this.send({ op: 'agents' })).data; }
175
+ async ask(env) { return (await this.send(Object.assign({ op: 'ask' }, env))).data; }
176
+ async job() { throw new LampsonError('jobs exist only in server mode (callbacks)'); }
177
+ async *stream(env) {
178
+ const queue = [];
179
+ let wake = null;
180
+ let finished = false;
181
+ let error = null;
182
+ this.send(Object.assign({ op: 'ask' }, env), ev => { queue.push(ev); if (wake) wake(); })
183
+ .then(() => { finished = true; if (wake) wake(); }, err => { error = err; finished = true; if (wake) wake(); });
184
+ while (true) {
185
+ if (queue.length) {
186
+ const ev = queue.shift();
187
+ const out = Object.assign({}, ev); delete out.id;
188
+ yield out;
189
+ if (ev.kind === 'done') return;
190
+ continue;
191
+ }
192
+ if (error) throw error;
193
+ if (finished) return;
194
+ await new Promise(r => { wake = r; });
195
+ wake = null;
196
+ }
197
+ }
198
+ async close() {
199
+ if (this.exited) return;
200
+ this.child.stdin.end();
201
+ await new Promise(resolve => {
202
+ if (this.exited) return resolve();
203
+ const t = setTimeout(() => { try { this.child.kill(); } catch {} resolve(); }, 5000);
204
+ this.child.once('exit', () => { clearTimeout(t); resolve(); });
205
+ });
206
+ }
207
+ }
208
+
209
+ class Lampson {
210
+ /**
211
+ * @param {object} opts { url, key } for server mode, or { local: { workspace, home?, env?, spawn? } }
212
+ */
213
+ constructor(opts = {}) {
214
+ this.transport = opts.local ? new LocalTransport(opts.local) : new HttpTransport(opts);
215
+ this.mode = opts.local ? 'local' : 'server';
216
+ }
217
+ /** Send a message to an agent and wait for its answer. Throws LampsonError if the turn ended in an error. */
218
+ async ask(msg) {
219
+ const result = await this.transport.ask(envelope(msg));
220
+ if (result && result.status === 'queued') return result; // server mode with callback: { job, status }
221
+ if (failed(result)) throw new LampsonError(result.stopped, { result });
222
+ return result;
223
+ }
224
+ /** The agent's steps as they happen: session, assistant, tool_call, tool_result…, and "done" last. */
225
+ async *stream(msg) {
226
+ const env = envelope(msg);
227
+ if (env.callback) throw new TypeError('stream does not take a callback (use ask)');
228
+ yield* this.transport.stream(env);
229
+ }
230
+ /** The agents this key (server) or this workspace (local) can use. */
231
+ async agents() { return this.transport.agents(); }
232
+ /** Server mode: status and result of a message sent with a callback. */
233
+ async job(id) { return this.transport.job(id); }
234
+ /** Local mode: stops the Lampson child process. Harmless in server mode. */
235
+ async close() { return this.transport.close(); }
236
+
237
+ /**
238
+ * Checks the X-Lampson-Signature of a callback (or approval webhook): "sha256=" + HMAC-SHA256(rawBody, secret),
239
+ * secret = LAMPSON_WEBHOOK_SECRET of that Lampson. Pass the raw body exactly as received (string or Buffer).
240
+ */
241
+ static verifySignature(rawBody, signature, secret) {
242
+ if (!signature || !secret) return false;
243
+ const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
244
+ const a = Buffer.from(String(signature)), b = Buffer.from(expected);
245
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
246
+ }
247
+ }
248
+
249
+ module.exports = { Lampson, LampsonError };
250
+ module.exports.default = Lampson;
package/sdk/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ // sdk/index.mjs — ESM entry: import { Lampson } from "lampson". Same code as sdk/index.js.
2
+ import sdk from './index.js';
3
+ export const { Lampson, LampsonError } = sdk;
4
+ export default sdk.Lampson;