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.
@@ -27,8 +27,8 @@ export let HUB_FILE be "hub.syn"
27
27
  export let HUB_TEMPLATE be "hub.tpl.syn"
28
28
  -- rango alto para no chocar con lo que usan las apps (3000, 5173, 8000, 8080-8090…): solo el hub queda en 8080
29
29
  let FIRST_PORT be 47101
30
- let LINKS be ["lib", "public", "skills", "plugins", "memory"]
31
- let COPIES be ["web.syn", "chat.syn"]
30
+ let LINKS be ["lib", "public", "skills", "plugins", "memory", "agents"]
31
+ let COPIES be ["web.syn", "chat.syn", "run.syn"]
32
32
 
33
33
  task is_win()
34
34
  give env("OS", "") == "Windows_NT"
@@ -215,6 +215,7 @@ export task prepare(w)
215
215
  require file(".lampson/*")
216
216
  require file.read("web.syn")
217
217
  require file.read("chat.syn")
218
+ require file.read("run.syn")
218
219
  let d be dir_of(w["slug"])
219
220
  let h be home()
220
221
  let sep be when is_win() then "\\" otherwise "/"
@@ -235,7 +236,13 @@ export task prepare(w)
235
236
  ensure_link(d + "/" + n, h + sep + n)
236
237
  ensure_link(d + "/.lampson/global", h + sep + ".lampson")
237
238
  each f in COPIES
238
- write_file(d + "/" + f, read_file(f))
239
+ -- run.syn (lampson run, 0.2.11): un hub viejo en memoria no tiene el permiso de leerlo → se saltea y el
240
+ -- workspace enciende igual; la próxima vez que el hub arranque con el template nuevo se copia
241
+ try
242
+ write_file(d + "/" + f, read_file(f))
243
+ recover err
244
+ when f != "run.syn"
245
+ raise(err)
239
246
  give d
240
247
 
241
248
  -- estado guardado ANTES de los workspaces (en <home>/.lampson, separado por slug en cada registro): sesiones y trazas
@@ -295,6 +302,7 @@ export task ensure(path)
295
302
  require file(".lampson/*")
296
303
  require file.read("web.syn")
297
304
  require file.read("chat.syn")
305
+ require file.read("run.syn")
298
306
  require file.read("hub.tpl.syn")
299
307
  require file("hub.syn")
300
308
  migrate_ports()
@@ -353,6 +361,12 @@ task hub_routes(w)
353
361
  each m in ["GET", "POST"]
