shadok-ai 0.17.58 → 0.17.60

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
@@ -1235,6 +1235,8 @@ client, or immediately on an explicit `stop` (which ends it for everyone).
1235
1235
 
1236
1236
  HTTP endpoints (same auth): `/usage`, `/live`, `/sessions`, `/recover`,
1237
1237
  `/diff`, `/channels` (its GET adds a **derived** `crons` field — never stored),
1238
+ `/channels/glance` (GET — each visible row's last-message time and context %,
1239
+ read from the transcript's tail so the list fills before the agents resume),
1238
1240
  `/channel` (DELETE), `/groups`, `/groups/ssh` (GET — the SSH **public** key to
1239
1241
  register per group, filtered like `/groups`), `/crons`, `/timezone`, `/title` (GET/PUT — the
1240
1242
  cockpit's name, per launch directory: click the header brand to rename it, so
@@ -0,0 +1,17 @@
1
+ import { type TokenUsage } from "./tail.js";
2
+ /** Enough for the last exchange of any realistic session (one assistant line
3
+ * with a big tool result is the worst case). Past this we just find nothing. */
4
+ export declare const TAIL_BYTES: number;
5
+ export interface Glance {
6
+ /** The last message a human sees in the chat (prompt or answer text), ms. */
7
+ lastAt: number | null;
8
+ /** The last assistant message's usage — the context fill's input. */
9
+ usage: TokenUsage | null;
10
+ }
11
+ /**
12
+ * Pure: scan a transcript's tail backwards. The first line may be cut in half
13
+ * by the byte window — it fails to parse and is skipped like any bad line.
14
+ */
15
+ export declare function glanceFromTail(text: string): Glance;
16
+ /** Reads the last `TAIL_BYTES` of `file` and glances at them. Missing file → empty. */
17
+ export declare function glanceFile(file: string): Promise<Glance>;
package/dist/glance.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A channel row's at-a-glance data — when it last spoke and how full its
3
+ * context is — read from the END of its transcript, without resuming the agent.
4
+ *
5
+ * Why it exists: on a page load every row stayed blank (no "3m ago", no %)
6
+ * until its own WebSocket resume finished, and a resume of a reclaimed agent
7
+ * spawns `claude` and replays the WHOLE transcript. With a dozen agents the
8
+ * column filled in one late burst. These two facts sit in the last few lines
9
+ * of the `.jsonl`, so one cheap read per channel paints every row at once and
10
+ * the resume replaces them with the authoritative values when it lands.
11
+ *
12
+ * Read-only and bounded: only the last `TAIL_BYTES` are read, async, so a huge
13
+ * transcript costs the same as a small one and never blocks the event loop.
14
+ */
15
+ import fs from "node:fs/promises";
16
+ import { parseTimestamp, parseUsage } from "./tail.js";
17
+ import { userPromptText } from "./prompt-kind.js";
18
+ /** Enough for the last exchange of any realistic session (one assistant line
19
+ * with a big tool result is the worst case). Past this we just find nothing. */
20
+ export const TAIL_BYTES = 256 * 1024;
21
+ function hasText(e) {
22
+ const c = e?.message?.content;
23
+ if (typeof c === "string")
24
+ return !!c.trim();
25
+ return Array.isArray(c) && c.some((b) => b?.type === "text" && typeof b.text === "string" && b.text.trim());
26
+ }
27
+ /**
28
+ * Pure: scan a transcript's tail backwards. The first line may be cut in half
29
+ * by the byte window — it fails to parse and is skipped like any bad line.
30
+ */
31
+ export function glanceFromTail(text) {
32
+ let lastAt = null;
33
+ let usage = null;
34
+ const lines = text.split("\n");
35
+ for (let i = lines.length - 1; i >= 0 && (lastAt === null || usage === null); i--) {
36
+ const line = lines[i];
37
+ if (!line.trim())
38
+ continue;
39
+ let e;
40
+ try {
41
+ e = JSON.parse(line);
42
+ }
43
+ catch {
44
+ continue;
45
+ }
46
+ if (e.type === "assistant") {
47
+ if (usage === null)
48
+ usage = parseUsage(e.message);
49
+ if (lastAt === null && hasText(e))
50
+ lastAt = parseTimestamp(e.timestamp);
51
+ }
52
+ else if (lastAt === null && userPromptText(e) !== null) {
53
+ lastAt = parseTimestamp(e.timestamp);
54
+ }
55
+ }
56
+ return { lastAt, usage };
57
+ }
58
+ /** Reads the last `TAIL_BYTES` of `file` and glances at them. Missing file → empty. */
59
+ export async function glanceFile(file) {
60
+ let fh;
61
+ try {
62
+ fh = await fs.open(file, "r");
63
+ const { size } = await fh.stat();
64
+ const len = Math.min(size, TAIL_BYTES);
65
+ const buf = Buffer.alloc(len);
66
+ await fh.read(buf, 0, len, size - len);
67
+ return glanceFromTail(buf.toString("utf8"));
68
+ }
69
+ catch {
70
+ return { lastAt: null, usage: null };
71
+ }
72
+ finally {
73
+ await fh?.close().catch(() => { });
74
+ }
75
+ }
76
+ //# sourceMappingURL=glance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"glance.js","sourceRoot":"","sources":["../src/glance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,UAAU,EAAmB,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD;iFACiF;AACjF,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,GAAG,IAAI,CAAC;AASrC,SAAS,OAAO,CAAC,CAAM;IACrB,MAAM,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC;IAC9B,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;AACnH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,IAAI,MAAM,GAAkB,IAAI,CAAC;IACjC,IAAI,KAAK,GAAsB,IAAI,CAAC;IACpC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,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AC,CAAC;QAC9B,MAAM,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC;QACvC,OAAO,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC9C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACvC,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC"}
package/dist/server.js CHANGED
@@ -92,6 +92,7 @@ import { acquireInstanceLock, releaseInstanceLock } from "./lock.js";
92
92
  import { bindRefusal, originAllowed, parseOrigins, resolveHost, browserOrigin, isLocalCaller, hostHeaderAllowed, hostRefusal, parseAllowedHosts, clientAddress, requestIsHttps, } from "./net.js";
93
93
  import { AttemptLimiter, LOGIN_LIMITS, loginKeys } from "./login-limit.js";
94
94
  import { pctFromUsage, windowForModel } from "./context.js";
95
+ import { glanceFile } from "./glance.js";
95
96
  import { BACKEND_PRESETS, backendEnv, backendFor, backendSaveVerdict, instanceEnv, joinUrl, looksLikeMessage, parseModelList, testFailure, testRequestBody, } from "./backend.js";
96
97
  import { availableModels, MODEL_FAMILIES } from "./claude-models.js";
97
98
  import { startHeartbeat } from "./heartbeat.js";
@@ -2454,6 +2455,25 @@ app.get("/channels", (req, res) => {
2454
2455
  return mine.length ? { ...ch, crons: mine.map((c) => scheduleLabel(c.schedule, cronTimeZone(c))) } : ch;
2455
2456
  }));
2456
2457
  });
