lampson 0.4.1 → 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.
Files changed (69) hide show
  1. package/README.md +19 -0
  2. package/chat.syn +1 -1
  3. package/hub.tpl.syn +55 -12
  4. package/lampson.ps1 +13 -6
  5. package/lampson.sh +11 -5
  6. package/lib/api.syn +224 -9
  7. package/lib/apikeys.syn +42 -9
  8. package/lib/apptools.syn +549 -0
  9. package/lib/diagnose.syn +142 -0
  10. package/lib/loop.syn +27 -0
  11. package/lib/mailbox.syn +24 -10
  12. package/lib/mcp_server.syn +6 -5
  13. package/lib/permission.syn +22 -1
  14. package/lib/plugins.syn +6 -4
  15. package/lib/provider.syn +16 -13
  16. package/lib/remotetools.syn +76 -0
  17. package/lib/runtime.syn +213 -9
  18. package/lib/schedule.syn +40 -2
  19. package/lib/sdktools.syn +73 -0
  20. package/lib/session.syn +8 -0
  21. package/lib/teamrun.syn +42 -5
  22. package/lib/teams.syn +397 -24
  23. package/lib/tools/common.syn +5 -0
  24. package/lib/tools/url.syn +82 -9
  25. package/lib/workspaces.syn +87 -3
  26. package/lib/worktree.syn +108 -0
  27. package/package.json +2 -2
  28. package/plugins/example-hello/plugin.json +1 -0
  29. package/public/css/chat.css +9 -8
  30. package/public/css/hub.css +69 -16
  31. package/public/css/layout.css +12 -4
  32. package/public/css/login.css +1 -1
  33. package/public/css/mobile.css +2 -2
  34. package/public/css/panel.css +18 -7
  35. package/public/css/sidebar.css +1 -1
  36. package/public/css/teams.css +701 -55
  37. package/public/css/tokens.css +36 -12
  38. package/public/css/views.css +124 -0
  39. package/public/hub.html +17 -9
  40. package/public/index.html +5 -2
  41. package/public/js/app.js +2 -2
  42. package/public/js/approvals.js +1 -1
  43. package/public/js/apptools.js +63 -0
  44. package/public/js/core.js +5 -2
  45. package/public/js/flow.js +187 -0
  46. package/public/js/hub.js +131 -31
  47. package/public/js/navtabs.js +23 -0
  48. package/public/js/objdiag.js +90 -0
  49. package/public/js/objlive.js +393 -0
  50. package/public/js/panel.js +3 -2
  51. package/public/js/plugins-home.js +59 -0
  52. package/public/js/plugins.js +40 -18
  53. package/public/js/schedules.js +5 -0
  54. package/public/js/sidebar.js +6 -4
  55. package/public/js/tasks-home.js +104 -0
  56. package/public/js/teams-home.js +64 -15
  57. package/public/js/teams.js +927 -202
  58. package/public/js/terminal.js +8 -2
  59. package/public/js/workspaces.js +6 -3
  60. package/public/plugins-home.html +32 -0
  61. package/public/tasks-home.html +31 -0
  62. package/public/teams-home.html +5 -2
  63. package/public/teams.html +33 -46
  64. package/public/vendor/xterm-addon-webgl.js +2 -0
  65. package/run.syn +87 -6
  66. package/sdk/index.d.ts +64 -3
  67. package/sdk/index.js +253 -11
  68. package/skills/lampson/SKILL.md +15 -0
  69. package/web.syn +91 -12
package/run.syn CHANGED
@@ -47,6 +47,8 @@ use "./lib/apikeys.syn" as apikeys
47
47
  use "./lib/mcp_server.syn" as mcp_server
48
48
  use "./lib/approvals.syn" as approvals
49
49
  use "./lib/plugins.syn" as plugins
50
+ use "./lib/sdktools.syn" as sdktools
51
+ use "./lib/apptools.syn" as apptools
50
52
  use "./lib/channels.syn" as channels
51
53
 
52
54
  -- `lampson key add|list|remove`: API keys de la API /v1 de este workspace (lib/apikeys.syn, lib/api.syn)
@@ -81,6 +83,8 @@ when key_cmd != ""
81
83
  print("")
