lampson 0.2.10 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lampson.sh CHANGED
@@ -6,10 +6,32 @@
6
6
  # lampson --domain lampson.midominio.com --email vos@midominio.com # HTTPS propio (opcional) · --domain off
7
7
  # lampson --pair [https://tu-dominio] # QR en la terminal para emparejar el celular
8
8
  # lampson --workspace /ruta [--agent plan] [--yolo|--strict|--ask] · --update
9
+ # lampson run [--agent ID] [--thread T | --session ID] [--json] [--yolo|--strict|--ask] "mensaje" # sin interfaz
10
+ # (sin mensaje lo lee de stdin; --json = eventos JSONL; ver spec/engine.md y run.syn)
11
+ # lampson run --stdio # modo local: un proceso abierto, un pedido JSON por línea (lo usa el SDK)
12
+ # lampson key add [--agent ID[,ID]] [--name NOMBRE] [--rate N] [--callback URL] · key list · key remove <id> # API keys /v1
13
+ # lampson mcp serve [--agent ID[,ID]] [--workspace RUTA] # Lampson como servidor MCP (stdio) para otros agentes
14
+ # lampson channel list · channel on|off <canal> · channel setup <canal> # canales (Telegram, Chatwoot…)
15
+ # lampson objective add "…" --agent ID | --team ID [--budget N] [--round S] · objective list · show <id> · reply <id> "…" [--approve|--deny] · cancel <id> # objetivos
16
+ # lampson team list # equipos de agentes y quién reporta a quién
9
17
  set -euo pipefail
10
- here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
18
+ # se lo llama por el symlink `lampson` (~/.local/bin): la carpeta es donde vive el script de verdad
19
+ here="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
11
20
  caller="$(pwd)"
12
21
  ws=""; web=0; hub=""; install=""; domain="-"; email=""; pair_url="-"
22
+ run=0; msg=""; perm_flag=""; key=""; key_name=""; key_id=""; mcp_serve=""; ch_cmd=""; ch_name=""
23
+ obj_cmd=""; obj_id=""; obj_team=""; obj_budget=""; obj_round=""; obj_decision=""; team_cmd=""
24
+ # `lampson run …`: subcomando sin interfaz (run.syn); las palabras sueltas son el mensaje, no el workspace
25
+ if [ "${1:-}" = run ]; then run=1; shift; fi
26
+ # `lampson key add|list|remove …`: API keys (también corre run.syn, con LAMPSON_KEY_CMD)
27
+ # `lampson mcp serve …`: servidor MCP por stdio (run.syn con LAMPSON_MCP_SERVE)
28
+ if [ "${1:-}" = mcp ] && [ "${2:-}" = serve ]; then run=1; mcp_serve=1; shift 2; fi
29
+ # `lampson channel list|on|off|setup <canal>` (run.syn con LAMPSON_CHANNEL_CMD)
30
+ if [ "${1:-}" = channel ]; then run=1; ch_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
31
+ if [ "${1:-}" = key ]; then run=1; key="${2:-help}"; shift; [ $# -gt 0 ] && shift; fi
32
+ # `lampson objective add|list|show|reply|cancel` y `lampson team list` (run.syn con LAMPSON_OBJ_CMD / LAMPSON_TEAM_CMD)
33
+ if [ "${1:-}" = objective ]; then run=1; obj_cmd="${2:-list}"; shift; [ $# -gt 0 ] && shift; fi
34
+ if [ "${1:-}" = team ]; then run=1; team_cmd=list; shift; [ $# -gt 0 ] && shift; fi
13
35
  while [ $# -gt 0 ]; do
14
36
  case "$1" in
15
37
  --web) web=1 ;;
@@ -21,12 +43,24 @@ while [ $# -gt 0 ]; do
21
43
  --uninstall) install=uninstall ;;
22
44
  --workspace) shift; ws="$1" ;;
23
45
  --agent) shift; export LAMPSON_AGENT="$1" ;;
24
- --yolo|--dangerously-skip-permissions) export LAMPSON_PERMISSION=yolo ;;
25
- --strict) export LAMPSON_PERMISSION=strict ;;
26
- --ask) export LAMPSON_PERMISSION=ask ;;
46
+ --yolo|--dangerously-skip-permissions) export LAMPSON_PERMISSION=yolo; perm_flag=yolo ;;
47
+ --strict) export LAMPSON_PERMISSION=strict; perm_flag=strict ;;
48
+ --ask) export LAMPSON_PERMISSION=ask; perm_flag=ask ;;
49
+ --thread) shift; export LAMPSON_THREAD="$1" ;;
50
+ --session) shift; export LAMPSON_SESSION="$1" ;;
51
+ --json) export LAMPSON_RUN_JSON=1 ;;
52
+ --stdio) export LAMPSON_RUN_STDIO=1 ;;
53
+ --name) shift; key_name="$1" ;;
54
+ --rate) shift; export LAMPSON_KEY_RATE="$1" ;;
55
+ --callback) shift; export LAMPSON_KEY_CALLBACKS="${LAMPSON_KEY_CALLBACKS:+$LAMPSON_KEY_CALLBACKS,}$1" ;;
56
+ --team) shift; obj_team="$1" ;;
57
+ --budget) shift; obj_budget="$1" ;;
58
+ --round) shift; obj_round="$1" ;;
59
+ --approve) obj_decision=approve ;;
60
+ --deny) obj_decision=deny ;;
27
61
  --update) echo "actualizando Lampson en $here"; git -C "$here" pull --ff-only origin main; echo "lampson $(git -C "$here" rev-parse --short HEAD)"; exit $? ;;