2458
+ // What each visible row shows before its agent is resumed: the last message's
2459
+ // time and the context fill, from the transcript's TAIL (src/glance.ts). The
2460
+ // boot paints every row from this one call instead of waiting for N resumes
2461
+ // (each a spawn + full history replay); the WS `history`/`context` that follow
2462
+ // overwrite it with the authoritative values. Same ACL as GET /channels.
2463
+ app.get("/channels/glance", async (req, res) => {
2464
+ const box = restrictedBoxOf(req);
2465
+ const visible = visibleChannels(loadChannels(), loadGroups(), viewerFor(currentAccount(req))).filter((ch) => !box || ownedByPeer(ch, box));
2466
+ const rows = await Promise.all(visible.map(async (ch) => {
2467
+ const live = sessions.get(ch.sessionId);
2468
+ const home = live ? live.transcriptHome : channelStateHome(ch);
2469
+ const g = await glanceFile(sessionFilePath(ch.cwd, ch.sessionId, home));
2470
+ const pct = live && !live.pilot.hasExited && live.contextPct !== null
2471
+ ? live.contextPct
2472
+ : pctFromUsage(g.usage ?? undefined, assumedContextWindow(ch.profile, ch.model, ch.group ?? null));
2473
+ return { sessionId: ch.sessionId, lastAt: g.lastAt, contextPct: pct };
2474
+ }));
2475
+ res.json(rows);
2476
+ });
2457
2477
  // ── Crons (scheduled channel prompts) ───────────────────────────────────────
2458
2478
  // Scoped like every other per-session read (invariant 60): a cron carries its
2459
2479
  // prompt and its guard command, i.e. another group's monitoring logic.
@@ -7076,6 +7096,15 @@ function ensureClaudeOnce(revalidate = true) {
7076
7096
  claudeReady = null; });
7077
7097
  return p;
7078
7098
  }
7099
+ /** The context window an agent is metered against. A custom backend's window is
7100
+ * whatever its server was started with, which no model name can tell us:
7101
+ * SHADOK_CONTEXT_WINDOW says it, and without it the usual assumption stands
7102
+ * (and `effectiveWindow` still promotes on proof). Shared by the spawn and
7103
+ * `GET /channels/glance`, so a row's pre-resume % matches the live one. */
7104
+ function assumedContextWindow(profile, model, group) {
7105
+ const backend = sessionBackend(profile, group);
7106
+ return (backend.kind === "custom" ? backend.contextWindow : null) ?? windowForModel(sessionModelSetting(profile, model));
7107
+ }
7079
7108
  async function createSession(id, cwd, args, worktree = null, profile = null, model = null, effort = null, by = SYSTEM_SPAWN,
7080
7109
  /** Multi-tenant isolation: the OS user to drop the agent to (null = commons /
7081
7110
  * mono-tenant, i.e. the server's own user). Resolved by the caller, which is
@@ -7092,11 +7121,7 @@ group = null) {
7092
7121
  // Resumed sessions start with what the transcript already consumed.
7093
7122
  const seededUsage = scanUsage(sessionFilePath(cwd, id, transcriptHome));
7094
7123
  const backend = sessionBackend(profile, group);
7095
- // A custom backend's window is whatever its server was started with, which
7096
- // no model name can tell us: SHADOK_CONTEXT_WINDOW says it, and without it
7097
- // the usual assumption stands (and `effectiveWindow` still promotes on proof).
7098
- const contextWindow = (backend.kind === "custom" ? backend.contextWindow : null) ??
7099
- windowForModel(sessionModelSetting(profile, model));
7124
+ const contextWindow = assumedContextWindow(profile, model, group);
7100
7125
  const s = {
7101
7126
  id,
7102
7127
  cwd,