82
84
  print(" " + k["key"])
83
85
  print("")
86
+ print(" Firma de sus callbacks (X-Lampson-Signature, verifySignature del SDK): " + k["secret"])
87
+ print("")
84
88
  print(" API (apps, bots): " + api_base + "/messages")
85
89
  print(" MCP (otros agentes): " + api_base + "/mcp con el header Authorization: Bearer <la key>")
86
90
  when pub == ""
@@ -92,7 +96,7 @@ when key_cmd != ""
92
96
  when length(ks) == 0
93
97
  print("sin API keys en este workspace (lampson key add [--agent ID] [--name NOMBRE])")
94
98
  each k in ks
95
- print(" " + k["id"] + " " + (when k["name"] == "" then "(sin nombre)" otherwise k["name"]) + " agentes: " + join(k["agents"], ", ") + " " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + "/min") + (when length(k["callbacks"]) > 0 then " callbacks: " + join(k["callbacks"], ", ") otherwise "") + " creada " + k["created"] + " último uso " + (when k["last_used"] == nothing then "nunca" otherwise text(k["last_used"])))
99
+ print(" " + k["id"] + " " + (when k["name"] == "" then "(sin nombre)" otherwise k["name"]) + " agentes: " + join(k["agents"], ", ") + " " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + "/min") + (when length(k["callbacks"]) > 0 then " callbacks: " + join(k["callbacks"], ", ") otherwise "") + (when not k["own_secret"] then " [vieja: firma con el secreto global" + (when length(k["callbacks"]) == 0 then " y manda callbacks a cualquier host público" otherwise "") + "; reemplazala]" otherwise "") + " creada " + k["created"] + " último uso " + (when k["last_used"] == nothing then "nunca" otherwise text(k["last_used"])))
96
100
  print(" API: " + api_base + "/messages · MCP: " + api_base + "/mcp")
97
101
  otherwise when key_cmd == "remove"
98
102
  let kid be env("LAMPSON_KEY_ID", "")
@@ -203,6 +207,55 @@ when env("LAMPSON_TEAM_CMD", "") != ""
203
207
  print(" ✗ " + e)
204
208
  exit(0)
205
209
 
