@staff0rd/assist 0.692.0 → 0.693.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.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { Command } from "commander";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@staff0rd/assist",
9
- version: "0.692.0",
9
+ version: "0.693.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -11976,6 +11976,22 @@ async function listUsagePeaks(db, options2) {
11976
11976
  return query;
11977
11977
  }
11978
11978
 
11979
+ // src/shared/usageWindowKey.ts
11980
+ var RATE_LIMIT_WINDOWS = ["five_hour", "seven_day"];
11981
+ var HARNESS_KINDS = ["claude", "codex", "pi"];
11982
+ function usageWindowKey(harness, window) {
11983
+ const kind = resolveHarness(harness);
11984
+ return kind === "claude" ? window : `${kind}:${window}`;
11985
+ }
11986
+ function parseUsageWindowKey(key) {
11987
+ const [prefix2, suffix] = key.includes(":") ? key.split(":", 2) : ["claude", key];
11988
+ const harness = HARNESS_KINDS.find((h) => h === prefix2);
11989
+ const window = RATE_LIMIT_WINDOWS.find((w) => w === suffix);
11990
+ if (!harness || !window) return void 0;
11991
+ if (harness === "claude" && key.includes(":")) return void 0;
11992
+ return { harness, window };
11993
+ }
11994
+
11979
11995
  // src/commands/sessions/web/respondPagedRows.ts
11980
11996
  var DEFAULT_PAGE_SIZE = 30;