28
- -*) echo "uso: lampson [--web] [--hub start|stop|status|logs|restart] [--domain DOMINIO|off [--email EMAIL]] [--pair [URL]] [--install|--uninstall] [--workspace RUTA] [--agent PERFIL] [--yolo|--strict|--ask] [--update]" >&2; exit 1 ;;
29
- *) ws="$1" ;;
62
+ -*) echo "uso: lampson run [--agent ID] [--thread T|--session ID] [--json] [--yolo|--strict|--ask] [mensaje]" >&2; echo "uso: lampson [--web] [--hub start|stop|status|logs|restart] [--domain DOMINIO|off [--email EMAIL]] [--pair [URL]] [--install|--uninstall] [--workspace RUTA] [--agent PERFIL] [--yolo|--strict|--ask] [--update]" >&2; exit 1 ;;
63
+ *) if [ -n "$obj_cmd" ] && [ -z "$obj_id" ] && { [ "$obj_cmd" = show ] || [ "$obj_cmd" = reply ] || [ "$obj_cmd" = cancel ]; }; then obj_id="$1"; elif [ -n "$obj_cmd" ]; then msg="${msg:+$msg }$1"; elif [ -n "$ch_cmd" ]; then ch_name="$1"; elif [ -n "$key" ]; then key_id="$1"; elif [ "$run" = 1 ]; then msg="${msg:+$msg }$1"; else ws="$1"; fi ;;
30
64
  esac
31
65
  shift
32
66
  done
@@ -56,6 +90,33 @@ cli() { # última línea = JSON
56
90
  echo "$out" | tail -n 1
57
91
  }
58
92
  json() { node -e "const j=JSON.parse(process.argv[1]);const v=j[process.argv[2]];console.log(typeof v==='object'?JSON.stringify(v):v)" "$1" "$2" 2>/dev/null || python3 -c "import json,sys;print(json.loads(sys.argv[1])[sys.argv[2]])" "$1" "$2"; }
93
+ unit="$HOME/.config/systemd/user/lampson-hub.service"
94
+ # systemd no hereda el PATH de la sesión (~/.local/bin, donde se instala synsema, no está): sin estas dos líneas el hub
95
+ # arranca pero no puede encender ningún workspace ni los agentes encuentran node, git, claude…
96
+ write_unit() {
97
+ mkdir -p "$(dirname "$unit")"
98
+ cat > "$unit" <<EOF
99
+ [Unit]
100
+ Description=Lampson hub (workspaces, tareas programadas, proxy)
101
+ After=network.target
102
+ [Service]
103
+ WorkingDirectory=$here
104
+ Environment=LAMPSON_HOME=$here
105
+ Environment="LAMPSON_SYNSEMA=$(command -v synsema)"
106
+ Environment="PATH=$(dirname "$(command -v synsema)"):$PATH"
107
+ ExecStart=$(command -v synsema) serve hub.syn
108
+ Restart=always
109
+ RestartSec=3
110
+ TimeoutStopSec=20
111
+ [Install]
112
+ WantedBy=default.target
113
+ EOF
114
+ }
115
+ # una unit de antes de ese arreglo se reescribe sola (una vez) y el hub se reinicia con el PATH bueno
116
+ if [ "$install" = "" ] && [ -f "$unit" ] && ! grep -q LAMPSON_SYNSEMA "$unit"; then
117
+ write_unit
118
+ systemctl --user daemon-reload && systemctl --user restart lampson-hub.service && echo "lampson: servicio del hub actualizado (PATH del motor)" >&2 || true
119
+ fi
59
120
  # dominio propio (opcional): HTTPS automático con Let's Encrypt delante del hub
60
121
  if [ "$domain" != "-" ]; then
61
122
  (cd "$here" && LAMPSON_CMD=domain LAMPSON_DOMAIN="$domain" LAMPSON_EMAIL="$email" synsema run cli.syn | sed '$d')
@@ -90,33 +151,20 @@ if [ -n "$hub" ]; then
90
151
  exit 0
91
152
  fi
92
153
  if [ "$install" = install ]; then