210
+ -- `lampson plugin list|on|off [nombre]`: encender un plugin sin interfaz (una VPS por SSH, un script)
211
+ let pl_cmd be env("LAMPSON_PLUGIN_CMD", "")
212
+ when pl_cmd != ""
213
+ let pl_name be lower(env("LAMPSON_PLUGIN_NAME", ""))
214
+ when pl_cmd == "list"
215
+ let ls be plugins.all()
216
+ when length(ls) == 0
217
+ print("no hay plugins (proyecto: workspace/.lampson/plugins/<nombre>/plugin.json · globales: plugins/<nombre>/)")
218
+ each l in ls
219
+ print(" " + (when l["enabled"] then "● " otherwise "○ ") + l["name"] + " " + l["scope"] + " " + (when l["error"] != nothing then "roto: " + text(l["error"]) otherwise join(apply((t) => t["name"], l["tools"]), ", ")))
220
+ exit(0)
221
+ when (pl_cmd == "on" or pl_cmd == "off") and pl_name != ""
222
+ try
223
+ print(plugins.set_enabled(pl_name, pl_cmd == "on"))
224
+ recover err
225
+ print("lampson plugin: " + text(err))
226
+ exit(2)
227
+ exit(0)
228
+ print("uso: lampson plugin list · plugin on|off <nombre>")
229
+ exit(2)
230
+
231
+ -- `lampson tools list|approve [nombre]`: las herramientas .syn del proyecto (lib/apptools.syn) y su aprobación
232
+ let tl_cmd be env("LAMPSON_TOOLS_CMD", "")
233
+ when tl_cmd != ""
234
+ let tl_name be env("LAMPSON_TOOLS_NAME", "")
235
+ let tdir be apptools.dir()
236
+ when tl_cmd == "list"
237
+ let st be apptools.approval()
238
+ when length(keys(st)) == 0
239
+ print("no hay herramientas .syn (" + slice(tdir, length("workspace/"), length(tdir)) + "/<nombre>.syn en el proyecto)")
240
+ let byfile be {}
241
+ each e in apptools.scan_files()
242
+ set byfile[e["file"]] to e
243
+ each f in sort(keys(st))
244
+ let mark be when st[f] == "ok" then "● " otherwise (when st[f] == "new" then "○ nueva, sin aprobar " otherwise (when st[f] == "missing" then "· borrada (estaba aprobada; approve la saca) " otherwise (when st[f] == "unreadable" then "✕ no se puede leer " otherwise (when st[f] == "too_big" then "✕ pasa el tope (1 MB por archivo, 500 .syn) " otherwise (when st[f] == "link" then "✕ link a una carpeta: no se permite " otherwise "△ cambió, sin aprobar ")))))
245
+ let info be when contains(byfile, f) then (when byfile[f]["error"] != nothing then "rota: " + text(byfile[f]["error"]) otherwise "puede tocar: " + apptools.ceiling(byfile[f])) otherwise (when starts_with(f, "_") then "ayudante" otherwise "va al prompt")
246
+ print(" " + mark + f + " " + info)
247
+ exit(0)
248
+ when tl_cmd == "approve"
249
+ let done be apptools.approve(tl_name)
250
+ when length(done) == 0
251
+ print(when tl_name == "" then "nada que aprobar: todo está al día" otherwise "nada que aprobar con ese nombre (lampson tools list)")
252
+ each f in done
253
+ let es be where(apptools.scan_files(), (e) => e["file"] == f)
254
+ print("aprobada " + f + (when length(es) > 0 and es[0]["error"] == nothing then " · puede tocar: " + apptools.ceiling(es[0]) otherwise ""))
255
+ exit(0)
256
+ print("uso: lampson tools list · tools approve [nombre] (sin nombre: todo lo que está en la carpeta)")
257
+ exit(2)
258
+
206
259
  -- `lampson channel list|on|off|setup [canal]`: los canales (plugins con "channel", lib/channels.syn)
207
260
  let ch_cmd be env("LAMPSON_CHANNEL_CMD", "")
208
261
  when ch_cmd != ""
@@ -269,7 +322,8 @@ task lampson_subagent(spec_json)
269
322
  -- {"id": "r2", "op": "agents"} · {"id": "r3", "op": "ping"}
270
323
  -- y por stdout, una línea JSON por evento con ese id: los mismos que `--json` (session, assistant, tool_call…) y
271
324
  -- {"id", "kind": "done", "data": {agent, thread, session, text, steps, usage, stopped}} al terminar cada ask. Al
272
- -- arrancar, {"kind": "ready", "data": {"agents": […], "protocol": 2}}.
325
+ -- arrancar, {"kind": "ready", "data": {"agents": […], "protocol": 2, "warnings": […]}}; antes de un ask cuyo agente lista
326
+ -- tools que no tiene (plugin apagado…), {"id", "kind": "warning", "data": "<por qué>"}.
273
327
  -- CONCURRENCIA (protocolo 2): cada ask corre en su propio agente de Synsema; conversaciones distintas van en
274
328
  -- paralelo, dos asks de la MISMA conversación (agente + thread) esperan en fila. Un agente que imprime sale con
275
329
  -- prefijo "[Agente_N]" (rompería el JSON): por eso los trabajos publican en el bus y SOLO el hilo principal escribe.
@@ -349,9 +403,15 @@ task stdio_ask(req, rid)
349
403
  let ss be when contains(req, "session") and req["session"] != nothing then text(req["session"]) otherwise ""
350
404
  -- la fila es por conversación: (agente, thread), o la sesión; sin ninguno, el pedido solo (va en paralelo)
351
405
  let key be when th != "" then agent_id + "\n" + th otherwise (when ss != "" then agent_id + "\nsession:" + ss otherwise "req:" + rid)
