shadok-ai 0.19.29 → 0.19.31

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/README.md CHANGED
@@ -86,7 +86,8 @@ Enter to skip; you can add it later from the web UI).
86
86
  with a speech bubble (and no presence dot).
87
87
  - **Groups** — on a desktop the groups live in their own **left column**: pick
88
88
  one to narrow the agents pane to it, and the global tools (Profiles, Ledger,
89
- Secrets, Users, Security, Telegram, Sound) stay in the header at the top. Each
89
+ Secrets, Users, Security) stay in the header at the top; Telegram and the
90
+ notification **Sound** live under the header **⋯** to keep the bar compact. Each
90
91
  agent is a round avatar with a presence dot (green ready, red working, hollow
91
92
  offline). A group's icon opens the icon picker: choose from the grid, type any
92
93
  emoji, or **type a word** (`rocket`, `bug`, `money`…) to search for one; its
@@ -202,7 +203,10 @@ Enter to skip; you can add it later from the web UI).
202
203
  secrets, so an agent may put one only on itself (a person may guard any agent
203
204
  they can drive). Each schedule in the ⏰ popin has a **▶ Run now** button —
204
205
  test a new one without waiting for its slot; its next run stays where it was —
205
- and shows when it runs next and how its last run ended.
206
+ and shows when it runs next and how its last run ended. A schedule belongs to
207
+ its agent: **closing the agent deletes its schedules** (and its webhooks) —
208
+ the confirmation says how many, since that cannot be undone. An agent that is
209
+ merely idle or asleep keeps them; waking it is what they are for.
206
210
  - **Webhooks** — let an outside system (CI, a form, a monitoring tool, Zapier…)
207
211
  wake an agent with an HTTP call, the event-driven twin of a schedule. Create
208
212
  one in the agent's **⚡ Webhooks** popin (the ⚡ icon in its bar, beside ⏰;
@@ -221,7 +225,8 @@ Enter to skip; you can add it later from the web UI).
221
225
  take a URL may pass `?token=…` instead of the header. Pause, rotate the token
222
226
  (↻) or delete it from the same popin. Only a person in the browser can create
223
227
  or change a webhook — never an agent. An unknown id, a paused webhook and a
224
- wrong token all answer the same `404`.
228
+ wrong token all answer the same `404`. Closing the agent deletes its
229
+ webhooks: the URL stops answering and the token is dead.
225
230
  - **Per-agent stats** — the agent's ⋯ menu has a **📊 Stats** view: token usage
226
231
  over the last hour / 24 h / 7 days / 30 days, split in a tooltip into input,
227
232
  output, cache-write and cache-read, with a **notional cost** beside each window.
@@ -663,7 +668,7 @@ topics* (and *Delete messages* so `/secret` can scrub values), then in the group
663
668
  | `/setup <code>` | bind this group as the board (one group per instance), with the code from the panel's **Pair Telegram** — in an already-bound board, it makes the sender an operator |
664
669
  | `/spawn [profile] <name>` | new isolated agent in its own topic (also a web tab) |
665
670
  | `/stop` (alias `/esc`) | interrupt the current turn — does **not** end the session |
