lampson 0.5.0 → 0.5.1

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 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) 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,100 @@ 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
+ // a JSON Schema from what the AI SDK world passes: jsonSchema(...) wrappers, zod (v4: z.toJSONSchema, v3 needs
143
+ // zod-to-json-schema in the app) or a plain JSON Schema object
144
+ function toJsonSchema(s, name) {
145
+ if (s == null) return { type: 'object', properties: {} };
146
+ if (s.jsonSchema && typeof s.jsonSchema === 'object') return s.jsonSchema;
147
+ if (typeof s.toJSONSchema === 'function') return s.toJSONSchema();
148
+ if (s._zod || s._def) {
149
+ const { createRequire } = require('module');
150
+ const req = createRequire(path.join(process.cwd(), 'noop.js'));
151
+ try { const z = req('zod'); if (typeof z.toJSONSchema === 'function') return z.toJSONSchema(s); } catch {}
152
+ try { return req('zod-to-json-schema').zodToJsonSchema(s); } catch {}
153
+ throw new TypeError('tool ' + name + ': cannot turn this zod schema into JSON Schema (zod 4 has z.toJSONSchema; with zod 3 install zod-to-json-schema), or pass `parameters` as a JSON Schema');
154
+ }
155
+ if (typeof s === 'object') return s;
156
+ throw new TypeError('tool ' + name + ': inputSchema/parameters must be a zod schema or a JSON Schema object');
157
+ }
158
+
159
+ function toolSpec(name, def) {
160
+ if (!TOOL_NAME.test(name || '')) throw new TypeError('tool name "' + name + '": lowercase letters, digits and _ (max 40), starting with a letter');
161
+ if (TAKEN.includes(name)) throw new TypeError('tool name "' + name + '" is a name Lampson already uses');
162
+ if (!def || typeof def.execute !== 'function') throw new TypeError('tool ' + name + ': needs execute(args, ctx)');
163
+ const schema = def.inputSchema || def.parameters;
164
+ return {
165
+ wire: { name, description: String(def.description || ''), parameters: toJsonSchema(schema, name), timeout: def.timeout },
166
+ schema, execute: def.execute,
167
+ };
168
+ }
169
+
170
+ // run one of your tools: what the model wrote is validated by a zod inputSchema before your code sees it; the
171
+ // answer is {output} or {error}, the same over stdio (local) and over HTTP (server)
172
+ async function executeTool(t, name, args, ctx) {
173
+ if (!t) return { error: 'the app has no tool ' + name };
174
+ try {
175
+ let input = args || {};
176
+ if (t.schema && typeof t.schema.safeParse === 'function') {
177
+ const v = t.schema.safeParse(input);
178
+ if (!v.success) return { error: 'invalid arguments for ' + name + ': ' + ((v.error && v.error.message) || 'schema mismatch') };
179
+ input = v.data;
180
+ }
181
+ const out = await t.execute(input, Object.freeze(Object.assign({}, ctx || {})));
182
+ return { output: out === undefined ? null : out };
183
+ } catch (e) {
184
+ return { error: (e && e.message) || String(e) };
185
+ }
186
+ }
187
+
188
+ // the RFC 9421 profile Synsema's http_sign uses: @method, @target-uri, content-digest; created, keyid, alg=hmac-sha256
189
+ function headerOf(headers, name) {
190
+ if (!headers) return '';
191
+ if (typeof headers.get === 'function') return headers.get(name) || '';
192
+ for (const k of Object.keys(headers)) if (k.toLowerCase() === name) return String(headers[k]);
193
+ return '';
194
+ }
195
+ function verifyToolRequest({ method, url, headers, body }, secret, opts = {}) {
196
+ if (!secret) return null;
197
+ const input = headerOf(headers, 'signature-input'), sigh = headerOf(headers, 'signature'), dig = headerOf(headers, 'content-digest');
198
+ const mi = /^sig1=(\("@method" "@target-uri" "content-digest"\);created=(\d+);keyid="([^"]*)";alg="hmac-sha256")$/.exec(input);
199
+ const ms = /^sig1=:([A-Za-z0-9+/=]+):$/.exec(sigh);
200
+ if (!mi || !ms) return null;
201
+ const created = Number(mi[2]);
202
+ const now = opts.now != null ? opts.now : Math.floor(Date.now() / 1000);
203
+ if (Math.abs(now - created) > 300) return null; // ±300 s, like http_signature_verify
204
+ const raw = Buffer.isBuffer(body) ? body : Buffer.from(String(body == null ? '' : body), 'utf8');
205
+ const wantDigest = 'sha-256=:' + crypto.createHash('sha256').update(raw).digest('base64') + ':';
206
+ if (dig !== wantDigest) return null;
207
+ const base = ['"@method": ' + String(method || 'POST').toUpperCase(), '"@target-uri": ' + url, '"content-digest": ' + dig, '"@signature-params": ' + mi[1]].join('\n');
208
+ const want = crypto.createHmac('sha256', secret).update(base).digest();
209
+ const got = Buffer.from(ms[1], 'base64');
210
+ if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) return null;
211
+ return { keyid: mi[3], created };
212
+ }
213
+
214
+ async function readNodeBody(req) {
215
+ if (req.body != null && (typeof req.body === 'string' || Buffer.isBuffer(req.body))) return req.body;
216
+ 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()');
217
+ const chunks = [];
218
+ for await (const c of req) chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c));
219
+ return Buffer.concat(chunks);
220
+ }
221
+
222
+ function killTree(child) {
223
+ try {
224
+ if (process.platform === 'win32') spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
225
+ else child.kill('SIGKILL');
226
+ } catch {}
227
+ }
228
+
115
229
  class LocalTransport {
116
- constructor({ workspace, home, env, spawn: spawnSpec }) {
230
+ constructor({ workspace, home, env, lampsonTools, tools, approveTools, spawn: spawnSpec }, onWarning) {
117
231
  if (!workspace && !spawnSpec) throw new TypeError('local.workspace is required (the project folder the agents work in)');
118
232
  let command, args, cwd;
119
233
  if (spawnSpec) {
@@ -126,7 +240,22 @@ class LocalTransport {
126
240
  cwd = path.resolve(workspace);
127
241
  }
128
242
  const childEnv = Object.assign({}, process.env, env || {});
129
- if (home) childEnv.LAMPSON_HOME = home;
243
+ // relative to the app, not to the workspace (the launcher runs with cwd = workspace): a relative home ended up
244
+ // inside the project (2026-10-18)
245
+ if (home) childEnv.LAMPSON_HOME = path.resolve(home);
246
+ if (lampsonTools === false) childEnv.LAMPSON_BUILTIN_TOOLS = 'off';
247
+ // you edit the .syn tools yourself: approve what is in the folder when it starts (never on a server: there a
248
+ // person runs `lampson tools approve`, so an agent that rewrites a tool cannot raise its own ceiling)
249
+ if (approveTools === true) childEnv.LAMPSON_APPROVE_TOOLS = '1';
250
+ if (tools) {
251
+ // the tools folder lives in the project (Lampson only reads inside it): pass it relative to the workspace
252
+ const rel = path.relative(path.resolve(workspace || '.'), path.resolve(tools)).split(path.sep).join('/');
253
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new TypeError('local.tools must be a folder inside local.workspace, got ' + tools);
254
+ childEnv.LAMPSON_TOOLS_DIR = rel;
255
+ }
256
+ this.warnings = [];
257
+ this.onWarning = onWarning;
258
+ this.tools = new Map(); // name → { wire, schema, execute }
130
259
  this.child = spawn(command, args, { cwd, env: childEnv, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
131
260
  this.pending = new Map(); // id → { onEvent, done }
132
261
  this.seq = 0;
@@ -145,15 +274,45 @@ class LocalTransport {
145
274
  const t = line.trim();
146
275
  if (!t.startsWith('{')) return; // launcher notices ("lampson updated…") are not protocol
147
276
  let m; try { m = JSON.parse(t); } catch { return; }
148
- if (m.kind === 'ready') { this.readyInfo = m.data; this._ready(m.data); return; }
277
+ if (m.kind === 'ready') {
278
+ this.readyInfo = m.data;
279
+ for (const w of (m.data && m.data.warnings) || []) this.warn(w);
280
+ this._ready(m.data);
281
+ return;
282
+ }
283
+ if (m.kind === 'warning') this.warn(m.data);
284
+ if (m.kind === 'tool_request') { this.runTool(m.data || {}); return; }
285
+ if (m.kind === 'tools') { for (const e of (m.data && m.data.errors) || []) this.warn(e); return; }
149
286
  const p = this.pending.get(m.id);
150
287
  if (!p) return;
151
288
  p.onEvent(m);
152
- if (m.kind === 'done' || m.kind === 'agents' || m.kind === 'pong' || m.kind === 'error') {
289
+ // an "error" inside a turn (it carries agent) is one more step: "done" still follows. Only the protocol's own
290
+ // error (bad line, unknown op) closes the request
291
+ if (m.kind === 'done' || m.kind === 'agents' || m.kind === 'pong' || (m.kind === 'error' && !('agent' in m))) {
153
292
  this.pending.delete(m.id);
154
293
  p.done(m);
155
294
  }
156
295
  }
296
+ warn(w) {
297
+ if (this.warnings.includes(w)) return; // ready lists them all; each ask repeats its agent's
298
+ // "tool 'x' is not available" for a tool this app registers (ready can come before lampson.tool()) is not real
299
+ const mt = /tool '([a-z0-9_]+)' is not available: no Lampson tool/.exec(w);
300
+ if (mt && this.tools.has(mt[1])) return;
301
+ this.warnings.push(w);
302
+ if (this.onWarning) this.onWarning(w);
303
+ }
304
+ setTools(list) {
305
+ for (const t of list) this.tools.set(t.wire.name, t);
306
+ // a warning about a tool that now exists is no longer true
307
+ 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])); });
308
+ if (this.exited) throw new LampsonError('lampson is not running');
309
+ // no pending entry: the answer ("tools") only carries errors, handled in onLine
310
+ this.child.stdin.write(JSON.stringify({ id: 't' + (++this.seq), op: 'tools', tools: [...this.tools.values()].map(t => t.wire) }) + '\n');
311
+ }
312
+ async runTool({ call_id, name, args, ctx }) {
313
+ const reply = r => { if (!this.exited) this.child.stdin.write(JSON.stringify(Object.assign({ op: 'tool_result', call_id }, r)) + '\n'); };
314
+ reply(await executeTool(this.tools.get(name), name, args, ctx));
315
+ }
157
316
  onExit(code, err) {
158
317
  this.exited = { code, err };
159
318
  const why = new LampsonError('lampson exited' + (code != null ? ' with code ' + code : '') + (err ? ': ' + err.message : '') +
@@ -200,7 +359,8 @@ class LocalTransport {
200
359
  this.child.stdin.end();
201
360
  await new Promise(resolve => {
202
361
  if (this.exited) return resolve();
203
- const t = setTimeout(() => { try { this.child.kill(); } catch {} resolve(); }, 5000);
362
+ // the child is a launcher (node → shell → synsema): kill the whole tree, or synsema outlives it
363
+ const t = setTimeout(() => { killTree(this.child); resolve(); }, 5000);
204
364
  this.child.once('exit', () => { clearTimeout(t); resolve(); });
205
365
  });
206
366
  }
@@ -208,25 +368,104 @@ class LocalTransport {
208
368
 
209
369
  class Lampson {
210
370
  /**
211
- * @param {object} opts { url, key } for server mode, or { local: { workspace, home?, env?, spawn? } }
371
+ * @param {object} opts { url, key, toolsUrl?, toolsSecret? } for server mode, or
372
+ * { local: { workspace, home?, env?, lampsonTools?, tools?, spawn? } };
373
+ * agent? — the default agent; onWarning?(message) — default console.warn
212
374
  */
213
375
  constructor(opts = {}) {
214
- this.transport = opts.local ? new LocalTransport(opts.local) : new HttpTransport(opts);
376
+ const onWarning = opts.onWarning === undefined ? (w => console.warn('lampson: ' + w)) : opts.onWarning;
377
+ this.transport = opts.local ? new LocalTransport(opts.local, onWarning) : new HttpTransport(opts);
215
378
  this.mode = opts.local ? 'local' : 'server';
379
+ this.agent = opts.agent || '';
380
+ // server mode: your tools travel with each message and Lampson POSTs the calls to toolsUrl (the PUBLIC URL of
381
+ // toolsHandler(), the one Lampson signs); toolsSecret = the key's signing secret from `lampson key add`
382
+ this.toolsUrl = opts.toolsUrl || '';
383
+ this.toolsSecret = opts.toolsSecret || '';
384
+ this.serverTools = new Map();
385
+ this.seenCalls = new Map(); // call_id → ms until it can be forgotten (toolsHandler: replays answer 409)
386
+ }
387
+ withAgent(msg) {
388
+ return this.agent && msg && typeof msg === 'object' && !msg.agent && !msg.to ? Object.assign({}, msg, { agent: this.agent }) : msg;
389
+ }
390
+ withTools(env) {
391
+ if (this.mode !== 'server' || this.serverTools.size === 0) return env;
392
+ return Object.assign({}, env, { tools: [...this.serverTools.values()].map(t => t.wire), tools_url: this.toolsUrl });
393
+ }
394
+ addTools(specs) {
395
+ if (this.mode === 'local') return this.transport.setTools(specs);
396
+ 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');
397
+ for (const t of specs) this.serverTools.set(t.wire.name, t);
398
+ }
399
+ /**
400
+ * Server mode: the endpoint Lampson POSTs your tool calls to. Verifies the signature (RFC 9421, the key's
401
+ * toolsSecret, ±300 s), runs the tool and answers {output} | {error}. Web standard (Next route handler, Hono, Bun,
402
+ * Deno: POST = lampson.toolsHandler()) or Node (Express: app.post(path, lampson.toolsHandler()); http.createServer).
403
+ */
404
+ toolsHandler(opts = {}) {
405
+ // seen(callId) → true if it already ran (and records it if not). Default: a Map in this process. With several
406
+ // instances (serverless, workers) pass a shared one: Redis `SET call:<id> 1 NX EX 600` → !ok
407
+ const seen = typeof opts.seen === 'function' ? opts.seen : (id => {
408
+ const now = Date.now();
409
+ for (const [k, until] of this.seenCalls) if (until < now) this.seenCalls.delete(k);
410
+ if (this.seenCalls.has(id)) return true;
411
+ this.seenCalls.set(id, now + 600000);
412
+ return false;
413
+ });
414
+ const answer = async (method, headers, body) => {
415
+ const v = verifyToolRequest({ method, url: this.toolsUrl, headers, body }, this.toolsSecret);
416
+ if (!v) return [401, { error: 'invalid or missing Lampson signature' }];
417
+ let msg;
418
+ try { msg = JSON.parse(Buffer.isBuffer(body) ? body.toString('utf8') : String(body)); } catch { return [400, { error: 'body must be JSON' }]; }
419
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return [400, { error: 'body must be a JSON object' }];
420
+ // the signature is valid for ±300 s: a captured request replayed in that window would run the tool again
421
+ // (the one that charges). Each call_id runs once — per process unless opts.seen is shared
422
+ if (msg.call_id != null) {
423
+ let dup;
424
+ // a fixed message: this text reaches the model, and a store's error can carry its host or password
425
+ 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' }]; }
426
+ if (dup) return [409, { error: 'call_id ' + msg.call_id + ' already ran' }];
427
+ }
428
+ return [200, await executeTool(this.serverTools.get(msg.name), msg.name, msg.args, msg.ctx)];
429
+ };
430
+ return async (req, res) => {
431
+ if (res && typeof res.setHeader === 'function') { // Node: Express, http.createServer
432
+ let status, out;
433
+ try { [status, out] = await answer(req.method, req.headers, await readNodeBody(req)); } catch (e) { [status, out] = [400, { error: e.message }]; }
434
+ res.statusCode = status; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(out));
435
+ return;
436
+ }
437
+ const [status, out] = await answer(req.method, req.headers, Buffer.from(await req.arrayBuffer()));
438
+ return new Response(JSON.stringify(out), { status, headers: { 'Content-Type': 'application/json' } });
439
+ };
216
440
  }
217
441
  /** Send a message to an agent and wait for its answer. Throws LampsonError if the turn ended in an error. */
218
442
  async ask(msg) {
219
- const result = await this.transport.ask(envelope(msg));
443
+ const result = await this.transport.ask(this.withTools(envelope(this.withAgent(msg))));
220
444
  if (result && result.status === 'queued') return result; // server mode with callback: { job, status }
221
445
  if (failed(result)) throw new LampsonError(result.stopped, { result });
222
446
  return result;
223
447
  }
224
448
  /** The agent's steps as they happen: session, assistant, tool_call, tool_result…, and "done" last. */
225
449
  async *stream(msg) {
226
- const env = envelope(msg);
450
+ const env = this.withTools(envelope(this.withAgent(msg)));
227
451
  if (env.callback) throw new TypeError('stream does not take a callback (use ask)');
228
452
  yield* this.transport.stream(env);
229
453
  }
454
+ /**
455
+ * Local mode: a function of your app as a tool. The AI SDK shape: { description, inputSchema (zod or JSON Schema)
456
+ * or parameters, execute(args, ctx), timeout? (s, default 60) }. List its name in the agent's "tools".
457
+ */
458
+ tool(name, def) {
459
+ this.addTools([toolSpec(name, def)]);
460
+ return this;
461
+ }
462
+ /** Several at once: { name: { description, inputSchema, execute } } — an AI SDK tools object works as is. */
463
+ tools(map) {
464
+ this.addTools(Object.entries(map || {}).map(([n, d]) => toolSpec(n, d)));
465
+ return this;
466
+ }
467
+ /** Local mode: tools some agent lists but will not have (plugin off, typo), one message each. */
468
+ get warnings() { return this.transport.warnings || []; }
230
469
  /** The agents this key (server) or this workspace (local) can use. */
231
470
  async agents() { return this.transport.agents(); }
232
471
  /** Server mode: status and result of a message sent with a callback. */
@@ -238,6 +477,9 @@ class Lampson {
238
477
  * Checks the X-Lampson-Signature of a callback (or approval webhook): "sha256=" + HMAC-SHA256(rawBody, secret),
239
478
  * secret = LAMPSON_WEBHOOK_SECRET of that Lampson. Pass the raw body exactly as received (string or Buffer).
240
479
  */
480
+ /** Checks a tool request's RFC 9421 signature by hand (toolsHandler() does it for you) → {keyid, created} | null. */
481
+ static verifyToolRequest(req, secret, opts) { return verifyToolRequest(req, secret, opts); }
482
+
241
483
  static verifySignature(rawBody, signature, secret) {
242
484
  if (!signature || !secret) return false;
243
485
  const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
@@ -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