352
- let sobre be {"to": agent_id, "thread": th, "session": ss, "from": {"id": "", "name": "", "kind": "human"}, "text": msg, "images": when contains(req, "images") and type_of(req["images"]) == "list" then req["images"] otherwise [], "channel": "sdk", "meta": when contains(req, "meta") and type_of(req["meta"]) == "map" then req["meta"] otherwise {}}
353
- give {"ok": true, "key": key, "job": {"id": rid, "to": agent_id, "thread": th, "mode": mode, "key": key, "sobre": sobre}}
406
+ -- from: quien escribe, tal como lo dice la app (el SDK lo documenta; las herramientas de la app lo reciben en ctx)
407
+ let rf be when contains(req, "from") and type_of(req["from"]) == "map" then req["from"] otherwise {}
408
+ let from be {"id": text(get(rf, "id", "")), "name": text(get(rf, "name", "")), "kind": text(get(rf, "kind", "human"))}
409
+ let sobre be {"to": agent_id, "thread": th, "session": ss, "from": from, "text": msg, "images": when contains(req, "images") and type_of(req["images"]) == "list" then req["images"] otherwise [], "channel": "sdk", "meta": when contains(req, "meta") and type_of(req["meta"]) == "map" then req["meta"] otherwise {}}
410
+ give {"ok": true, "key": key, "warnings": runtime.missing(spec), "job": {"id": rid, "to": agent_id, "thread": th, "mode": mode, "key": key, "sobre": sobre}}
354
411
 
412
+ when env("LAMPSON_RUN_STDIO", "") == "1" and env("LAMPSON_APPROVE_TOOLS", "") == "1"
413
+ -- SDK local con approveTools: lo que dejó el dev en la carpeta, aprobado una vez al arrancar (lib/apptools.syn)
414
+ apptools.approve("")
355
415
  when env("LAMPSON_RUN_STDIO", "") == "1"
356
416
  share {"id": text(now())} as "lampson:run"
357
417
  share {"kind": "sdk"} as "lampson:ui"
@@ -365,7 +425,11 @@ when env("LAMPSON_RUN_STDIO", "") == "1"
365
425
  mcp.start_all(8)
366
426
  let sub be bus_subscribe(["stdio.line", "stdio.out", "stdio.done", "stdio.eof"], {"max_queue": 100000, "on_full": "error"})
367
427
  spawn StdioReader
368
- stdio_out({"kind": "ready", "data": {"agents": all_names, "protocol": 2}})
428
+ -- tools que algún agente lista y no va a tener (plugin apagado, nombre mal escrito): el SDK las muestra al arrancar
429
+ let warns be []
430
+ each n in all_names
431
+ set warns to warns + runtime.missing(runtime.get(n))
432
+ stdio_out({"kind": "ready", "data": {"agents": all_names, "protocol": 2, "warnings": warns}})
369
433
  let busy be {}
370
434
  let waiting be {}
371
435
  let running be 0
@@ -408,10 +472,20 @@ when env("LAMPSON_RUN_STDIO", "") == "1"
408
472
  let op be when contains(req, "op") and req["op"] != nothing then lower(text(req["op"])) otherwise "ask"
409
473
  when op == "ping"
410
474
  stdio_out({"id": rid, "kind": "pong"})
475
+ otherwise when op == "tools"
476
+ -- funciones de la app (lampson.tool() del SDK, lib/sdktools.syn): reemplaza la lista entera
477
+ let nt be sdktools.normalize(when contains(req, "tools") then req["tools"] otherwise [])
478
+ share {"tools": nt["tools"]} as "sdk:tools"
479
+ stdio_out({"id": rid, "kind": "tools", "data": {"tools": apply((t) => t["name"], nt["tools"]), "errors": nt["errors"]}})
480
+ otherwise when op == "tool_result"
481
+ bus_publish("sdktool.result", req)
411
482
  otherwise when op == "agents"
412
483
  stdio_out({"id": rid, "kind": "agents", "data": apply((n) => {"id": n, "description": runtime.get(n)["description"]}, runtime.names())})
413
484
  otherwise when op == "ask"
414
485
  let a be stdio_ask(req, rid)
486
+ when a["ok"]
487
+ each w in a["warnings"]
488
+ stdio_out({"id": rid, "kind": "warning", "data": w, "tag": "", "agent": a["job"]["to"], "thread": a["job"]["thread"]})
415
489
  when not a["ok"]