354
362
  set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/api/*path\" requires auth\n proxy to \"" + base + "\"")
355
363
  set lines to append(lines, " route \"GET /w/" + w["slug"] + "/approve/*path\"\n proxy to \"" + base + "\"")
364
+ -- la API /v1 para apps (lib/api.syn) tampoco: la autentica el proceso del workspace con su API key (Bearer lk_…)
365
+ each m in ["GET", "POST"]
366
+ set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/v1/*path\"\n proxy to \"" + base + "\"")
367
+ -- los webhooks de los canales (lib/channels.syn) tampoco: la firma de la plataforma la verifica el plugin
368
+ each m in ["GET", "POST"]
369
+ set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/ch/*path\"\n proxy to \"" + base + "\"")
356
370
  give join(lines, "\n")
357
371
 
358
372
  -- reescribe hub.syn desde la plantilla si cambió (bajo --watch, el hub se reinicia solo)
@@ -407,6 +421,7 @@ export task start_ws(w)
407
421
  require file(".lampson/*")
408
422
  require file.read("web.syn")
409
423
  require file.read("chat.syn")
424
+ require file.read("run.syn")
410
425
  require file.read(".env")
411
426
  -- encender levanta la pausa manual
412
427
  when contains(w, "paused") and w["paused"] == true
@@ -725,6 +740,10 @@ export task should_live(w, hc)
725
740
  give true
726
741
  when schedules_on_disk(w) > 0
727
742
  give true
743
+ -- con API keys (lib/apikeys.syn) el workspace atiende apps (un bot, un webhook): apagarlo por inactividad haría
744
+ -- que el próximo mensaje encuentre un 502 en el hub
745
+ when api_keys_on_disk(w) > 0
746
+ give true
728
747
  let ih be idle_hours()
729
748
  when ih == 0
730
749
  give true
@@ -732,6 +751,12 @@ export task should_live(w, hc)
732
751
  give now() - last < ih * 3600
733
752
 
734
753
  -- tareas encendidas según el json del workspace (sirve aunque el proceso esté apagado)
754
+ task api_keys_on_disk(w)
755
+ try
756
+ give length(json_decode(read_file(dir_of(w["slug"]) + "/.lampson/api_keys.json"))["keys"])
757
+ recover err
758
+ give 0
759
+
735
760
  task schedules_on_disk(w)
736
761
  try
737
762
  let doc be json_decode(read_file(dir_of(w["slug"]) + "/.lampson/schedules.json"))
@@ -750,6 +775,7 @@ export task tick()
750
775
  require file(".lampson/*")
751
776
  require file.read("web.syn")
752
777
  require file.read("chat.syn")
778
+ require file.read("run.syn")
753
779
  when migrate_ports() and hub_alive()
754
780
  restart_hub_later()
755
781
  keep_edge()
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lampson",
3
- "version": "0.2.9",
4
- "description": "A coding agent written in Synsema: terminal + web, tools confined to the mounted project, plugins (your own tools, any language), LSP, MCP, sub-agents.",
3
+ "version": "0.3.0",
4
+ "description": "A coding agent written in Synsema: terminal + web, tools confined to the mounted project, plugins (your own tools, any language), LSP, MCP, sub-agents. Also an SDK: import { Lampson } from \"lampson\" (server or local mode).",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -23,11 +23,15 @@
23
23
  },
24
24
  "files": [
25
25
  "bin/",
26
+ "sdk/index.js",
27
+ "sdk/index.mjs",
28
+ "sdk/index.d.ts",
26
29
  "lib/",
27
30
  "public/",
28
31
  "skills/",
29
32
  "plugins/",
30
33
  "chat.syn",
34
+ "run.syn",
31
35
  "web.syn",
32
36
  "hub.tpl.syn",
33
37
  "edge.syn",
@@ -47,5 +51,15 @@
47
51
  },
48
52
  "scripts": {
49
53
  "test": "pwsh -NoProfile -File tests/run.ps1"
54
+ },
55
+ "main": "sdk/index.js",
56
+ "types": "sdk/index.d.ts",
57
+ "exports": {
58
+ ".": {
59
+ "types": "./sdk/index.d.ts",
60
+ "import": "./sdk/index.mjs",
61
+ "require": "./sdk/index.js"
62
+ },
63
+ "./package.json": "./package.json"
50
64
  }
51
65
  }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "chatwoot",
3
+ "description": "Channel: answer your Chatwoot inbox (WhatsApp, Instagram, Facebook, email, web chat… everything Chatwoot connects) with a Lampson agent.",
4
+ "kind": "syn",
5
+ "entry": "plugin.syn",
6
+ "caps": "net",
7
+ "timeout": 30,
8
+ "config": ["CHATWOOT_URL", "CHATWOOT_TOKEN", "CHATWOOT_WEBHOOK_SECRET"],
9
+ "channel": {"agent": ""},
10
+ "tools": []
11
+ }
@@ -0,0 +1,143 @@
1
+ -- plugins/chatwoot/plugin.syn — canal Chatwoot (contrato en lib/channels.syn)
2
+ --
3
+ -- Chatwoot ya une WhatsApp, Instagram, Facebook, Telegram, email y el chat web en una bandeja: con este canal, un
4
+ -- agente de Lampson contesta todo eso. Lampson lo corre con techo: stdout, time, env=PLUGIN_*, net.
5
+ --
6
+ -- receive el webhook de Chatwoot (evento message_created). Verifica X-Chatwoot-Signature si hay secreto
7
+ -- (HMAC-SHA256 de "<X-Chatwoot-Timestamp>.<body crudo>", con tolerancia de 5 min contra replays), y solo
8
+ -- pasa los mensajes ENTRANTES y públicos: los salientes (incluidas las respuestas del propio agente, que
9
+ -- Chatwoot también notifica) y las notas privadas se ignoran — si no, el agente se contestaría a sí mismo.
10
+ -- send POST /api/v1/accounts/<account>/conversations/<conversation>/messages con api_access_token.
11
+ --
12
+ -- Config (en el .env de Lampson): LAMPSON_CHATWOOT_URL=https://app.chatwoot.com (o tu instancia),
13
+ -- LAMPSON_CHATWOOT_TOKEN=<access token de un agente o agent bot>, LAMPSON_CHATWOOT_WEBHOOK_SECRET=<el secreto que
14
+ -- Chatwoot muestra al crear el webhook>, y LAMPSON_CHANNEL_CHATWOOT_AGENT=<el agente que atiende>.
15
+ intent: "lampson channel plugin: Chatwoot inbox ↔ Lampson agent"
16
+
17
+ require env("PLUGIN_*")
18
+ require net
19
+ require time
20
+
21
+ let action be env("PLUGIN_TOOL", "")
22
+ let args be json_decode(env("PLUGIN_ARGS", "{}"))
23
+
24
+ task header(h, name)
25
+ each k in keys(h)
26
+ when lower(k) == name
27
+ give text(h[k])
28
+ give ""
29
+
30
+ task field(m, k, fallback)
31
+ when m != nothing and type_of(m) == "map" and contains(m, k) and m[k] != nothing
32
+ give m[k]
33
+ give fallback
34
+
35
+ task out(m)
36
+ print(json_encode(m))
37
+
38
+ task ignore(why)
39
+ out({"messages": [], "ignored": why})
40
+
41
+ task fetch_image(u)
42
+ try
43
+ let r be http_bytes("GET", u, {}, nothing, nothing, 20)
44
+ when not r["ok"] or length(r["bytes"]) == 0 or length(r["bytes"]) > 1500000
45
+ give nothing
46
+ let ct be ""
47
+ each k in keys(field(r, "headers", {}))
48
+ when lower(k) == "content-type"
49
+ set ct to lower(text(r["headers"][k]))
50
+ when not starts_with(ct, "image/")
51
+ set ct to when ends_with(lower(u), ".png") then "image/png" otherwise "image/jpeg"
52
+ give {"media_type": split(ct, ";")[0], "data": decode(r["bytes"], "base64")}
53
+ recover err
54
+ give nothing
55
+
56
+ task receive()
57
+ let body be text(field(args, "body", ""))
58
+ let h be field(args, "headers", {})
59
+ let sec be env("PLUGIN_CHATWOOT_WEBHOOK_SECRET", "")
60
+ when sec != ""
61
+ let ts be header(h, "x-chatwoot-timestamp")
62
+ let sig be header(h, "x-chatwoot-signature")
63
+ let expected be "sha256=" + decode(hmac(ts + "." + body, sec), "hex")
64
+ when ts == "" or sig != expected
65
+ out({"messages": [], "http": {"status": 401, "body": "invalid signature"}})
66
+ give false
67
+ let age be 0
68
+ try
69
+ set age to now() - number(ts)
70
+ recover err
71
+ set age to 99999
72
+ when age > 300 or age < -300
73
+ out({"messages": [], "http": {"status": 401, "body": "stale timestamp"}})
74
+ give false
75
+ let ev be nothing
76
+ try
77
+ set ev to json_decode(body)
78
+ recover err
79
+ ignore("body is not JSON")
80
+ give false
81
+ when text(field(ev, "event", "")) != "message_created"
82
+ ignore("event " + text(field(ev, "event", "")))
83
+ give false
84
+ -- message_type llega como texto ("incoming") o, según la versión, como número (0 = incoming)
85
+ let mt be field(ev, "message_type", "")
86
+ when not (mt == "incoming" or mt == 0)
87
+ ignore("not an incoming message")
88
+ give false
89
+ when field(ev, "private", false) == true
90
+ ignore("private note")
91
+ give false
92
+ let content be text(field(ev, "content", ""))
93
+ -- adjuntos: una IMAGEN (hasta 1,5 MB) viaja como imagen para el modelo; lo demás, como link en el texto
94
+ let images be []
95
+ each a in field(ev, "attachments", [])
96
+ let u be text(field(a, "data_url", ""))
97
+ let img be nothing
98
+ when u != "" and text(field(a, "file_type", "")) == "image"
99
+ set img to fetch_image(u)
100
+ when img != nothing
101
+ set images to append(images, img)
102
+ otherwise when u != ""
103
+ set content to content + "\n[attachment: " + u + "]"
104
+ when trim(content) == "" and length(images) > 0
105
+ set content to "[image]"
106
+ when trim(content) == ""
107
+ ignore("empty message")
108
+ give false
109
+ let conv be field(ev, "conversation", {})
110
+ let conv_id be field(conv, "display_id", field(conv, "id", nothing))
111
+ let account_id be field(field(ev, "account", {}), "id", nothing)
112
+ when conv_id == nothing or account_id == nothing
113
+ ignore("no account or conversation id")
114
+ give false
115
+ let who be field(ev, "sender", field(ev, "contact", {}))
116
+ let created be field(ev, "created_at", nothing)
117
+ let sent_at be when type_of(created) == "number" then created otherwise nothing
118
+ out({"messages": [{"thread": text(account_id) + ":" + text(conv_id), "text": content, "sent_at": sent_at, "from": {"id": text(field(who, "id", "")), "name": text(field(who, "name", "")), "kind": "human"}, "images": images, "meta": {"account_id": account_id, "conversation_id": conv_id, "message_id": field(ev, "id", nothing), "inbox_id": field(field(ev, "inbox", {}), "id", nothing)}}]})
119
+ give true
120
+
121
+ task send()
122
+ let base be env("PLUGIN_CHATWOOT_URL", "")
123
+ let tok be env("PLUGIN_CHATWOOT_TOKEN", "")
124
+ when base == "" or tok == ""
125
+ print("ERROR: set LAMPSON_CHATWOOT_URL and LAMPSON_CHATWOOT_TOKEN in Lampson's .env")
126
+ give false
127
+ while ends_with(base, "/")
128
+ set base to slice(base, 0, length(base) - 1)
129
+ let meta be field(args, "meta", {})
130
+ let url be base + "/api/v1/accounts/" + text(field(meta, "account_id", "")) + "/conversations/" + text(field(meta, "conversation_id", "")) + "/messages"
131
+ let r be http_post(url, json_encode({"content": text(field(args, "text", "")), "message_type": "outgoing", "private": false}), {"api_access_token": tok, "Content-Type": "application/json"}, 20)
132
+ when r["ok"]
133
+ print("sent to conversation " + text(field(meta, "conversation_id", "")))
134
+ give true
135
+ print("ERROR: Chatwoot answered " + text(r["status"]) + ": " + slice(text(field(r, "body", "")), 0, 200))
136
+ give false
137
+
138
+ when action == "receive"
139
+ receive()
140
+ otherwise when action == "send"
141
+ send()
142
+ otherwise
143
+ print("ERROR: unknown action '" + action + "'")
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "telegram",
3
+ "description": "Channel: a Telegram bot answered by a Lampson agent. Free, no middleman: create the bot with @BotFather, put its token in .env, then `lampson channel setup telegram`.",
4
+ "kind": "syn",
5
+ "entry": "plugin.syn",
6
+ "caps": "net",
7
+ "timeout": 30,
8
+ "config": ["TELEGRAM_TOKEN", "TELEGRAM_WEBHOOK_SECRET", "TELEGRAM_API"],
9
+ "channel": {"agent": "", "typing": true, "poll": true},
10
+ "tools": []
11
+ }
@@ -0,0 +1,272 @@
1
+ -- plugins/telegram/plugin.syn — canal Telegram (contrato en lib/channels.syn)
2
+ --
3
+ -- Un bot de Telegram contestado por un agente de Lampson. Gratis y sin intermediarios. Lampson lo corre con techo:
4
+ -- stdout, time, env=PLUGIN_*, net.
5
+ --
6
+ -- setup registra el webhook en Telegram (setWebhook) con la URL que le pasa `lampson channel setup telegram`
7
+ -- y el secreto de LAMPSON_TELEGRAM_WEBHOOK_SECRET; muestra el @usuario del bot (getMe).
8
+ -- receive un Update de Telegram. Si hay secreto, exige X-Telegram-Bot-Api-Secret-Token (Telegram lo manda en cada
9
+ -- webhook). Pasa los mensajes nuevos de personas: ignora ediciones, posts de canales y mensajes de otros
10
+ -- bots. Una FOTO llega como imagen (la versión más grande hasta 1 MB, descargada con getFile; el caption es
11
+ -- el texto); audio/documento/ubicación como una nota en el texto. Avisa "escribiendo…" apenas llega.
12
+ -- typing sendChatAction "typing" (Lampson la renueva mientras el agente trabaja: en Telegram dura ~5 s).
13
+ -- poll SIN URL PÚBLICA: getUpdates con espera larga (LAMPSON_TELEGRAM_POLL_WAIT s, 20 por defecto) desde el
14
+ -- cursor; devuelve los mensajes convertidos igual que receive y el próximo offset.
15
+ -- send sendMessage al chat, en partes de hasta 4000 caracteres (Telegram corta en 4096), texto plano (sin parse
16
+ -- mode: un markdown mal formado haría fallar el envío; se quitan los ** del modelo).
17
+ --
18
+ -- Config (en el .env de Lampson): LAMPSON_TELEGRAM_TOKEN=<token de @BotFather>,
19
+ -- LAMPSON_TELEGRAM_WEBHOOK_SECRET=<cualquier texto largo: letras, números, _ y ->, LAMPSON_CHANNEL_TELEGRAM_AGENT=<el
20
+ -- agente que atiende>. LAMPSON_TELEGRAM_API = otra base (un Bot API server propio, o los tests); por defecto la oficial.
21
+ intent: "lampson channel plugin: Telegram bot ↔ Lampson agent"
22
+
23
+ require env("PLUGIN_*")
24
+ require net
25
+ require time
26
+
27
+ let action be env("PLUGIN_TOOL", "")
28
+ let args be json_decode(env("PLUGIN_ARGS", "{}"))
29
+
30
+ task field(m, k, fallback)
31
+ when m != nothing and type_of(m) == "map" and contains(m, k) and m[k] != nothing
32
+ give m[k]
33
+ give fallback
34
+
35
+ task header(h, name)
36
+ each k in keys(h)
37
+ when lower(k) == name
38
+ give text(h[k])
39
+ give ""
40
+
41
+ task api(method)
42
+ let base be env("PLUGIN_TELEGRAM_API", "")
43
+ when base == ""
44
+ set base to "https://api.telegram.org"
45
+ while ends_with(base, "/")
46
+ set base to slice(base, 0, length(base) - 1)
47
+ give base + "/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/" + method
48
+
49
+ task tg(method, body)
50
+ let r be http_post(api(method), json_encode(body), {"Content-Type": "application/json"}, 20)
51
+ let d be {}
52
+ try
53
+ set d to json_decode(text(field(r, "body", "{}")))
54
+ recover err
55
+ set d to {}
56
+ give {"ok": r["ok"] and field(d, "ok", false) == true, "status": r["status"], "data": d}
57
+
58
+ task out(m)
59
+ print(json_encode(m))
60
+
61
+ task ignore(why)
62
+ out({"messages": [], "ignored": why})
63
+
64
+ task need_token()
65
+ when env("PLUGIN_TELEGRAM_TOKEN", "") == ""
66
+ print("ERROR: set LAMPSON_TELEGRAM_TOKEN in Lampson's .env (the token @BotFather gave you)")
67
+ give false
68
+ give true
69
+
70
+ task setup()
71
+ when not need_token()
72
+ give false
73
+ when text(field(args, "mode", "webhook")) == "poll"
74
+ -- getUpdates no funciona con un webhook registrado: se quita (los mensajes pendientes quedan)
75
+ let me0 be tg("getMe", {})
76
+ let dw be tg("deleteWebhook", {"drop_pending_updates": false})
77
+ when not dw["ok"]
78
+ print("ERROR: deleteWebhook failed (" + text(dw["status"]) + "): " + text(field(dw["data"], "description", "")))
79
+ give false
80
+ print("polling mode: " + (when me0["ok"] then "@" + text(field(field(me0["data"], "result", {}), "username", "?")) otherwise "your bot") + " — Lampson asks Telegram for new messages (no public URL needed)")
81
+ give true
82
+ let url be text(field(args, "webhook_url", ""))
83
+ when not starts_with(url, "https://")
84
+ print("ERROR: Telegram only sends webhooks to an https:// URL (got '" + url + "')")
85
+ give false
86
+ let body be {"url": url, "allowed_updates": ["message"]}
87
+ let sec be env("PLUGIN_TELEGRAM_WEBHOOK_SECRET", "")
88
+ when sec != ""
89
+ set body["secret_token"] to sec
90
+ let me be tg("getMe", {})
91
+ let r be tg("setWebhook", body)
92
+ when not r["ok"]
93
+ print("ERROR: setWebhook failed (" + text(r["status"]) + "): " + text(field(r["data"], "description", "")))
94
+ give false
95
+ let who be when me["ok"] then "@" + text(field(field(me["data"], "result", {}), "username", "?")) otherwise "your bot"
96
+ print("webhook registered: " + who + " → " + url + (when sec == "" then " (no secret: set LAMPSON_TELEGRAM_WEBHOOK_SECRET and run setup again so only Telegram can post here)" otherwise " (with secret token)"))
97
+ give true
98
+
99
+ -- la foto como imagen para el modelo: la versión más grande que entre en 1 MB (Telegram manda varias resoluciones)
100
+ task photo_image(sizes)
101
+ let best be nothing
102
+ each s in sizes
103
+ let sz be field(s, "file_size", 0)
104
+ when sz <= 1000000 and (best == nothing or sz > field(best, "file_size", 0))
105
+ set best to s
106
+ when best == nothing or env("PLUGIN_TELEGRAM_TOKEN", "") == ""
107
+ give nothing
108
+ try
109
+ let f be tg("getFile", {"file_id": field(best, "file_id", "")})
110
+ let fp be text(field(field(f["data"], "result", {}), "file_path", ""))
111
+ when not f["ok"] or fp == ""
112
+ give nothing
113
+ let base be api("getMe")
114
+ set base to slice(base, 0, length(base) - length("/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/getMe"))
115
+ let r be http_bytes("GET", base + "/file/bot" + env("PLUGIN_TELEGRAM_TOKEN", "") + "/" + fp, {}, nothing, nothing, 20)
116
+ when not r["ok"] or length(r["bytes"]) == 0 or length(r["bytes"]) > 1500000
117
+ give nothing
118
+ let mt be when ends_with(lower(fp), ".png") then "image/png" otherwise (when ends_with(lower(fp), ".webp") then "image/webp" otherwise "image/jpeg")
119
+ give {"media_type": mt, "data": decode(r["bytes"], "base64")}
120
+ recover err
121
+ give nothing
122
+
123
+ task typing()
124
+ let meta be field(args, "meta", {})
125
+ let chat_id be field(meta, "chat_id", field(args, "thread", nothing))
126
+ when env("PLUGIN_TELEGRAM_TOKEN", "") == "" or chat_id == nothing
127
+ give false
128
+ tg("sendChatAction", {"chat_id": chat_id, "action": "typing"})
129
+ print("typing")
130
+ give true
131
+
132
+ -- un Update → el mensaje en el formato de Lampson, o nothing (lo comparten receive y poll)
133
+ task convert(up)
134
+ let m be field(up, "message", nothing)
135
+ when m == nothing
136
+ give nothing
137
+ let who be field(m, "from", {})
138
+ when field(who, "is_bot", false) == true
139
+ give nothing
140
+ let content be text(field(m, "text", field(m, "caption", "")))
141
+ let notes be []
142
+ let images be []
143
+ when contains(m, "photo")
144
+ let img be photo_image(field(m, "photo", []))
145
+ when img != nothing
146
+ set images to append(images, img)
147
+ otherwise
148
+ set notes to append(notes, "[the user sent a photo that could not be loaded]")
149
+ when contains(m, "voice") or contains(m, "audio")
150
+ set notes to append(notes, "[the user sent an audio message]")
151
+ when contains(m, "document")
152
+ set notes to append(notes, "[the user sent a file: " + text(field(field(m, "document", {}), "file_name", "")) + "]")
153
+ when contains(m, "location")
154
+ set notes to append(notes, "[the user shared a location]")
155
+ when length(notes) > 0
156
+ set content to trim(content + "\n" + join(notes, "\n"))
157
+ when trim(content) == "" and length(images) > 0
158
+ set content to "[photo]"
159
+ let chat be field(m, "chat", {})
160
+ let chat_id be field(chat, "id", nothing)
161
+ when trim(content) == "" or chat_id == nothing
162
+ give nothing
163
+ let name be trim(text(field(who, "first_name", "")) + " " + text(field(who, "last_name", "")))
164
+ give {"thread": text(chat_id), "text": content, "sent_at": field(m, "date", nothing), "from": {"id": text(field(who, "id", "")), "name": name, "username": text(field(who, "username", "")), "kind": "human"}, "images": images, "meta": {"chat_id": chat_id, "message_id": field(m, "message_id", nothing), "chat_type": text(field(chat, "type", ""))}}
165
+
166
+ task poll()
167
+ when not need_token()
168
+ give false
169
+ let wait be 20
170
+ try
171
+ set wait to int(env("PLUGIN_TELEGRAM_POLL_WAIT", "20"))
172
+ recover err
173
+ set wait to 20
174
+ let body be {"timeout": wait, "allowed_updates": ["message"]}
175
+ let cur be field(args, "cursor", nothing)
176
+ when cur != nothing
177
+ set body["offset"] to cur
178
+ let r be http_post(api("getUpdates"), json_encode(body), {"Content-Type": "application/json"}, wait + 10)
179
+ let d be {}
180
+ try
181
+ set d to json_decode(text(field(r, "body", "{}")))
182
+ recover err
183
+ set d to {}
184
+ when not r["ok"] or field(d, "ok", false) != true
185
+ print("ERROR: getUpdates failed (" + text(r["status"]) + "): " + text(field(d, "description", "")))
186
+ give false
187
+ let msgs be []
188
+ let next be cur
189
+ each up in field(d, "result", [])
190
+ set next to field(up, "update_id", 0) + 1
191
+ let m be convert(up)
192
+ when m != nothing
193
+ try
194
+ tg("sendChatAction", {"chat_id": m["meta"]["chat_id"], "action": "typing"})
195
+ recover err
196
+ set next to next
197
+ set msgs to append(msgs, m)
198
+ out({"messages": msgs, "cursor": next})
199
+ give true
200
+
201
+ task receive()
202
+ let h be field(args, "headers", {})
203
+ let sec be env("PLUGIN_TELEGRAM_WEBHOOK_SECRET", "")
204
+ when sec != "" and header(h, "x-telegram-bot-api-secret-token") != sec
205
+ out({"messages": [], "http": {"status": 401, "body": "invalid secret token"}})
206
+ give false
207
+ let up be nothing
208
+ try
209
+ set up to json_decode(text(field(args, "body", "")))
210
+ recover err
211
+ ignore("body is not JSON")
212
+ give false
213
+ -- solo mensajes nuevos de personas (convert): una edición contestada otra vez sería una respuesta duplicada
214
+ let msg be convert(up)
215
+ when msg == nothing
216
+ ignore("not a new message from a person (edit, channel post, bot, or empty)")
217
+ give false
218
+ -- "escribiendo…" mientras el agente trabaja (dura ~5 s en Telegram; si falla no importa)
219
+ when env("PLUGIN_TELEGRAM_TOKEN", "") != ""
220
+ try
221
+ tg("sendChatAction", {"chat_id": msg["meta"]["chat_id"], "action": "typing"})
222
+ recover err
223
+ set msg to msg
224
+ out({"messages": [msg]})
225
+ give true
226
+
227
+ -- partes de hasta `max` caracteres, cortando en un salto de línea si hay uno cerca
228
+ task chunks(t, max)
229
+ let parts be []
230
+ let rest be t
231
+ while length(rest) > max
232
+ let cut be max
233
+ let head be slice(rest, 0, max)
234
+ let nl be split(head, "\n")
235
+ when length(nl) > 1
236
+ let last_len be length(nl[length(nl) - 1])
237
+ when max - last_len > max / 2
238
+ set cut to max - last_len
239
+ set parts to append(parts, trim(slice(rest, 0, cut)))
240
+ set rest to slice(rest, cut, length(rest))
241
+ when trim(rest) != ""
242
+ set parts to append(parts, trim(rest))
243
+ give parts
244
+
245
+ task send()
246
+ when not need_token()
247
+ give false
248
+ let meta be field(args, "meta", {})
249
+ let chat_id be field(meta, "chat_id", field(args, "thread", nothing))
250
+ let t be replace(text(field(args, "text", "")), "**", "")
251
+ let n be 0
252
+ each part in chunks(t, 4000)
253
+ let r be tg("sendMessage", {"chat_id": chat_id, "text": part})
254
+ when not r["ok"]
255
+ print("ERROR: sendMessage failed (" + text(r["status"]) + "): " + text(field(r["data"], "description", "")))
256
+ give false
257
+ set n to n + 1
258
+ print("sent " + text(n) + " message(s) to chat " + text(chat_id))
259
+ give true
260
+
261
+ when action == "setup"
262
+ setup()
263
+ otherwise when action == "poll"
264
+ poll()
265
+ otherwise when action == "typing"
266
+ typing()
267
+ otherwise when action == "receive"
268
+ receive()
269
+ otherwise when action == "send"
270
+ send()
271
+ otherwise
272
+ print("ERROR: unknown action '" + action + "'")