shadok-ai 0.19.10 → 0.19.12
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 +20 -1
- package/dist/prompt-kind.js +3 -2
- package/dist/prompt-kind.js.map +1 -1
- package/dist/server.js +173 -1
- package/dist/server.js.map +1 -1
- package/dist/webhooks.d.ts +88 -0
- package/dist/webhooks.js +144 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +1 -1
- package/public/index.html +171 -16
package/README.md
CHANGED
|
@@ -194,6 +194,25 @@ Enter to skip; you can add it later from the web UI).
|
|
|
194
194
|
nothing most of the day. The guard runs with the target agent's profile
|
|
195
195
|
secrets, so an agent may put one only on itself (a person may guard any agent
|
|
196
196
|
they can drive).
|
|
197
|
+
- **Webhooks** — let an outside system (CI, a form, a monitoring tool, Zapier…)
|
|
198
|
+
wake an agent with an HTTP call, the event-driven twin of a schedule. Create
|
|
199
|
+
one in the agent's **⏰ Schedule** popin (name + the prompt to run); you get a
|
|
200
|
+
URL and a secret token, shown **once**:
|
|
201
|
+
|
|
202
|
+
```bash
|
|
203
|
+
curl -X POST https://<your-cockpit>/hooks/<id> \
|
|
204
|
+
-H 'Authorization: Bearer whk_…' \
|
|
205
|
+
-H 'Content-Type: application/json' -d '{"status":"failed"}'
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
The call answers `202` at once and the agent runs in the background with your
|
|
209
|
+
prompt, followed by the request body (≤16 kB, labelled as **untrusted** data —
|
|
210
|
+
it never speaks for you). Calls to the same webhook are queued and run one
|
|
211
|
+
after the other; a busy agent is retried for ~10 min. A sender that can only
|
|
212
|
+
take a URL may pass `?token=…` instead of the header. Pause, rotate the token
|
|
213
|
+
(↻) or delete it from the same popin. Only a person in the browser can create
|
|
214
|
+
or change a webhook — never an agent. An unknown id, a paused webhook and a
|
|
215
|
+
wrong token all answer the same `404`.
|
|
197
216
|
- **Per-agent stats** — the agent's ⋯ menu has a **📊 Stats** view: token usage
|
|
198
217
|
over the last hour / 24 h / 7 days / 30 days, split in a tooltip into input,
|
|
199
218
|
output, cache-write and cache-read, with a **notional cost** beside each window.
|
|
@@ -1353,7 +1372,7 @@ HTTP endpoints (same auth): `/usage`, `/live`, `/sessions`, `/recover`,
|
|
|
1353
1372
|
`/channels/glance` (GET — each visible row's last-message time and context %,
|
|
1354
1373
|
read from the transcript's tail so the list fills before the agents resume),
|
|
1355
1374
|
`/channel` (DELETE), `/groups`, `/groups/ssh` (GET — the SSH **public** key to
|
|
1356
|
-
register per group, filtered like `/groups`), `/crons`, `/timezone`, `/title` (GET/PUT — the
|
|
1375
|
+
register per group, filtered like `/groups`), `/crons`, `/webhooks` (GET; POST create, PATCH/DELETE `/webhooks/:id`, POST `/webhooks/:id/rotate` — writes browser person only, the token is returned only by create/rotate; the call itself, `POST /hooks/:id`, sits before the password gate and authenticates with the webhook's own token), `/timezone`, `/title` (GET/PUT — the
|
|
1357
1376
|
cockpit's name, per launch directory: click the header brand to rename it, so
|
|
1358
1377
|
several cockpits stay apart in the tab bar; an empty PUT reverts to the default),
|
|
1359
1378
|
`/theme` (GET/PUT — the cockpit's colour palette, per launch directory: an accent
|
package/dist/prompt-kind.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isCronPrompt } from "./crons.js";
|
|
2
|
+
import { isWebhookPrompt } from "./webhooks.js";
|
|
2
3
|
import { isAgentPrompt } from "./kinship.js";
|
|
3
4
|
import { stripPromptMeta, parsePromptMeta, hasPromptMeta, markPromptMeta } from "./promptmeta.js";
|
|
4
5
|
import { stripLedgerBlock, hasLedgerBlock } from "./ledger.js";
|
|
@@ -10,7 +11,7 @@ export const FORGED_ESCAPE = "\\";
|
|
|
10
11
|
* header, a ledger block, a cron fire, a parent notification? */
|
|
11
12
|
function looksServerWritten(line) {
|
|
12
13
|
const l = line.trimStart();
|
|
13
|
-
return hasPromptMeta(l) || hasLedgerBlock(l) || isCronPrompt(l) || isAgentPrompt(l);
|
|
14
|
+
return hasPromptMeta(l) || hasLedgerBlock(l) || isCronPrompt(l) || isWebhookPrompt(l) || isAgentPrompt(l);
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
17
|
* Escape every line of HUMAN text that is shaped like a server-written mark, so
|
|
@@ -97,7 +98,7 @@ export function classifyUserLine(e) {
|
|
|
97
98
|
// agent prompt no longer starts with its hiding mark and would leak into
|
|
98
99
|
// the display.
|
|
99
100
|
const bare = stripLedgerBlock(text);
|
|
100
|
-
if (isCronPrompt(bare) || isAgentPrompt(bare))
|
|
101
|
+
if (isCronPrompt(bare) || isWebhookPrompt(bare) || isAgentPrompt(bare))
|
|
101
102
|
return { kind: "hidden" };
|
|
102
103
|
// A human prompt may still open with a context header (⟦platform · time ·
|
|
103
104
|
// who⟧) the agent was given; strip it for display — leaving the message —
|
package/dist/prompt-kind.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-kind.js","sourceRoot":"","sources":["../src/prompt-kind.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAClG,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE/D;;qDAEqD;AACrD,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC;AAElC;kEACkE;AAClE,SAAS,kBAAkB,CAAC,IAAY;IACtC,MAAM,CAAC,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAC3B,OAAO,aAAa,CAAC,CAAC,CAAC,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,CAAC,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"prompt-kind.js","sourceRoot":"","sources":["../src/pr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ED
|
@@ -68,6 +68,7 @@ import { HOME_SKILLS_BASE, rewriteSkillsBase } from "./skill-paths.js";
|
|
|
68
68
|
import { instanceKey } from "./paths.js";
|
|
69
69
|
import { peerFileFor, loadPeers, savePeers, peerFromToken, signPeerToken, newPeer, withSalts, redeemVerdict, redeemPeer, normPeerName, removePeer, ownedByPeer, peersOutFileFor, tierPeersOutSeed, agentInvitePrompt, peerScope, } from "./peers.js";
|
|
70
70
|
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";
|
|
71
|
+
import { loadWebhooks, upsertWebhook, removeWebhook, recordWebhookRun, publicWebhook, newWebhookToken, hashWebhookToken, presentedToken, callVerdict, payloadText, webhookPrompt, isWebhookPrompt, } from "./webhooks.js";
|
|
71
72
|
import { isSlashCommand, promptMetaHeader, connectionOrigin } from "./promptmeta.js";
|
|
72
73
|
import { markHumanPrompt } from "./prompt-kind.js";
|
|
73
74
|
import { listCommands } from "./slash-commands.js";
|
|
@@ -624,6 +625,75 @@ function driveChannel(sessionId, text, target) {
|
|
|
624
625
|
ws.on("close", () => finish({ ok: false, reason: "ws-error", detail: "closed before the turn ended" }));
|
|
625
626
|
});
|
|
626
627
|
}
|
|
628
|
+
// ── Webhook delivery ─────────────────────────────────────────────────────
|
|
629
|
+
// One queue per webhook, drained one call at a time: `driveChannel` holds until
|
|
630
|
+
// the turn ends, so two calls of the same hook land as two turns, in order,
|
|
631
|
+
// instead of the second being refused `busy`. Capped, so a sender looping on
|
|
632
|
+
// the URL cannot pile up an unbounded backlog (it gets a 429 instead).
|
|
633
|
+
const WEBHOOK_QUEUE_MAX = 10;
|
|
634
|
+
// The agent may be mid-turn (a human, a cron): a busy refusal is retried for a
|
|
635
|
+
// while rather than lost. Other failures are recorded, not retried — a pace
|
|
636
|
+
// block can last hours, and a gone/exited channel won't heal in a minute.
|
|
637
|
+
const WEBHOOK_BUSY_RETRY_MS = 30_000;
|
|
638
|
+
const WEBHOOK_BUSY_RETRIES = 20; // ≈ 10 min
|
|
639
|
+
const webhookQueues = new Map();
|
|
640
|
+
const webhookDraining = new Set();
|
|
641
|
+
/** Queue one call's prompt for `hookId`. False when the queue is full. */
|
|
642
|
+
function enqueueWebhook(hookId, text) {
|
|
643
|
+
const q = webhookQueues.get(hookId) ?? [];
|
|
644
|
+
if (q.length >= WEBHOOK_QUEUE_MAX)
|
|
645
|
+
return false;
|
|
646
|
+
q.push(text);
|
|
647
|
+
webhookQueues.set(hookId, q);
|
|
648
|
+
if (!webhookDraining.has(hookId))
|
|
649
|
+
void drainWebhook(hookId);
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
async function drainWebhook(hookId) {
|
|
653
|
+
webhookDraining.add(hookId);
|
|
654
|
+
const tag = `webhook: ${hookId.slice(0, 8)}`;
|
|
655
|
+
try {
|
|
656
|
+
for (;;) {
|
|
657
|
+
const q = webhookQueues.get(hookId);
|
|
658
|
+
const text = q?.shift();
|
|
659
|
+
if (text === undefined)
|
|
660
|
+
break;
|
|
661
|
+
// Re-read at delivery time: the hook may have been deleted, disabled or
|
|
662
|
+
// repointed while the call waited in the queue.
|
|
663
|
+
const hook = loadWebhooks().find((w) => w.id === hookId);
|
|
664
|
+
if (!hook || !hook.enabled) {
|
|
665
|
+
console.log(`${tag} dropped a queued call (webhook gone or disabled)`);
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
const target = resolveSessionTarget(loadChannels(), hook.sessionId, process.cwd());
|
|
669
|
+
let outcome = "error";
|
|
670
|
+
for (let attempt = 0;; attempt++) {
|
|
671
|
+
const res = await driveChannel(hook.sessionId, text, target);
|
|
672
|
+
if (res.ok) {
|
|
673
|
+
outcome = "ok";
|
|
674
|
+
break;
|
|
675
|
+
}
|
|
676
|
+
outcome = res.reason;
|
|
677
|
+
if (res.reason !== "busy" || attempt >= WEBHOOK_BUSY_RETRIES) {
|
|
678
|
+
console.log(`${tag} delivery failed: ${res.reason}${res.detail ? ` (${res.detail})` : ""}`);
|
|
679
|
+
break;
|
|
680
|
+
}
|
|
681
|
+
await new Promise((r) => setTimeout(r, WEBHOOK_BUSY_RETRY_MS).unref?.());
|
|
682
|
+
}
|
|
683
|
+
if (outcome === "ok")
|
|
684
|
+
console.log(`${tag} delivered -> ok`);
|
|
685
|
+
recordWebhookRun(hookId, outcome, Date.now());
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
catch (e) {
|
|
689
|
+
console.log(`${tag} crashed: ${e?.message ?? e}`);
|
|
690
|
+
}
|
|
691
|
+
finally {
|
|
692
|
+
webhookDraining.delete(hookId);
|
|
693
|
+
if (!webhookQueues.get(hookId)?.length)
|
|
694
|
+
webhookQueues.delete(hookId);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
627
697
|
/**
|
|
628
698
|
* Notifications waiting for a parent that is mid-turn, keyed by the PARENT's
|
|
629
699
|
* session id. A prompt sent during a turn is refused (`code:"busy"`), so
|
|
@@ -1626,6 +1696,29 @@ app.post("/peers/enrol", (req, res) => {
|
|
|
1626
1696
|
console.log(`peers: ${v.name} enrolled (ticket consumed)`);
|
|
1627
1697
|
res.json({ ok: true, name: v.name, token: signPeerToken(v.name, signingSecret(), row.salt) });
|
|
1628
1698
|
});
|
|
1699
|
+
/**
|
|
1700
|
+
* Call a webhook: `POST /hooks/<id>` with the token as `Authorization: Bearer`
|
|
1701
|
+
* (or `X-Shadok-Webhook-Token`, or `?token=` for senders that only take a URL).
|
|
1702
|
+
*
|
|
1703
|
+
* BEFORE the password gate on purpose: the caller is a machine with no cookie,
|
|
1704
|
+
* and the per-hook token IS its credential (src/webhooks.ts). Unknown id,
|
|
1705
|
+
* disabled hook and wrong token all answer the same 404. The agent is driven
|
|
1706
|
+
* in the background (202): a turn can take minutes, far past a sender's timeout.
|
|
1707
|
+
* JSON bodies are already parsed by the global `express.json`; anything else
|
|
1708
|
+
* arrives raw here.
|
|
1709
|
+
*/
|
|
1710
|
+
app.post("/hooks/:id", express.raw({ type: () => true, limit: "256kb" }), (req, res) => {
|
|
1711
|
+
const token = presentedToken(req.headers, req.query);
|
|
1712
|
+
const v = callVerdict(loadWebhooks(), String(req.params.id), token);
|
|
1713
|
+
if (!v.ok)
|
|
1714
|
+
return res.status(404).json({ error: "not found" });
|
|
1715
|
+
const text = webhookPrompt(v.hook, payloadText(req.body));
|
|
1716
|
+
if (!enqueueWebhook(v.hook.id, text)) {
|
|
1717
|
+
res.setHeader("Retry-After", "60");
|
|
1718
|
+
return res.status(429).json({ error: "too many calls queued for this webhook" });
|
|
1719
|
+
}
|
|
1720
|
+
res.status(202).json({ ok: true, queued: webhookQueues.get(v.hook.id)?.length ?? 0 });
|
|
1721
|
+
});
|
|
1629
1722
|
// Who am I? The client labels itself with this, and a tab whose session expired
|
|
1630
1723
|
// finds out here rather than by a silent failure.
|
|
1631
1724
|
app.get("/me", (req, res) => {
|
|
@@ -2982,6 +3075,84 @@ app.post("/crons", (req, res) => {
|
|
|
2982
3075
|
upsertCron(cron);
|
|
2983
3076
|
res.json({ ...cron, timezone: cronTimeZone(cron) });
|
|
2984
3077
|
});
|
|
3078
|
+
// ── Webhooks (management) ─────────────────────────────────────────────────
|
|
3079
|
+
// Listing is scoped like /crons. Every WRITE is a person's act in a browser:
|
|
3080
|
+
// a webhook is a door from outside into an agent, so an agent must not be able
|
|
3081
|
+
// to open one (on itself or a sibling) — src/webhooks.ts.
|
|
3082
|
+
app.get("/webhooks", (req, res) => res.json(loadWebhooks().filter((w) => mayActFor(req, w.sessionId)).map(publicWebhook)));
|
|
3083
|
+
// Create: { sessionId, name, prompt }. The token is in the answer ONCE.
|
|
3084
|
+
app.post("/webhooks", (req, res) => {
|
|
3085
|
+
if (!requestFromBrowser(req))
|
|
3086
|
+
return res.status(403).json({ error: "same-origin browser only" });
|
|
3087
|
+
const b = req.body ?? {};
|
|
3088
|
+
const sessionId = String(b.sessionId ?? "").trim();
|
|
3089
|
+
const prompt = String(b.prompt ?? "").trim();
|
|
3090
|
+
const name = String(b.name ?? "").trim().slice(0, 80) || "webhook";
|
|
3091
|
+
if (!sessionId || !prompt)
|
|
3092
|
+
return res.status(400).json({ error: "sessionId and prompt are required" });
|
|
3093
|
+
if (!mayActFor(req, sessionId))
|
|
3094
|
+
return res.status(403).json({ error: "not your agent" });
|
|
3095
|
+
const token = newWebhookToken();
|
|
3096
|
+
const hook = {
|
|
3097
|
+
id: randomUUID(),
|
|
3098
|
+
sessionId,
|
|
3099
|
+
name,
|
|
3100
|
+
prompt,
|
|
3101
|
+
tokenHash: hashWebhookToken(token),
|
|
3102
|
+
enabled: true,
|
|
3103
|
+
createdAt: Date.now(),
|
|
3104
|
+
};
|
|
3105
|
+
upsertWebhook(hook);
|
|
3106
|
+
res.json({ ...publicWebhook(hook), token });
|
|
3107
|
+
});
|
|
3108
|
+
/** The hook this request may write, or an error already sent. */
|
|
3109
|
+
function writableWebhook(req, res) {
|
|
3110
|
+
if (!requestFromBrowser(req)) {
|
|
3111
|
+
res.status(403).json({ error: "same-origin browser only" });
|
|
3112
|
+
return null;
|
|
3113
|
+
}
|
|
3114
|
+
const hook = loadWebhooks().find((w) => w.id === String(req.params.id));
|
|
3115
|
+
// Another group's hook answers like a missing one: no existence leak.
|
|
3116
|
+
if (!hook || !mayActFor(req, hook.sessionId)) {
|
|
3117
|
+
res.status(404).json({ error: "no such webhook" });
|
|
3118
|
+
return null;
|
|
3119
|
+
}
|
|
3120
|
+
return hook;
|
|
3121
|
+
}
|
|
3122
|
+
// Edit: { name?, prompt?, enabled? }. Never the target agent: repointing a
|
|
3123
|
+
// token someone already holds at another agent is a new webhook, not an edit.
|
|
3124
|
+
app.patch("/webhooks/:id", (req, res) => {
|
|
3125
|
+
const hook = writableWebhook(req, res);
|
|
3126
|
+
if (!hook)
|
|
3127
|
+
return;
|
|
3128
|
+
const b = req.body ?? {};
|
|
3129
|
+
if (typeof b.name === "string" && b.name.trim())
|
|
3130
|
+
hook.name = b.name.trim().slice(0, 80);
|
|
3131
|
+
if (typeof b.prompt === "string" && b.prompt.trim())
|
|
3132
|
+
hook.prompt = b.prompt.trim();
|
|
3133
|
+
if (typeof b.enabled === "boolean")
|
|
3134
|
+
hook.enabled = b.enabled;
|
|
3135
|
+
upsertWebhook(hook);
|
|
3136
|
+
res.json(publicWebhook(hook));
|
|
3137
|
+
});
|
|
3138
|
+
// A new token, the old one dead at once. Answered ONCE, like at creation.
|
|
3139
|
+
app.post("/webhooks/:id/rotate", (req, res) => {
|
|
3140
|
+
const hook = writableWebhook(req, res);
|
|
3141
|
+
if (!hook)
|
|
3142
|
+
return;
|
|
3143
|
+
const token = newWebhookToken();
|
|
3144
|
+
hook.tokenHash = hashWebhookToken(token);
|
|
3145
|
+
upsertWebhook(hook);
|
|
3146
|
+
res.json({ ...publicWebhook(hook), token });
|
|
3147
|
+
});
|
|
3148
|
+
app.delete("/webhooks/:id", (req, res) => {
|
|
3149
|
+
const hook = writableWebhook(req, res);
|
|
3150
|
+
if (!hook)
|
|
3151
|
+
return;
|
|
3152
|
+
removeWebhook(hook.id);
|
|
3153
|
+
webhookQueues.delete(hook.id);
|
|
3154
|
+
res.json({ ok: true, id: hook.id });
|
|
3155
|
+
});
|
|
2985
3156
|
// Default zone for `daily` crons. GET also returns the machine's zone, so the
|
|
2986
3157
|
// caller can show what actually applies when nothing is set.
|
|
2987
3158
|
app.get("/timezone", (_req, res) => res.json({ timezone: defaultTimeZone() ?? null, system: systemTimeZone() }));
|
|
@@ -9956,7 +10127,8 @@ wss.on("connection", (ws, req) => {
|
|
|
9956
10127
|
// text would glue onto the previous turn. Flag it for the tail.
|
|
9957
10128
|
session.gapBeforeNextText = true;
|
|
9958
10129
|
}
|
|
9959
|
-
session.turnOrigin =
|
|
10130
|
+
session.turnOrigin =
|
|
10131
|
+
origin === "cron" ? (isCronPrompt(text) ? "cron" : isWebhookPrompt(text) ? "webhook" : "agent") : origin;
|
|
9960
10132
|
session.busy = true;
|
|
9961
10133
|
session.turnStartedAt = Date.now();
|
|
9962
10134
|
broadcast(session, workingMessage(session));
|