416
490
  stdio_out({"id": rid, "kind": "done", "data": a["done"], "tag": "", "agent": a["done"]["agent"], "thread": a["done"]["thread"]})
417
491
  otherwise when contains(busy, a["key"]) and busy[a["key"]]
@@ -422,7 +496,7 @@ when env("LAMPSON_RUN_STDIO", "") == "1"
422
496
  set running to running + 1
423
497
  spawn StdioJob with spec_json = json_encode(a["job"])
424
498
  otherwise
425
- stdio_out({"id": rid, "kind": "error", "data": "unknown op '" + op + "' (ask, agents, ping)"})
499
+ stdio_out({"id": rid, "kind": "error", "data": "unknown op '" + op + "' (ask, agents, tools, tool_result, ping)"})
426
500
  exit(0)
427
501
 
428
502
  let json_out be env("LAMPSON_RUN_JSON", "") == "1"
@@ -467,6 +541,13 @@ task emit_json(kind, data, tag)
467
541
  print(json_encode({"kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": thread}))
468
542
  flush()
469
543
 
544
+ -- en texto el aviso va a stderr (eprint, Synsema 0.6.42+): stdout queda solo para la respuesta
545
+ each w in runtime.missing(spec)
546
+ when json_out
547
+ print(json_encode({"kind": "warning", "data": w, "tag": "", "agent": agent_id, "thread": thread}))
548
+ otherwise
549
+ eprint("lampson run: warning: " + w)
550
+
470
551
  task on_start(info)
471
552
  set thread to info["thread"]
472
553
  when json_out
package/sdk/index.d.ts CHANGED
@@ -9,14 +9,27 @@ export interface ServerOptions {
9
9
  fetch?: typeof fetch;
10
10
  /** Per-request timeout in ms (default 15 min: an agent can take a while). */
11
11
  timeout?: number;
12
+ /** Your tools in server mode: the PUBLIC URL of toolsHandler(), where Lampson POSTs each call (in the key's list). */
13
+ toolsUrl?: string;
14
+ /** The key's signing secret (whsec_…, shown by `lampson key add`): toolsHandler() verifies Lampson's calls with it. */
15
+ toolsSecret?: string;
12
16
  }
13
17
 
