lampson 0.3.0 → 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/lib/teams.syn ADDED
@@ -0,0 +1,802 @@
1
+ -- lib/teams.syn — equipos de agentes: el grafo, el tablero, el registro, los mensajes, las rondas y el presupuesto
2
+ --
3
+ -- Vocabulario (spec/engine.md, fase 6): agente · equipo · rol · tablero con tareas · ronda · mensaje · objetivo.
4
+ --
5
+ -- Un EQUIPO es un archivo del proyecto, workspace/.lampson/teams/<id>.team.json:
6
+ -- {"id": "empresa", "description": "…",
7
+ -- "members": [{"agent": "ceo", "role": "CEO"},
8
+ -- {"agent": "cto", "role": "CTO", "reports_to": "ceo"},
9
+ -- {"agent": "dev", "role": "Dev", "reports_to": "cto"}],
10
+ -- "talks": [["cmo", "cpo"]], (opcional: pares que también se escriben, además de jefe ↔ reporte)
11
+ -- "round_minutes": 60, (opcional: cada cuánto un agente con trabajo hace una ronda; 0 = sin rondas)
12
+ -- "budget_daily_tokens": 400000} (opcional: tope diario POR agente dentro del equipo; 0 = sin tope)
13
+ -- Los agentes son los de siempre (lib/runtime.syn): su archivo pone la personalidad, el modelo y los permisos; el
14
+ -- equipo pone el rol y el grafo. El grafo es una REGLA: `send` a quien no tiene flecha se rechaza en el motor.
15
+ --
16
+ -- Todo lo compartido vive en SQLite (.lampson/teams.db, del workspace): varios agentes trabajan en paralelo y un
17
+ -- JSON se pisaría; "tomar una tarea" es un UPDATE condicional (gana uno solo). Si el proceso se reinicia, nada se
18
+ -- pierde. Tablas:
19
+ -- tasks (id, scope, title, notes, owner, status, depends, created_by, created_at, updated_at)
20
+ -- ledger el registro: quién hizo qué y cuándo — solo crece (como el historial de git)
21
+ -- messages de un agente a otro; el tick del servidor (lib/teamrun.syn) los entrega por el buzón
22
+ -- cursors hasta dónde leyó cada agente el registro (para «desde tu último turno pasó esto»)
23
+ -- rounds cuándo fue la última ronda de cada agente
24
+ -- spend tokens por día y por agente (el presupuesto)
25
+ -- objectives un OBJETIVO: lo que le pedís a un agente para que trabaje solo hasta terminarlo (más abajo)
26
+ -- scope = "team:<id>" u "objective:<id>".
27
+ --
28
+ -- Quién llama: las tools `send` y `board` reciben `_agent` (lo pone lib/loop.syn desde opts.agent_id; el modelo no
29
+ -- puede elegirlo). Este módulo no importa runtime ni mailbox (ellos lo importan a él).
30
+
31
+ export let DB be ".lampson/teams.db"
32
+ export let DIR be "workspace/.lampson/teams"
33
+ export let STATUSES be ["todo", "doing", "review", "done", "blocked"]
34
+ let DIGEST_MAX be 30
35
+
36
+ -- ---------- base de datos ----------
37
+ task open()
38
+ require db(".lampson/teams.db")
39
+ require file(".lampson")
40
+ require file(".lampson/*")
41
+ db_open(DB)
42
+ sql_exec("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, title TEXT NOT NULL, notes TEXT DEFAULT '', owner TEXT DEFAULT '', status TEXT DEFAULT 'todo', depends TEXT DEFAULT '[]', created_by TEXT DEFAULT '', created_at REAL, updated_at REAL)")
43
+ sql_exec("CREATE TABLE IF NOT EXISTS ledger (id INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, at REAL, actor TEXT, kind TEXT, ref TEXT DEFAULT '', text TEXT DEFAULT '')")
44
+ sql_exec("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, scope TEXT NOT NULL, sender TEXT, recipient TEXT, text TEXT, at REAL, state TEXT DEFAULT 'pending')")
45
+ sql_exec("CREATE TABLE IF NOT EXISTS cursors (agent TEXT, scope TEXT, last INTEGER DEFAULT 0, PRIMARY KEY (agent, scope))")
46
+ sql_exec("CREATE TABLE IF NOT EXISTS rounds (agent TEXT, scope TEXT, last_at REAL DEFAULT 0, PRIMARY KEY (agent, scope))")
47
+ sql_exec("CREATE TABLE IF NOT EXISTS spend (day TEXT, agent TEXT, tokens INTEGER DEFAULT 0, PRIMARY KEY (day, agent))")
48
+ sql_exec("CREATE TABLE IF NOT EXISTS objectives (id INTEGER PRIMARY KEY AUTOINCREMENT, agent TEXT NOT NULL, text TEXT NOT NULL, status TEXT DEFAULT 'active', progress TEXT DEFAULT '', question TEXT DEFAULT '', question_kind TEXT DEFAULT '', reply TEXT DEFAULT '', result TEXT DEFAULT '', round_seconds INTEGER DEFAULT 20, budget_tokens INTEGER DEFAULT 500000, spent INTEGER DEFAULT 0, turns INTEGER DEFAULT 0, last_start REAL DEFAULT 0, last_end REAL DEFAULT 0, created_by TEXT DEFAULT '', created_at REAL, updated_at REAL, team TEXT DEFAULT '')")
49
+ -- bases creadas antes de los objetivos de equipo
50
+ try
51
+ sql_exec("ALTER TABLE objectives ADD COLUMN team TEXT DEFAULT ''")
52
+ recover err
53
+ set err to err
54
+ give true
55
+
56
+ -- ---------- equipos (archivos) ----------
57
+ task field(m, k, fallback)
58
+ when contains(m, k) and m[k] != nothing
59
+ give m[k]
60
+ give fallback
61
+
62
+ -- valida un equipo; {ok, team} o {ok: false, error}
63
+ export task validate(raw, source)
64
+ when type_of(raw) != "map"
65
+ give {"ok": false, "error": source + ": a team is a JSON object"}
66
+ let id be lower(text(field(raw, "id", "")))
67
+ when not matches(id, "[a-z0-9][a-z0-9-]{0,39}")
68
+ give {"ok": false, "error": source + ": id must be lowercase letters, digits and - (got '" + id + "')"}
69
+ let raw_members be field(raw, "members", [])
70
+ when type_of(raw_members) != "list" or length(raw_members) == 0
71
+ give {"ok": false, "error": source + ": members must be a non-empty list"}
72
+ let members be []
73
+ let names be []
74
+ each m in raw_members
75
+ let a be lower(text(field(m, "agent", "")))
76
+ when a == ""
77
+ give {"ok": false, "error": source + ": every member needs \"agent\""}
78
+ when contains(names, a)
79
+ give {"ok": false, "error": source + ": agent '" + a + "' is twice in the team"}
80
+ set names to append(names, a)
81
+ set members to append(members, {"agent": a, "role": text(field(m, "role", a)), "reports_to": lower(text(field(m, "reports_to", "")))})
82
+ each m in members
83
+ when m["reports_to"] != "" and not contains(names, m["reports_to"])
84
+ give {"ok": false, "error": source + ": " + m["agent"] + " reports_to '" + m["reports_to"] + "', who is not in the team"}
85
+ let talks be []
86
+ each pair in field(raw, "talks", [])
87
+ when type_of(pair) != "list" or length(pair) != 2 or not contains(names, lower(text(pair[0]))) or not contains(names, lower(text(pair[1])))
88
+ give {"ok": false, "error": source + ": talks is a list of [agent, agent] pairs of team members"}
89
+ set talks to append(talks, [lower(text(pair[0])), lower(text(pair[1]))])
90
+ give {"ok": true, "team": {"id": id, "description": text(field(raw, "description", "")), "members": members, "talks": talks, "round_minutes": number(field(raw, "round_minutes", 0)), "worktrees": field(raw, "worktrees", true) != false, "budget_daily_tokens": floor(number(field(raw, "budget_daily_tokens", 0))), "source": source}}
91
+
92
+ -- todos los equipos del proyecto: {teams, errors}
93
+ export task scan()
94
+ require file.read("workspace")
95
+ require file.read("workspace/*")
96
+ let teams be []
97
+ let errors be []
98
+ try
99
+ each e in list_dir(DIR)
100
+ when not e["is_dir"] and ends_with(e["name"], ".team.json")
101
+ let src be ".lampson/teams/" + e["name"]
102
+ try
103
+ let v be validate(json_decode(read_file(DIR + "/" + e["name"])), src)
104
+ when v["ok"]
105
+ set teams to append(teams, v["team"])
106
+ otherwise
107
+ set errors to append(errors, v["error"])
108
+ recover err
109
+ set errors to append(errors, src + ": " + text(err))
110
+ recover err
111
+ give {"teams": [], "errors": []}
112
+ give {"teams": teams, "errors": errors}
113
+
114
+ export task all()
115
+ require file.read("workspace")
116
+ require file.read("workspace/*")
117
+ give scan()["teams"]
118
+
119
+ export task get(id)
120
+ require file.read("workspace")
121
+ require file.read("workspace/*")
122
+ let f be where(all(), (t) => t["id"] == id)
123
+ give when length(f) == 0 then nothing otherwise f[0]
124
+
125
+ export task teams_of(agent)
126
+ require file.read("workspace")
127
+ require file.read("workspace/*")
128
+ give where(all(), (t) => length(where(t["members"], (m) => m["agent"] == agent)) > 0)
129
+
130
+ export task member(team, agent)
131
+ let f be where(team["members"], (m) => m["agent"] == agent)
132
+ give when length(f) == 0 then nothing otherwise f[0]
133
+
134
+ -- a quién le puede escribir `agent` en el equipo: su jefe, los que le reportan y los pares de "talks"
135
+ export task peers(team, agent)
136
+ let me be member(team, agent)
137
+ when me == nothing
138
+ give []
139
+ let out be []
140
+ each m in team["members"]
141
+ when m["agent"] != agent and (m["agent"] == me["reports_to"] or m["reports_to"] == agent)
142
+ set out to append(out, m["agent"])
143
+ each pair in team["talks"]
144
+ when pair[0] == agent and not contains(out, pair[1])
145
+ set out to append(out, pair[1])
146
+ when pair[1] == agent and not contains(out, pair[0])
147
+ set out to append(out, pair[0])
148
+ give out
149
+
150
+ -- el jefe de `agent` y los jefes de su jefe (para quién puede reasignar sus tareas)
151
+ task managers(team, agent)
152
+ let out be []
153
+ let cur be member(team, agent)
154
+ while cur != nothing and cur["reports_to"] != "" and not contains(out, cur["reports_to"])
155
+ set out to append(out, cur["reports_to"])
156
+ set cur to member(team, cur["reports_to"])
157
+ give out
158
+
159
+ -- el equipo de una llamada: el pedido (`team`) o el único del agente. {ok, team} / {ok: false, error}
160
+ export task resolve(agent, wanted)
161
+ require file.read("workspace")
162
+ require file.read("workspace/*")
163
+ let mine be teams_of(agent)
164
+ when wanted != nothing and text(wanted) != ""
165
+ let f be where(mine, (t) => t["id"] == lower(text(wanted)))
166
+ when length(f) == 0
167
+ give {"ok": false, "error": "you are not in a team called '" + text(wanted) + "'" + (when length(mine) > 0 then " (yours: " + join(apply(mine, (t) => t["id"]), ", ") + ")" otherwise "")}
168
+ give {"ok": true, "team": f[0]}
169
+ when length(mine) == 0
170
+ give {"ok": false, "error": "you are not in any team"}
171
+ when length(mine) > 1
172
+ give {"ok": false, "error": "you are in several teams — say which: " + join(apply(mine, (t) => t["id"]), ", ")}
173
+ give {"ok": true, "team": mine[0]}
174
+
175
+ -- lo que el agente tiene que saber de su equipo, para su prompt (lib/runtime.syn → system_for)
176
+ export task instructions(agent)
177
+ require file.read("workspace")
178
+ require file.read("workspace/*")
179
+ let out be ""
180
+ each t in teams_of(agent)
181
+ let me be member(t, agent)
182
+ let lines be []
183
+ each m in t["members"]
184
+ set lines to append(lines, "- " + m["agent"] + ": " + m["role"] + (when m["reports_to"] != "" then " (reports to " + m["reports_to"] + ")" otherwise ""))
185
+ let ps be peers(t, agent)
186
+ set out to out + "\n\n# Team " + t["id"] + (when t["description"] != "" then " — " + t["description"] otherwise "") + "\nYou are " + agent + ", role: " + me["role"] + "." + (when me["reports_to"] != "" then " You report to " + me["reports_to"] + "." otherwise "") + "\nMembers:\n" + join(lines, "\n") + "\nYou can message: " + (when length(ps) == 0 then "nobody" otherwise join(ps, ", ")) + " (with `send`). Messages to anyone else are rejected.\nThe shared work lives on the board (`board`): list it, take a task before working on it (`claim`), move it as you go (doing → review → done, or blocked with a note), add the tasks you break work into. Never work on a task someone else owns. Each turn starts with what changed in the team since your last turn. Your final reply in a turn is not seen by anyone: to tell someone something, `send` it; to record progress, update the board." + (when t["worktrees"] then "\nGit: if the project uses git, you work in your OWN working copy (it is your root for files and bash), on branch team/" + t["id"] + "/" + agent + ", and your commits carry your name. Commit your work there and say which branch when you hand it over. The main checkout is ../../.. — merging into it (e.g. `git -C ../../.. merge team/" + t["id"] + "/<agent>`) or pushing touches the shared history: Lampson asks the person to approve it first. Don't edit files of other agents' copies." otherwise "")
187
+ give out
188
+
189
+ -- ---------- registro ----------
190
+ export task log(scope, actor, kind, ref, txt)
191
+ require db(".lampson/teams.db")
192
+ require file(".lampson")
193
+ require file(".lampson/*")
194
+ require time
195
+ open()
196
+ give sql_exec("INSERT INTO ledger (scope, at, actor, kind, ref, text) VALUES (?, ?, ?, ?, ?, ?)", [scope, now(), actor, kind, ref, slice(text(txt), 0, 400)])["last_id"]
197
+
198
+ export task ledger(scope, after, limit)
199
+ require db(".lampson/teams.db")
200
+ require file(".lampson")
201
+ require file(".lampson/*")
202
+ open()
203
+ give sql("SELECT * FROM ledger WHERE scope = ? AND id > ? ORDER BY id DESC LIMIT ?", [scope, after, limit])
204
+
205
+ -- lo que pasó en el equipo desde el último turno de `agent` (sin lo suyo), y avanza su cursor
206
+ export task digest(scope, agent)
207
+ require db(".lampson/teams.db")
208
+ require file(".lampson")
209
+ require file(".lampson/*")
210
+ open()
211
+ let cur be sql("SELECT last FROM cursors WHERE agent = ? AND scope = ?", [agent, scope])
212
+ let after be when length(cur) == 0 then 0 otherwise cur[0]["last"]
213
+ let rows be sql("SELECT * FROM ledger WHERE scope = ? AND id > ? ORDER BY id", [scope, after])
214
+ let top be sql("SELECT MAX(id) AS m FROM ledger WHERE scope = ?", [scope])
215
+ let last be when length(top) == 0 or top[0]["m"] == nothing then 0 otherwise top[0]["m"]
216
+ sql_exec("INSERT INTO cursors (agent, scope, last) VALUES (?, ?, ?) ON CONFLICT(agent, scope) DO UPDATE SET last = excluded.last", [agent, scope, last])
217
+ let others be where(rows, (r) => r["actor"] != agent)
218
+ let shown be when length(others) > DIGEST_MAX then slice(others, length(others) - DIGEST_MAX, length(others)) otherwise others
219
+ give apply(shown, (r) => format_time(r["at"], "%H:%M") + " " + r["actor"] + " " + r["kind"] + (when r["ref"] != "" then " " + r["ref"] otherwise "") + (when r["text"] != "" then ": " + r["text"] otherwise ""))
220
+
221
+ -- ---------- tablero ----------
222
+ task row_text(t)
223
+ let deps be json_decode(t["depends"])
224
+ give "#" + text(t["id"]) + " [" + t["status"] + "] " + t["title"] + (when t["owner"] != "" then " — " + t["owner"] otherwise " — (nobody)") + (when length(deps) > 0 then " · depends on " + join(apply(deps, (d) => "#" + text(d)), ", ") otherwise "") + (when t["notes"] != "" then "\n " + t["notes"] otherwise "")
225
+
226
+ export task tasks(scope)
227
+ require db(".lampson/teams.db")
228
+ require file(".lampson")
229
+ require file(".lampson/*")
230
+ open()
231
+ give sql("SELECT * FROM tasks WHERE scope = ? ORDER BY id", [scope])
232
+
233
+ export task task_get(scope, id)
234
+ require db(".lampson/teams.db")
235
+ require file(".lampson")
236
+ require file(".lampson/*")
237
+ open()
238
+ let r be sql("SELECT * FROM tasks WHERE scope = ? AND id = ?", [scope, id])
239
+ give when length(r) == 0 then nothing otherwise r[0]
240
+
241
+ export task add_task(scope, actor, title, notes, owner, depends)
242
+ require db(".lampson/teams.db")
243
+ require file(".lampson")
244
+ require file(".lampson/*")
245
+ require time
246
+ open()
247
+ when trim(text(title)) == ""
248
+ raise("a task needs a title")
249
+ each d in depends
250
+ when task_get(scope, d) == nothing
251
+ raise("depends on #" + text(d) + ", which does not exist")
252
+ let id be sql_exec("INSERT INTO tasks (scope, title, notes, owner, status, depends, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [scope, trim(text(title)), text(notes), owner, "todo", json_encode(depends), actor, now(), now()])["last_id"]
253
+ log(scope, actor, "added", "#" + text(id), trim(text(title)) + (when owner != "" then " → " + owner otherwise ""))
254
+ give id
255
+
256
+ -- tomar una tarea sin dueño: atómico (UPDATE condicional). Las dependencias tienen que estar hechas.
257
+ export task claim(scope, actor, id)
258
+ require db(".lampson/teams.db")
259
+ require file(".lampson")
260
+ require file(".lampson/*")
261
+ require time
262
+ open()
263
+ let t be task_get(scope, id)
264
+ when t == nothing
265
+ raise("no task #" + text(id))
266
+ when t["owner"] == actor
267
+ give "#" + text(id) + " is already yours"
268
+ when t["owner"] != ""
269
+ raise("#" + text(id) + " is " + t["owner"] + "'s — pick another one or message them")
270
+ each d in json_decode(t["depends"])
271
+ let dt be task_get(scope, d)
272
+ when dt != nothing and dt["status"] != "done"
273
+ raise("#" + text(id) + " depends on #" + text(d) + " (" + dt["status"] + (when dt["owner"] != "" then ", " + dt["owner"] otherwise "") + ") — it has to be done first")
274
+ let r be sql_exec("UPDATE tasks SET owner = ?, status = 'doing', updated_at = ? WHERE scope = ? AND id = ? AND owner = ''", [actor, now(), scope, id])
275
+ when r["rows_affected"] == 0
276
+ let again be task_get(scope, id)
277
+ raise("#" + text(id) + " was just taken by " + again["owner"])
278
+ log(scope, actor, "claimed", "#" + text(id), t["title"])
279
+ give "#" + text(id) + " is yours now (doing)"
280
+
281
+ -- mover una tarea: estado, notas, dueño. Puede su dueño, quien la creó o un jefe del dueño; una tarea sin dueño,
282
+ -- cualquiera del equipo (para asignarla).
283
+ export task update_task(scope, team, actor, id, changes)
284
+ require db(".lampson/teams.db")
285
+ require file(".lampson")
286
+ require file(".lampson/*")
287
+ require time
288
+ open()
289
+ let t be task_get(scope, id)
290
+ when t == nothing
291
+ raise("no task #" + text(id))
292
+ let boss be team != nothing and contains(managers(team, t["owner"]), actor)
293
+ when team != nothing and t["owner"] != "" and t["owner"] != actor and t["created_by"] != actor and not boss
294
+ raise("#" + text(id) + " is " + t["owner"] + "'s — only they, whoever created it or their manager can change it")
295
+ let parts be []
296
+ let st be t["status"]
297
+ when contains(changes, "status") and changes["status"] != nothing and text(changes["status"]) != ""
298
+ set st to lower(text(changes["status"]))
299
+ when not contains(STATUSES, st)
300
+ raise("status must be one of " + join(STATUSES, ", "))
301
+ set parts to append(parts, t["status"] + " → " + st)
302
+ let owner be t["owner"]
303
+ when contains(changes, "owner") and changes["owner"] != nothing
304
+ set owner to lower(text(changes["owner"]))
305
+ when owner != "" and team != nothing and member(team, owner) == nothing
306
+ raise("'" + owner + "' is not in the team")
307
+ set parts to append(parts, "owner " + (when owner == "" then "(nobody)" otherwise owner))
308
+ let notes be t["notes"]
309
+ when contains(changes, "notes") and changes["notes"] != nothing and text(changes["notes"]) != ""
310
+ set notes to text(changes["notes"])
311
+ set parts to append(parts, "notes: " + slice(notes, 0, 160))
312
+ sql_exec("UPDATE tasks SET status = ?, owner = ?, notes = ?, updated_at = ? WHERE id = ?", [st, owner, notes, now(), id])
313
+ log(scope, actor, "updated", "#" + text(id), t["title"] + " · " + join(parts, " · "))
314
+ give "#" + text(id) + " updated: " + join(parts, " · ")
315
+
316
+ -- ---------- mensajes ----------
317
+ export task send(team, sender, dest, txt)
318
+ require db(".lampson/teams.db")
319
+ require file(".lampson")
320
+ require file(".lampson/*")
321
+ require time
322
+ require file.read("workspace")
323
+ require file.read("workspace/*")
324
+ require file.read("agents")
325
+ require file.read("agents/*")
326
+ open()
327
+ let d be lower(trim(text(dest)))
328
+ when member(team, d) == nothing
329
+ raise("'" + d + "' is not in team " + team["id"])
330
+ when not contains(peers(team, sender), d)
331
+ let ps be peers(team, sender)
332
+ raise("you can't message " + d + " in team " + team["id"] + " — you can message: " + (when length(ps) == 0 then "nobody" otherwise join(ps, ", ")))
333
+ when trim(text(txt)) == "" or contains(["null", "none", "undefined"], lower(trim(text(txt))))
334
+ raise("empty message — write what you want to tell them in `message`")
335
+ when not file_exists("workspace/.lampson/agents/" + d + ".agent.json") and not file_exists("agents/" + d + ".agent.json")
336
+ raise(d + " is in the team but has no agent file, so nobody would read it — tell the person (the team needs .lampson/agents/" + d + ".agent.json)")
337
+ let scope be "team:" + team["id"]
338
+ let id be sql_exec("INSERT INTO messages (scope, sender, recipient, text, at) VALUES (?, ?, ?, ?, ?)", [scope, sender, d, text(txt), now()])["last_id"]
339
+ log(scope, sender, "message", "→ " + d, text(txt))
340
+ give id
341
+
342
+ -- los mensajes por entregar (los entrega lib/teamrun.syn por el buzón)
343
+ export task pending()
344
+ require db(".lampson/teams.db")
345
+ require file(".lampson")
346
+ require file(".lampson/*")
347
+ open()
348
+ give sql("SELECT * FROM messages WHERE state = 'pending' ORDER BY id", [])
349
+
350
+ export task mark(id, state)
351
+ require db(".lampson/teams.db")
352
+ require file(".lampson")
353
+ require file(".lampson/*")
354
+ open()
355
+ sql_exec("UPDATE messages SET state = ? WHERE id = ?", [state, id])
356
+ give true
357
+
358
+ -- ---------- presupuesto ----------
359
+ task today()
360
+ require time
361
+ give format_time(now(), "%Y-%m-%d")
362
+
363
+ export task record_spend(agent, tokens)
364
+ require db(".lampson/teams.db")
365
+ require file(".lampson")
366
+ require file(".lampson/*")
367
+ require time
368
+ open()
369
+ sql_exec("INSERT INTO spend (day, agent, tokens) VALUES (?, ?, ?) ON CONFLICT(day, agent) DO UPDATE SET tokens = tokens + excluded.tokens", [today(), agent, floor(tokens)])
370
+ give true
371
+
372
+ export task spent_today(agent)
373
+ require db(".lampson/teams.db")
374
+ require file(".lampson")
375
+ require file(".lampson/*")
376
+ require time
377
+ open()
378
+ let r be sql("SELECT tokens FROM spend WHERE day = ? AND agent = ?", [today(), agent])
379
+ give when length(r) == 0 then 0 otherwise r[0]["tokens"]
380
+
381
+ export task over_budget(team, agent)
382
+ require db(".lampson/teams.db")
383
+ require file(".lampson")
384
+ require file(".lampson/*")
385
+ require time
386
+ give team["budget_daily_tokens"] > 0 and spent_today(agent) >= team["budget_daily_tokens"]
387
+
388
+ -- ---------- rondas ----------
389
+ -- ¿tiene `agent` algo que hacer en el equipo? tareas suyas abiertas, o novedades que son PARA él: una tarea que le
390
+ -- asignaron, una de las suyas que otro movió, y (si lidera) lo que dijo la persona. El resto del movimiento del equipo
391
+ -- lo ve cuando le toca un turno por otra cosa. (Visto 2026-10-16: con «cualquier novedad», el objetivo nuevo despertó
392
+ -- a los cinco a la vez y cada uno se armó sus propias tareas: seis duplicados que el equipo tuvo que limpiar.)
393
+ export task has_work(scope, agent)
394
+ require db(".lampson/teams.db")
395
+ require file(".lampson")
396
+ require file(".lampson/*")
397
+ open()
398
+ let mine be sql("SELECT COUNT(*) AS n FROM tasks WHERE scope = ? AND owner = ? AND status IN ('todo', 'doing')", [scope, agent])
399
+ when mine[0]["n"] > 0
400
+ give true
401
+ let cur be sql("SELECT last FROM cursors WHERE agent = ? AND scope = ?", [agent, scope])
402
+ let after be when length(cur) == 0 then 0 otherwise cur[0]["last"]
403
+ let leads be false
404
+ when starts_with(scope, "team:")
405
+ let tm be get(slice(scope, 5, length(scope)))
406
+ set leads to tm != nothing and lead_of(tm) == agent
407
+ each r in sql("SELECT * FROM ledger WHERE scope = ? AND id > ? AND actor != ?", [scope, after, agent])
408
+ when r["kind"] == "message" and r["ref"] == "→ " + agent
409
+ give true
410
+ when r["kind"] == "added" and ends_with(r["text"], "→ " + agent)
411
+ give true
412
+ when r["kind"] == "updated" and (contains(r["text"], "owner " + agent) or owner_of(scope, r["ref"]) == agent)
413
+ give true
414
+ when leads and contains(["objective", "approved", "denied", "answered"], r["kind"])
415
+ give true
416
+ give false
417
+
418
+ -- el dueño de una tarea por su ref ("#12")
419
+ task owner_of(scope, ref)
420
+ when not starts_with(text(ref), "#")
421
+ give ""
422
+ let t be task_get(scope, floor(number(slice(text(ref), 1, length(text(ref))))))
423
+ give when t == nothing then "" otherwise t["owner"]
424
+
425
+ -- marca la ronda si toca: true = toca ahora (y queda registrada), false = todavía no
426
+ export task round_due(team, agent)
427
+ require db(".lampson/teams.db")
428
+ require file(".lampson")
429
+ require file(".lampson/*")
430
+ require time
431
+ when team["round_minutes"] <= 0
432
+ give false
433
+ open()
434
+ let scope be "team:" + team["id"]
435
+ let r be sql("SELECT last_at FROM rounds WHERE agent = ? AND scope = ?", [agent, scope])
436
+ let last be when length(r) == 0 then 0 otherwise r[0]["last_at"]
437
+ when now() - last < team["round_minutes"] * 60
438
+ give false
439
+ when not has_work(scope, agent)
440
+ give false
441
+ let upd be sql_exec("INSERT INTO rounds (agent, scope, last_at) VALUES (?, ?, ?) ON CONFLICT(agent, scope) DO UPDATE SET last_at = excluded.last_at WHERE rounds.last_at = ?", [agent, scope, now(), last])
442
+ give upd["rows_affected"] > 0
443
+
444
+ -- el texto con el que arranca un turno de equipo: lo que llegó + novedades + sus tareas
445
+ export task turn_text(team, agent, head)
446
+ require db(".lampson/teams.db")
447
+ require file(".lampson")
448
+ require file(".lampson/*")
449
+ require time
450
+ let scope be "team:" + team["id"]
451
+ let news be digest(scope, agent)
452
+ let mine be where(tasks(scope), (t) => t["owner"] == agent and t["status"] != "done")
453
+ let free be where(tasks(scope), (t) => t["owner"] == "" and t["status"] == "todo")
454
+ let out be head
455
+ set out to out + "\n\n[team " + team["id"] + "] Since your last turn:" + (when length(news) == 0 then " nothing new." otherwise "\n" + join(apply(news, (n) => "- " + n), "\n"))
456
+ set out to out + "\nYour open tasks:" + (when length(mine) == 0 then " none." otherwise "\n" + join(apply(mine, (t) => row_text(t)), "\n"))
457
+ when length(free) > 0
458
+ set out to out + "\nTasks nobody owns:\n" + join(apply(free, (t) => row_text(t)), "\n")
459
+ give out
460
+
461
+ -- ---------- tools del modelo ----------
462
+ export let SEND_SPEC be {
463
+ "name": "send",
464
+ "description": "Send a message to a teammate (only the ones your team lets you message: your manager, the people who report to you, and explicit pairs). It arrives in their conversation as a new message and they act on it. Use it to ask, hand over work, report or answer — your final reply in a turn is not seen by anyone.",
465
+ "parameters": {"type": "object", "properties": {
466
+ "recipient": {"type": "string", "description": "the teammate's agent id"},
467
+ "message": {"type": "string", "description": "what you want to tell them"},
468
+ "team": {"type": "string", "description": "only if you are in several teams"}
469
+ }, "required": ["recipient", "message"]}
470
+ }
471
+
472
+ export let BOARD_SPEC be {
473
+ "name": "board",
474
+ "description": "Your team's shared board of tasks. list: every task (or mine=true for yours). add: a new task (title, notes, optional owner and depends=[ids]). claim: take a task nobody owns before working on it (fails if someone took it or its dependencies are not done). update: move a task you own (or created, or that belongs to someone who reports to you): status todo|doing|review|done|blocked, notes, owner. show: one task. log: the last entries of the team's record.",
475
+ "parameters": {"type": "object", "properties": {
476
+ "action": {"type": "string", "enum": ["list", "add", "claim", "update", "show", "log"]},
477
+ "id": {"type": "integer"},
478
+ "title": {"type": "string"},
479
+ "notes": {"type": "string"},
480
+ "owner": {"type": "string"},
481
+ "status": {"type": "string", "enum": ["todo", "doing", "review", "done", "blocked"]},
482
+ "depends": {"type": "array", "items": {"type": "integer"}},
483
+ "mine": {"type": "boolean"},
484
+ "team": {"type": "string", "description": "only if you are in several teams"}
485
+ }, "required": ["action"]}
486
+ }
487
+
488
+ -- call_tool pasa los args del modelo como parámetros CON NOMBRE (y `to`/`text` no sirven de nombre: palabra
489
+ -- reservada y builtin). Las versiones *_with reciben el mapa (los tests las usan directo).
490
+ export task send_tool(recipient, message, team, _agent, _scope)
491
+ require file.read("agents")
492
+ require file.read("agents/*")
493
+ require db(".lampson/teams.db")
494
+ require file(".lampson")
495
+ require file(".lampson/*")
496
+ require file.read("workspace")
497
+ require file.read("workspace/*")
498
+ require time
499
+ give send_with({"recipient": recipient, "message": message, "team": team, "_agent": _agent, "_scope": _scope})
500
+
501
+ export task board_tool(action, id, title, notes, owner, status, depends, mine, team, _agent, _scope)
502
+ require db(".lampson/teams.db")
503
+ require file(".lampson")
504
+ require file(".lampson/*")
505
+ require file.read("workspace")
506
+ require file.read("workspace/*")
507
+ require time
508
+ let a be {"_agent": _agent, "_scope": _scope}
509
+ each pair in [["action", action], ["id", id], ["title", title], ["notes", notes], ["owner", owner], ["status", status], ["depends", depends], ["mine", mine], ["team", team]]
510
+ when pair[1] != nothing
511
+ set a[pair[0]] to pair[1]
512
+ give board_with(a)
513
+
514
+ export task send_with(args)
515
+ require file.read("agents")
516
+ require file.read("agents/*")
517
+ require db(".lampson/teams.db")
518
+ require file(".lampson")
519
+ require file(".lampson/*")
520
+ require file.read("workspace")
521
+ require file.read("workspace/*")
522
+ require time
523
+ let me be text(field(args, "_agent", ""))
524
+ when me == ""
525
+ give "ERROR: send needs to know who is sending (not available here)"
526
+ let sc be text(field(args, "_scope", ""))
527
+ let rt be resolve(me, when field(args, "team", "") == "" and starts_with(sc, "team:") then slice(sc, 5, length(sc)) otherwise field(args, "team", ""))
528
+ when not rt["ok"]
529
+ give "ERROR: " + rt["error"]
530
+ try
531
+ send(rt["team"], me, field(args, "recipient", ""), field(args, "message", ""))
532
+ give "sent to " + lower(text(field(args, "recipient", ""))) + " — it reaches them as a new message"
533
+ recover err
534
+ give "ERROR: " + regex_replace(text(err), "^.*?:\\d+:\\d+: ", "")
535
+
536
+ export task board_with(args)
537
+ require db(".lampson/teams.db")
538
+ require file(".lampson")
539
+ require file(".lampson/*")
540
+ require file.read("workspace")
541
+ require file.read("workspace/*")
542
+ require time
543
+ let me be text(field(args, "_agent", ""))
544
+ when me == ""
545
+ give "ERROR: board needs to know who is asking (not available here)"
546
+ let sc be text(field(args, "_scope", ""))
547
+ let team be nothing
548
+ let scope be ""
549
+ when starts_with(sc, "objective:")
550
+ -- el tablero de un objetivo: el plan del agente que lo trabaja
551
+ let o be obj_get(floor(number(slice(sc, 10, length(sc)))))
552
+ when o == nothing or o["agent"] != me
553
+ give "ERROR: this objective is not yours"
554
+ set scope to sc
555
+ otherwise
556
+ let rt be resolve(me, when field(args, "team", "") == "" and starts_with(sc, "team:") then slice(sc, 5, length(sc)) otherwise field(args, "team", ""))
557
+ when not rt["ok"]
558
+ give "ERROR: " + rt["error"]
559
+ set team to rt["team"]
560
+ set scope to "team:" + team["id"]
561
+ let action be lower(text(field(args, "action", "list")))
562
+ try
563
+ when action == "list"
564
+ let all_t be tasks(scope)
565
+ let rows be when field(args, "mine", false) == true then where(all_t, (t) => t["owner"] == me) otherwise all_t
566
+ give when length(rows) == 0 then "the board is empty" otherwise join(apply(rows, (t) => row_text(t)), "\n")
567
+ when action == "show"
568
+ let t be task_get(scope, floor(number(field(args, "id", 0))))
569
+ give when t == nothing then "ERROR: no such task" otherwise row_text(t)
570
+ when action == "add"
571
+ let owner be lower(text(field(args, "owner", "")))
572
+ when owner != "" and team != nothing and member(team, owner) == nothing
573
+ give "ERROR: '" + owner + "' is not in the team"
574
+ let deps be apply(field(args, "depends", []), (d) => floor(number(d)))
575
+ let id be add_task(scope, me, field(args, "title", ""), field(args, "notes", ""), owner, deps)
576
+ give "added #" + text(id) + (when owner != "" then " for " + owner otherwise " (nobody owns it yet)")
577
+ when action == "claim"
578
+ give claim(scope, me, floor(number(field(args, "id", 0))))
579
+ when action == "update"
580
+ give update_task(scope, team, me, floor(number(field(args, "id", 0))), args)
581
+ when action == "log"
582
+ let rows be ledger(scope, 0, 20)
583
+ give join(apply(rows, (r) => format_time(r["at"], "%m-%d %H:%M") + " " + r["actor"] + " " + r["kind"] + " " + r["ref"] + (when r["text"] != "" then ": " + r["text"] otherwise "")), "\n")
584
+ give "ERROR: unknown action '" + action + "' (list, add, claim, update, show, log)"
585
+ recover err
586
+ give "ERROR: " + regex_replace(text(err), "^.*?:\\d+:\\d+: ", "")
587
+
588
+
589
+ -- ---------- objetivos ----------
590
+ -- Un OBJETIVO es lo que le pedís a un agente para que trabaje solo hasta terminarlo («agregá tal feature», «buscá
591
+ -- el precio más barato de…»). Vive en la tabla objectives; su scope es "objective:<id>" (su tablero y su registro) y su
592
+ -- conversación es el thread "objective:<id>". El pulso (lib/teamrun.syn) le da un turno nuevo cuando terminó el
593
+ -- anterior y pasaron round_seconds, mientras esté "active". Estados:
594
+ -- active trabajando · waiting preguntó algo o pidió aprobación (sin turnos hasta que la persona responda)
595
+ -- done / failed terminó (result) · cancelled lo cortó la persona · paused se quedó sin presupuesto
596
+ export let OBJ_STATUSES be ["active", "waiting", "done", "failed", "cancelled", "paused"]
597
+
598
+ export task obj_create(agent, txt, opts)
599
+ require db(".lampson/teams.db")
600
+ require file(".lampson")
601
+ require file(".lampson/*")
602
+ require time
603
+ open()
604
+ when trim(text(txt)) == ""
605
+ raise("an objective needs a text")
606
+ let tid be lower(text(field(opts, "team", "")))
607
+ let rs be floor(number(field(opts, "round_seconds", when tid != "" then 60 otherwise 20)))
608
+ let bt be floor(number(field(opts, "budget_tokens", 500000)))
609
+ let id be sql_exec("INSERT INTO objectives (agent, text, round_seconds, budget_tokens, created_by, created_at, updated_at, team) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", [agent, trim(text(txt)), max(5, rs), bt, text(field(opts, "created_by", "")), now(), now(), tid])["last_id"]
610
+ log(obj_scope({"id": id, "team": tid}), text(field(opts, "created_by", "person")), "objective", "O-" + text(id), trim(text(txt)) + " → " + (when tid != "" then "team " + tid + " (led by " + agent + ")" otherwise agent))
611
+ give id
612
+
613
+ -- el scope donde vive el trabajo de un objetivo: el de su equipo, o el suyo
614
+ export task obj_scope(o)
615
+ give when field(o, "team", "") != "" then "team:" + o["team"] otherwise "objective:" + text(o["id"])
616
+
617
+ -- el líder de un equipo: el primero que no reporta a nadie
618
+ export task lead_of(team)
619
+ let roots be where(team["members"], (m) => m["reports_to"] == "")
620
+ give when length(roots) == 0 then team["members"][0]["agent"] otherwise roots[0]["agent"]
621
+
622
+ -- el objetivo abierto que lidera `agent` en el equipo (o nothing)
623
+ export task team_objective(team_id, agent)
624
+ require db(".lampson/teams.db")
625
+ require file(".lampson")
626
+ require file(".lampson/*")
627
+ open()
628
+ let r be sql("SELECT * FROM objectives WHERE team = ? AND agent = ? AND status IN ('active', 'waiting', 'paused') ORDER BY id DESC LIMIT 1", [team_id, agent])
629
+ give when length(r) == 0 then nothing otherwise r[0]
630
+
631
+ -- fin de un turno en la conversación de un equipo: su gasto cuenta para el objetivo abierto del equipo; si es el
632
+ -- líder, además cierra su turno de objetivo
633
+ export task team_turn_end(team_id, agent, tokens)
634
+ require db(".lampson/teams.db")
635
+ require file(".lampson")
636
+ require file(".lampson/*")
637
+ require time
638
+ open()
639
+ each o in sql("SELECT * FROM objectives WHERE team = ? AND status IN ('active', 'waiting')", [team_id])
640
+ sql_exec("UPDATE objectives SET spent = spent + ?, updated_at = ? WHERE id = ?", [floor(tokens), now(), o["id"]])
641
+ when o["agent"] == agent
642
+ sql_exec("UPDATE objectives SET last_end = ? WHERE id = ?", [now(), o["id"]])
643
+ let cur be obj_get(o["id"])
644
+ when cur["status"] == "active" and cur["budget_tokens"] > 0 and cur["spent"] >= cur["budget_tokens"]
645
+ obj_set(o["id"], {"status": "paused"})
646
+ log("team:" + team_id, "lampson", "paused", "O-" + text(o["id"]), "budget reached (" + text(cur["spent"]) + " of " + text(cur["budget_tokens"]) + " tokens)")
647
+ give true
648
+
649
+ export task obj_get(id)
650
+ require db(".lampson/teams.db")
651
+ require file(".lampson")
652
+ require file(".lampson/*")
653
+ open()
654
+ let r be sql("SELECT * FROM objectives WHERE id = ?", [id])
655
+ give when length(r) == 0 then nothing otherwise r[0]
656
+
657
+ export task obj_list()
658
+ require db(".lampson/teams.db")
659
+ require file(".lampson")
660
+ require file(".lampson/*")
661
+ open()
662
+ give sql("SELECT * FROM objectives ORDER BY id DESC", [])
663
+
664
+ -- cambia campos de un objetivo (status, progress, question, question_kind, reply, result, last_start, turns)
665
+ export task obj_set(id, changes)
666
+ require db(".lampson/teams.db")
667
+ require file(".lampson")
668
+ require file(".lampson/*")
669
+ require time
670
+ open()
671
+ let allowed_keys be ["status", "progress", "question", "question_kind", "reply", "result", "last_start", "turns"]
672
+ each k in keys(changes)
673
+ when contains(allowed_keys, k)
674
+ sql_exec("UPDATE objectives SET " + k + " = ?, updated_at = ? WHERE id = ?", [changes[k], now(), id])
675
+ give obj_get(id)
676
+
677
+ -- fin de un turno del objetivo: gasto y hora (lo llama runtime.turn). Sin presupuesto → paused.
678
+ export task obj_turn_end(id, tokens)
679
+ require db(".lampson/teams.db")
680
+ require file(".lampson")
681
+ require file(".lampson/*")
682
+ require time
683
+ open()
684
+ sql_exec("UPDATE objectives SET spent = spent + ?, last_end = ?, updated_at = ? WHERE id = ?", [floor(tokens), now(), now(), id])
685
+ let o be obj_get(id)
686
+ when o != nothing and o["status"] == "active" and o["budget_tokens"] > 0 and o["spent"] >= o["budget_tokens"]
687
+ obj_set(id, {"status": "paused"})
688
+ log("objective:" + text(id), "lampson", "paused", "O-" + text(id), "budget reached (" + text(o["spent"]) + " of " + text(o["budget_tokens"]) + " tokens)")
689
+ give true
690
+
691
+ -- la persona responde una pregunta o una aprobación: vuelve a active y la respuesta abre el próximo turno
692
+ export task obj_reply(id, txt, approved, who)
693
+ require db(".lampson/teams.db")
694
+ require file(".lampson")
695
+ require file(".lampson/*")
696
+ require time
697
+ let o be obj_get(id)
698
+ when o == nothing
699
+ raise("no objective O-" + text(id))
700
+ when o["status"] != "waiting" and o["status"] != "active" and o["status"] != "paused"
701
+ raise("O-" + text(id) + " is " + o["status"])
702
+ let head be ""
703
+ when o["question_kind"] == "approval"
704
+ set head to (when approved == true then "[approved by " + who + "] " otherwise "[denied by " + who + "] ") + o["question"] + (when trim(text(txt)) != "" then "\n" + text(txt) otherwise "")
705
+ otherwise
706
+ set head to "[" + who + " answered] " + text(txt)
707
+ -- sin presupuesto: seguir le da otro tramo igual al que tenía
708
+ when o["status"] == "paused" and o["budget_tokens"] > 0
709
+ open()
710
+ sql_exec("UPDATE objectives SET budget_tokens = spent + ? WHERE id = ?", [o["budget_tokens"], id])
711
+ obj_set(id, {"status": "active", "reply": head, "question": "", "question_kind": ""})
712
+ log(obj_scope(o), who, when o["question_kind"] == "approval" then (when approved == true then "approved" otherwise "denied") otherwise "answered", "O-" + text(id), text(txt))
713
+ give obj_get(id)
714
+
715
+ export task obj_cancel(id, who)
716
+ require db(".lampson/teams.db")
717
+ require file(".lampson")
718
+ require file(".lampson/*")
719
+ require time
720
+ let o be obj_get(id)
721
+ when o == nothing
722
+ raise("no objective O-" + text(id))
723
+ obj_set(id, {"status": "cancelled"})
724
+ log(obj_scope(o), who, "cancelled", "O-" + text(id), "")
725
+ give obj_get(id)
726
+
727
+ -- el texto de un turno del objetivo: el primero lo presenta; después, lo que respondió la persona o la ronda
728
+ -- la cabeza de un turno del objetivo: la presentación, lo que respondió la persona o la ronda
729
+ export task obj_head(o)
730
+ when o["turns"] == 0 and field(o, "team", "") != ""
731
+ give "[objective O-" + text(o["id"]) + " for team " + o["team"] + "] " + o["text"] + "\n\nYou lead this objective with your team. How:\n- Break it into tasks on the team board (`board` add, with owner = who should do it, and depends when one needs another) and `send` each teammate what you need from them. They work in parallel in their own copies; follow up every turn with what changed.\n- Keep the person informed with `objective` (action report) at milestones. Before anything that leaves the workspace or can't be undone (merge into main, push, release, publish, buy, send), `objective` action request_approval and wait — Lampson also asks the person before any merge or push.\n- When everything is delivered and verified, `objective` action done with the result (what was done, by whom, where, how to check). If it can't be done, action fail with why."
732
+ when o["turns"] == 0
733
+ give "[objective O-" + text(o["id"]) + "] " + o["text"] + "\n\nWork on this on your own until it is done. How:\n- First plan it: break it into tasks on your board (`board` add), then work through them (claim → doing → done).\n- Each turn, move the work forward and end the turn; you'll get the next turn automatically. Nobody reads your final reply: report with `objective` (action report) when you reach something worth telling.\n- Need a decision or information only the person has? `objective` action ask. Before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book, send an email), `objective` action request_approval and wait for the answer — never do it without an approval.\n- When it is done, `objective` action done with the result (what you did, where, how to check it). If it can't be done, action fail with why."
734
+ when o["reply"] != ""
735
+ give o["reply"]
736
+ give "[round] Keep working on O-" + text(o["id"]) + ": " + o["text"]
737
+
738
+ export task obj_turn_text(o)
739
+ require db(".lampson/teams.db")
740
+ require file(".lampson")
741
+ require file(".lampson/*")
742
+ require time
743
+ let scope be "objective:" + text(o["id"])
744
+ let head be obj_head(o)
745
+ let news be digest(scope, o["agent"])
746
+ let ts be tasks(scope)
747
+ let out be head
748
+ when length(news) > 0
749
+ set out to out + "\n\nSince your last turn:\n" + join(apply(news, (n) => "- " + n), "\n")
750
+ set out to out + "\n\nYour board:" + (when length(ts) == 0 then " empty." otherwise "\n" + join(apply(ts, (t) => row_text(t)), "\n"))
751
+ give out
752
+
753
+ export let OBJECTIVE_SPEC be {
754
+ "name": "objective",
755
+ "description": "The objective you are working on. report: tell the person where you are (message). ask: ask the person something only they can answer (message) — no more turns until they answer. request_approval: ask permission before anything that leaves this workspace or can't be undone (merge into main, push, deploy, buy, book…) — describe exactly what (message); wait for the answer. done: finish it with the result (message: what you did, where, how to check). fail: give up with why (message). show: the objective and its status.",
756
+ "parameters": {"type": "object", "properties": {
757
+ "action": {"type": "string", "enum": ["report", "ask", "request_approval", "done", "fail", "show"]},
758
+ "message": {"type": "string"}
759
+ }, "required": ["action"]}
760
+ }
761
+
762
+ export task objective_tool(action, message, _agent, _scope)
763
+ require db(".lampson/teams.db")
764
+ require file(".lampson")
765
+ require file(".lampson/*")
766
+ require time
767
+ let sc be text(_scope)
768
+ let o be nothing
769
+ when starts_with(sc, "team:")
770
+ set o to team_objective(slice(sc, 5, length(sc)), text(_agent))
771
+ when o == nothing
772
+ give "ERROR: you don't lead an open objective in this team"
773
+ otherwise when starts_with(sc, "objective:")
774
+ set o to obj_get(floor(number(slice(sc, 10, length(sc)))))
775
+ when o == nothing or o["agent"] != text(_agent)
776
+ give "ERROR: this objective is not yours"
777
+ otherwise
778
+ give "ERROR: you are not working on an objective in this conversation"
779
+ let id be o["id"]
780
+ set sc to obj_scope(o)
781
+ let act be lower(text(action))
782
+ let msg be when message == nothing then "" otherwise trim(text(message))
783
+ let ref be "O-" + text(id)
784
+ when act == "show"
785
+ give ref + " [" + o["status"] + "] " + o["text"] + (when o["progress"] != "" then "\nlast report: " + o["progress"] otherwise "")
786
+ when o["status"] != "active"
787
+ give "ERROR: " + ref + " is " + o["status"] + " — nothing to do"
788
+ when msg == "" and act != "show"
789
+ give "ERROR: " + act + " needs a message"
790
+ when act == "report"
791
+ obj_set(id, {"progress": msg})
792
+ log(sc, o["agent"], "report", ref, msg)
793
+ give "reported"
794
+ when act == "ask" or act == "request_approval"
795
+ obj_set(id, {"status": "waiting", "question": msg, "question_kind": when act == "ask" then "question" otherwise "approval"})
796
+ log(sc, o["agent"], when act == "ask" then "asked" otherwise "approval requested", ref, msg)
797
+ give "sent to the person — end your turn now; their answer opens your next turn"
798
+ when act == "done" or act == "fail"
799
+ obj_set(id, {"status": when act == "done" then "done" otherwise "failed", "result": msg})
800
+ log(sc, o["agent"], when act == "done" then "done" otherwise "failed", ref, msg)
801
+ give ref + " is " + (when act == "done" then "done" otherwise "failed") + " — end your turn"
802
+ give "ERROR: unknown action '" + act + "' (report, ask, request_approval, done, fail, show)"