11981
11997
  async function respondPagedRows(req, res, load3) {
@@ -11987,7 +12003,9 @@ async function respondPagedRows(req, res, load3) {
11987
12003
 
11988
12004
  // src/commands/sessions/web/listUsageHistory.ts
11989
12005
  function parseWindow(value) {
11990
- return value === "five_hour" || value === "seven_day" ? value : void 0;
12006
+ if (!value) return void 0;
12007
+ const parsed = parseUsageWindowKey(value);
12008
+ return parsed ? usageWindowKey(parsed.harness, parsed.window) : void 0;
11991
12009
  }
11992
12010
  function listUsageHistory(req, res) {
11993
12011
  return respondPagedRows(req, res, async (range, params) => {
@@ -18967,21 +18985,46 @@ function registerCodeComment(parent) {
18967
18985
 
18968
18986
  // src/commands/codexHook/parseCodexHookInput.ts
18969
18987
  var SUPPORTED_TOOLS = /* @__PURE__ */ new Set(["Bash", "PowerShell"]);
18988
+ function optionalString(value) {
18989
+ return typeof value === "string" ? value : void 0;
18990
+ }
18970
18991
  function parseCodexHookInput(raw) {
18971
18992
  try {
18972
18993
  const data = JSON.parse(raw);
18973
- const event = data.hook_event_name ?? "PreToolUse";
18974
- const cwd = typeof data.cwd === "string" ? data.cwd : void 0;
18994
+ const base = {
18995
+ event: data.hook_event_name ?? "PreToolUse",
18996
+ cwd: optionalString(data.cwd)
18997
+ };
18998
+ const transcriptPath2 = optionalString(data.transcript_path);
18999
+ if (transcriptPath2) base.transcriptPath = transcriptPath2;
18975
19000
  const command = data.tool_input?.command;
18976
- if (typeof command !== "string" || !command.trim()) return { event, cwd };
18977
- if (!data.tool_name || !SUPPORTED_TOOLS.has(data.tool_name))
18978
- return { event, cwd };
18979
- return { event, cwd, toolName: data.tool_name, command: command.trim() };
19001
+ if (typeof command !== "string" || !command.trim()) return base;
19002
+ if (!data.tool_name || !SUPPORTED_TOOLS.has(data.tool_name)) return base;
19003
+ return { ...base, toolName: data.tool_name, command: command.trim() };
18980
19004
  } catch {
18981
19005
  return void 0;
18982
19006
  }
18983
19007
  }
18984
19008
 
19009
+ // src/commands/codexHook/relayCodexUsage.ts
19010
+ var USAGE_EVENTS = /* @__PURE__ */ new Set(["PostToolUse", "Stop"]);
19011
+ async function relayCodexUsage(event, transcriptPath2) {
19012
+ const sessionId = process.env.ASSIST_SESSION_ID;
19013
+ if (!sessionId || !transcriptPath2 || !USAGE_EVENTS.has(event)) return;
19014
+ try {
19015
+ await sendToDaemonAwaitAck({
19016
+ type: "codex-usage",
19017
+ sessionId,
19018
+ transcriptPath: transcriptPath2,
19019
+ ack: true
19020
+ });
19021
+ } catch (error) {
19022
+ appendDaemonLog(
19023
+ `codex-usage relay failed: id=${sessionId}: ${error instanceof Error ? error.message : String(error)}`
19024
+ );
19025
+ }
19026
+ }
19027
+
18985
19028
  // src/commands/codexHook/codexStatusFor.ts
18986
19029
  function codexStatusFor(event, autoDecided) {
18987
19030
  if (event === "UserPromptSubmit")
@@ -19041,6 +19084,7 @@ async function codexHook() {
19041
19084
  const output = outputFor(input, decision);
19042
19085
  if (output) console.log(JSON.stringify(output));
19043
19086
  await reportCodexStatus(input.event, decision !== void 0);
19087
+ await relayCodexUsage(input.event, input.transcriptPath);
19044
19088
  }
19045
19089
 
19046
19090
  // src/commands/registerCodexHook.ts
@@ -29926,9 +29970,15 @@ function screenshot(processName) {
29926
29970
  import chalk205 from "chalk";
29927
29971
 
29928
29972
  // src/shared/contextLevel.ts
29929
- function contextLevel(pct) {
29930
- if (pct >= 30) return "red";
29931
- if (pct >= 20) return "yellow";
29973
+ var THRESHOLDS = {
29974
+ claude: { red: 30, yellow: 20 },
29975
+ codex: { red: 75, yellow: 50 },
29976
+ pi: { red: 30, yellow: 20 }
29977
+ };
29978
+ function contextLevel(pct, harness) {
29979
+ const { red, yellow } = THRESHOLDS[resolveHarness(harness)];
29980
+ if (pct >= red) return "red";
29981
+ if (pct >= yellow) return "yellow";
29932
29982
  return "dim";
29933
29983
  }
29934
29984
 
@@ -38964,33 +39014,40 @@ function broadcastSessions(sessions, clients, windowsSessions = [], active) {
38964
39014
  }
38965
39015
 
38966
39016
  // src/shared/activeWindows.ts
38967
- var WINDOWS = ["five_hour", "seven_day"];
38968
- function activeWindows(rateLimits) {
39017
+ function activeWindows(rateLimits, harness) {
38969
39018
  if (!rateLimits) return [];
38970
39019
  const out = [];
38971
- for (const window of WINDOWS) {
39020
+ for (const window of RATE_LIMIT_WINDOWS) {
38972
39021
  const resetsAt = rateLimits[window]?.resets_at;
38973
- if (typeof resetsAt === "number") out.push({ window, resetsAt });
39022
+ if (typeof resetsAt === "number")
39023
+ out.push({ window: usageWindowKey(harness, window), resetsAt });
38974
39024
  }
38975
39025
  return out;
38976
39026
  }
38977
39027
 
38978
39028
  // src/shared/db/recordUsagePeak.ts
38979
- var WINDOWS2 = ["five_hour", "seven_day"];
38980
- async function recordUsagePeak(db, rateLimits, now = Math.floor(Date.now() / 1e3)) {
38981
- for (const window of WINDOWS2) {
39029
+ async function recordUsagePeak(db, rateLimits, now = Math.floor(Date.now() / 1e3), harness) {
39030
+ for (const window of RATE_LIMIT_WINDOWS) {
38982
39031
  const w = rateLimits[window];
38983
39032
  if (!w || typeof w.resets_at !== "number" || typeof w.used_percentage !== "number")
38984
39033
  continue;
38985
- await recordWindowPeak(db, window, w.resets_at, w.used_percentage, now);
39034
+ await recordWindowPeak(
39035
+ db,
39036
+ usageWindowKey(harness, window),
39037
+ w.resets_at,
39038
+ w.used_percentage,
39039
+ now
39040
+ );
38986
39041
  }
38987
39042
  }
38988
39043
 
38989
39044
  // src/commands/sessions/daemon/persistUsagePeak.ts
38990
- async function persistUsagePeak(rateLimits) {
39045
+ async function persistUsagePeak(rateLimits, harness) {
38991
39046
  try {
38992
39047
  if (!process.env.ASSIST_DATABASE_URL && !loadConfig().database.url) return;
38993
- await recordUsagePeak(await getDb(), rateLimits);
39048
+ const db = await getDb();
39049
+ if (harness) await recordUsagePeak(db, rateLimits, void 0, harness);
39050
+ else await recordUsagePeak(db, rateLimits);
38994
39051
  } catch (error) {
38995
39052
  daemonLog(`usage-peak persist failed: ${String(error)}`);
38996
39053
  }
@@ -39004,6 +39061,7 @@ var ClientHub = class extends Set {
39004
39061
  this.persistPeak = persistPeak;
39005
39062
  }
39006
39063
  latestLimits;
39064
+ harnessLimits = /* @__PURE__ */ new Map();
39007
39065
  // why: log delivery is opt-in so browser tabs aren't spammed; only connections that ask via subscribe-logs receive daemonLog lines.
39008
39066
  logSubscribers = /* @__PURE__ */ new Set();
39009
39067
  updateLimits(rateLimits) {
@@ -39011,13 +39069,26 @@ var ClientHub = class extends Set {
39011
39069
  broadcast(this, { type: "limits", rateLimits });
39012
39070
  this.persistPeak?.(rateLimits);
39013
39071
  }
39014
- currentWindows() {
39015
- return activeWindows(this.latestLimits);
39072
+ updateHarnessLimits(harness, rateLimits) {
39073
+ if (harness === "claude") {
39074
+ this.updateLimits(rateLimits);
39075
+ return;
39076
+ }
39077
+ this.harnessLimits.set(harness, rateLimits);
39078
+ broadcast(this, { type: "limits", harness, rateLimits });
39079
+ this.persistPeak?.(rateLimits, harness);
39080
+ }
39081
+ currentWindows(harness) {
39082
+ if (!harness || harness === "claude")
39083
+ return activeWindows(this.latestLimits);
39084
+ return activeWindows(this.harnessLimits.get(harness), harness);
39016
39085
  }
39017
39086
  greet(client) {
39018
39087
  if (this.latestLimits) {
39019
39088
  sendTo(client, { type: "limits", rateLimits: this.latestLimits });
39020
39089
  }
39090
+ for (const [harness, rateLimits] of this.harnessLimits)
39091
+ sendTo(client, { type: "limits", harness, rateLimits });
39021
39092
  }
39022
39093
  subscribeLogs(client, replay = true) {
39023
39094
  if (replay) {
@@ -40970,6 +41041,35 @@ function makeSessionSpawner(sessions, clients, counter, onStatusChange, notify2)
40970
41041
  };
40971
41042
  }
40972
41043
 
41044
+ // src/commands/sessions/shared/transcriptUsage.ts
41045
+ import * as fs54 from "fs";
41046
+ function transcriptUsage(lines2) {
41047
+ const byId = /* @__PURE__ */ new Map();
41048
+ for (const line of lines2) {
41049
+ if (!line.trim()) continue;
41050
+ let entry;
41051
+ try {
41052
+ entry = JSON.parse(line);
41053
+ } catch {
41054
+ continue;
41055
+ }
41056
+ if (entry.type !== "assistant") continue;
41057
+ const id = entry.message?.id;
41058
+ const usage = entry.message?.usage;
41059
+ if (!id || !usage) continue;
41060
+ byId.set(id, {
41061
+ messageId: id,
41062
+ inputTokens: usage.input_tokens ?? 0,
41063
+ outputTokens: usage.output_tokens ?? 0
41064
+ });
41065
+ }
41066
+ return [...byId.values()];
41067
+ }
41068
+ async function readTranscriptUsage(transcriptPath2) {
41069
+ const content = await fs54.promises.readFile(transcriptPath2, "utf8");
41070
+ return transcriptUsage(content.split("\n"));
41071
+ }
41072
+
40973
41073
  // src/shared/db/recordPhaseCycleContext.ts
40974
41074
  import { sql as sql25 } from "drizzle-orm";
40975
41075
  async function recordPhaseCycleContext(db, itemId2, phaseIdx, window, resetsAt, pct) {
@@ -41043,37 +41143,8 @@ async function recordWindowTokens(db, window, resetsAt, tokensUp, tokensDown) {
41043
41143
  );
41044
41144
  }
41045
41145
 
41046
- // src/commands/sessions/shared/transcriptUsage.ts
41047
- import * as fs54 from "fs";
41048
- function transcriptUsage(lines2) {
41049
- const byId = /* @__PURE__ */ new Map();
41050
- for (const line of lines2) {
41051
- if (!line.trim()) continue;
41052
- let entry;
41053
- try {
41054
- entry = JSON.parse(line);
41055
- } catch {
41056
- continue;
41057
- }
41058
- if (entry.type !== "assistant") continue;
41059
- const id = entry.message?.id;
41060
- const usage = entry.message?.usage;
41061
- if (!id || !usage) continue;
41062
- byId.set(id, {
41063
- messageId: id,
41064
- inputTokens: usage.input_tokens ?? 0,
41065
- outputTokens: usage.output_tokens ?? 0
41066
- });
41067
- }
41068
- return [...byId.values()];
41069
- }
41070
- async function readTranscriptUsage(transcriptPath2) {
41071
- const content = await fs54.promises.readFile(transcriptPath2, "utf8");
41072
- return transcriptUsage(content.split("\n"));
41073
- }
41074
-
41075
41146
  // src/commands/sessions/daemon/persistPhaseTokens.ts
41076
- async function persistPhaseTokens(itemId2, phaseIdx, transcriptPath2, usedPct, windows) {
41147
+ async function persistPhaseTokens(itemId2, phaseIdx, loadResponses, usedPct, windows) {
41077
41148
  try {
41078
41149
  if (!process.env.ASSIST_DATABASE_URL && !loadConfig().database.url) return;
41079
41150
  const db = await getDb();
@@ -41090,7 +41161,7 @@ async function persistPhaseTokens(itemId2, phaseIdx, transcriptPath2, usedPct, w
41090
41161
  );
41091
41162
  }
41092
41163
  }
41093
- const responses = await readTranscriptUsage(transcriptPath2);
41164
+ const responses = await loadResponses();
41094
41165
  if (responses.length === 0) return;
41095
41166
  const { tokensUp, tokensDown } = await recordPhaseTranscriptUsage(
41096
41167
  db,
@@ -41116,7 +41187,7 @@ function recordSessionUsage(sessions, claudeSessionId, transcriptPath2, usedPct,
41116
41187
  void persistPhaseTokens(
41117
41188
  phase.itemId,
41118
41189
  phase.phaseIdx,
41119
- transcriptPath2,
41190
+ () => readTranscriptUsage(transcriptPath2),
41120
41191
  usedPct,
41121
41192
  windows
41122
41193
  );
@@ -43916,6 +43987,119 @@ function creator(isNew, spawn13) {
43916
43987
  };
43917
43988
  }
43918
43989
 
43990
+ // src/commands/sessions/shared/codex/codexRolloutUsage.ts
43991
+ import * as fs55 from "fs";
43992
+
43993
+ // src/commands/sessions/shared/codex/applyTokenInfo.ts
43994
+ function applyTokenInfo(usage, byId, conversationId, rawInfo) {
43995
+ if (!rawInfo || typeof rawInfo !== "object") return;
43996
+ const info = rawInfo;
43997
+ const last = info.last_token_usage;
43998
+ const cumulative = info.total_token_usage?.total_tokens;
43999
+ if (!last || typeof cumulative !== "number") return;
44000
+ const messageId = `codex:${conversationId}:${cumulative}`;
44001
+ byId.set(messageId, {
44002
+ messageId,
44003
+ inputTokens: Math.max(
44004
+ 0,
44005
+ (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)
44006
+ ),
44007
+ outputTokens: last.output_tokens ?? 0
44008
+ });
44009
+ const contextWindow = info.model_context_window;
44010
+ if (contextWindow && typeof last.total_tokens === "number")
44011
+ usage.usedPct = Math.min(100, last.total_tokens / contextWindow * 100);
44012
+ }
44013
+
44014
+ // src/commands/sessions/shared/codex/toRateLimits.ts
44015
+ var WINDOW_BY_MINUTES = {
44016
+ 300: "five_hour",
44017
+ 10080: "seven_day"
44018
+ };
44019
+ function toRateLimits(raw) {
44020
+ if (!raw || typeof raw !== "object") return void 0;
44021
+ const { primary, secondary } = raw;
44022
+ const rateLimits = {};
44023
+ for (const candidate of [primary, secondary]) {
44024
+ if (!candidate || typeof candidate !== "object") continue;
44025
+ const limit = candidate;
44026
+ const window = WINDOW_BY_MINUTES[limit.window_minutes ?? 0];
44027
+ if (!window || typeof limit.used_percent !== "number") continue;
44028
+ rateLimits[window] = {
44029
+ used_percentage: limit.used_percent,
44030
+ resets_at: limit.resets_at
44031
+ };
44032
+ }
44033
+ return Object.keys(rateLimits).length > 0 ? rateLimits : void 0;
44034
+ }
44035
+
44036
+ // src/commands/sessions/shared/codex/codexRolloutUsage.ts
44037
+ function codexRolloutUsage(lines2) {
44038
+ const usage = { responses: [] };
44039
+ const byId = /* @__PURE__ */ new Map();
44040
+ let conversationId = "";
44041
+ for (const line of lines2) {
44042
+ const entry = parseRolloutEntry(line);
44043
+ if (!entry) continue;
44044
+ conversationId ||= sessionMetaId(entry);
44045
+ const payload = tokenCountPayload(entry);
44046
+ if (!payload) continue;
44047
+ applyTokenInfo(usage, byId, conversationId, payload.info);
44048
+ usage.rateLimits = toRateLimits(payload.rate_limits) ?? usage.rateLimits;
44049
+ }
44050
+ usage.responses = [...byId.values()];
44051
+ return usage;
44052
+ }
44053
+ async function readCodexRolloutUsage(rolloutPath) {
44054
+ const content = await fs55.promises.readFile(rolloutPath, "utf8");
44055
+ return codexRolloutUsage(content.split("\n"));
44056
+ }
44057
+ function sessionMetaId(entry) {
44058
+ if (entry.type !== "session_meta") return "";
44059
+ return rolloutString(rolloutPayload(entry).session_id);
44060
+ }
44061
+ function tokenCountPayload(entry) {
44062
+ if (entry.type !== "event_msg") return void 0;
44063
+ const payload = rolloutPayload(entry);
44064
+ return payload.type === "token_count" ? payload : void 0;
44065
+ }
44066
+
44067
+ // src/commands/sessions/daemon/applyCodexUsage.ts
44068
+ function applyCodexUsage(sessions, sessionId, usage, windows) {
44069
+ const session = sessions.get(sessionId);
44070
+ if (!session) return false;
44071
+ if (usage.usedPct !== void 0) session.usedPct = usage.usedPct;
44072
+ const phase = sessionBacklogPhase(session);
44073
+ if (phase)
44074
+ void persistPhaseTokens(
44075
+ phase.itemId,
44076
+ phase.phaseIdx,
44077
+ async () => usage.responses,
44078
+ usage.usedPct,
44079
+ windows
44080
+ );
44081
+ void flushPhaseActiveMs(session);
44082
+ return true;
44083
+ }
44084
+
44085
+ // src/commands/sessions/daemon/handleCodexUsage.ts
44086
+ var handleCodexUsage = (client, m, d) => {
44087
+ if (m.windowsProxy.route(client, d)) return;
44088
+ const sessionId = d.sessionId;
44089
+ if (d.ack) sendTo(client, { type: "ack", sessionId });
44090
+ void readCodexRolloutUsage(d.transcriptPath).then(
44091
+ (usage) => {
44092
+ if (usage.rateLimits)
44093
+ m.clients.updateHarnessLimits("codex", usage.rateLimits);
44094
+ const windows = m.clients.currentWindows("codex");
44095
+ m.update(
44096
+ (sessions) => applyCodexUsage(sessions, sessionId, usage, windows)
44097
+ );
44098
+ },
44099
+ (error) => daemonLog(`codex-usage read failed: ${String(error)}`)
44100
+ );
44101
+ };
44102
+
43919
44103
  // src/commands/sessions/daemon/spawnContextFrom.ts
43920
44104
  function spawnContextFrom(d) {
43921
44105
  return {
@@ -43976,7 +44160,7 @@ function handleSetStatus(client, m, d) {
43976
44160
  }
43977
44161
 
43978
44162
  // src/commands/sessions/shared/parseTranscript.ts
43979
- import * as fs55 from "fs";
44163
+ import * as fs56 from "fs";
43980
44164
 
43981
44165
  // src/commands/sessions/shared/codex/findCodexRolloutPath.ts
43982
44166
  import * as path90 from "path";
@@ -44059,7 +44243,7 @@ async function parseTranscript(sessionId) {
44059
44243
  }
44060
44244
  async function readMessages(filePath, parse5) {
44061
44245
  try {
44062
- const raw = await fs55.promises.readFile(filePath, "utf8");
44246
+ const raw = await fs56.promises.readFile(filePath, "utf8");
44063
44247
  return parse5(raw.split("\n"));
44064
44248
  } catch {
44065
44249
  return [];
@@ -44253,6 +44437,7 @@ var messageHandlers = {
44253
44437
  d.transcriptPath,
44254
44438
  d.usedPct
44255
44439
  ),
44440
+ "codex-usage": handleCodexUsage,
44256
44441
  input: routed(
44257
44442
  (_client, m, d) => m.writeToSession(d.sessionId, d.data)
44258
44443
  ),
@@ -44624,17 +44809,17 @@ async function renameSession(title) {
44624
44809
  }
44625
44810
 
44626
44811
  // src/commands/sessions/summarise/index.ts
44627
- import * as fs57 from "fs";
44812
+ import * as fs58 from "fs";
44628
44813
  import chalk246 from "chalk";
44629
44814
 
44630
44815
  // src/commands/sessions/summarise/shared.ts
44631
- import * as fs56 from "fs";
44816
+ import * as fs57 from "fs";
44632
44817
  function writeSummary(jsonlPath2, summary) {
44633
- fs56.writeFileSync(summaryPathFor(jsonlPath2), `${summary.trim()}
44818
+ fs57.writeFileSync(summaryPathFor(jsonlPath2), `${summary.trim()}
44634
44819
  `, "utf8");
44635
44820
  }
44636
44821
  function hasSummary(jsonlPath2) {
44637
- return fs56.existsSync(summaryPathFor(jsonlPath2));
44822
+ return fs57.existsSync(summaryPathFor(jsonlPath2));
44638
44823
  }
44639
44824
  function summaryPathFor(jsonlPath2) {
44640
44825
  return jsonlPath2.replace(/\.jsonl$/, ".summary");
@@ -44706,7 +44891,7 @@ function selectCandidates(files, options2) {
44706
44891
  const candidates = options2.force ? files : files.filter((f) => !hasSummary(f));
44707
44892
  candidates.sort((a, b) => {
44708
44893
  try {
44709
- return fs57.statSync(b).mtimeMs - fs57.statSync(a).mtimeMs;
44894
+ return fs58.statSync(b).mtimeMs - fs58.statSync(a).mtimeMs;
44710
44895
  } catch {
44711
44896
  return 0;
44712
44897
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staff0rd/assist",
3
- "version": "0.692.0",
3
+ "version": "0.693.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "bin": {