lampson 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/run.syn ADDED
@@ -0,0 +1,394 @@
1
+ -- run.syn — Lampson sin interfaz: un mensaje entra, el agente trabaja, la respuesta sale (spec/engine.md, fase 1)
2
+ --
3
+ -- lampson run "resumí los cambios de hoy" -- texto final por stdout
4
+ -- echo "hola" | lampson run --agent soporte --thread whatsapp:+54911… --json
5
+ --
6
+ -- Corre como chat.syn: cwd = .lampson/ws/<slug> con la junction `workspace` (los launchers lo preparan).
7
+ -- Entrada por entorno (los launchers la arman desde los flags):
8
+ -- LAMPSON_MESSAGE el mensaje; vacío → se lee stdin hasta EOF
9
+ -- LAMPSON_AGENT el agente (integrado o workspace/.lampson/agents/<id>.agent.json); default build
10
+ -- LAMPSON_THREAD identidad externa de la conversación (cliente, canal, tarea): misma → misma sesión
11
+ -- LAMPSON_SESSION o el id de una sesión ya existente
12
+ -- LAMPSON_RUN_JSON=1 eventos JSONL por stdout (uno por línea) y al final {"kind":"done",…}
13
+ -- LAMPSON_RUN_PERMISSION ask|strict|yolo; vacío → el del agente, y si no dice → strict
14
+ -- Sin humano delante: lo que pida aprobación se DENIEGA (no hay ask_fn); el modelo lo ve y lo informa.
15
+ -- Código de salida: 0 ok · 1 el turno terminó en error · 2 uso inválido (agente inexistente, mensaje vacío).
16
+
17
+ intent: "Headless Lampson: deliver one message to an agent and print its answer (or the event stream as JSONL)"
18
+
19
+ require net
20
+ require time
21
+ require stdin
22
+ require exec
23
+ require random
24
+ require env("LAMPSON_*")
25
+ require env("OS")
26
+ require secret("LAMPSON_*")
27
+ require judge
28
+ require file("workspace")
29
+ require file("workspace/*")
30
+ require file.read("skills")
31
+ require file.read("skills/*")
32
+ require file.read("plugins")
33
+ require file.read("plugins/*")
34
+ require file.read("agents")
35
+ require file.read("agents/*")
36
+ require file("memory")
37
+ require file("memory/*")
38
+ require file(".lampson")
39
+ require file(".lampson/*")
40
+
41
+ use "./lib/runtime.syn" as runtime
42
+ use "./lib/agents.syn" as agents
43
+ use "./lib/mcp.syn" as mcp
44
+ use "./lib/apikeys.syn" as apikeys
45
+ use "./lib/mcp_server.syn" as mcp_server
46
+ use "./lib/approvals.syn" as approvals
47
+ use "./lib/plugins.syn" as plugins
48
+ use "./lib/channels.syn" as channels
49
+
50
+ -- `lampson key add|list|remove`: API keys de la API /v1 de este workspace (lib/apikeys.syn, lib/api.syn)
51
+ -- LAMPSON_KEY_CMD=add [LAMPSON_KEY_NAME] [LAMPSON_KEY_AGENTS=tienda,soporte] [LAMPSON_KEY_RATE=60]
52
+ -- [LAMPSON_KEY_CALLBACKS=https://a/,https://b/] · list · remove LAMPSON_KEY_ID
53
+ let key_cmd be env("LAMPSON_KEY_CMD", "")
54
+ when key_cmd != ""
55
+ let ws_path be "/w/" + env("LAMPSON_WS", "<slug>") + "/v1"
56
+ -- la URL pública de este lampson (--domain, túnel o LAMPSON_PUBLIC_URL), si hay: la que se pega en otra app o agente
57
+ let pub be approvals.public_url()
58
+ let api_base be when pub != "" then pub + ws_path otherwise "http://127.0.0.1:8080" + ws_path
59
+ when key_cmd == "add"
60
+ let ag be where(apply((x) => lower(trim(x)), split(env("LAMPSON_KEY_AGENTS", ""), ",")), (x) => x != "")
61
+ each a in ag
62
+ when a != "*" and not contains(runtime.names(), a)
63
+ print("lampson key: no agent named '" + a + "' · available: " + join(runtime.names(), ", "))
64
+ exit(2)
65
+ let rate_s be trim(env("LAMPSON_KEY_RATE", ""))
66
+ let cbs be where(apply((x) => trim(x), split(env("LAMPSON_KEY_CALLBACKS", ""), ",")), (x) => x != "")
67
+ each cb in cbs
68
+ when not (starts_with(cb, "https://") or starts_with(cb, "http://"))
69
+ print("lampson key: --callback must be an http(s) URL prefix, got '" + cb + "'")
70
+ exit(2)
71
+ let kopts be {"callbacks": cbs}
72
+ when rate_s != ""
73
+ when not matches(rate_s, "[0-9]{1,6}")
74
+ print("lampson key: --rate must be a number of requests per minute (0 = no limit)")
75
+ exit(2)
76
+ set kopts["rate"] to int(rate_s)
77
+ let k be apikeys.create_with(env("LAMPSON_KEY_NAME", ""), ag, kopts)
78
+ print("API key creada (" + k["id"] + ") para " + (when contains(k["agents"], "*") then "todos los agentes" otherwise join(k["agents"], ", ")) + " · " + (when k["rate"] == 0 then "sin límite" otherwise text(k["rate"]) + " pedidos/min") + (when length(k["callbacks"]) > 0 then " · callbacks solo a " + join(k["callbacks"], ", ") otherwise "") + ". Guardala ahora: no se vuelve a mostrar.")
79
+ print("")
80
+ print(" " + k["key"])
81
+ print("")
82
+ print(" API (apps, bots): " + api_base + "/messages")
83
+ print(" MCP (otros agentes): " + api_base + "/mcp con el header Authorization: Bearer <la key>")
84
+ when pub == ""
85
+ print(" (solo desde esta PC: para usarla desde afuera, `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
86
+ print("")
87
+ print(" curl -X POST " + api_base + "/messages -H \"Authorization: Bearer " + k["key"] + "\" -H \"Content-Type: application/json\" -d '{\"to\": \"" + (when contains(k["agents"], "*") then runtime.default_agent() otherwise k["agents"][0]) + "\", \"thread\": \"cliente-1\", \"text\": \"hola\"}'")
88
+ otherwise when key_cmd == "list"
89
+ let ks be apikeys.list()
90
+ when length(ks) == 0
91
+ print("sin API keys en este workspace (lampson key add [--agent ID] [--name NOMBRE])")
92
+ each k in ks
93
+ 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"])))
94
+ print(" API: " + api_base + "/messages · MCP: " + api_base + "/mcp")
95
+ otherwise when key_cmd == "remove"
96
+ let kid be env("LAMPSON_KEY_ID", "")
97
+ when apikeys.remove(kid)
98
+ print("API key " + kid + " revocada")
99
+ otherwise
100
+ print("lampson key: no existe la key '" + kid + "' (lampson key list)")
101
+ exit(2)
102
+ otherwise
103
+ print("uso: lampson key add [--agent ID[,ID]] [--name NOMBRE] · lampson key list · lampson key remove <id>")
104
+ exit(2)
105
+ exit(0)
106
+
107
+ -- `lampson channel list|on|off|setup [canal]`: los canales (plugins con "channel", lib/channels.syn)
108
+ let ch_cmd be env("LAMPSON_CHANNEL_CMD", "")
109
+ when ch_cmd != ""
110
+ let ch_name be lower(env("LAMPSON_CHANNEL_NAME", ""))
111
+ let pub_ch be approvals.public_url()
112
+ let slug be env("LAMPSON_WS", "")
113
+ task hook_url(n)
114
+ give channels.webhook_url(n, pub_ch, slug)
115
+ let chs be where(plugins.all(), (l) => l["channel"] != nothing)
116
+ when ch_cmd == "list"
117
+ when length(chs) == 0
118
+ print("no hay canales instalados (un canal es un plugin con \"channel\" en su plugin.json)")
119
+ each l in chs
120
+ let ag be when l["error"] == nothing then channels.agent_for(l["name"], l, {}) otherwise "?"
121
+ let md be channels.mode_of(l["name"])
122
+ print(" " + (when l["enabled"] then "● " otherwise "○ ") + l["name"] + " " + (when l["error"] != nothing then "roto: " + text(l["error"]) otherwise "agente: " + ag + " " + (when md == "poll" then "modo: sin URL pública (poll)" otherwise "webhook: " + hook_url(l["name"]))))
123
+ when pub_ch == ""
124
+ print(" (sin URL pública: las plataformas no llegan a esta PC. `lampson --domain …` o un túnel; ver lampson.org/docs/phone)")
125
+ exit(0)
126
+ let found be where(chs, (l) => l["name"] == ch_name)
127
+ when length(found) == 0
128
+ print("lampson channel: no hay un canal '" + ch_name + "' · instalados: " + join(apply((l) => l["name"], chs), ", "))
129
+ exit(2)
130
+ let l be found[0]
131
+ when ch_cmd == "on" or ch_cmd == "off"
132
+ plugins.set_enabled(ch_name, ch_cmd == "on")
133
+ print("canal " + ch_name + (when ch_cmd == "on" then " encendido · webhook: " + hook_url(ch_name) otherwise " apagado"))
134
+ exit(0)
135
+ when ch_cmd == "setup"
136
+ when not l["enabled"]
137
+ print("lampson channel: el canal " + ch_name + " está apagado — `lampson channel on " + ch_name + "` primero")
138
+ exit(2)
139
+ let su be channels.setup_channel(ch_name, pub_ch, slug)
140
+ print(su["out"])
141
+ exit(su["code"])
142
+ print("uso: lampson channel list · channel on|off <canal> · channel setup <canal>")
143
+ exit(2)
144
+
145
+ -- `lampson mcp serve`: Lampson como servidor MCP por stdio (lib/mcp_server.syn); stdout queda SOLO para JSON-RPC
146
+ when env("LAMPSON_MCP_SERVE", "") == "1"
147
+ let offered be mcp_server.offered()
148
+ when length(offered) == 0
149
+ print(json_encode({"jsonrpc": "2.0", "id": nothing, "error": {"code": -32603, "message": "no agents match LAMPSON_MCP_AGENTS"}}))
150
+ exit(2)
151
+ share {"id": text(now())} as "lampson:run"
152
+ share {"kind": "mcp"} as "lampson:ui"
153
+ -- servers MCP propios de Lampson solo si algún agente ofrecido puede usarlos
154
+ let uses_mcp be false
155
+ each n in offered
156
+ let ts be runtime.get(n)["tools"]
157
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
158
+ set uses_mcp to true
159
+ when uses_mcp
160
+ mcp.start_all(8)
161
+ mcp_server.serve()
162
+ exit(0)
163
+
164
+ -- Subagente en background: `agent Child` (lib/agents.syn) solo llama tasks TOP-LEVEL del programa de entrada
165
+ task lampson_subagent(spec_json)
166
+ give agents.run_child_json(spec_json)
167
+
168
+ -- `lampson run --stdio`: MODO LOCAL (lo usa el SDK). Un proceso abierto, un pedido JSON por línea en stdin:
169
+ -- {"id": "r1", "op": "ask", "to"?, "thread"?, "session"?, "text", "images"?, "meta"?, "mode"?: "strict"|"yolo"}
170
+ -- {"id": "r2", "op": "agents"} · {"id": "r3", "op": "ping"}
171
+ -- y por stdout, una línea JSON por evento con ese id: los mismos que `--json` (session, assistant, tool_call…) y
172
+ -- {"id", "kind": "done", "data": {agent, thread, session, text, steps, usage, stopped}} al terminar cada ask. Al
173
+ -- arrancar, {"kind": "ready", "data": {"agents": […], "protocol": 2}}.
174
+ -- CONCURRENCIA (protocolo 2): cada ask corre en su propio agente de Synsema; conversaciones distintas van en
175
+ -- paralelo, dos asks de la MISMA conversación (agente + thread) esperan en fila. Un agente que imprime sale con
176
+ -- prefijo "[Agente_N]" (rompería el JSON): por eso los trabajos publican en el bus y SOLO el hilo principal escribe.
177
+ -- Sin humano: lo que pida aprobación se deniega; "mode" lo puede fijar quien llama (es su programa, en su máquina).
178
+ task stdio_out(m)
179
+ print(json_encode(m))
180
+ flush()
181
+
182
+ -- un ask, dentro de un agente StdioJob (los agentes solo ven tasks TOP-LEVEL del entry)
183
+ task lampson_stdio_job(req_json)
184
+ let req be json_decode(req_json)
185
+ let rid be req["id"]
186
+ let agent_id be req["to"]
187
+ let th be req["thread"]
188
+ task out(m)
189
+ bus_publish("stdio.out", m)
190
+ task on_event(kind, data, tag)
191
+ when kind != "busy" and kind != "idle"
192
+ out({"id": rid, "kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": th})
193
+ task on_start(info)
194
+ set th to info["thread"]
195
+ out({"id": rid, "kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]})
196
+ let r be nothing
197
+ try
198
+ set r to runtime.deliver(req["sobre"], {"mode": req["mode"], "ask_fn": nothing, "on_event": on_event, "on_start": on_start})
199
+ recover err
200
+ set r to {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
201
+ out({"id": rid, "kind": "done", "data": r, "tag": "", "agent": r["agent"], "thread": r["thread"]})
202
+ bus_publish("stdio.done", {"key": req["key"]})
203
+ give true
204
+
205
+ agent StdioReader
206
+ require stdin
207
+ let l be read_line("")
208
+ while l != nothing
209
+ bus_publish("stdio.line", l)
210
+ set l to read_line("")
211
+ bus_publish("stdio.eof", true)
212
+
213
+ agent StdioJob
214
+ require net
215
+ require exec
216
+ require time
217
+ require random
218
+ require env("LAMPSON_*")
219
+ require env("OS")
220
+ require secret("LAMPSON_*")
221
+ require file("workspace")
222
+ require file("workspace/*")
223
+ require file.read("skills")
224
+ require file.read("skills/*")
225
+ require file.read("plugins")
226
+ require file.read("plugins/*")
227
+ require file.read("agents")
228
+ require file.read("agents/*")
229
+ require file("memory")
230
+ require file("memory/*")
231
+ require file(".lampson")
232
+ require file(".lampson/*")
233
+ lampson_stdio_job(spec_json)
234
+
235
+ -- un pedido ask ya leído → {ok, job, error}: el spec del trabajo (o por qué no)
236
+ task stdio_ask(req, rid)
237
+ let agent_id be lower(text(when contains(req, "to") and req["to"] != nothing and text(req["to"]) != "" then req["to"] otherwise runtime.default_agent()))
238
+ let th be when contains(req, "thread") and req["thread"] != nothing then text(req["thread"]) otherwise ""
239
+ let msg be when contains(req, "text") and req["text"] != nothing then text(req["text"]) otherwise ""
240
+ let spec be runtime.get(agent_id)
241
+ let fail_r be {"agent": agent_id, "thread": th, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": ""}
242
+ when spec == nothing
243
+ set fail_r["stopped"] to "error: no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", ")
244
+ give {"ok": false, "done": fail_r}
245
+ when trim(msg) == ""
246
+ set fail_r["stopped"] to "error: text is required"
247
+ give {"ok": false, "done": fail_r}
248
+ let want be when contains(req, "mode") and req["mode"] != nothing then lower(text(req["mode"])) otherwise ""
249
+ let mode be when want == "strict" or want == "yolo" then want otherwise (when spec["permission"] == "" then "strict" otherwise "")
250
+ let ss be when contains(req, "session") and req["session"] != nothing then text(req["session"]) otherwise ""
251
+ -- la fila es por conversación: (agente, thread), o la sesión; sin ninguno, el pedido solo (va en paralelo)
252
+ let key be when th != "" then agent_id + "\n" + th otherwise (when ss != "" then agent_id + "\nsession:" + ss otherwise "req:" + rid)
253
+ 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 {}}
254
+ give {"ok": true, "key": key, "job": {"id": rid, "to": agent_id, "thread": th, "mode": mode, "key": key, "sobre": sobre}}
255
+
256
+ when env("LAMPSON_RUN_STDIO", "") == "1"
257
+ share {"id": text(now())} as "lampson:run"
258
+ share {"kind": "sdk"} as "lampson:ui"
259
+ let all_names be runtime.names()
260
+ let any_mcp be false
261
+ each n in all_names
262
+ let ts be runtime.get(n)["tools"]
263
+ when contains(ts, "mcp") or length(where(ts, (t) => starts_with(t, "mcp_"))) > 0
264
+ set any_mcp to true
265
+ when any_mcp
266
+ mcp.start_all(8)
267
+ let sub be bus_subscribe(["stdio.line", "stdio.out", "stdio.done", "stdio.eof"], {"max_queue": 100000, "on_full": "error"})
268
+ spawn StdioReader
269
+ stdio_out({"kind": "ready", "data": {"agents": all_names, "protocol": 2}})
270
+ let busy be {}
271
+ let waiting be {}
272
+ let running be 0
273
+ let eof be false
274
+ let open be true
275
+ while open
276
+ let ev be bus_recv(sub, 3600)
277
+ when ev == nothing
278
+ set open to running > 0 or not eof
279
+ otherwise when ev["topic"] == "stdio.out"
280
+ stdio_out(ev["data"])
281
+ otherwise when ev["topic"] == "stdio.done"
282
+ let k be ev["data"]["key"]
283
+ set running to running - 1
284
+ let q be when contains(waiting, k) then waiting[k] otherwise []
285
+ when length(q) > 0
286
+ set waiting[k] to slice(q, 1, length(q))
287
+ set running to running + 1
288
+ spawn StdioJob with spec_json = json_encode(q[0])
289
+ otherwise
290
+ set busy[k] to false
291
+ when eof and running == 0
292
+ set open to false
293
+ otherwise when ev["topic"] == "stdio.eof"
294
+ set eof to true
295
+ when running == 0
296
+ set open to false
297
+ otherwise when ev["topic"] == "stdio.line"
298
+ let line be ev["data"]
299
+ when trim(line) != ""
300
+ let req be nothing
301
+ try
302
+ set req to json_decode(line)
303
+ recover err
304
+ set req to nothing
305
+ when req == nothing or type_of(req) != "map"
306
+ stdio_out({"id": "", "kind": "error", "data": "each line must be a JSON object"})
307
+ otherwise
308
+ let rid be when contains(req, "id") and req["id"] != nothing then text(req["id"]) otherwise ""
309
+ let op be when contains(req, "op") and req["op"] != nothing then lower(text(req["op"])) otherwise "ask"
310
+ when op == "ping"
311
+ stdio_out({"id": rid, "kind": "pong"})
312
+ otherwise when op == "agents"
313
+ stdio_out({"id": rid, "kind": "agents", "data": apply((n) => {"id": n, "description": runtime.get(n)["description"]}, runtime.names())})
314
+ otherwise when op == "ask"
315
+ let a be stdio_ask(req, rid)
316
+ when not a["ok"]
317
+ stdio_out({"id": rid, "kind": "done", "data": a["done"], "tag": "", "agent": a["done"]["agent"], "thread": a["done"]["thread"]})
318
+ otherwise when contains(busy, a["key"]) and busy[a["key"]]
319
+ let wq be when contains(waiting, a["key"]) then waiting[a["key"]] otherwise []
320
+ set waiting[a["key"]] to append(wq, a["job"])
321
+ otherwise
322
+ set busy[a["key"]] to true
323
+ set running to running + 1
324
+ spawn StdioJob with spec_json = json_encode(a["job"])
325
+ otherwise
326
+ stdio_out({"id": rid, "kind": "error", "data": "unknown op '" + op + "' (ask, agents, ping)"})
327
+ exit(0)
328
+
329
+ let json_out be env("LAMPSON_RUN_JSON", "") == "1"
330
+ let agent_id be runtime.default_agent()
331
+ let thread be env("LAMPSON_THREAD", "")
332
+
333
+ task fail_usage(msg)
334
+ when json_out
335
+ print(json_encode({"kind": "error", "data": msg, "tag": "", "agent": agent_id, "thread": thread}))
336
+ otherwise
337
+ print("lampson run: " + msg)
338
+ exit(2)
339
+
340
+ let spec be runtime.get(agent_id)
341
+ when spec == nothing
342
+ fail_usage("no agent named '" + agent_id + "' · available: " + join(runtime.names(), ", "))
343
+
344
+ let message be env("LAMPSON_MESSAGE", "")
345
+ when message == ""
346
+ let lines be []
347
+ let l be read_line("")
348
+ while l != nothing
349
+ set lines to append(lines, l)
350
+ set l to read_line("")
351
+ set message to join(lines, "\n")
352
+ when trim(message) == ""
353
+ fail_usage("empty message (pass it as an argument or on stdin)")
354
+
355
+ let mode be lower(env("LAMPSON_RUN_PERMISSION", ""))
356
+ when mode == "" and spec["permission"] == ""
357
+ set mode to "strict"
358
+
359
+ -- servers MCP solo si el agente puede usarlos (arrancarlos cuesta hasta unos segundos)
360
+ when contains(spec["tools"], "mcp") or length(where(spec["tools"], (t) => starts_with(t, "mcp_"))) > 0
361
+ mcp.start_all(8)
362
+
363
+ share {"id": text(now())} as "lampson:run"
364
+ share {"kind": "cli"} as "lampson:ui"
365
+
366
+ task emit_json(kind, data, tag)
367
+ when kind != "busy" and kind != "idle"
368
+ print(json_encode({"kind": kind, "data": data, "tag": tag, "agent": agent_id, "thread": thread}))
369
+ flush()
370
+
371
+ task on_start(info)
372
+ set thread to info["thread"]
373
+ when json_out
374
+ print(json_encode({"kind": "session", "data": info, "tag": "", "agent": info["agent"], "thread": info["thread"]}))
375
+ flush()
376
+
377
+ let sobre be {"to": agent_id, "thread": thread, "session": env("LAMPSON_SESSION", ""), "from": {"id": "", "name": "", "kind": "human"}, "text": message, "channel": "cli", "meta": {}}
378
+ let hooks be {"mode": mode, "ask_fn": nothing, "on_start": on_start, "on_event": when json_out then emit_json otherwise nothing}
379
+ let result be nothing
380
+ try
381
+ set result to runtime.deliver(sobre, hooks)
382
+ recover err
383
+ set result to {"agent": agent_id, "thread": thread, "session": "", "text": "", "steps": 0, "usage": {"input": 0, "output": 0, "cached": 0}, "stopped": "error: " + text(err)}
384
+
385
+ when json_out
386
+ print(json_encode({"kind": "done", "data": result, "tag": "", "agent": result["agent"], "thread": result["thread"]}))
387
+ otherwise
388
+ when starts_with(result["stopped"], "error")
389
+ print("lampson run: " + result["stopped"])
390
+ otherwise
391
+ print(result["text"])
392
+ flush()
393
+ when starts_with(result["stopped"], "error")
394
+ exit(1)
package/sdk/index.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ // sdk/index.d.ts — types for the Lampson SDK (sdk/index.js)
2
+
3
+ export interface ServerOptions {
4
+ /** The workspace base: "https://my-lampson.com/w/<workspace>" (a trailing /v1 is fine too). */
5
+ url: string;
6
+ /** An API key from `lampson key add`. */
7
+ key: string;
8
+ /** A fetch implementation (default: the global one, Node 18+). */
9
+ fetch?: typeof fetch;
10
+ /** Per-request timeout in ms (default 15 min: an agent can take a while). */
11
+ timeout?: number;
12
+ }
13
+
14
+ export interface LocalOptions {
15
+ local: {
16
+ /** The project folder the agents work in. */
17
+ workspace: string;
18
+ /** LAMPSON_HOME: where Lampson keeps its config, sessions and plugins (default ~/lampson). */
19
+ home?: string;
20
+ /** Extra environment for the Lampson process (e.g. provider keys). */
21
+ env?: Record<string, string>;
22
+ /** Advanced / tests: an exact command that speaks the `lampson run --stdio` protocol. */
23
+ spawn?: { command: string; args?: string[]; cwd?: string };
24
+ };
25
+ }
26
+
27
+ export interface Message {
28
+ /** The agent that answers (alias: `to`). Default: the workspace's default agent. */
29
+ agent?: string;
30
+ to?: string;
31
+ /** Who/what this conversation is (a customer, a ticket, "cto:task-17"): same thread = same conversation. */
32
+ thread?: string;
33
+ /** Or continue a known session id. */
34
+ session?: string;
35
+ text: string;
36
+ images?: { media_type: string; data: string }[];
37
+ meta?: Record<string, unknown>;
38
+ from?: { id?: string; name?: string; kind?: 'human' | 'agent' | 'system' };
39
+ /** When the user wrote it (unix seconds): orders a burst that arrived out of order (server mode). */
40
+ sentAt?: number;
41
+ /** Server mode: answer now with { job, status: "queued" } and POST the result here later. */
42
+ callback?: string;
43
+ /** Local mode: "strict" | "yolo" for this request (default: the agent's, else strict). */
44
+ mode?: 'strict' | 'yolo';
45
+ }
46
+
47
+ export interface Usage { input: number; output: number; cached: number }
48
+
49
+ export interface Result {
50
+ agent: string;
51
+ thread: string;
52
+ session: string;
53
+ text: string;
54
+ steps: number;
55
+ usage: Usage;
56
+ /** "done" | "max_steps" | "budget" | "error: …" */
57
+ stopped: string;
58
+ /** Server mode: ids of the messages answered together (a burst), and the one that leads it. */
59
+ batch?: string[];
60
+ lead?: string;
61
+ }
62
+
63
+ export interface Queued { job: string; status: 'queued' }
64
+
65
+ export interface LampsonEvent {
66
+ kind: 'session' | 'assistant' | 'tool_call' | 'tool_result' | 'tool_denied' | 'usage' | 'inbox' | 'error' | 'compact' | 'done' | string;
67
+ data: any;
68
+ tag?: string;
69
+ agent?: string;
70
+ thread?: string;
71
+ }
72
+
73
+ export interface AgentInfo { id: string; description: string }
74
+
75
+ export class LampsonError extends Error {
76
+ status?: number;
77
+ body?: unknown;
78
+ result?: Result;
79
+ code?: number | null;
80
+ stderr?: string[];
81
+ }
82
+
83
+ export class Lampson {
84
+ constructor(opts: ServerOptions | LocalOptions);
85
+ readonly mode: 'server' | 'local';
86
+ ask(msg: Message): Promise<Result | Queued>;
87
+ stream(msg: Omit<Message, 'callback'>): AsyncGenerator<LampsonEvent, void, unknown>;
88
+ agents(): Promise<AgentInfo[]>;
89
+ job(id: string): Promise<unknown>;
90
+ close(): Promise<void>;
91
+ static verifySignature(rawBody: string | Buffer, signature: string | undefined, secret: string): boolean;
92
+ }
93
+
94
+ export default Lampson;