14
18
  export interface LocalOptions {
15
19
  local: {
16
20
  /** The project folder the agents work in. */
17
21
  workspace: string;
18
- /** LAMPSON_HOME: where Lampson keeps its config, sessions and plugins (default ~/lampson). */
22
+ /** LAMPSON_HOME: where Lampson keeps its config, sessions and plugins (default ~/lampson). Relative to process.cwd(). */
19
23
  home?: string;
24
+ /** false: no tool of Lampson's own (bash, read, write, fetch…) exists in this process, not even for the built-in
25
+ * agents — your agents get only the tools you give them. Default true. */
26
+ lampsonTools?: boolean;
27
+ /** Your tools in Synsema: a folder inside `workspace` with one `<name>.syn` per tool (default `<workspace>/.lampson/tools`).
28
+ * Each file has an `intent:` line (its description), its `require`s (all it can touch) and `export task <name>(…)`. */
29
+ tools?: string;
30
+ /** A `.syn` tool runs only once a person approved that exact content (`lampson tools approve`). true approves what
31
+ * is in the folder when Lampson starts (later changes, even the agent's, need approval): for development, where you edit the tools. Never on a shared server. */
32
+ approveTools?: boolean;
20
33
  /** Extra environment for the Lampson process (e.g. provider keys). */
21
34
  env?: Record<string, string>;
22
35
  /** Advanced / tests: an exact command that speaks the `lampson run --stdio` protocol. */
@@ -24,6 +37,13 @@ export interface LocalOptions {
24
37
  };
25
38
  }
26
39
 
40
+ export interface CommonOptions {
41
+ /** The agent that answers when a message does not say `agent`. Without it: the workspace default ("build"). */
42
+ agent?: string;
43
+ /** Local mode: called once per tool an agent lists but will not have (plugin off, typo). Default console.warn; null = silent. */
44
+ onWarning?: ((message: string) => void) | null;
45
+ }
46
+
27
47
  export interface Message {
28
48
  /** The agent that answers (alias: `to`). Default: the workspace's default agent. */
29
49
  agent?: string;
@@ -63,7 +83,7 @@ export interface Result {
63
83
  export interface Queued { job: string; status: 'queued' }
64
84
 
65
85
  export interface LampsonEvent {
66
- kind: 'session' | 'assistant' | 'tool_call' | 'tool_result' | 'tool_denied' | 'usage' | 'inbox' | 'error' | 'compact' | 'done' | string;
86
+ kind: 'session' | 'assistant' | 'tool_call' | 'tool_result' | 'tool_denied' | 'usage' | 'inbox' | 'error' | 'compact' | 'warning' | 'done' | string;
67
87
  data: any;
68
88
  tag?: string;
69
89
  agent?: string;
@@ -80,14 +100,55 @@ export class LampsonError extends Error {
80
100
  stderr?: string[];
81
101
  }
82
102
 
103
+ /** What your app's tool receives besides its arguments: set by your app (the message), never by the model. */
104
+ export interface ToolContext {
105
+ from?: { id?: string; name?: string; kind?: string };
106
+ thread?: string;
107
+ agent?: string;
108
+ session?: string;
109
+ meta?: Record<string, unknown>;
110
+ channel?: string;
111
+ }
112
+
113
+ /** A function of your app as a tool — the AI SDK shape. */
114
+ export interface ToolDefinition<A = any> {
115
+ description?: string;
116
+ /** A zod schema (validated before execute) or a JSON Schema. */
117
+ inputSchema?: unknown;
118
+ /** A JSON Schema (alias of inputSchema). */
119
+ parameters?: unknown;
120
+ execute: (args: A, ctx: Readonly<ToolContext>) => unknown | Promise<unknown>;
121
+ /** Seconds Lampson waits for the answer (default 60, max 600). */
122
+ timeout?: number;
123
+ }
124
+
83
125
  export class Lampson {
84
- constructor(opts: ServerOptions | LocalOptions);
126
+ constructor(opts: (ServerOptions | LocalOptions) & CommonOptions);
85
127
  readonly mode: 'server' | 'local';
128
+ /** A function of your app as a tool (server mode needs toolsUrl); list its name in the agent's "tools". */
129
+ tool<A = any>(name: string, def: ToolDefinition<A>): this;
130
+ /** Several tools at once — an AI SDK tools object works as is. */
131
+ tools(map: Record<string, ToolDefinition>): this;
132
+ /**
133
+ * Server mode: the endpoint for Lampson's tool calls — verifies the signature, runs the tool, answers.
134
+ * Web standard (Next route handler, Hono, Bun, Deno) or Node (Express, http.createServer).
135
+ */
136
+ toolsHandler(opts?: {
137
+ /** true if this call_id already ran (and record it if not). Default: in this process. With several instances
138
+ * (serverless, workers) share it, e.g. Redis `SET call:<id> 1 NX EX 600`. A repeated call answers 409. */
139
+ seen?: (callId: string) => boolean | Promise<boolean>;
140
+ }): (req: any, res?: any) => Promise<Response | void>;
141
+ /** The default agent given in the options ("" = the workspace default). */
142
+ readonly agent: string;
143
+ /** Local mode: tools some agent lists but will not have, one message each (filled once the process is ready). */
144
+ readonly warnings: string[];
86
145
  ask(msg: Message): Promise<Result | Queued>;
87
146
  stream(msg: Omit<Message, 'callback'>): AsyncGenerator<LampsonEvent, void, unknown>;
88
147
  agents(): Promise<AgentInfo[]>;
89
148
  job(id: string): Promise<unknown>;
90
149
  close(): Promise<void>;
150
+ /** Checks a tool call's RFC 9421 signature by hand (toolsHandler() does it) → {keyid, created} or null. */
151
+ static verifyToolRequest(req: { method: string; url: string; headers: Record<string, string> | Headers; body: string | Buffer }, secret: string, opts?: { now?: number }): { keyid: string; created: number } | null;
91
152
  static verifySignature(rawBody: string | Buffer, signature: string | undefined, secret: string): boolean;
92
153
  }
93
154
 
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');