666
- | `/new` · `/end` | reset · kill the session |
671
+ | `/new` · `/end` | reset · kill the session (`/end` also deletes the agent's schedules and webhooks, and says so) |
667
672
  | `/restart` | respawn the agent in place (e.g. to pick up new secrets) |
668
673
  | `/profiles` · `/list` | list profiles · list bindings |
669
674
  | `/cron every 30m <prompt>` · `/cron daily 09:00 <prompt>` · `/cron daily 09:00 mon-fri <prompt>` | schedule a recurring prompt on this agent |
@@ -1425,7 +1430,7 @@ client, or immediately on an explicit `stop` (which ends it for everyone).
1425
1430
  | `{type:"gone"}` / `{type:"error", message, code?}` / `{type:"exited", code}` / `{type:"stopped"}` | session lost, errors, termination. `error.code` is `"busy"` for a prompt refused mid-turn and `"logged-out"` for a spawn refused because the instance isn't signed in, `"resume-refused"` for a `resume` whose shortened id matches no agent or several — so a machine client needn't match on the message text |
1426
1431
 
1427
1432
  HTTP endpoints (same auth): `/usage`, `/live`, `/sessions`, `/recover`,
1428
- `/diff`, `/channels` (its GET adds a **derived** `crons` field — never stored),
1433
+ `/diff`, `/channels` (its GET adds a **derived** `crons` field, and `closes` — how many schedules and webhooks closing that agent would delete — never stored),
1429
1434
  `/channels/glance` (GET — each visible row's last-message time and context %,
1430
1435
  read from the transcript's tail so the list fills before the agents resume),
1431
1436
  `/channel` (DELETE), `/groups`, `/groups/ssh` (GET — the SSH **public** key to
@@ -0,0 +1,44 @@
1
+ /**
2
+ * What goes away WITH a channel: the schedules and webhooks that target it.
3
+ *
4
+ * Both stores key their rows on a `sessionId`, and neither was told when the
5
+ * channel behind that id was closed. A schedule then kept firing at a session
6
+ * that no longer existed — every slot, a failure nobody was shown — and a
7
+ * webhook kept a live URL and a valid token pointing at nothing.
8
+ *
9
+ * The one rule that makes this safe: the cleanup is keyed on the channel being
10
+ * REMOVED, never on "no process is running". A dormant channel has no process
11
+ * by definition, and waking it is exactly what a schedule or a webhook is for —
12
+ * a liveness test here would delete the feature along with the bug. So nothing
13
+ * in this file can see a session, a pilot or a registry: it filters by id, and
14
+ * the caller decides WHEN (`endChannel`, on an explicit close).
15
+ *
16
+ * Pure, tested by `test/channel-triggers.test.ts`.
17
+ */
18
+ /** Anything stored against a channel. */
19
+ interface Targeted {
20
+ sessionId: string;
21
+ }
22
+ /**
23
+ * Split a store into the rows that stay and the rows that target `sessionId`.
24
+ * An empty id removes NOTHING: `"" === ""` must never be a way to match a
25
+ * malformed row and wipe it on someone else's close.
26
+ */
27
+ export declare function splitBySession<T extends Targeted>(list: readonly T[], sessionId: string): {
28
+ kept: T[];
29
+ removed: T[];
30
+ };
31
+ /** How many of each a close would delete. */
32
+ export interface TriggerCount {
33
+ schedules: number;
34
+ webhooks: number;
35
+ }
36
+ /**
37
+ * Counts EVERY row, paused ones included: a paused schedule is deleted by the
38
+ * close just the same, so a confirmation that counted only the enabled ones
39
+ * would under-announce an irreversible act.
40
+ */
41
+ export declare function triggerCount(sessionId: string, crons: readonly Targeted[], webhooks: readonly Targeted[]): TriggerCount;
42
+ /** "2 schedules and 1 webhook" — or "" when there is nothing to name. */
43
+ export declare function triggerSummary(n: TriggerCount): string;
44
+ export {};
@@ -0,0 +1,46 @@
1
+ /**
2
+ * What goes away WITH a channel: the schedules and webhooks that target it.
3
+ *
4
+ * Both stores key their rows on a `sessionId`, and neither was told when the
5
+ * channel behind that id was closed. A schedule then kept firing at a session
6
+ * that no longer existed — every slot, a failure nobody was shown — and a
7
+ * webhook kept a live URL and a valid token pointing at nothing.
8
+ *
9
+ * The one rule that makes this safe: the cleanup is keyed on the channel being
10
+ * REMOVED, never on "no process is running". A dormant channel has no process
11
+ * by definition, and waking it is exactly what a schedule or a webhook is for —
12
+ * a liveness test here would delete the feature along with the bug. So nothing
13
+ * in this file can see a session, a pilot or a registry: it filters by id, and
14
+ * the caller decides WHEN (`endChannel`, on an explicit close).
15
+ *
16
+ * Pure, tested by `test/channel-triggers.test.ts`.
17
+ */
18
+ /**
19
+ * Split a store into the rows that stay and the rows that target `sessionId`.
20
+ * An empty id removes NOTHING: `"" === ""` must never be a way to match a
21
+ * malformed row and wipe it on someone else's close.
22
+ */
23
+ export function splitBySession(list, sessionId) {
24
+ const kept = [];
25
+ const removed = [];
26
+ for (const row of list)
27
+ (sessionId && row.sessionId === sessionId ? removed : kept).push(row);
28
+ return { kept, removed };
29
+ }
30
+ /**
31
+ * Counts EVERY row, paused ones included: a paused schedule is deleted by the
32
+ * close just the same, so a confirmation that counted only the enabled ones
33
+ * would under-announce an irreversible act.
34
+ */
35
+ export function triggerCount(sessionId, crons, webhooks) {
36
+ return {
37
+ schedules: splitBySession(crons, sessionId).removed.length,
38
+ webhooks: splitBySession(webhooks, sessionId).removed.length,
39
+ };
40
+ }
41
+ /** "2 schedules and 1 webhook" — or "" when there is nothing to name. */
42
+ export function triggerSummary(n) {
43
+ const part = (count, noun) => (count ? `${count} ${noun}${count === 1 ? "" : "s"}` : "");
44
+ return [part(n.schedules, "schedule"), part(n.webhooks, "webhook")].filter(Boolean).join(" and ");
45
+ }
46
+ //# sourceMappingURL=channel-triggers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel-triggers.js","sourceRoot":"","sources":["../src/channel-triggers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAOH;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAqB,IAAkB,EAAE,SAAiB;IACtF,MAAM,IAAI,GAAQ,EAAE,CAAC;IACrB,MAAM,OAAO,GAAQ,EAAE,CAAC;IACxB,KAAK,MAAM,GAAG,IAAI,IAAI;QAAE,CAAC,SAAS,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9F,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAC3B,CAAC;AAQD;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,SAAiB,EACjB,KAA0B,EAC1B,QAA6B;IAE7B,OAAO;QACL,SAAS,EAAE,cAAc,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,MAAM;QAC1D,QAAQ,EAAE,cAAc,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,MAAM;KAC7D,CAAC;AACJ,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,cAAc,CAAC,CAAe;IAC5C,MAAM,IAAI,GAAG,CAAC,KAAa,EAAE,IAAY,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACzG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE,UAAU,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACpG,CAAC"}
package/dist/server.js CHANGED
@@ -70,7 +70,8 @@ import { HOME_SKILLS_BASE, missingHomeSkillLinks, rewriteSkillsBase } from "./sk
70
70
  import { instanceKey } from "./paths.js";
71
71
  import { peerFileFor, loadPeers, savePeers, peerFromToken, signPeerToken, newPeer, withSalts, redeemVerdict, redeemPeer, normPeerName, removePeer, ownedByPeer, peersOutFileFor, tierPeersOutSeed, agentInvitePrompt, peerScope, } from "./peers.js";
72
72
  import { loadCrons, saveCrons, upsertCron, removeCron, resolveCronId, nextRunFor, nextRunAfterFailure, isTransient, CRON_MAX_RETRIES, markCronPrompt, isCronPrompt, normalizeSchedule, parseDays, onceAt, stateAfterFire, scheduleLabel, cronTimeZone, defaultTimeZone, systemTimeZone, isValidTimeZone, } from "./crons.js";
73
- import { loadWebhooks, upsertWebhook, removeWebhook, recordWebhookRun, publicWebhook, newWebhookToken, hashWebhookToken, presentedToken, callVerdict, payloadText, webhookPrompt, isWebhookPrompt, } from "./webhooks.js";
73
+ import { loadWebhooks, saveWebhooks, upsertWebhook, removeWebhook, recordWebhookRun, publicWebhook, newWebhookToken, hashWebhookToken, presentedToken, callVerdict, payloadText, webhookPrompt, isWebhookPrompt, } from "./webhooks.js";
74
+ import { splitBySession, triggerCount, triggerSummary } from "./channel-triggers.js";
74
75
  import { isSlashCommand, promptMetaHeader, connectionOrigin } from "./promptmeta.js";
75
76
  import { markHumanPrompt } from "./prompt-kind.js";
76
77
  import { listCommands } from "./slash-commands.js";
@@ -405,7 +406,7 @@ async function startFirstAgent() {
405
406
  }
406
407
  function restartTelegram() {
407
408
  tgBridge.stop();
408
- tgBridge = startTelegram(boundPort, tgCookie(), DEPLOYMENT_MODE === "multi-tenant", { mediaDirFor: mediaDirForSession, readAgentFile: readSessionFile, bridgeSecret: TELEGRAM_BRIDGE_SECRET, rooms: roomHooks });
409
+ tgBridge = startTelegram(boundPort, tgCookie(), DEPLOYMENT_MODE === "multi-tenant", { mediaDirFor: mediaDirForSession, readAgentFile: readSessionFile, bridgeSecret: TELEGRAM_BRIDGE_SECRET, rooms: roomHooks, onChannelClosed: forgetChannelTriggers });
409
410
  }
410
411
  // ── Cron scheduler ───────────────────────────────────────────────────────────
411
412
  // Scheduled per-channel prompts (monitoring/reporting). The server drives the
@@ -2651,16 +2652,26 @@ app.get("/stars", async (_req, res) => res.json({ count: await starCount() }));
2651
2652
  * avoids a second poll — `/channels` is already re-read every 4 s.
2652
2653
  */
2653
2654
  app.get("/channels", (req, res) => {
2654
- const active = loadCrons().filter((c) => c.enabled);
2655
2655
  // ACL: a caller sees only its own groups' channels + public/commons. The
2656
2656
  // registry is the authority — the client is never trusted to filter. A null
2657
2657
  // viewer (deleted account / no session) resolves to public-only, never a 500.
2658
2658
  // Mono-tenant leaves every channel group-less, so visibleChannels is a no-op.
2659
2659
  const box = restrictedBoxOf(req);
2660
2660
  const visible = visibleChannels(loadChannels(), loadGroups(), viewerFor(currentAccount(req))).filter((ch) => !box || ownedByPeer(ch, box));
2661
+ // `closes` — what closing this agent would delete along with it, so the
2662
+ // confirmation can say so BEFORE an irreversible act. Derived like `crons`,
2663
+ // never stored; unlike `crons` it counts paused rows too, since they go as well.
2664
+ const allCrons = loadCrons();
2665
+ const allHooks = loadWebhooks();
2666
+ const active = allCrons.filter((c) => c.enabled);
2661
2667
  res.json(visible.map((ch) => {
2662
2668
  const mine = active.filter((c) => c.sessionId === ch.sessionId);
2663
- return mine.length ? { ...ch, crons: mine.map((c) => scheduleLabel(c.schedule, cronTimeZone(c))) } : ch;
2669
+ const closes = triggerCount(ch.sessionId, allCrons, allHooks);
2670
+ return {
2671
+ ...ch,
2672
+ ...(mine.length ? { crons: mine.map((c) => scheduleLabel(c.schedule, cronTimeZone(c))) } : {}),
2673
+ ...(closes.schedules || closes.webhooks ? { closes } : {}),
2674
+ };
2664
2675
  }));
2665
2676
  });
2666
2677
  // What each visible row shows before its agent is resumed: the last message's
@@ -8745,6 +8756,40 @@ function destroySession(s) {
8745
8756
  // so no work is ever silently lost.
8746
8757
  sessions.delete(s.id);
8747
8758
  }
8759
+ /**
8760
+ * Delete the schedules and webhooks that target a channel which is being
8761
+ * CLOSED, and say so in the log.
8762
+ *
8763
+ * Called only from a path that removes the channel for good — never from
8764
+ * `destroySession`, the idle reclaim or a restart: those end a PROCESS, and a
8765
+ * channel without a process is precisely what a schedule exists to wake (see
8766
+ * `src/channel-triggers.ts`). Idempotent, so a close that reaches it twice (the
8767
+ * Telegram bridge and the `stop` it sent) deletes once and logs once.
8768
+ *
8769
+ * Each store is rewritten only when it actually loses a row: a close is the
8770
+ * common case, a close with schedules the rare one, and an unconditional save
8771
+ * is one more chance to write a list read a moment too early.
8772
+ */
8773
+ function forgetChannelTriggers(sessionId) {
8774
+ const crons = splitBySession(loadCrons(), sessionId);
8775
+ if (crons.removed.length)
8776
+ saveCrons(crons.kept);
8777
+ const hooks = splitBySession(loadWebhooks(), sessionId);
8778
+ if (hooks.removed.length) {
8779
+ saveWebhooks(hooks.kept);
8780
+ // Calls already queued for a hook that no longer exists have nowhere to go.
8781
+ for (const w of hooks.removed)
8782
+ webhookQueues.delete(w.id);
8783
+ }
8784
+ const count = { schedules: crons.removed.length, webhooks: hooks.removed.length };
8785
+ // One line, with the ids: deleting someone's schedule in silence would be its
8786
+ // own bug, and the id is what lets a person find the fire lines that stop here.
8787
+ if (count.schedules || count.webhooks) {
8788
+ const ids = [...crons.removed, ...hooks.removed].map((r) => r.id.slice(0, 8)).join(", ");
8789
+ console.log(`channel ${sessionId.slice(0, 8)} closed: deleted ${triggerSummary(count)} (${ids})`);
8790
+ }
8791
+ return count;
8792
+ }
8748
8793
  /**
8749
8794
  * End a channel by id, whichever interface asked — works even when the session
8750
8795
  * isn't live (a dead/zombie channel after a crash): always drops it from the
@@ -8761,6 +8806,17 @@ async function endChannel(sessionId) {
8761
8806
  if (ch && isHomeChannel(ch))
8762
8807
  return false;
8763
8808
  removeChannel(sessionId); // registry first, so the sync poll sees it gone
8809
+ // After the home refusal (a channel that stays keeps everything) and before
8810
+ // the slow part: `pilot.stop()` can take seconds, and a schedule due in that
8811
+ // window would resume the very agent being closed.
8812
+ //
8813
+ // Only for a row we actually READ. With none, there is no telling a closed
8814
+ // agent from the home base — the Telegram bridge drops the row itself before
8815
+ // its `stop` lands here, for `/new` on the General as much as for `/end` — and
8816
+ // an irreversible delete must not ride on a guess. That caller decides for
8817
+ // itself (`onChannelClosed`).
8818
+ if (ch)
8819
+ forgetChannelTriggers(sessionId);
8764
8820
  if (ch?.telegram?.threadId)
8765
8821
  closeTelegramTopic(ch.telegram.chatId, ch.telegram.threadId);
8766
8822
  const s = sessions.get(sessionId);
@@ -11318,7 +11374,7 @@ server.listen(port, HOST, () => {
11318
11374
  // the internal auth cookie so it gets through the GUI password gate. The
11319
11375
  // handle + bound port let /telegram restart it hot when the config changes.
11320
11376
  boundPort = port;
11321
- tgBridge = startTelegram(port, tgCookie(), DEPLOYMENT_MODE === "multi-tenant", { mediaDirFor: mediaDirForSession, readAgentFile: readSessionFile, bridgeSecret: TELEGRAM_BRIDGE_SECRET, rooms: roomHooks });
11377
+ tgBridge = startTelegram(port, tgCookie(), DEPLOYMENT_MODE === "multi-tenant", { mediaDirFor: mediaDirForSession, readAgentFile: readSessionFile, bridgeSecret: TELEGRAM_BRIDGE_SECRET, rooms: roomHooks, onChannelClosed: forgetChannelTriggers });
11322
11378
  if (GUI_PASSWORD)
11323
11379
  console.log("gui: password protection ON");
11324
11380
  // Cron scheduler: prime nextRun then tick every 30s (unref'd so it never