93
- unit="$HOME/.config/systemd/user/lampson-hub.service"; mkdir -p "$(dirname "$unit")"
94
- cat > "$unit" <<EOF
95
- [Unit]
96
- Description=Lampson hub (workspaces, tareas programadas, proxy)
97
- After=network.target
98
- [Service]
99
- WorkingDirectory=$here
100
- Environment=LAMPSON_HOME=$here
101
- ExecStart=$(command -v synsema) serve hub.syn
102
- Restart=always
103
- RestartSec=3
104
- TimeoutStopSec=20
105
- [Install]
106
- WantedBy=default.target
107
- EOF
154
+ write_unit
108
155
  (cd "$here" && LAMPSON_CMD=hub-stop synsema run cli.syn >/dev/null 2>&1 || true)
109
156
  systemctl --user daemon-reload && systemctl --user enable --now lampson-hub.service && echo "instalado: systemd --user lampson-hub.service (arranca con tu sesión; 'loginctl enable-linger $USER' para que viva sin sesión abierta)"
110
157
  exit 0
111
158
  fi
112
- if [ "$install" = uninstall ]; then systemctl --user disable --now lampson-hub.service || true; rm -f "$HOME/.config/systemd/user/lampson-hub.service"; systemctl --user daemon-reload; echo "quitado"; exit 0; fi
159
+ if [ "$install" = uninstall ]; then systemctl --user disable --now lampson-hub.service || true; rm -f "$unit"; systemctl --user daemon-reload; echo "quitado"; exit 0; fi
113
160
  # --- proyecto ---
114
161
  [ -z "$ws" ] && [ "$caller" != "$here" ] && ws="$caller"
115
162
  [ -n "$ws" ] || { echo "corré lampson desde la carpeta del proyecto, o --workspace /ruta (lampson --hub status lista los workspaces)" >&2; exit 1; }
116
163
  [ -d "$ws" ] || { echo "el workspace no existe o no es un directorio: $ws" >&2; exit 1; }
117
164
  ws="$(cd "$ws" && pwd -P)"
118
165
  [ "$ws" = "$HOME" ] || [ "$ws" = "/" ] && { echo "'$ws' no es un proyecto" >&2; exit 1; }
119
- r="$(cli ensure "$ws")"
166
+ # `run`, `key`, `channel` y `mcp serve` no necesitan servidor: solo la carpeta del workspace (sin hub)
167
+ r="$(cli "$([ "$run" = 1 ] && echo prepare || echo ensure)" "$ws")"
120
168
  slug="$(json "$r" slug)"; port="$(json "$r" port)"; url="$(json "$r" url)"; dir="$(json "$r" dir)"
121
169
  if [ "$web" = 1 ]; then
122
170
  echo "Lampson web · $url (workspace $slug)"
@@ -130,4 +178,14 @@ jp="$(json "$r" judge_provider)"; jm="$(json "$r" judge_model)"; jk="$(json "$r"
130
178
  [ -n "$jp" ] && export SYNSEMA_JUDGE_PROVIDER="$jp"
131
179
  [ -n "$jm" ] && export SYNSEMA_JUDGE_MODEL="$jm"
132
180
  [ -n "$jk" ] && export TYPESAFE_API_KEY="$jk"
