lampson 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/lampson.ps1 +13 -6
- package/lampson.sh +11 -5
- package/lib/api.syn +46 -2
- package/lib/apikeys.syn +42 -9
- package/lib/apptools.syn +549 -0
- package/lib/loop.syn +13 -0
- package/lib/mailbox.syn +24 -10
- package/lib/mcp_server.syn +6 -5
- package/lib/permission.syn +22 -1
- package/lib/remotetools.syn +76 -0
- package/lib/runtime.syn +157 -9
- package/lib/sdktools.syn +73 -0
- package/lib/session.syn +8 -0
- package/lib/tools/common.syn +5 -0
- package/lib/tools/url.syn +82 -9
- package/lib/workspaces.syn +29 -3
- package/package.json +2 -2
- package/public/css/panel.css +2 -0
- package/public/index.html +2 -0
- package/public/js/apptools.js +63 -0
- package/public/js/panel.js +2 -2
- package/run.syn +87 -6
- package/sdk/index.d.ts +64 -3
- package/sdk/index.js +297 -12
- package/skills/lampson/SKILL.md +15 -0
- package/web.syn +30 -4
package/sdk/index.js
CHANGED
|
@@ -10,13 +10,35 @@
|
|
|
10
10
|
// LOCAL new Lampson({ local: { workspace: "./my-project" } })
|
|
11
11
|
// starts Lampson ITSELF as a child process on this machine (`lampson run --stdio`): no hub, no port, no
|
|
12
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.
|
|
13
|
+
// the same conversation (agent + thread) are answered in order. `home` and `workspace` resolve against
|
|
14
|
+
// process.cwd().
|
|
15
|
+
// An agent that lists a tool it will not have (typo, plugin off) is reported through onWarning
|
|
16
|
+
// (default console.warn, each message once per process) and in lampson.warnings.
|
|
17
|
+
// `lampsonTools: false` → no tool of Lampson's own exists in that process (bash, read, write, fetch…),
|
|
18
|
+
// not even for the built-in agents: your agents get only the tools you give them.
|
|
19
|
+
// A .syn tool runs only once approved (`lampson tools approve`, its sha256); `approveTools: true`
|
|
20
|
+
// approves what is in the folder when Lampson starts — for development, where you edit it.
|
|
21
|
+
// Your own tools in Synsema: one file per tool in <workspace>/.lampson/tools/ (or `tools: "./tools"`,
|
|
22
|
+
// inside the workspace) — `export task <file name>(…)`, an `intent:` line and its `require`s, which are
|
|
23
|
+
// all it can touch. List the name in the agent's "tools". See lampson.org/docs/sdk.
|
|
24
|
+
//
|
|
25
|
+
// lampson.tool("order_status", { description, inputSchema, execute: async (args, ctx) => … }) local mode
|
|
26
|
+
// a function of YOUR app as a tool (the AI SDK shape: zod, a JSON Schema or jsonSchema()). It runs in your
|
|
27
|
+
// process; Lampson asks for it over stdio. `ctx` = {from, thread, agent, session, meta, channel} of the
|
|
28
|
+
// message — set by your app, never seen or written by the model. List the name in the agent's "tools".
|
|
29
|
+
// lampson.tools({ order_status: tool({...}), ... }) registers several (an AI SDK tools object as is).
|
|
30
|
+
// Server mode too: new Lampson({ url, key, toolsUrl: "https://my-app/api/lampson/tools", toolsSecret })
|
|
31
|
+
// sends the tools with each message; Lampson POSTs each call there, signed (RFC 9421) with the key's
|
|
32
|
+
// secret, and lampson.toolsHandler() answers it: export const POST = lampson.toolsHandler().
|
|
33
|
+
//
|
|
34
|
+
// new Lampson({ agent: "support", ... }) the agent that answers when a message does not say `agent`
|
|
35
|
+
// (without it, the workspace default: "build", Lampson's coding agent, with all of Lampson's tools)
|
|
14
36
|
//
|
|
15
37
|
// await lampson.ask({ agent: "shop", thread: "customer-42", text: "do you have whole-wheat bread?" })
|
|
16
38
|
// → { agent, thread, session, text, steps, usage, stopped } (throws LampsonError if the turn failed)
|
|
17
39
|
// for await (const ev of lampson.stream({ ... })) { ... } the agent's steps live, last one kind "done"
|
|
18
40
|
// await lampson.agents() [{ id, description }]
|
|
19
|
-
// await lampson.close() local mode: stops the child process
|
|
41
|
+
// await lampson.close() local mode: stops the child process (and its own)
|
|
20
42
|
// Lampson.verifySignature(rawBody, req.headers["x-lampson-signature"], secret) for callbacks / webhooks
|
|
21
43
|
//
|
|
22
44
|
// Contracts behind it: spec/engine.md (envelope, events), lib/api.syn (HTTP), run.syn (--stdio).
|
|
@@ -112,8 +134,133 @@ class HttpTransport {
|
|
|
112
134
|
|
|
113
135
|
// ---------- local mode: `lampson run --stdio` as a child process ----------
|
|
114
136
|
|
|
137
|
+
// ---------- your app's functions as tools (local mode) ----------
|
|
138
|
+
|
|
139
|
+
const TOOL_NAME = /^[a-z][a-z0-9_]{0,39}$/;
|
|
140
|
+
const TAKEN = ['read', 'write', 'edit', 'ls', 'find', 'grep', 'lsp', 'fetch', 'bash', 'process', 'memory', 'todo', 'skill', 'mcp', 'plugin', 'schedule', 'computer_use', 'delegate', 'send', 'board', 'objective'];
|
|
141
|
+
|
|
142
|
+
// zod 3 has no toJSONSchema: the common shapes from its _def (typeName), without adding zod-to-json-schema. Anything
|
|
143
|
+
// else (unions, records, refinements…) → null, and the caller says how to fix it
|
|
144
|
+
function zod3Schema(s) {
|
|
145
|
+
const d = s && s._def;
|
|
146
|
+
if (!d || typeof d.typeName !== 'string') return null;
|
|
147
|
+
const desc = x => (d.description ? Object.assign(x, { description: d.description }) : x);
|
|
148
|
+
switch (d.typeName) {
|
|
149
|
+
case 'ZodString': return desc({ type: 'string' });
|
|
150
|
+
case 'ZodNumber': return desc({ type: (d.checks || []).some(c => c.kind === 'int') ? 'integer' : 'number' });
|
|
151
|
+
case 'ZodBoolean': return desc({ type: 'boolean' });
|
|
152
|
+
case 'ZodEnum': return desc({ type: 'string', enum: d.values });
|
|
153
|
+
case 'ZodArray': { const it = zod3Schema(d.type); return it && desc({ type: 'array', items: it }); }
|
|
154
|
+
case 'ZodNullable': { const it = zod3Schema(d.innerType); return it && desc({ anyOf: [it, { type: 'null' }] }); }
|
|
155
|
+
case 'ZodOptional': case 'ZodDefault': { const it = zod3Schema(d.innerType); return it && (d.description ? desc(it) : it); }
|
|
156
|
+
case 'ZodObject': {
|
|
157
|
+
const shape = typeof d.shape === 'function' ? d.shape() : d.shape;
|
|
158
|
+
const properties = {}, required = [];
|
|
159
|
+
for (const [k, v] of Object.entries(shape || {})) {
|
|
160
|
+
const it = zod3Schema(v);
|
|
161
|
+
if (!it) return null;
|
|
162
|
+
properties[k] = it;
|
|
163
|
+
const t = v._def.typeName;
|
|
164
|
+
if (t !== 'ZodOptional' && t !== 'ZodDefault') required.push(k);
|
|
165
|
+
}
|
|
166
|
+
return desc(Object.assign({ type: 'object', properties }, required.length ? { required } : {}));
|
|
167
|
+
}
|
|
168
|
+
default: return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// a JSON Schema from what the AI SDK world passes: jsonSchema(...) wrappers, zod (v4: z.toJSONSchema; v3: its
|
|
173
|
+
// zod-to-json-schema if the app has it, else zod3Schema) or a plain JSON Schema object
|
|
174
|
+
function toJsonSchema(s, name) {
|
|
175
|
+
if (s == null) return { type: 'object', properties: {} };
|
|
176
|
+
if (s.jsonSchema && typeof s.jsonSchema === 'object') return s.jsonSchema;
|
|
177
|
+
if (typeof s.toJSONSchema === 'function') return s.toJSONSchema();
|
|
178
|
+
if (s._zod || s._def) {
|
|
179
|
+
const { createRequire } = require('module');
|
|
180
|
+
const req = createRequire(path.join(process.cwd(), 'noop.js'));
|
|
181
|
+
try { const z = req('zod'); if (typeof z.toJSONSchema === 'function') return z.toJSONSchema(s); } catch {}
|
|
182
|
+
try { return req('zod-to-json-schema').zodToJsonSchema(s); } catch {}
|
|
183
|
+
const own = zod3Schema(s);
|
|
184
|
+
if (own) return own;
|
|
185
|
+
throw new TypeError('tool ' + name + ': cannot turn this zod schema into JSON Schema (zod 3 here covers object, string, number, boolean, enum, array, optional, nullable and describe; for the rest use zod 4, or install zod-to-json-schema), or pass `parameters` as a JSON Schema');
|
|
186
|
+
}
|
|
187
|
+
if (typeof s === 'object') return s;
|
|
188
|
+
throw new TypeError('tool ' + name + ': inputSchema/parameters must be a zod schema or a JSON Schema object');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function toolSpec(name, def) {
|
|
192
|
+
if (!TOOL_NAME.test(name || '')) throw new TypeError('tool name "' + name + '": lowercase letters, digits and _ (max 40), starting with a letter');
|
|
193
|
+
if (TAKEN.includes(name)) throw new TypeError('tool name "' + name + '" is a name Lampson already uses');
|
|
194
|
+
if (!def || typeof def.execute !== 'function') throw new TypeError('tool ' + name + ': needs execute(args, ctx)');
|
|
195
|
+
const schema = def.inputSchema || def.parameters;
|
|
196
|
+
return {
|
|
197
|
+
wire: { name, description: String(def.description || ''), parameters: toJsonSchema(schema, name), timeout: def.timeout },
|
|
198
|
+
schema, execute: def.execute,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// run one of your tools: what the model wrote is validated by a zod inputSchema before your code sees it; the
|
|
203
|
+
// answer is {output} or {error}, the same over stdio (local) and over HTTP (server)
|
|
204
|
+
async function executeTool(t, name, args, ctx) {
|
|
205
|
+
if (!t) return { error: 'the app has no tool ' + name };
|
|
206
|
+
try {
|
|
207
|
+
let input = args || {};
|
|
208
|
+
if (t.schema && typeof t.schema.safeParse === 'function') {
|
|
209
|
+
const v = t.schema.safeParse(input);
|
|
210
|
+
if (!v.success) return { error: 'invalid arguments for ' + name + ': ' + ((v.error && v.error.message) || 'schema mismatch') };
|
|
211
|
+
input = v.data;
|
|
212
|
+
}
|
|
213
|
+
const out = await t.execute(input, Object.freeze(Object.assign({}, ctx || {})));
|
|
214
|
+
return { output: out === undefined ? null : out };
|
|
215
|
+
} catch (e) {
|
|
216
|
+
return { error: (e && e.message) || String(e) };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// the RFC 9421 profile Synsema's http_sign uses: @method, @target-uri, content-digest; created, keyid, alg=hmac-sha256
|
|
221
|
+
function headerOf(headers, name) {
|
|
222
|
+
if (!headers) return '';
|
|
223
|
+
if (typeof headers.get === 'function') return headers.get(name) || '';
|
|
224
|
+
for (const k of Object.keys(headers)) if (k.toLowerCase() === name) return String(headers[k]);
|
|
225
|
+
return '';
|
|
226
|
+
}
|
|
227
|
+
function verifyToolRequest({ method, url, headers, body }, secret, opts = {}) {
|
|
228
|
+
if (!secret) return null;
|
|
229
|
+
const input = headerOf(headers, 'signature-input'), sigh = headerOf(headers, 'signature'), dig = headerOf(headers, 'content-digest');
|
|
230
|
+
const mi = /^sig1=(\("@method" "@target-uri" "content-digest"\);created=(\d+);keyid="([^"]*)";alg="hmac-sha256")$/.exec(input);
|
|
231
|
+
const ms = /^sig1=:([A-Za-z0-9+/=]+):$/.exec(sigh);
|
|
232
|
+
if (!mi || !ms) return null;
|
|
233
|
+
const created = Number(mi[2]);
|
|
234
|
+
const now = opts.now != null ? opts.now : Math.floor(Date.now() / 1000);
|
|
235
|
+
if (Math.abs(now - created) > 300) return null; // ±300 s, like http_signature_verify
|
|
236
|
+
const raw = Buffer.isBuffer(body) ? body : Buffer.from(String(body == null ? '' : body), 'utf8');
|
|
237
|
+
const wantDigest = 'sha-256=:' + crypto.createHash('sha256').update(raw).digest('base64') + ':';
|
|
238
|
+
if (dig !== wantDigest) return null;
|
|
239
|
+
const base = ['"@method": ' + String(method || 'POST').toUpperCase(), '"@target-uri": ' + url, '"content-digest": ' + dig, '"@signature-params": ' + mi[1]].join('\n');
|
|
240
|
+
const want = crypto.createHmac('sha256', secret).update(base).digest();
|
|
241
|
+
const got = Buffer.from(ms[1], 'base64');
|
|
242
|
+
if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) return null;
|
|
243
|
+
return { keyid: mi[3], created };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function readNodeBody(req) {
|
|
247
|
+
if (req.body != null && (typeof req.body === 'string' || Buffer.isBuffer(req.body))) return req.body;
|
|
248
|
+
if (req.body != null && typeof req.body === 'object' && req.readableEnded) throw new Error('the body was already parsed as JSON: mount toolsHandler() before express.json(), or use express.raw()');
|
|
249
|
+
const chunks = [];
|
|
250
|
+
for await (const c of req) chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c));
|
|
251
|
+
return Buffer.concat(chunks);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function killTree(child) {
|
|
255
|
+
try {
|
|
256
|
+
if (process.platform === 'win32') spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
257
|
+
// Linux/Mac: the child leads its own process group (spawn detached), so -pid reaches the launcher, npx and synsema
|
|
258
|
+
else { try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); } }
|
|
259
|
+
} catch {}
|
|
260
|
+
}
|
|
261
|
+
|
|
115
262
|
class LocalTransport {
|
|
116
|
-
constructor({ workspace, home, env, spawn: spawnSpec }) {
|
|
263
|
+
constructor({ workspace, home, env, lampsonTools, tools, approveTools, spawn: spawnSpec }, onWarning) {
|
|
117
264
|
if (!workspace && !spawnSpec) throw new TypeError('local.workspace is required (the project folder the agents work in)');
|
|
118
265
|
let command, args, cwd;
|
|
119
266
|
if (spawnSpec) {
|
|
@@ -126,8 +273,24 @@ class LocalTransport {
|
|
|
126
273
|
cwd = path.resolve(workspace);
|
|
127
274
|
}
|
|
128
275
|
const childEnv = Object.assign({}, process.env, env || {});
|
|
129
|
-
|
|
130
|
-
|
|
276
|
+
// relative to the app, not to the workspace (the launcher runs with cwd = workspace): a relative home ended up
|
|
277
|
+
// inside the project (2026-10-18)
|
|
278
|
+
if (home) childEnv.LAMPSON_HOME = path.resolve(home);
|
|
279
|
+
if (lampsonTools === false) childEnv.LAMPSON_BUILTIN_TOOLS = 'off';
|
|
280
|
+
// you edit the .syn tools yourself: approve what is in the folder when it starts (never on a server: there a
|
|
281
|
+
// person runs `lampson tools approve`, so an agent that rewrites a tool cannot raise its own ceiling)
|
|
282
|
+
if (approveTools === true) childEnv.LAMPSON_APPROVE_TOOLS = '1';
|
|
283
|
+
if (tools) {
|
|
284
|
+
// the tools folder lives in the project (Lampson only reads inside it): pass it relative to the workspace
|
|
285
|
+
const rel = path.relative(path.resolve(workspace || '.'), path.resolve(tools)).split(path.sep).join('/');
|
|
286
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new TypeError('local.tools must be a folder inside local.workspace, got ' + tools);
|
|
287
|
+
childEnv.LAMPSON_TOOLS_DIR = rel;
|
|
288
|
+
}
|
|
289
|
+
this.warnings = [];
|
|
290
|
+
this.onWarning = onWarning;
|
|
291
|
+
this.tools = new Map(); // name → { wire, schema, execute }
|
|
292
|
+
// detached on Linux/Mac = its own process group, for killTree (on Windows it would open a console; taskkill /T there)
|
|
293
|
+
this.child = spawn(command, args, { cwd, env: childEnv, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' });
|
|
131
294
|
this.pending = new Map(); // id → { onEvent, done }
|
|
132
295
|
this.seq = 0;
|
|
133
296
|
this.stderr = [];
|
|
@@ -145,15 +308,45 @@ class LocalTransport {
|
|
|
145
308
|
const t = line.trim();
|
|
146
309
|
if (!t.startsWith('{')) return; // launcher notices ("lampson updated…") are not protocol
|
|
147
310
|
let m; try { m = JSON.parse(t); } catch { return; }
|
|
148
|
-
if (m.kind === 'ready') {
|
|
311
|
+
if (m.kind === 'ready') {
|
|
312
|
+
this.readyInfo = m.data;
|
|
313
|
+
for (const w of (m.data && m.data.warnings) || []) this.warn(w);
|
|
314
|
+
this._ready(m.data);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (m.kind === 'warning') this.warn(m.data);
|
|
318
|
+
if (m.kind === 'tool_request') { this.runTool(m.data || {}); return; }
|
|
319
|
+
if (m.kind === 'tools') { for (const e of (m.data && m.data.errors) || []) this.warn(e); return; }
|
|
149
320
|
const p = this.pending.get(m.id);
|
|
150
321
|
if (!p) return;
|
|
151
322
|
p.onEvent(m);
|
|
152
|
-
|
|
323
|
+
// an "error" inside a turn (it carries agent) is one more step: "done" still follows. Only the protocol's own
|
|
324
|
+
// error (bad line, unknown op) closes the request
|
|
325
|
+
if (m.kind === 'done' || m.kind === 'agents' || m.kind === 'pong' || (m.kind === 'error' && !('agent' in m))) {
|
|
153
326
|
this.pending.delete(m.id);
|
|
154
327
|
p.done(m);
|
|
155
328
|
}
|
|
156
329
|
}
|
|
330
|
+
warn(w) {
|
|
331
|
+
if (this.warnings.includes(w)) return; // ready lists them all; each ask repeats its agent's
|
|
332
|
+
// "tool 'x' is not available" for a tool this app registers (ready can come before lampson.tool()) is not real
|
|
333
|
+
const mt = /tool '([a-z0-9_]+)' is not available: no Lampson tool/.exec(w);
|
|
334
|
+
if (mt && this.tools.has(mt[1])) return;
|
|
335
|
+
this.warnings.push(w);
|
|
336
|
+
if (this.onWarning) this.onWarning(w);
|
|
337
|
+
}
|
|
338
|
+
setTools(list) {
|
|
339
|
+
for (const t of list) this.tools.set(t.wire.name, t);
|
|
340
|
+
// a warning about a tool that now exists is no longer true
|
|
341
|
+
this.warnings = this.warnings.filter(w => { const mt = /tool '([a-z0-9_]+)' is not available: no Lampson tool/.exec(w); return !(mt && this.tools.has(mt[1])); });
|
|
342
|
+
if (this.exited) throw new LampsonError('lampson is not running');
|
|
343
|
+
// no pending entry: the answer ("tools") only carries errors, handled in onLine
|
|
344
|
+
this.child.stdin.write(JSON.stringify({ id: 't' + (++this.seq), op: 'tools', tools: [...this.tools.values()].map(t => t.wire) }) + '\n');
|
|
345
|
+
}
|
|
346
|
+
async runTool({ call_id, name, args, ctx }) {
|
|
347
|
+
const reply = r => { if (!this.exited) this.child.stdin.write(JSON.stringify(Object.assign({ op: 'tool_result', call_id }, r)) + '\n'); };
|
|
348
|
+
reply(await executeTool(this.tools.get(name), name, args, ctx));
|
|
349
|
+
}
|
|
157
350
|
onExit(code, err) {
|
|
158
351
|
this.exited = { code, err };
|
|
159
352
|
const why = new LampsonError('lampson exited' + (code != null ? ' with code ' + code : '') + (err ? ': ' + err.message : '') +
|
|
@@ -200,33 +393,122 @@ class LocalTransport {
|
|
|
200
393
|
this.child.stdin.end();
|
|
201
394
|
await new Promise(resolve => {
|
|
202
395
|
if (this.exited) return resolve();
|
|
203
|
-
|
|
396
|
+
// the child is a launcher (node → shell → synsema): kill the whole tree, or synsema outlives it
|
|
397
|
+
const t = setTimeout(() => { killTree(this.child); resolve(); }, 5000);
|
|
204
398
|
this.child.once('exit', () => { clearTimeout(t); resolve(); });
|
|
205
399
|
});
|
|
206
400
|
}
|
|
207
401
|
}
|
|
208
402
|
|
|
403
|
+
// the default onWarning: each distinct message once per process (ready lists them, and every new Lampson, or a
|
|
404
|
+
// restarted one, would print them again). The stream's `warning` events are data for the app and do not change
|
|
405
|
+
const shownWarnings = new Set();
|
|
406
|
+
function defaultWarning(w) {
|
|
407
|
+
if (shownWarnings.has(w)) return;
|
|
408
|
+
shownWarnings.add(w);
|
|
409
|
+
console.warn('lampson: ' + w);
|
|
410
|
+
}
|
|
411
|
+
|
|
209
412
|
class Lampson {
|
|
210
413
|
/**
|
|
211
|
-
* @param {object} opts { url, key } for server mode, or
|
|
414
|
+
* @param {object} opts { url, key, toolsUrl?, toolsSecret? } for server mode, or
|
|
415
|
+
* { local: { workspace, home?, env?, lampsonTools?, tools?, spawn? } };
|
|
416
|
+
* agent? — the default agent; onWarning?(message) — default console.warn, each message once per process
|
|
212
417
|
*/
|
|
213
418
|
constructor(opts = {}) {
|
|
214
|
-
|
|
419
|
+
const onWarning = opts.onWarning === undefined ? defaultWarning : opts.onWarning;
|
|
420
|
+
this.transport = opts.local ? new LocalTransport(opts.local, onWarning) : new HttpTransport(opts);
|
|
215
421
|
this.mode = opts.local ? 'local' : 'server';
|
|
422
|
+
this.agent = opts.agent || '';
|
|
423
|
+
// server mode: your tools travel with each message and Lampson POSTs the calls to toolsUrl (the PUBLIC URL of
|
|
424
|
+
// toolsHandler(), the one Lampson signs); toolsSecret = the key's signing secret from `lampson key add`
|
|
425
|
+
this.toolsUrl = opts.toolsUrl || '';
|
|
426
|
+
this.toolsSecret = opts.toolsSecret || '';
|
|
427
|
+
this.serverTools = new Map();
|
|
428
|
+
this.seenCalls = new Map(); // call_id → ms until it can be forgotten (toolsHandler: replays answer 409)
|
|
429
|
+
}
|
|
430
|
+
withAgent(msg) {
|
|
431
|
+
return this.agent && msg && typeof msg === 'object' && !msg.agent && !msg.to ? Object.assign({}, msg, { agent: this.agent }) : msg;
|
|
432
|
+
}
|
|
433
|
+
withTools(env) {
|
|
434
|
+
if (this.mode !== 'server' || this.serverTools.size === 0) return env;
|
|
435
|
+
return Object.assign({}, env, { tools: [...this.serverTools.values()].map(t => t.wire), tools_url: this.toolsUrl });
|
|
436
|
+
}
|
|
437
|
+
addTools(specs) {
|
|
438
|
+
if (this.mode === 'local') return this.transport.setTools(specs);
|
|
439
|
+
if (!this.toolsUrl) throw new LampsonError('server mode: pass toolsUrl (the public URL of lampson.toolsHandler()) to register tools, or write them in Synsema: .lampson/tools/<name>.syn');
|
|
440
|
+
for (const t of specs) this.serverTools.set(t.wire.name, t);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Server mode: the endpoint Lampson POSTs your tool calls to. Verifies the signature (RFC 9421, the key's
|
|
444
|
+
* toolsSecret, ±300 s), runs the tool and answers {output} | {error}. Web standard (Next route handler, Hono, Bun,
|
|
445
|
+
* Deno: POST = lampson.toolsHandler()) or Node (Express: app.post(path, lampson.toolsHandler()); http.createServer).
|
|
446
|
+
*/
|
|
447
|
+
toolsHandler(opts = {}) {
|
|
448
|
+
// seen(callId) → true if it already ran (and records it if not). Default: a Map in this process. With several
|
|
449
|
+
// instances (serverless, workers) pass a shared one: Redis `SET call:<id> 1 NX EX 600` → !ok
|
|
450
|
+
const seen = typeof opts.seen === 'function' ? opts.seen : (id => {
|
|
451
|
+
const now = Date.now();
|
|
452
|
+
for (const [k, until] of this.seenCalls) if (until < now) this.seenCalls.delete(k);
|
|
453
|
+
if (this.seenCalls.has(id)) return true;
|
|
454
|
+
this.seenCalls.set(id, now + 600000);
|
|
455
|
+
return false;
|
|
456
|
+
});
|
|
457
|
+
const answer = async (method, headers, body) => {
|
|
458
|
+
const v = verifyToolRequest({ method, url: this.toolsUrl, headers, body }, this.toolsSecret);
|
|
459
|
+
if (!v) return [401, { error: 'invalid or missing Lampson signature' }];
|
|
460
|
+
let msg;
|
|
461
|
+
try { msg = JSON.parse(Buffer.isBuffer(body) ? body.toString('utf8') : String(body)); } catch { return [400, { error: 'body must be JSON' }]; }
|
|
462
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return [400, { error: 'body must be a JSON object' }];
|
|
463
|
+
// the signature is valid for ±300 s: a captured request replayed in that window would run the tool again
|
|
464
|
+
// (the one that charges). Each call_id runs once — per process unless opts.seen is shared
|
|
465
|
+
if (msg.call_id != null) {
|
|
466
|
+
let dup;
|
|
467
|
+
// a fixed message: this text reaches the model, and a store's error can carry its host or password
|
|
468
|
+
try { dup = await seen(String(msg.call_id)); } catch (e) { console.error('lampson: seen failed:', e); return [503, { error: 'cannot check call_id: not run' }]; }
|
|
469
|
+
if (dup) return [409, { error: 'call_id ' + msg.call_id + ' already ran' }];
|
|
470
|
+
}
|
|
471
|
+
return [200, await executeTool(this.serverTools.get(msg.name), msg.name, msg.args, msg.ctx)];
|
|
472
|
+
};
|
|
473
|
+
return async (req, res) => {
|
|
474
|
+
if (res && typeof res.setHeader === 'function') { // Node: Express, http.createServer
|
|
475
|
+
let status, out;
|
|
476
|
+
try { [status, out] = await answer(req.method, req.headers, await readNodeBody(req)); } catch (e) { [status, out] = [400, { error: e.message }]; }
|
|
477
|
+
res.statusCode = status; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(out));
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const [status, out] = await answer(req.method, req.headers, Buffer.from(await req.arrayBuffer()));
|
|
481
|
+
return new Response(JSON.stringify(out), { status, headers: { 'Content-Type': 'application/json' } });
|
|
482
|
+
};
|
|
216
483
|
}
|
|
217
484
|
/** Send a message to an agent and wait for its answer. Throws LampsonError if the turn ended in an error. */
|
|
218
485
|
async ask(msg) {
|
|
219
|
-
const result = await this.transport.ask(envelope(msg));
|
|
486
|
+
const result = await this.transport.ask(this.withTools(envelope(this.withAgent(msg))));
|
|
220
487
|
if (result && result.status === 'queued') return result; // server mode with callback: { job, status }
|
|
221
488
|
if (failed(result)) throw new LampsonError(result.stopped, { result });
|
|
222
489
|
return result;
|
|
223
490
|
}
|
|
224
491
|
/** The agent's steps as they happen: session, assistant, tool_call, tool_result…, and "done" last. */
|
|
225
492
|
async *stream(msg) {
|
|
226
|
-
const env = envelope(msg);
|
|
493
|
+
const env = this.withTools(envelope(this.withAgent(msg)));
|
|
227
494
|
if (env.callback) throw new TypeError('stream does not take a callback (use ask)');
|
|
228
495
|
yield* this.transport.stream(env);
|
|
229
496
|
}
|
|
497
|
+
/**
|
|
498
|
+
* Local mode: a function of your app as a tool. The AI SDK shape: { description, inputSchema (zod or JSON Schema)
|
|
499
|
+
* or parameters, execute(args, ctx), timeout? (s, default 60) }. List its name in the agent's "tools".
|
|
500
|
+
*/
|
|
501
|
+
tool(name, def) {
|
|
502
|
+
this.addTools([toolSpec(name, def)]);
|
|
503
|
+
return this;
|
|
504
|
+
}
|
|
505
|
+
/** Several at once: { name: { description, inputSchema, execute } } — an AI SDK tools object works as is. */
|
|
506
|
+
tools(map) {
|
|
507
|
+
this.addTools(Object.entries(map || {}).map(([n, d]) => toolSpec(n, d)));
|
|
508
|
+
return this;
|
|
509
|
+
}
|
|
510
|
+
/** Local mode: tools some agent lists but will not have (plugin off, typo), one message each. */
|
|
511
|
+
get warnings() { return this.transport.warnings || []; }
|
|
230
512
|
/** The agents this key (server) or this workspace (local) can use. */
|
|
231
513
|
async agents() { return this.transport.agents(); }
|
|
232
514
|
/** Server mode: status and result of a message sent with a callback. */
|
|
@@ -238,6 +520,9 @@ class Lampson {
|
|
|
238
520
|
* Checks the X-Lampson-Signature of a callback (or approval webhook): "sha256=" + HMAC-SHA256(rawBody, secret),
|
|
239
521
|
* secret = LAMPSON_WEBHOOK_SECRET of that Lampson. Pass the raw body exactly as received (string or Buffer).
|
|
240
522
|
*/
|
|
523
|
+
/** Checks a tool request's RFC 9421 signature by hand (toolsHandler() does it for you) → {keyid, created} | null. */
|
|
524
|
+
static verifyToolRequest(req, secret, opts) { return verifyToolRequest(req, secret, opts); }
|
|
525
|
+
|
|
241
526
|
static verifySignature(rawBody, signature, secret) {
|
|
242
527
|
if (!signature || !secret) return false;
|
|
243
528
|
const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
|
package/skills/lampson/SKILL.md
CHANGED
|
@@ -115,6 +115,21 @@ the terminal button and run `npm run dev`), then tell me the URL".
|
|
|
115
115
|
- Save what you would otherwise rediscover: how to run/test, env quirks, decisions, where things live,
|
|
116
116
|
root causes of bugs. Update notes instead of contradicting them. The user can read and edit them.
|
|
117
117
|
|
|
118
|
+
## App tools (`.lampson/tools/*.syn`) — when the user asks you to write one
|
|
119
|
+
- One file per tool in `workspace/.lampson/tools/<name>.syn`: an `intent: "…"` line (the description the model
|
|
120
|
+
sees), its `require` lines AT THE TOP (all it can touch: `net("api.x.com")`, `env("STRIPE_KEY")`…) and
|
|
121
|
+
`export task <name>(…)` with the file's name. A default makes a parameter optional. Helpers start with `_`.
|
|
122
|
+
- `env(…)` only with exact names; `LAMPSON_*` is Lampson's, except `env("LAMPSON_CTX")`, which gives the trusted
|
|
123
|
+
context (`from`, `thread`, `meta`…) that the app set — use it to decide what each customer may see, never trust
|
|
124
|
+
an id the model wrote in the arguments.
|
|
125
|
+
- Writing anywhere under `.lampson/` asks the user (in `strict` it is denied). And a tool only runs once the
|
|
126
|
+
USER approved that exact content (`lampson tools approve` or *herramientas* in the web header): after you
|
|
127
|
+
write or change one, tell them to review and approve it — any unapproved `.syn` in the folder stops all of
|
|
128
|
+
them. Never try to approve it yourself or touch `apptools_approved.json`.
|
|
129
|
+
- No links to other folders inside it; limits: 1 MB per file, 5 MB in total, 500 `.syn`.
|
|
130
|
+
- Test it with `synsema test .lampson/tools/<name>.syn` (its `test` blocks). Paths ending in `.` or a space,
|
|
131
|
+
with `~` + digit, or with `:` are rejected by the file tools (Windows aliases): use the plain name.
|
|
132
|
+
|
|
118
133
|
## Sessions and memory
|
|
119
134
|
- The whole history — including every tool result, error and DENIED message — is persisted in
|
|
120
135
|
`.lampson/sessions/<id>.json` and resent to you each turn, so you know exactly what happened.
|
package/web.syn
CHANGED
|
@@ -30,6 +30,8 @@ require random
|
|
|
30
30
|
require env("LAMPSON_*")
|
|
31
31
|
require env("OS")
|
|
32
32
|
require secret("LAMPSON_*")
|
|
33
|
+
-- firmar los pedidos a las funciones de la app en modo servidor (lib/remotetools.syn, http_sign RFC 9421)
|
|
34
|
+
require sign("LAMPSON_TOOLS")
|
|
33
35
|
require db(".lampson/teams.db")
|
|
34
36
|
require judge
|
|
35
37
|
require file("workspace")
|
|
@@ -61,6 +63,7 @@ use "./lib/settings.syn" as settings
|
|
|
61
63
|
use "./lib/trace.syn" as trace
|
|
62
64
|
use "./lib/mcp.syn" as mcp
|
|
63
65
|
use "./lib/plugins.syn" as plugins
|
|
66
|
+
use "./lib/apptools.syn" as apptools
|
|
64
67
|
use "./lib/lsp.syn" as lsp
|
|
65
68
|
use "./lib/tools/todo.syn" as todo
|
|
66
69
|
use "./lib/schedule.syn" as schedule
|
|
@@ -171,7 +174,7 @@ serve on 8080
|
|
|
171
174
|
describe
|
|
172
175
|
about: "Lampson API — agents of this workspace for your apps, channels and other agents"
|
|
173
176
|
version: "1.0.0"
|
|
174
|
-
api: ["POST /w/:slug/v1/messages -- send a message to an agent and get its answer (JSON); with \"callback\", 202 now and the answer POSTed later. Body: {to, thread, text, images?, from?, meta?, sent_at?, session?, callback?}", "POST /w/:slug/v1/messages/stream -- the same, as Server-Sent Events: session, the agent's steps, done", "GET /w/:slug/v1/agents -- the agents this API key can use", "GET /w/:slug/v1/jobs/:id -- status and result of a message sent with a callback", "POST /w/:slug/v1/mcp -- Model Context Protocol (Streamable HTTP, JSON responses): tools ask, agents and history, for other AI agents", "POST /w/:slug/v1/mcp/stream -- the same MCP server answering with Server-Sent Events: with params._meta.progressToken, each step of the agent arrives as notifications/progress before the result", "GET /w/:slug/v1/mcp -- 405: this MCP server opens no server-to-client stream", "POST /w/:slug/v1/objectives -- give an agent (or a team) an objective to work on by itself until done; it plans on a board, works in rounds and asks before anything irreversible. Body: {text, agent? | team?, budget_tokens?, round_seconds?}", "GET /w/:slug/v1/objectives -- the objectives this API key can see", "GET /w/:slug/v1/objectives/:id -- one objective: status, last report, question or approval it waits for, result, board and record", "POST /w/:slug/v1/objectives/:id/reply -- answer its question, or approve/deny what it asked: {text?, approved?}", "POST /w/:slug/v1/objectives/:id/cancel -- stop it"]
|
|
177
|
+
api: ["POST /w/:slug/v1/messages -- send a message to an agent and get its answer (JSON); with \"callback\", 202 now and the answer POSTed later. Body: {to, thread, text, images?, from?, meta?, sent_at?, session?, callback?, tools?, tools_url?} — tools: your app's functions [{name, description, parameters, timeout?}], called with a signed POST to tools_url", "POST /w/:slug/v1/messages/stream -- the same, as Server-Sent Events: session, the agent's steps, done", "GET /w/:slug/v1/agents -- the agents this API key can use", "GET /w/:slug/v1/jobs/:id -- status and result of a message sent with a callback", "POST /w/:slug/v1/mcp -- Model Context Protocol (Streamable HTTP, JSON responses): tools ask, agents and history, for other AI agents", "POST /w/:slug/v1/mcp/stream -- the same MCP server answering with Server-Sent Events: with params._meta.progressToken, each step of the agent arrives as notifications/progress before the result", "GET /w/:slug/v1/mcp -- 405: this MCP server opens no server-to-client stream", "POST /w/:slug/v1/objectives -- give an agent (or a team) an objective to work on by itself until done; it plans on a board, works in rounds and asks before anything irreversible. Body: {text, agent? | team?, budget_tokens?, round_seconds?}", "GET /w/:slug/v1/objectives -- the objectives this API key can see", "GET /w/:slug/v1/objectives/:id -- one objective: status, last report, question or approval it waits for, result, board and record", "POST /w/:slug/v1/objectives/:id/reply -- answer its question, or approve/deny what it asked: {text?, approved?}", "POST /w/:slug/v1/objectives/:id/cancel -- stop it"]
|
|
175
178
|
|
|
176
179
|
-- la UI vive bajo /w/<slug> (BASE en js/core.js); si alguien entra por el puerto del proceso, es lo mismo
|
|
177
180
|
-- Acceso DIRECTO por el puerto del proceso (sin X-Forwarded-Host, que solo agrega el hub al proxyear): la UI se
|
|
@@ -443,6 +446,29 @@ serve on 8080
|
|
|
443
446
|
recover err
|
|
444
447
|
give fail(400, text(err))
|
|
445
448
|
|
|
449
|
+
-- herramientas .syn del proyecto (lib/apptools.syn): ver cada archivo, su código y su techo, y aprobarlo. Solo la
|
|
450
|
+
-- persona: el agente no tiene ninguna tool que llegue acá
|
|
451
|
+
route "GET /w/:slug/api/apptools" requires auth
|
|
452
|
+
private
|
|
453
|
+
give apptools.summary()
|
|
454
|
+
|
|
455
|
+
route "GET /w/:slug/api/apptools/source" requires auth
|
|
456
|
+
private
|
|
457
|
+
let f be when contains(query, "file") then text(query.file) otherwise ""
|
|
458
|
+
try
|
|
459
|
+
give {"file": f, "text": apptools.source(f)}
|
|
460
|
+
recover err
|
|
461
|
+
give fail(400, text(err))
|
|
462
|
+
|
|
463
|
+
route "POST /w/:slug/api/apptools/approve" requires auth
|
|
464
|
+
private
|
|
465
|
+
let b be json of request
|
|
466
|
+
let n be when contains(b, "name") then text(b["name"]) otherwise ""
|
|
467
|
+
try
|
|
468
|
+
give {"ok": true, "approved": apptools.approve(n), "summary": apptools.summary()}
|
|
469
|
+
recover err
|
|
470
|
+
give fail(400, text(err))
|
|
471
|
+
|
|
446
472
|
route "POST /w/:slug/api/plugins/toggle" requires auth
|
|
447
473
|
private
|
|
448
474
|
expect body {name: text}
|
|
@@ -841,7 +867,7 @@ serve on 8080
|
|
|
841
867
|
let offered be apply((x) => x["id"], api.agents_for(a["key"]))
|
|
842
868
|
when length(offered) == 0
|
|
843
869
|
give fail(403, "this API key has no agents")
|
|
844
|
-
let resp be mcp_server.handle(json of request, offered, api.mcp_deliver)
|
|
870
|
+
let resp be mcp_server.handle(json of request, offered, api.mcp_deliver, api.space_of(a["key"]))
|
|
845
871
|
when resp == nothing
|
|
846
872
|
give respond("", "application/json", 202)
|
|
847
873
|
give resp
|
|
@@ -882,14 +908,14 @@ serve on 8080
|
|
|
882
908
|
set result to r
|
|
883
909
|
state_delete("mb:res:" + mid)
|
|
884
910
|
bus_unsubscribe(sub)
|
|
885
|
-
give when result == nothing then {"agent": sobre["to"], "thread": sobre["thread"], "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: timed out"} otherwise result
|
|
911
|
+
give when result == nothing then {"agent": sobre["to"], "thread": get(sobre, "shown_thread", sobre["thread"]), "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: timed out"} otherwise result
|
|
886
912
|
when not a["ok"]
|
|
887
913
|
send {"jsonrpc": "2.0", "id": nothing, "error": {"code": -32001, "message": a["error"]}} as "message"
|
|
888
914
|
otherwise when length(offered) == 0
|
|
889
915
|
send {"jsonrpc": "2.0", "id": nothing, "error": {"code": -32001, "message": "this API key has no agents"}} as "message"
|
|
890
916
|
otherwise
|
|
891
917
|
state_set("lampson:last_used", now())
|
|
892
|
-
let resp be mcp_server.handle(req, offered, deliver_sse)
|
|
918
|
+
let resp be mcp_server.handle(req, offered, deliver_sse, api.space_of(a["key"]))
|
|
893
919
|
when resp != nothing
|
|
894
920
|
send resp as "message"
|
|
895
921
|
|