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.
@@ -361,9 +361,11 @@ task hub_routes(w)
361
361
  each m in ["GET", "POST"]
362
362
  set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/api/*path\" requires auth\n proxy to \"" + base + "\"")
363
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_…)
364
+ -- la API /v1 para apps (lib/api.syn) tampoco: la autentica el proceso del workspace con su API key (Bearer lk_…).
365
+ -- POST /v1/messages espera al agente (buzón + turno con tools): sin `timeout` el proxy corta a los 30 s con 504
366
+ -- (visto 2026-10-16 con una ráfaga real); 600 s, como el bash más largo
365
367
  each m in ["GET", "POST"]
366
- set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/v1/*path\"\n proxy to \"" + base + "\"")
368
+ set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/v1/*path\"\n timeout 600\n proxy to \"" + base + "\"")
367
369
  -- los webhooks de los canales (lib/channels.syn) tampoco: la firma de la plataforma la verifica el plugin
368
370
  each m in ["GET", "POST"]
369
371
  set lines to append(lines, " route \"" + m + " /w/" + w["slug"] + "/ch/*path\"\n proxy to \"" + base + "\"")
@@ -744,6 +746,13 @@ export task should_live(w, hc)
744
746
  -- que el próximo mensaje encuentre un 502 en el hub
745
747
  when api_keys_on_disk(w) > 0
746
748
  give true
749
+ -- con un canal encendido (lib/channels.syn) también: en modo poll se caería el poller, y en modo webhook la
750
+ -- plataforma recibiría un 502 del hub (que no enciende workspaces por un webhook)
751
+ when channels_on_disk(w) > 0
752
+ give true
753
+ -- con un equipo que hace rondas (lib/teams.syn: round_minutes > 0): las rondas corren en el proceso del workspace
754
+ when teams_on_disk(w) > 0
755
+ give true
747
756
  let ih be idle_hours()
748
757
  when ih == 0
749
758
  give true
@@ -751,6 +760,46 @@ export task should_live(w, hc)
751
760
  give now() - last < ih * 3600
752
761
 
753
762
  -- tareas encendidas según el json del workspace (sirve aunque el proceso esté apagado)
763
+ -- canales encendidos en el workspace: plugins encendidos (.lampson/plugins.json del ws) cuyo plugin.json declara
764
+ -- "channel" — globales (plugins/ de la instalación, leídos por el link del ws) o del proyecto (.lampson/plugins/)
765
+ export task channels_on_disk(w)
766
+ let n be 0
767
+ try
768
+ let st be json_decode(read_file(dir_of(w["slug"]) + "/.lampson/plugins.json"))
769
+ let on be when contains(st, "enabled") then st["enabled"] otherwise {}
770
+ each name in keys(on)
771
+ when on[name] == true
772
+ let found be false
773
+ each f in [dir_of(w["slug"]) + "/plugins/" + name + "/plugin.json", dir_of(w["slug"]) + "/workspace/.lampson/plugins/" + name + "/plugin.json"]
774
+ when not found
775
+ try
776
+ when contains(read_file(f), "\"channel\"")
777
+ set found to true
778
+ recover err
779
+ set found to found
780
+ when found
781
+ set n to n + 1
782
+ recover err
783
+ give 0
784
+ give n
785
+
786
+ -- equipos con rondas en el proyecto (leídos por el link workspace/ del ws: el hub no tiene permiso sobre el proyecto)
787
+ export task teams_on_disk(w)
788
+ let n be 0
789
+ try
790
+ let d be dir_of(w["slug"]) + "/workspace/.lampson/teams"
791
+ each e in list_dir(d)
792
+ when ends_with(e["name"], ".team.json")
793
+ try
794
+ let t be json_decode(read_file(d + "/" + e["name"]))
795
+ when contains(t, "round_minutes") and t["round_minutes"] != nothing and number(t["round_minutes"]) > 0
796
+ set n to n + 1
797
+ recover err
798
+ set n to n
799
+ recover err
800
+ give 0
801
+ give n
802
+
754
803
  task api_keys_on_disk(w)
755
804
  try
756
805
  give length(json_decode(read_file(dir_of(w["slug"]) + "/.lampson/api_keys.json"))["keys"])
@@ -0,0 +1,105 @@
1
+ -- lib/worktree.syn — la copia de trabajo de cada agente de un equipo (git worktree)
2
+ --
3
+ -- En un proyecto con git, cada miembro de un equipo trabaja en SU copia: workspace/.lampson/worktrees/<agente>, en
4
+ -- su rama team/<equipo>/<agente> (sale de la rama actual del proyecto), con SU nombre de autor (config de git por
5
+ -- worktree: extensions.worktreeConfig). Así dos agentes no se pisan archivos ni ramas, y el registro de git dice
6
+ -- quién hizo cada commit. La copia principal (la de la persona, con main) no se toca.
7
+ -- * .lampson/ queda en .git/info/exclude (exclusión local: no cambia ningún archivo del repo)
8
+ -- * lib/loop.syn traduce: las tools de archivos y bash del agente operan en su copia; para él es la raíz
9
+ -- * un merge/push que sale de su copia (toca la historia compartida) pide aprobación a la persona (lib/loop.syn)
10
+ use "./tools/common.syn" as c
11
+
12
+ export let DIR be ".lampson/worktrees"
13
+ let G be "git"
14
+
15
+ task git(args, cwd)
16
+ require exec
17
+ require time
18
+ require file("workspace")
19
+ require file("workspace/*")
20
+ try
21
+ let r be run(G, args, 30, {"cwd": cwd})
22
+ give {"ok": r["exit_code"] == 0, "out": trim(r["stdout"] + "\n" + r["stderr"])}
23
+ recover err
24
+ give {"ok": false, "out": text(err)}
25
+
26
+ -- ¿el proyecto es un repo de git (con al menos un commit)?
27
+ export task is_repo()
28
+ require exec
29
+ require time
30
+ require file("workspace")
31
+ require file("workspace/*")
32
+ give git(["rev-parse", "--verify", "HEAD"], c.ROOT)["ok"]
33
+
34
+ -- la copia de `agent` (la crea si falta). → {ok, root, branch, error}; root es relativa al workspace
35
+ export task ensure(team_id, agent, author)
36
+ require exec
37
+ require time
38
+ require file("workspace")
39
+ require file("workspace/*")
40
+ let rel be DIR + "/" + agent
41
+ let branch be "team/" + team_id + "/" + agent
42
+ when not is_repo()
43
+ give {"ok": false, "root": "", "branch": "", "error": "not a git repository (or no commits yet)"}
44
+ when not file_exists(c.ROOT + "/" + rel + "/.git")
45
+ -- .lampson/ fuera de git sin tocar el .gitignore del repo
46
+ let ex be c.ROOT + "/.git/info/exclude"
47
+ let cur be ""
48
+ try
49
+ set cur to read_file(ex)
50
+ recover err
51
+ set cur to ""
52
+ when not contains(cur, "/.lampson/")
53
+ write_file(ex, cur + (when cur == "" or ends_with(cur, "\n") then "" otherwise "\n") + "/.lampson/\n")
54
+ let exists be git(["rev-parse", "--verify", "refs/heads/" + branch], c.ROOT)["ok"]
55
+ let add be git(when exists then ["worktree", "add", rel, branch] otherwise ["worktree", "add", "-b", branch, rel], c.ROOT)
56
+ when not add["ok"]
57
+ give {"ok": false, "root": "", "branch": branch, "error": "git worktree add failed: " + add["out"]}
58
+ -- autor del agente, solo en su copia
59
+ git(["config", "extensions.worktreeConfig", "true"], c.ROOT)
60
+ git(["config", "--worktree", "user.name", author["name"]], c.ROOT + "/" + rel)
61
+ git(["config", "--worktree", "user.email", author["email"]], c.ROOT + "/" + rel)
62
+ give {"ok": true, "root": rel, "branch": branch, "error": ""}
63
+
64
+ -- la rama principal del proyecto (la de la copia de la persona)
65
+ export task main_branch()
66
+ require exec
67
+ require time
68
+ require file("workspace")
69
+ require file("workspace/*")
70
+ let r be git(["rev-parse", "--abbrev-ref", "HEAD"], c.ROOT)
71
+ give when r["ok"] then r["out"] otherwise "main"
72
+
73
+ -- las tools que operan en la copia del agente, y cómo se traducen sus args
74
+ export let FILE_TOOLS be ["read", "write", "edit", "ls", "find", "grep"]
75
+
76
+ export task rooted(name, args, root)
77
+ let a be args
78
+ when name == "bash"
79
+ set a["command"] to "cd \"" + root + "\" && " + text(args["command"])
80
+ give a
81
+ let p be when contains(args, "path") and args["path"] != nothing then replace(text(args["path"]), "\\", "/") otherwise "."
82
+ while starts_with(p, "./")
83
+ set p to slice(p, 2, length(p))
84
+ when p == "." or p == ""
85
+ set a["path"] to root
86
+ otherwise when starts_with(p, root + "/") or p == root or starts_with(p, ".lampson/spill/")
87
+ set a["path"] to p
88
+ otherwise
89
+ set a["path"] to root + "/" + p
90
+ give a
91
+
92
+ -- ¿este comando toca la historia compartida desde una copia de agente? push siempre; merge/rebase/update-ref/branch -f
93
+ -- cuando sale de su copia (-C, cd o ../): adentro de su copia puede traer main a su rama sin pedir nada
94
+ export task touches_shared(command)
95
+ let cmd be " " + lower(replace(text(command), "\n", " ")) + " "
96
+ when not contains(cmd, "git")
97
+ give ""
98
+ when matches(cmd, ".*\\bgit\\b.*\\bpush\\b.*")
99
+ give "git push"
100
+ let leaves be contains(cmd, " -c ") or contains(cmd, "../") or contains(cmd, "..\\") or matches(cmd, ".*\\bcd\\b.*")
101
+ when leaves and matches(cmd, ".*\\bgit\\b.*\\b(merge|rebase|update-ref|cherry-pick|reset)\\b.*")
102
+ give "git merge/rebase/reset outside your working copy"
103
+ when matches(cmd, ".*\\bgit\\b.*\\bbranch\\b.*\\s-(f|d|D)\\b.*") or matches(cmd, ".*\\bgit\\b.*\\bupdate-ref\\b.*")
104
+ give "git branch -f/-d or update-ref"
105
+ give ""
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lampson",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
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": {
@@ -0,0 +1,16 @@
1
+ You can take orders with the `plugin_orders_*` tools. They work the same whether a customer is chatting with you or a system sends you the order.
2
+
3
+ Rules that always apply:
4
+ - Product, price, stock, delivery, hours and payment facts come from `catalog`. What is not there, you don't know. A product with stock 0 is not available: its notes say when it comes back.
5
+ - Every total comes from `quote` (promos, packs and delivery fee applied) — never add up yourself, never invent discounts or order numbers.
6
+ - An order needs: items with quantities, delivery or pickup, the address for delivery (street, number, apartment, a reference), the customer's name, and a payment method from the catalog.
7
+ - `place_order` saves the order and lowers the stock: call it once per order, only when the data is complete and confirmed. If it answers with an error (no stock, missing data), fix the cause — don't retry the same call.
8
+ - A placed order can be changed (`update_order`: add or remove items, delivery, address, payment, time) or cancelled (`cancel_order`) while its status is "new". Change the existing order instead of placing a second one; confirm the new total (from `quote`) before `update_order`, and the cancellation before `cancel_order`. If the store already started it, the tool says so: tell the customer to contact the store.
9
+
10
+ When a customer is chatting with you (they write from their phone, keep each message short):
11
+ 1. Help them choose; if the store is closed now, say when it opens and that you can still take the order for later. Several messages in a row are one message: answer them together.
12
+ 2. Ask only for what is missing, one or two things per message. With a phone number, `find_customer` may already have their address: confirm it instead of asking again.
13
+ 3. Send a short summary (items, delivery or pickup, address, payment, total from `quote`) and ask for confirmation. Place the order ONLY after a clear yes.
14
+ 4. Then give the order number, the total and when it arrives (the catalog's delivery time) or when to pick it up.
15
+
16
+ When a system sends you a complete order (an API call, a script, another agent — nobody to ask): check it with `quote`, place it, and answer with the order number and total; if something is missing or out of stock, answer with exactly what and don't place it.
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "orders",
3
+ "description": "Take orders by chat: catalog, quotes with promos and delivery, orders saved with customer and address (and changed or cancelled while still new), stock kept up to date. Data in .lampson/orders/ of the project.",
4
+ "kind": "syn",
5
+ "entry": "plugin.syn",
6
+ "caps": "file=workspace/.lampson/orders,file=workspace/.lampson/orders/*",
7
+ "timeout": 20,
8
+ "instructions": "INSTRUCTIONS.md",
9
+ "tools": [
10
+ {
11
+ "name": "catalog",
12
+ "description": "The store's catalog: products (sku, name, price, unit, stock, notes, promos), hours, delivery and payment methods. Read it before talking about products, prices, stock, delivery or hours.",
13
+ "parameters": {"type": "object", "properties": {}},
14
+ "readonly": true
15
+ },
16
+ {
17
+ "name": "quote",
18
+ "description": "Prices a cart exactly: lines, promos and packs applied, delivery fee and total, plus any item without enough stock. Use it for every total you tell the customer; never add up yourself.",
19
+ "parameters": {
20
+ "type": "object",
21
+ "properties": {
22
+ "items": {"type": "array", "description": "the cart", "items": {"type": "object", "properties": {"sku": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}}, "required": ["sku", "qty"]}},
23
+ "delivery": {"type": "string", "enum": ["delivery", "pickup"], "description": "delivery to an address, or pickup at the store"}
24
+ },
25
+ "required": ["items"]
26
+ },
27
+ "readonly": true
28
+ },
29
+ {
30
+ "name": "place_order",
31
+ "description": "Places the order once the customer CONFIRMED the summary: saves it with an order number, saves the customer (name, phone, address) and lowers the stock. Prices are computed here again from the catalog.",
32
+ "parameters": {
33
+ "type": "object",
34
+ "properties": {
35
+ "customer": {"type": "object", "properties": {"name": {"type": "string"}, "phone": {"type": "string"}}, "required": ["name"]},
36
+ "items": {"type": "array", "items": {"type": "object", "properties": {"sku": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}}, "required": ["sku", "qty"]}},
37
+ "delivery": {"type": "string", "enum": ["delivery", "pickup"]},
38
+ "address": {"type": "string", "description": "street, number, floor/apartment and any reference — required for delivery"},
39
+ "payment": {"type": "string", "description": "one of the catalog's payment methods"},
40
+ "when": {"type": "string", "description": "when the customer wants it, if they said (e.g. 'today 18 h'); empty = as soon as possible"},
41
+ "notes": {"type": "string", "description": "anything else the store must know"}
42
+ },
43
+ "required": ["customer", "items", "delivery", "payment"]
44
+ }
45
+ },
46
+ {
47
+ "name": "update_order",
48
+ "description": "Changes an order that is still 'new' (the store hasn't started it): the cart, delivery or pickup, address, payment, time or notes. Pass `items` as the WHOLE cart after the change (omit it to keep the cart). Re-prices everything and moves the stock. Only after the customer confirmed the change.",
49
+ "parameters": {
50
+ "type": "object",
51
+ "properties": {
52
+ "order_id": {"type": "string"},
53
+ "items": {"type": "array", "description": "the whole cart after the change", "items": {"type": "object", "properties": {"sku": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}}, "required": ["sku", "qty"]}},
54
+ "delivery": {"type": "string", "enum": ["delivery", "pickup"]},
55
+ "address": {"type": "string"},
56
+ "payment": {"type": "string"},
57
+ "when": {"type": "string"},
58
+ "notes": {"type": "string"}
59
+ },
60
+ "required": ["order_id"]
61
+ }
62
+ },
63
+ {
64
+ "name": "cancel_order",
65
+ "description": "Cancels an order that is still 'new' and puts its stock back. Only after the customer clearly asked to cancel it.",
66
+ "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}, "reason": {"type": "string"}}, "required": ["order_id"]}
67
+ },
68
+ {
69
+ "name": "find_customer",
70
+ "description": "Looks up a returning customer by phone (or by name): saved address and last orders.",
71
+ "parameters": {"type": "object", "properties": {"phone": {"type": "string"}, "name": {"type": "string"}}},
72
+ "readonly": true
73
+ },
74
+ {
75
+ "name": "order_status",
76
+ "description": "An order by its number (e.g. P-0003): items, total, delivery and status.",
77
+ "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
78
+ "readonly": true
79
+ }
80
+ ]
81
+ }
@@ -0,0 +1,342 @@
1
+ -- plugins/orders/plugin.syn — tomar pedidos: catálogo, cotización exacta, pedido guardado, clientes, stock
2
+ --
3
+ -- Lampson lo corre por cada llamada con el techo del manifiesto: solo puede tocar workspace/.lampson/orders/.
4
+ -- catalog.json el catálogo (lo escribe el dueño; ver docs/recipes): store, hours, delivery, payment, products, policies
5
+ -- producto: {sku, name, price, unit, stock, notes, pack: {qty, price}, second_half: true}
6
+ -- P-0001.json … un archivo por pedido
7
+ -- customers.json clientes por teléfono (o por nombre si no dio teléfono): nombre, dirección, pedidos
8
+ -- Los precios se calculan SIEMPRE acá desde el catálogo: el modelo nunca suma ni pone precios.
9
+ intent: "lampson plugin: take orders against a catalog — quote, place, customers, stock"
10
+
11
+ require env("PLUGIN_*")
12
+ require time
13
+ require file("workspace/.lampson/orders")
14
+ require file("workspace/.lampson/orders/*")
15
+
16
+ let DIR be "workspace/.lampson/orders"
17
+ let CATALOG be DIR + "/catalog.json"
18
+ let CUSTOMERS be DIR + "/customers.json"
19
+
20
+ task out(v)
21
+ print(json_encode(v))
22
+
23
+ task fail(msg)
24
+ out({"ok": false, "error": msg})
25
+
26
+ task load_catalog()
27
+ when not file_exists(CATALOG)
28
+ raise("no catalog yet: the store owner writes .lampson/orders/catalog.json")
29
+ give json_decode(read_file(CATALOG))
30
+
31
+ task num(m, k, fallback)
32
+ when contains(m, k) and m[k] != nothing
33
+ give number(m[k])
34
+ give fallback
35
+
36
+ task round_money(x)
37
+ give floor(x + 0.5)
38
+
39
+ -- montos enteros como enteros (3200, no 3200.0); con centavos, tal cual
40
+ task money(x)
41
+ let v be number(x)
42
+ give when v == floor(v) then floor(v) otherwise v
43
+
44
+ -- una línea del carrito: precio de lista, pack (p. ej. docena) y "segunda a mitad de precio"
45
+ task price_line(p, qty)
46
+ let unit be money(p["price"])
47
+ let plain be unit * qty
48
+ let amount be plain
49
+ let promo be ""
50
+ when contains(p, "pack") and p["pack"] != nothing
51
+ let n be floor(num(p["pack"], "qty", 0))
52
+ when n > 1 and qty >= n
53
+ let packs be floor(qty / n)
54
+ set amount to packs * money(p["pack"]["price"]) + (qty - packs * n) * unit
55
+ set promo to text(packs) + " x pack of " + text(n)
56
+ when contains(p, "second_half") and p["second_half"] == true and qty >= 2
57
+ let pairs be floor(qty / 2)
58
+ set amount to plain - round_money(pairs * unit / 2)
59
+ set promo to text(pairs) + " x second at half price"
60
+ give {"sku": p["sku"], "name": p["name"], "qty": qty, "unit_price": unit, "list": plain, "discount": plain - amount, "amount": amount, "promo": promo}
61
+
62
+ -- cotiza un carrito: {ok, lines, subtotal, discount, delivery_fee, total, short, unknown}
63
+ task quote_of(cat, items, delivery)
64
+ let by_sku be {}
65
+ each p in cat["products"]
66
+ set by_sku[upper(text(p["sku"]))] to p
67
+ let merged be {}
68
+ let order be []
69
+ each it in items
70
+ let sku be upper(trim(text(it["sku"])))
71
+ let qty be floor(num(it, "qty", 0))
72
+ when qty > 0
73
+ when not contains(merged, sku)
74
+ set merged[sku] to 0
75
+ set order to append(order, sku)
76
+ set merged[sku] to merged[sku] + qty
77
+ let lines be []
78
+ let short be []
79
+ let unknown be []
80
+ let subtotal be 0
81
+ let discount be 0
82
+ each sku in order
83
+ when not contains(by_sku, sku)
84
+ set unknown to append(unknown, sku)
85
+ otherwise
86
+ let p be by_sku[sku]
87
+ let ln be price_line(p, merged[sku])
88
+ set lines to append(lines, ln)
89
+ set subtotal to subtotal + ln["amount"]
90
+ set discount to discount + ln["discount"]
91
+ let stock be floor(num(p, "stock", 0))
92
+ when merged[sku] > stock
93
+ set short to append(short, {"sku": sku, "name": p["name"], "asked": merged[sku], "available": stock, "notes": when contains(p, "notes") then p["notes"] otherwise ""})
94
+ let fee be 0
95
+ let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
96
+ when delivery == "delivery"
97
+ set fee to money(num(d, "fee", 0))
98
+ when contains(d, "free_from") and d["free_from"] != nothing and subtotal >= number(d["free_from"])
99
+ set fee to 0
100
+ -- un sku inventado (visto: "pan-sin-gluten-arroz-mijo") → la lista de los válidos, para que el modelo corrija solo
101
+ let hint be when length(unknown) > 0 then apply(cat["products"], (p) => text(p["sku"]) + " = " + text(p["name"])) otherwise []
102
+ give {"valid_skus": hint, "ok": length(short) == 0 and length(unknown) == 0 and length(lines) > 0, "lines": lines, "subtotal": subtotal, "discount": discount, "delivery": delivery, "delivery_fee": fee, "total": subtotal + fee, "short": short, "unknown": unknown, "currency": when contains(cat, "currency") then cat["currency"] otherwise ""}
103
+
104
+ task load_customers()
105
+ when not file_exists(CUSTOMERS)
106
+ give {}
107
+ give json_decode(read_file(CUSTOMERS))
108
+
109
+ task customer_key(c)
110
+ let phone be when contains(c, "phone") and c["phone"] != nothing then replace(replace(replace(trim(text(c["phone"])), " ", ""), "-", ""), "(", "") otherwise ""
111
+ when phone != ""
112
+ give "tel:" + replace(phone, ")", "")
113
+ give "name:" + lower(trim(text(c["name"])))
114
+
115
+ task order_ids()
116
+ give apply(where(list_dir(DIR), (e) => starts_with(e["name"], "P-") and ends_with(e["name"], ".json")), (e) => slice(e["name"], 0, length(e["name"]) - 5))
117
+
118
+ task next_id()
119
+ let n be length(order_ids()) + 1
120
+ let id be ""
121
+ while true
122
+ let digits be text(n)
123
+ each i in range(length(digits), 4)
124
+ set digits to "0" + digits
125
+ set id to "P-" + digits
126
+ when not file_exists(DIR + "/" + id + ".json")
127
+ give id
128
+ set n to n + 1
129
+
130
+ task arg(args, k)
131
+ when contains(args, k) and args[k] != nothing
132
+ give trim(text(args[k]))
133
+ give ""
134
+
135
+ -- ---------- stock y pedidos guardados (update_order / cancel_order) ----------
136
+ task qty_by_sku(lines)
137
+ let m be {}
138
+ each ln in lines
139
+ let k be upper(text(ln["sku"]))
140
+ set m[k] to (when contains(m, k) then m[k] otherwise 0) + floor(number(ln["qty"]))
141
+ give m
142
+
143
+ -- el catálogo con el stock movido: deltas = {sku: unidades que SALEN} (negativo = vuelven)
144
+ task shift_stock(cat, deltas)
145
+ let prods be []
146
+ each p in cat["products"]
147
+ let k be upper(text(p["sku"]))
148
+ when contains(deltas, k)
149
+ set p["stock"] to floor(num(p, "stock", 0)) - deltas[k]
150
+ set prods to append(prods, p)
151
+ set cat["products"] to prods
152
+ give cat
153
+
154
+ task negate(m)
155
+ let out be {}
156
+ each k in keys(m)
157
+ set out[k] to 0 - m[k]
158
+ give out
159
+
160
+ -- lo que cambia entre dos carritos: nuevo - viejo, por sku
161
+ task delta(new_q, old_q)
162
+ let out be {}
163
+ each k in keys(new_q)
164
+ set out[k] to new_q[k] - (when contains(old_q, k) then old_q[k] otherwise 0)
165
+ each k in keys(old_q)
166
+ when not contains(new_q, k)
167
+ set out[k] to 0 - old_q[k]
168
+ give out
169
+
170
+ task quote_problem(q)
171
+ give (when length(q["unknown"]) > 0 then "unknown sku " + join(q["unknown"], ", ") + " " otherwise "") + (when length(q["short"]) > 0 then "not enough stock for " + join(apply(q["short"], (s) => s["name"] + " (asked " + text(s["asked"]) + ", available " + text(s["available"]) + ")"), ", ") otherwise "") + (when length(q["lines"]) == 0 then "empty cart" otherwise "")
172
+
173
+ -- un pedido guardado que todavía se puede tocar: {ok, order} o {ok: false, error}
174
+ task editable(oid)
175
+ when not matches(oid, "P-[0-9]{1,8}") or not file_exists(DIR + "/" + oid + ".json")
176
+ give {"ok": false, "error": "no order " + oid}
177
+ let o be json_decode(read_file(DIR + "/" + oid + ".json"))
178
+ when o["status"] != "new"
179
+ give {"ok": false, "error": "order " + oid + " is '" + text(o["status"]) + "': it can't be changed or cancelled from here anymore — the customer has to talk to the store"}
180
+ give {"ok": true, "order": o}
181
+
182
+ let tool be env("PLUGIN_TOOL", "")
183
+ let args be json_decode(env("PLUGIN_ARGS", "{}"))
184
+
185
+ try
186
+ when tool == "catalog"
187
+ out(load_catalog())
188
+ otherwise when tool == "quote"
189
+ let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise []
190
+ out(quote_of(load_catalog(), items, when arg(args, "delivery") == "" then "pickup" otherwise arg(args, "delivery")))
191
+ otherwise when tool == "place_order"
192
+ let cat be load_catalog()
193
+ let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise []
194
+ let delivery be arg(args, "delivery")
195
+ let cust be when contains(args, "customer") and args["customer"] != nothing then args["customer"] otherwise {}
196
+ let name be arg(cust, "name")
197
+ let payment be arg(args, "payment")
198
+ let address be arg(args, "address")
199
+ let methods be when contains(cat, "payment") and cat["payment"] != nothing then cat["payment"] otherwise []
200
+ let missing be []
201
+ when length(items) == 0
202
+ set missing to append(missing, "items")
203
+ when name == ""
204
+ set missing to append(missing, "customer.name")
205
+ when delivery != "delivery" and delivery != "pickup"
206
+ set missing to append(missing, "delivery (delivery or pickup)")
207
+ when delivery == "delivery" and address == ""
208
+ set missing to append(missing, "address")
209
+ when payment == ""
210
+ set missing to append(missing, "payment")
211
+ when length(missing) > 0
212
+ fail("missing: " + join(missing, ", ") + " — ask the customer, then place the order")
213
+ otherwise when length(methods) > 0 and length(where(methods, (m) => lower(text(m)) == lower(payment))) == 0
214
+ fail("payment '" + payment + "' is not accepted; accepted: " + join(apply(methods, (m) => text(m)), ", "))
215
+ otherwise
216
+ when length(methods) > 0
217
+ set payment to text(where(methods, (m) => lower(text(m)) == lower(payment))[0])
218
+ let q be quote_of(cat, items, delivery)
219
+ when not q["ok"]
220
+ out({"ok": false, "error": "cannot place it: " + (when length(q["unknown"]) > 0 then "unknown sku " + join(q["unknown"], ", ") + " " otherwise "") + (when length(q["short"]) > 0 then "not enough stock for " + join(apply(q["short"], (s) => s["name"] + " (asked " + text(s["asked"]) + ", available " + text(s["available"]) + ")"), ", ") otherwise "") + (when length(q["lines"]) == 0 then "empty cart" otherwise ""), "quote": q})
221
+ otherwise
222
+ let id be next_id()
223
+ let ckey be customer_key(cust)
224
+ let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
225
+ let order be {"id": id, "created": format_time(now(), "%Y-%m-%d %H:%M"), "status": "new", "customer": {"name": name, "phone": arg(cust, "phone"), "key": ckey}, "lines": q["lines"], "subtotal": q["subtotal"], "discount": q["discount"], "delivery": delivery, "address": address, "delivery_fee": q["delivery_fee"], "total": q["total"], "payment": payment, "when": arg(args, "when"), "notes": arg(args, "notes")}
226
+ write_file(DIR + "/" + id + ".json", json_encode(order))
227
+ -- stock: baja lo vendido en el catálogo
228
+ let sold be {}
229
+ each ln in q["lines"]
230
+ set sold[upper(text(ln["sku"]))] to ln["qty"]
231
+ let prods be []
232
+ each p in cat["products"]
233
+ let k be upper(text(p["sku"]))
234
+ when contains(sold, k)
235
+ set p["stock"] to floor(num(p, "stock", 0)) - sold[k]
236
+ set prods to append(prods, p)
237
+ set cat["products"] to prods
238
+ write_file(CATALOG, json_encode(cat))
239
+ -- cliente: nombre, teléfono, última dirección, sus pedidos
240
+ let cs be load_customers()
241
+ let prev be when contains(cs, ckey) then cs[ckey] otherwise {"orders": []}
242
+ set cs[ckey] to {"name": name, "phone": arg(cust, "phone"), "address": when address != "" then address otherwise (when contains(prev, "address") then prev["address"] otherwise ""), "orders": append(prev["orders"], id), "last": order["created"]}
243
+ write_file(CUSTOMERS, json_encode(cs))
244
+ out({"ok": true, "order_id": id, "total": q["total"], "subtotal": q["subtotal"], "discount": q["discount"], "delivery_fee": q["delivery_fee"], "delivery": delivery, "address": address, "payment": payment, "eta": when delivery == "delivery" and contains(d, "eta") then d["eta"] otherwise "", "lines": q["lines"]})
245
+ otherwise when tool == "update_order"
246
+ let ed be editable(upper(arg(args, "order_id")))
247
+ when not ed["ok"]
248
+ fail(ed["error"])
249
+ otherwise
250
+ let o be ed["order"]
251
+ let cat be load_catalog()
252
+ let old be qty_by_sku(o["lines"])
253
+ -- sin "items" el carrito queda como estaba (cambia solo la entrega, el pago, la hora o las notas)
254
+ let items be when contains(args, "items") and args["items"] != nothing then args["items"] otherwise apply(o["lines"], (l) => {"sku": l["sku"], "qty": l["qty"]})
255
+ let delivery be when arg(args, "delivery") != "" then arg(args, "delivery") otherwise o["delivery"]
256
+ let address be when arg(args, "address") != "" then arg(args, "address") otherwise o["address"]
257
+ let payment be when arg(args, "payment") != "" then arg(args, "payment") otherwise o["payment"]
258
+ let methods be when contains(cat, "payment") and cat["payment"] != nothing then cat["payment"] otherwise []
259
+ when delivery != "delivery" and delivery != "pickup"
260
+ fail("delivery must be delivery or pickup")
261
+ otherwise when delivery == "delivery" and address == ""
262
+ fail("missing: address — ask the customer, then update the order")
263
+ otherwise when length(methods) > 0 and length(where(methods, (m) => lower(text(m)) == lower(payment))) == 0
264
+ fail("payment '" + payment + "' is not accepted; accepted: " + join(apply(methods, (m) => text(m)), ", "))
265
+ otherwise
266
+ when length(methods) > 0
267
+ set payment to text(where(methods, (m) => lower(text(m)) == lower(payment))[0])
268
+ -- lo que este pedido ya tiene reservado cuenta como disponible para él
269
+ let q be quote_of(shift_stock(cat, negate(old)), items, delivery)
270
+ when not q["ok"]
271
+ out({"ok": false, "error": "cannot update it: " + quote_problem(q), "quote": q})
272
+ otherwise
273
+ write_file(CATALOG, json_encode(shift_stock(cat, delta(qty_by_sku(q["lines"]), old))))
274
+ let before be o["total"]
275
+ let stamp be format_time(now(), "%Y-%m-%d %H:%M")
276
+ let hist be when contains(o, "history") and o["history"] != nothing then o["history"] otherwise []
277
+ set o["history"] to append(hist, {"at": stamp, "change": "updated", "total_before": before})
278
+ set o["lines"] to q["lines"]
279
+ set o["subtotal"] to q["subtotal"]
280
+ set o["discount"] to q["discount"]
281
+ set o["delivery"] to delivery
282
+ set o["address"] to address
283
+ set o["delivery_fee"] to q["delivery_fee"]
284
+ set o["total"] to q["total"]
285
+ set o["payment"] to payment
286
+ set o["updated"] to stamp
287
+ when contains(args, "when") and args["when"] != nothing
288
+ set o["when"] to arg(args, "when")
289
+ when contains(args, "notes") and args["notes"] != nothing
290
+ set o["notes"] to arg(args, "notes")
291
+ write_file(DIR + "/" + o["id"] + ".json", json_encode(o))
292
+ when address != "" and contains(o["customer"], "key")
293
+ let cs be load_customers()
294
+ when contains(cs, o["customer"]["key"])
295
+ let c be cs[o["customer"]["key"]]
296
+ set c["address"] to address
297
+ set cs[o["customer"]["key"]] to c
298
+ write_file(CUSTOMERS, json_encode(cs))
299
+ let d be when contains(cat, "delivery") and cat["delivery"] != nothing then cat["delivery"] otherwise {}
300
+ out({"ok": true, "order_id": o["id"], "total": q["total"], "total_before": before, "subtotal": q["subtotal"], "discount": q["discount"], "delivery_fee": q["delivery_fee"], "delivery": delivery, "address": address, "payment": payment, "when": o["when"], "eta": when delivery == "delivery" and contains(d, "eta") then d["eta"] otherwise "", "lines": q["lines"]})
301
+ otherwise when tool == "cancel_order"
302
+ let ed be editable(upper(arg(args, "order_id")))
303
+ when not ed["ok"]
304
+ fail(ed["error"])
305
+ otherwise
306
+ let o be ed["order"]
307
+ -- el stock vuelve al catálogo
308
+ write_file(CATALOG, json_encode(shift_stock(load_catalog(), negate(qty_by_sku(o["lines"])))))
309
+ let stamp be format_time(now(), "%Y-%m-%d %H:%M")
310
+ let hist be when contains(o, "history") and o["history"] != nothing then o["history"] otherwise []
311
+ set o["history"] to append(hist, {"at": stamp, "change": "cancelled", "reason": arg(args, "reason")})
312
+ set o["status"] to "cancelled"
313
+ set o["cancelled"] to stamp
314
+ write_file(DIR + "/" + o["id"] + ".json", json_encode(o))
315
+ out({"ok": true, "order_id": o["id"], "status": "cancelled", "total_was": o["total"]})
316
+ otherwise when tool == "find_customer"
317
+ let cs be load_customers()
318
+ let key be ""
319
+ when arg(args, "phone") != ""
320
+ set key to customer_key({"phone": arg(args, "phone"), "name": ""})
321
+ otherwise when arg(args, "name") != ""
322
+ set key to customer_key({"name": arg(args, "name")})
323
+ when key == "" or not contains(cs, key)
324
+ out({"found": false})
325
+ otherwise
326
+ let c be cs[key]
327
+ let recent be []
328
+ each oid in slice(c["orders"], max(0, length(c["orders"]) - 3), length(c["orders"]))
329
+ when file_exists(DIR + "/" + oid + ".json")
330
+ let o be json_decode(read_file(DIR + "/" + oid + ".json"))
331
+ set recent to append(recent, {"id": oid, "created": o["created"], "total": o["total"], "status": o["status"], "items": apply(o["lines"], (l) => {"sku": l["sku"], "qty": l["qty"], "name": l["name"]}), "delivery": o["delivery"], "payment": o["payment"]})
332
+ out({"found": true, "name": c["name"], "phone": c["phone"], "address": c["address"], "orders": recent})
333
+ otherwise when tool == "order_status"
334
+ let oid be upper(arg(args, "order_id"))
335
+ when not matches(oid, "P-[0-9]{1,8}") or not file_exists(DIR + "/" + oid + ".json")
336
+ fail("no order " + oid)
337
+ otherwise
338
+ out(json_decode(read_file(DIR + "/" + oid + ".json")))
339
+ otherwise
340
+ fail("unknown tool '" + tool + "'")
341
+ recover err
342
+ fail(text(err))