133
- if [ -f "$here/.env" ]; then exec synsema run --env-file "$here/.env" chat.syn; else exec synsema run chat.syn; fi
181
+ entry=chat.syn
182
+ if [ "$run" = 1 ]; then
183
+ # sin interfaz: los permisos los fija el flag, o el agente (run.syn: strict si el agente no dice nada)
184
+ entry=run.syn; export LAMPSON_MESSAGE="$msg" LAMPSON_RUN_PERMISSION="$perm_flag"
185
+ export LAMPSON_KEY_CMD="$key" LAMPSON_KEY_NAME="$key_name" LAMPSON_KEY_ID="$key_id" LAMPSON_KEY_AGENTS="${LAMPSON_AGENT:-}"
186
+ export LAMPSON_CHANNEL_CMD="$ch_cmd" LAMPSON_CHANNEL_NAME="$ch_name"
187
+ export LAMPSON_OBJ_CMD="$obj_cmd" LAMPSON_OBJ_ID="$obj_id" LAMPSON_OBJ_AGENT="$([ -n "$obj_cmd" ] && echo "${LAMPSON_AGENT:-}")" LAMPSON_OBJ_TEAM="$obj_team"
188
+ export LAMPSON_OBJ_BUDGET="$obj_budget" LAMPSON_OBJ_ROUND="$obj_round" LAMPSON_OBJ_DECISION="$obj_decision" LAMPSON_TEAM_CMD="$team_cmd"
189
+ export LAMPSON_MCP_SERVE="$mcp_serve" LAMPSON_MCP_AGENTS="$([ -n "$mcp_serve" ] && echo "${LAMPSON_AGENT:-}")"
190
+ fi
191
+ if [ -f "$here/.env" ]; then exec synsema run --env-file "$here/.env" "$entry"; else exec synsema run "$entry"; fi
package/lib/api.syn ADDED
@@ -0,0 +1,292 @@
1
+ -- lib/api.syn — la API HTTP /v1 de un workspace (spec/engine.md, fase 2). Las rutas viven en web.syn; acá la lógica.
2
+ --
3
+ -- GET /w/<slug>/v1/agents los agentes que la key puede usar
4
+ -- POST /w/<slug>/v1/messages un sobre → respuesta. Tres formas:
5
+ -- {"to", "thread", "text", "images", "from", "meta"} → JSON con el resultado (espera el turno)
6
+ -- … + "stream": true → SSE: los mismos eventos que `lampson run --json`
7
+ -- … + "callback": "https://…" → 202 {job} enseguida; el resultado va por POST
8
+ -- al callback (canal `http`: WhatsApp, n8n…)
9
+ -- GET /w/<slug>/v1/jobs/<id> estado de un trabajo asíncrono
10
+ --
11
+ -- Auth: SIEMPRE `Authorization: Bearer lk_…` (lib/apikeys.syn), también por loopback: el hub reenvía /v1 sin pedir
12
+ -- passkey y este proceso confía en todo lo que le llega del hub, así que la key es la única puerta.
13
+ -- Todo mensaje pasa por el buzón de su conversación (lib/mailbox.syn): fila por (agente, thread), espera de silencio
14
+ -- ("buffer" del agente; default 3 s / tope 15 s) y lo que llega a mitad de turno entra al turno en curso. Los
15
+ -- mensajes de una ráfaga reciben la MISMA respuesta, con "batch" (ids del lote) y "lead" (el que lo encabeza).
16
+ -- Permisos: el modo del agente, o strict si no dice. En `ask`, la aprobación sale por la cola de lib/approvals.syn
17
+ -- (UI, link firmado al webhook, /approve en la terminal) y vence → denegado. Nunca se auto-aprueba.
18
+ -- Callback: UN POST por lote y URL: {job, jobs, batch, status, agent, thread, session, text, steps, usage, stopped,
19
+ -- meta}; con LAMPSON_WEBHOOK_SECRET va firmado (X-Lampson-Signature: sha256=<hmac hex>). Los demás jobs del lote
20
+ -- quedan "merged" (merged_into = el que encabeza).
21
+
22
+ use "./runtime.syn" as runtime
23
+ use "./apikeys.syn" as apikeys
24
+ use "./mailbox.syn" as mailbox
25
+ use "./teams.syn" as teams
26
+
27
+
28
+ -- la key del header Authorization (o nothing)
29
+ export task bearer_of(h)
30
+ let a be ""
31
+ each k in keys(h)
32
+ when lower(k) == "authorization"
33
+ set a to text(h[k])
34
+ when starts_with(lower(a), "bearer ")
35
+ give trim(slice(a, 7, length(a)))
36
+ give nothing
37
+
38
+ -- {ok, key, status, error}: la key válida, o por qué no
39
+ export task authorize(h)
40
+ require time
41
+ require file(".lampson")
42
+ require file(".lampson/*")
43
+ let rec be apikeys.check(bearer_of(h))
44
+ when rec == nothing
45
+ give {"ok": false, "key": nothing, "status": 401, "error": "missing or invalid API key (Authorization: Bearer lk_…; create one with `lampson key add`)", "retry_after": 0}
46
+ -- rate limit por key: ventana de un minuto (estado de serve, compartido por todos los handlers)
47
+ when rec["rate"] > 0
48
+ let win be floor(now() / 60)
49
+ let n be state_incr("rl:" + rec["id"] + ":" + text(win), 1)
50
+ when n == 1
51
+ state_delete("rl:" + rec["id"] + ":" + text(win - 1))
52
+ when n > rec["rate"]
53
+ give {"ok": false, "key": rec, "status": 429, "error": "rate limit: " + text(rec["rate"]) + " requests per minute for this API key", "retry_after": 60 - floor(now() - win * 60)}
54
+ give {"ok": true, "key": rec, "status": 200, "error": "", "retry_after": 0}
55
+
56
+ -- la respuesta de error de authorize (429 con Retry-After)
57
+ export task refuse(a)
58
+ let r be fail(a["status"], a["error"])
59
+ when a["status"] == 429
60
+ give with_header(r, "Retry-After", text(a["retry_after"]))
61
+ give r
62
+
63
+ -- los agentes que esta key puede usar: [{id, description}]
64
+ export task agents_for(rec)
65
+ require file.read("workspace")
66
+ require file.read("workspace/*")
67
+ require file.read("agents")
68
+ require file.read("agents/*")
69
+ let out be []
70
+ each id in runtime.names()
71
+ when apikeys.allows(rec, id)
72
+ set out to append(out, {"id": id, "description": runtime.get(id)["description"]})
73
+ give out
74
+
75
+ task field(m, k, fallback)
76
+ when contains(m, k)
77
+ when m[k] != nothing
78
+ give m[k]
79
+ give fallback
80
+
81
+ -- {ok, sobre, callback, stream, status, error}: el body de POST /v1/messages ya validado contra la key
82
+ export task parse(body, rec)
83
+ require env("LAMPSON_*")
84
+ require file.read("workspace")
85
+ require file.read("workspace/*")
86
+ require file.read("agents")
87
+ require file.read("agents/*")
88
+ when body == nothing or type_of(body) != "map"
89
+ give {"ok": false, "status": 400, "error": "body must be a JSON object"}
90
+ let msg be text(field(body, "text", ""))
91
+ when trim(msg) == ""
92
+ give {"ok": false, "status": 400, "error": "text is required"}
93
+ let target be lower(text(field(body, "to", runtime.default_agent())))
94
+ when not contains(runtime.names(), target)
95
+ give {"ok": false, "status": 404, "error": "no agent named '" + target + "'"}
96
+ when not apikeys.allows(rec, target)
97
+ give {"ok": false, "status": 403, "error": "this API key cannot use agent '" + target + "'"}
98
+ let cb be text(field(body, "callback", ""))
99
+ when cb != "" and not (starts_with(cb, "https://") or starts_with(cb, "http://"))
100
+ give {"ok": false, "status": 400, "error": "callback must be an http(s) URL"}
101
+ when cb != "" and not apikeys.callback_allowed(rec, cb)
102
+ give {"ok": false, "status": 403, "error": "this API key cannot send callbacks to " + cb + " (allowed: " + join(rec["callbacks"], ", ") + ")"}
103
+ let images be field(body, "images", [])
104
+ when type_of(images) != "list"
105
+ set images to []
106
+ let from be field(body, "from", {})
107
+ when type_of(from) != "map"
108
+ set from to {}
109
+ let meta be field(body, "meta", {})
110
+ when type_of(meta) != "map"
111
+ set meta to {}
112
+ -- la hora en que el cliente escribió (unix s), si el canal la da: ordena una ráfaga que llegó desordenada
113
+ when contains(body, "sent_at") and body["sent_at"] != nothing
114
+ set meta["sent_at"] to body["sent_at"]
115
+ let sobre be {"to": target, "thread": text(field(body, "thread", "")), "session": text(field(body, "session", "")), "from": from, "text": msg, "images": images, "channel": text(field(body, "channel", "http")), "meta": meta}
116
+ give {"ok": true, "status": 200, "error": "", "sobre": sobre, "callback": cb, "stream": field(body, "stream", false) == true}
117
+
118
+ -- el modo de un agente por la API: el suyo, y si no dice → strict (nadie en la request para preguntarle)
119
+ export task mode_for(spec)
120
+ give when spec != nothing and spec["permission"] != "" then "" otherwise "strict"
121
+
122
+ -- opts del buzón (lib/mailbox.syn) para un sobre ya validado
123
+ export task mailbox_opts(sobre)
124
+ require file.read("workspace")
125
+ require file.read("workspace/*")
126
+ require file.read("agents")
127
+ require file.read("agents/*")
128
+ let spec be runtime.get(sobre["to"])
129
+ give {"mode": mode_for(spec), "buffer": mailbox.buffer_of(spec, mailbox.DEFAULT_BUFFER)}
130
+
131
+ -- registro de un trabajo con callback (lo completa el worker del buzón al entregar)
132
+ export task create_job(id, rec, sobre, callback)
133
+ require time
134
+ require file(".lampson")
135
+ require file(".lampson/*")
136
+ mailbox.save_job({"job": id, "status": "queued", "key": rec["id"], "agent": sobre["to"], "thread": sobre["thread"], "callback": callback, "created": format_time(now()), "result": nothing, "delivered": false, "merged_into": nothing})
137
+
138
+ export task job(id)
139
+ require file.read(".lampson")
140
+ require file.read(".lampson/*")
141
+ give mailbox.job(id)
142
+
143
+ -- MCP por HTTP (lib/mcp_server.syn): un `ask` pasa por el buzón de su conversación. Entre agentes no hay espera de
144
+ -- silencio salvo que el agente la configure (`buffer`): la fila sí, siempre.
145
+ export task mcp_deliver(sobre, mode)
146
+ require time
147
+ require random
148
+ require file.read("workspace")
149
+ require file.read("workspace/*")
150
+ require file.read("agents")
151
+ require file.read("agents/*")
152
+ let spec be runtime.get(sobre["to"])
153
+ let s be mailbox.submit(sobre, {"mode": mode, "buffer": mailbox.buffer_of(spec, false)})
154
+ give mailbox.wait(s["id"])
155
+
156
+
157
+ -- ---------- objetivos (lib/teams.syn) ----------
158
+ -- un objetivo con su tablero y su registro, como lo devuelve la API
159
+ export task objective_view(o)
160
+ require db(".lampson/teams.db")
161
+ require file(".lampson")
162
+ require file(".lampson/*")
163
+ let scope be teams.obj_scope(o)
164
+ let ts be apply(teams.tasks(scope), (t) => {"id": t["id"], "title": t["title"], "status": t["status"], "owner": t["owner"], "notes": t["notes"], "depends": json_decode(t["depends"])})
165
+ let lg be apply(teams.ledger(scope, 0, 100), (r) => {"id": r["id"], "at": r["at"], "actor": r["actor"], "kind": r["kind"], "ref": r["ref"], "text": r["text"]})
166
+ give {"id": o["id"], "ref": "O-" + text(o["id"]), "agent": o["agent"], "team": o["team"], "text": o["text"], "status": o["status"], "progress": o["progress"], "question": o["question"], "question_kind": o["question_kind"], "result": o["result"], "turns": o["turns"], "spent": o["spent"], "budget_tokens": o["budget_tokens"], "round_seconds": o["round_seconds"], "created_at": o["created_at"], "updated_at": o["updated_at"], "tasks": ts, "ledger": lg}
167
+
168
+ -- POST /v1/objectives: {agent, text, round_seconds?, budget_tokens?} → {ok, id} / {ok: false, status, error}
169
+ export task create_objective(body, rec)
170
+ require db(".lampson/teams.db")
171
+ require time
172
+ require file(".lampson")
173
+ require file(".lampson/*")
174
+ require file.read("workspace")
175
+ require file.read("workspace/*")
176
+ require file.read("agents")
177
+ require file.read("agents/*")
178
+ let agent be lower(text(field(body, "agent", "")))
179
+ let tid be lower(text(field(body, "team", "")))
180
+ when tid != ""
181
+ let tm be teams.get(tid)
182
+ when tm == nothing
183
+ give {"ok": false, "status": 404, "error": "no team named '" + tid + "'"}
184
+ when agent == ""
185
+ set agent to teams.lead_of(tm)
186
+ when teams.member(tm, agent) == nothing
187
+ give {"ok": false, "status": 400, "error": agent + " is not in team " + tid}
188
+ when agent == ""
189
+ give {"ok": false, "status": 400, "error": "agent (or team) is required"}
190
+ when runtime.get(agent) == nothing
191
+ give {"ok": false, "status": 404, "error": "no agent named '" + agent + "'"}
192
+ when not apikeys.allows(rec, agent)
193
+ give {"ok": false, "status": 403, "error": "this API key can't use agent '" + agent + "'"}
194
+ when trim(text(field(body, "text", ""))) == ""
195
+ give {"ok": false, "status": 400, "error": "text is required"}
196
+ let opts be {"budget_tokens": field(body, "budget_tokens", 500000), "created_by": "api:" + rec["name"], "team": tid}
197
+ when field(body, "round_seconds", nothing) != nothing
198
+ set opts["round_seconds"] to body["round_seconds"]
199
+ let id be teams.obj_create(agent, field(body, "text", ""), opts)
200
+ give {"ok": true, "id": id}
201
+
202
+ -- el objetivo si la key puede verlo (su agente), si no nothing
203
+ export task objective_for(id, rec)
204
+ require db(".lampson/teams.db")
205
+ require file(".lampson")
206
+ require file(".lampson/*")
207
+ let o be teams.obj_get(floor(number(id)))
208
+ when o == nothing or not apikeys.allows(rec, o["agent"])
209
+ give nothing
210
+ give o
211
+
212
+
213
+ -- los equipos con su gente (rol, a quién reporta, si está trabajando ahora, lo gastado hoy), su tablero y su registro
214
+ export task teams_view()
215
+ require db(".lampson/teams.db")
216
+ require time
217
+ require file(".lampson")
218
+ require file(".lampson/*")
219
+ require file.read("workspace")
220
+ require file.read("workspace/*")
221
+ require file.read("agents")
222
+ require file.read("agents/*")
223
+ let sc be teams.scan()
224
+ let out be []
225
+ each t in sc["teams"]
226
+ let scope be "team:" + t["id"]
227
+ let members be []
228
+ each m in t["members"]
229
+ let spec be runtime.get(m["agent"])
230
+ set members to append(members, {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"], "description": when spec == nothing then "" otherwise spec["description"], "system": when spec == nothing then "" otherwise spec["system"], "tools": when spec == nothing then [] otherwise spec["tools"], "permission": when spec == nothing then "" otherwise spec["permission"], "missing": spec == nothing, "working": mailbox.working(m["agent"], scope), "spent_today": teams.spent_today(m["agent"]), "peers": teams.peers(t, m["agent"])})
231
+ let ts be apply(teams.tasks(scope), (x) => {"id": x["id"], "title": x["title"], "status": x["status"], "owner": x["owner"], "notes": x["notes"], "depends": json_decode(x["depends"])})
232
+ let lg be apply(teams.ledger(scope, 0, 150), (r) => {"id": r["id"], "at": r["at"], "actor": r["actor"], "kind": r["kind"], "ref": r["ref"], "text": r["text"]})
233
+ set out to append(out, {"id": t["id"], "description": t["description"], "members": members, "talks": t["talks"], "round_minutes": t["round_minutes"], "budget_daily_tokens": t["budget_daily_tokens"], "worktrees": t["worktrees"], "lead": teams.lead_of(t), "tasks": ts, "ledger": lg})
234
+ give {"teams": out, "errors": sc["errors"]}
235
+
236
+
237
+ -- guardar un equipo desde la pantalla: el archivo del equipo y los de sus agentes (los que vienen). Cada agente
238
+ -- conserva lo que su archivo ya tenía y pisa solo lo que se editó. → {ok, error}
239
+ export let TOOL_PRESETS be {"code": ["read", "write", "edit", "ls", "find", "grep", "bash", "todo"], "read": ["read", "ls", "find", "grep", "bash"], "none": []}
240
+
241
+ export task save_team(body)
242
+ require db(".lampson/teams.db")
243
+ require time
244
+ require file(".lampson")
245
+ require file(".lampson/*")
246
+ require file("workspace")
247
+ require file("workspace/*")
248
+ require file.read("agents")
249
+ require file.read("agents/*")
250
+ let t be field(body, "team", nothing)
251
+ when t == nothing
252
+ give {"ok": false, "error": "team is required"}
253
+ let v be teams.validate(t, "team")
254
+ when not v["ok"]
255
+ give {"ok": false, "error": v["error"]}
256
+ let team be v["team"]
257
+ let files be []
258
+ each a in field(body, "agents", [])
259
+ let id be lower(text(field(a, "id", "")))
260
+ let path be runtime.PROJECT_DIR + "/" + id + runtime.SUFFIX
261
+ let cur be {}
262
+ when file_exists(path)
263
+ try
264
+ set cur to json_decode(read_file(path))
265
+ recover err
266
+ set cur to {}
267
+ set cur["id"] to id
268
+ each key in ["description", "system", "permission", "base"]
269
+ when contains(a, key) and a[key] != nothing
270
+ set cur[key] to text(a[key])
271
+ when not contains(cur, "base")
272
+ set cur["base"] to "lampson"
273
+ when contains(a, "preset") and a["preset"] != nothing and contains(TOOL_PRESETS, text(a["preset"]))
274
+ set cur["tools"] to TOOL_PRESETS[text(a["preset"])]
275
+ when not contains(cur, "tools")
276
+ set cur["tools"] to TOOL_PRESETS["code"]
277
+ when not contains(cur, "steps")
278
+ set cur["steps"] to 25
279
+ let av be runtime.validate(cur, id + runtime.SUFFIX)
280
+ when not av["ok"]
281
+ give {"ok": false, "error": av["error"]}
282
+ set files to append(files, {"path": path, "doc": cur})
283
+ -- los miembros sin archivo de agente (ni del proyecto ni global) no pueden trabajar
284
+ each m in team["members"]
285
+ when runtime.get(m["agent"]) == nothing and length(where(files, (f) => f["doc"]["id"] == m["agent"])) == 0
286
+ give {"ok": false, "error": "agent '" + m["agent"] + "' has no file yet — give it a personality to create it"}
287
+ each f in files
288
+ write_file(f["path"], json_encode(f["doc"]))
289
+ let raw be {"id": team["id"], "description": team["description"], "members": apply(team["members"], (m) => {"agent": m["agent"], "role": m["role"], "reports_to": m["reports_to"]}), "talks": team["talks"], "round_minutes": team["round_minutes"], "budget_daily_tokens": team["budget_daily_tokens"], "worktrees": team["worktrees"]}
290
+ write_file(teams.DIR + "/" + team["id"] + ".team.json", json_encode(raw))
291
+ teams.log("team:" + team["id"], "person", "team saved", "", join(apply(team["members"], (m) => m["agent"] + " (" + m["role"] + ")"), ", "))
292
+ give {"ok": true, "error": ""}
@@ -0,0 +1,115 @@
1
+ -- lib/apikeys.syn — API keys de la API /v1 (spec/engine.md, fase 2)
2
+ --
3
+ -- Una key = acceso por HTTP a ciertos agentes de ESTE workspace. Se guarda solo su hash (sha256), en el estado del
4
+ -- workspace (.lampson/api_keys.json, al lado de las sesiones): nunca en la carpeta del proyecto, que puede ir a git.
5
+ -- La key en claro se muestra UNA vez, al crearla (`lampson key add`).
6
+ --
7
+ -- create(name, agents) → {id, key, name, agents} agents: ["tienda"] o ["*"] (todos los elegibles)
8
+ -- create_with(name, agents, {rate, callbacks}) rate = pedidos/minuto (default 120; 0 = sin límite);
9
+ -- callbacks = prefijos de URL permitidos ([] = cualquiera)
10
+ -- check(key) → registro sin hash | nothing (y anota last_used)
11
+ -- allows(rec, agent) → bool
12
+ -- list() / remove(id)
13
+
14
+ export let FILE be ".lampson/api_keys.json"
15
+ export let PREFIX be "lk_"
16
+ export let DEFAULT_RATE be 120
17
+
18
+ task hash_of(key)
19
+ give decode(sha256("lampson-api:" + key), "hex")
20
+
21
+ task load()
22
+ require file.read(".lampson")
23
+ require file.read(".lampson/*")
24
+ try
25
+ let d be json_decode(read_file(FILE))
26
+ when contains(d, "keys")
27
+ give d["keys"]
28
+ recover err
29
+ give []
30
+ give []
31
+
32
+ task store(keys_list)
33
+ require file(".lampson")
34
+ require file(".lampson/*")
35
+ write_file(FILE, json_encode({"keys": keys_list}))
36
+
37
+ task public(k)
38
+ give {"id": k["id"], "name": k["name"], "agents": k["agents"], "created": k["created"], "last_used": k["last_used"], "rate": when contains(k, "rate") then k["rate"] otherwise DEFAULT_RATE, "callbacks": when contains(k, "callbacks") then k["callbacks"] otherwise []}
39
+
40
+ export task create(name, agents)
41
+ require time
42
+ require random
43
+ require file(".lampson")
44
+ require file(".lampson/*")
45
+ give create_with(name, agents, {})
46
+
47
+ export task create_with(name, agents, opts)
48
+ require time
49
+ require random
50
+ require file(".lampson")
51
+ require file(".lampson/*")
52
+ let ag be when agents == nothing or length(agents) == 0 then ["*"] otherwise agents
53
+ let rate be when contains(opts, "rate") and opts["rate"] != nothing then floor(number(opts["rate"])) otherwise DEFAULT_RATE
54
+ let cbs be when contains(opts, "callbacks") and opts["callbacks"] != nothing then opts["callbacks"] otherwise []
55
+ let key be PREFIX + token(24)
56
+ let id be "k" + slice(token(16), 0, 8)
57
+ let rec be {"id": id, "name": text(name), "agents": ag, "hash": hash_of(key), "created": format_time(now()), "last_used": nothing, "rate": rate, "callbacks": cbs}
58
+ store(append(load(), rec))
59
+ give {"id": id, "key": key, "name": rec["name"], "agents": ag, "rate": rate, "callbacks": cbs}
60
+
61
+ -- ¿esta key puede pedir un callback a esta URL? sin lista = cualquiera; con lista = solo esos prefijos
62
+ export task callback_allowed(rec, url)
63
+ when not contains(rec, "callbacks") or length(rec["callbacks"]) == 0
64
+ give true
65
+ each pre in rec["callbacks"]
66
+ when starts_with(url, pre)
67
+ give true
68
+ give false
69
+
70
+ export task list()
71
+ require file.read(".lampson")
72
+ require file.read(".lampson/*")
73
+ give apply((k) => public(k), load())
74
+
75
+ export task remove(id)
76
+ require file(".lampson")
77
+ require file(".lampson/*")
78
+ let all be load()
79
+ let rest be where(all, (k) => k["id"] != id)
80
+ when length(rest) == length(all)
81
+ give false
82
+ store(rest)
83
+ give true
84
+
85
+ -- el registro de la key (sin hash) o nothing. Anota last_used como mucho una vez por minuto (no reescribir en cada request)
86
+ export task check(key)
87
+ require time
88
+ require file(".lampson")
89
+ require file(".lampson/*")
90
+ when key == nothing
91
+ give nothing
92
+ let k be text(key)
93
+ when not starts_with(k, PREFIX)
94
+ give nothing
95
+ let h be hash_of(k)
96
+ let all be load()
97
+ let found be nothing
98
+ let changed be false
99
+ let out be []
100
+ each r in all
101
+ when r["hash"] == h
102
+ set found to public(r)
103
+ let stamp be format_time(now(), "%Y-%m-%dT%H:%M")
104
+ when r["last_used"] == nothing or slice(text(r["last_used"]), 0, 16) != stamp
105
+ set r["last_used"] to format_time(now())
106
+ set changed to true
107
+ set out to append(out, r)
108
+ when changed
109
+ store(out)
110
+ give found
111
+
112
+ export task allows(rec, agent)
113
+ when rec == nothing
114
+ give false
115
+ give contains(rec["agents"], "*") or contains(rec["agents"], agent)
package/lib/approvals.syn CHANGED
@@ -131,6 +131,13 @@ export task wait(id, timeout_s)
131
131
  share nothing as "approval:token:" + id
132
132
  give ok
133
133
 
134
+ -- lo mismo, diciendo si nadie respondió (para que el agente sepa que no fue un «no»)
135
+ export task wait_detail(id, timeout_s)
136
+ require time
137
+ let ok be wait(id, timeout_s)
138
+ let meta be meta_of(id)
139
+ give {"approved": ok, "expired": meta != nothing and meta["status"] == "expired", "minutes": floor(timeout_s / 60)}
140
+
134
141
  -- responder desde la UI (loopback, ya autenticado) o desde la terminal: sin token
135
142
  export task answer(id, decision)
136
143
  let meta be meta_of(id)