@kapybara/zerosub 1.3.0 → 1.5.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/server/handoff.ts CHANGED
@@ -9,12 +9,48 @@ export const CONTINUED_FROM_LABEL = "zerosub.continued-from";
9
9
 
10
10
  const MAX_TRANSCRIPT = 40_000;
11
11
  const MAX_FIRST_MESSAGE = 6_000;
12
+ const MAX_EARLIER_HANDOFF = 6_000;
13
+
14
+ const OPEN = "<previous-session>";
15
+ const CLOSE = "</previous-session>";
12
16
 
13
17
  function clip(text: string, max: number): string {
14
18
  const trimmed = text.trim();
15
19
  return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}…`;
16
20
  }
17
21
 
22
+ /**
23
+ * Fits a long text into `max` characters by keeping its start (where the request usually is) and
24
+ * its end (the most recent context), with a marker where the middle was cut. The end gets more room.
25
+ */
26
+ export function keepEnds(text: string, max: number, marker = "[… omitted …]"): string {
27
+ if (text.length <= max) return text;
28
+ const room = Math.max(0, max - marker.length - 4);
29
+ const head = Math.floor(room / 3);
30
+ return `${text.slice(0, head).trimEnd()}\n\n${marker}\n\n${text.slice(text.length - (room - head)).trimStart()}`;
31
+ }
32
+
33
+ /** Tags become plain words, so a quote can't open or close the block around it. */
34
+ function neutralise(text: string): string {
35
+ return text.replaceAll(OPEN, "[earlier session:").replaceAll(CLOSE, "]");
36
+ }
37
+
38
+ /**
39
+ * A continuation's first message quotes the session before it. Quoting that again would nest every
40
+ * earlier hand-off inside the next, so keep only the start of the earlier session (its original
41
+ * request) and its end (where it left off), and say what was cut. Based on liloli's version in #14.
42
+ */
43
+ export function shortenEarlierHandOff(text: string): string {
44
+ const open = text.indexOf(OPEN);
45
+ if (open < 0) return text;
46
+ const close = text.lastIndexOf(CLOSE);
47
+ const end = close > open ? close : text.length;
48
+ const inner = neutralise(shortenEarlierHandOff(text.slice(open + OPEN.length, end))).trim();
49
+ const kept = keepEnds(inner, MAX_EARLIER_HANDOFF, "[… middle of that earlier session omitted …]");
50
+ const after = close > open ? text.slice(close + CLOSE.length) : "";
51
+ return `${neutralise(text.slice(0, open))}${OPEN}\n${kept}\n${CLOSE}${neutralise(after)}`;
52
+ }
53
+
18
54
  function describeTool(item: Extract<AgentTimelineItem, { type: "tool_call" }>): string {
19
55
  const detail = item.detail;
20
56
  const failed = item.status === "failed" ? " (failed)" : "";
@@ -48,10 +84,13 @@ export function buildTranscript(timeline: readonly AgentTimelineItem[], max = MA
48
84
  let todos: string | null = null;
49
85
  for (const item of timeline) {
50
86
  switch (item.type) {
51
- case "user_message":
52
- if (firstUser === null) firstUser = clip(item.text, MAX_FIRST_MESSAGE);
53
- lines.push(`User: ${item.text.trim()}`);
87
+ case "user_message": {
88
+ // Clipping below can't then split a quoted pair: the prompt's own tags are the only ones.
89
+ const text = neutralise(shortenEarlierHandOff(item.text));
90
+ if (firstUser === null) firstUser = clip(text, MAX_FIRST_MESSAGE);
91
+ lines.push(`User: ${text.trim()}`);
54
92
  break;
93
+ }
55
94
  case "assistant_message":
56
95
  if (item.text.trim()) lines.push(`Assistant: ${item.text.trim()}`);
57
96
  break;
@@ -81,9 +120,9 @@ export function continuationPrompt(transcript: string, why: string, previous = "
81
120
  `This task is continuing from an earlier ${previous} session that stopped because ${why}.`,
82
121
  "The working directory already contains every change that session made. Here is its conversation, oldest first:",
83
122
  "",
84
- "<previous-session>",
123
+ OPEN,
85
124
  transcript,
86
- "</previous-session>",
125
+ CLOSE,
87
126
  "",
88
127
  "Pick up exactly where it left off. Check the current state of the files before changing anything, and don't redo finished work.",
89
128
  ].join("\n");
@@ -128,6 +167,9 @@ export async function continueInNewAgent(options: {
128
167
  target?: ContinuationTarget;
129
168
  /** What to call the session that stopped, e.g. `Claude Code`. */
130
169
  previous?: string;
170
+ agentId?: string;
171
+ /** Create the pre-bound tab first; the caller delivers its handoff separately. */
172
+ deferPrompt?: boolean;
131
173
  }): Promise<Continuation> {
132
174
  const { paseo, sourceAgentId } = options;
133
175
  const refreshed = await paseo.agents.ref(sourceAgentId).refresh();
@@ -135,7 +177,7 @@ export async function continueInNewAgent(options: {
135
177
  if (!source) throw new Error("The original agent is no longer available.");
136
178
 
137
179
  let timeline = options.timeline;
138
- if (!timeline) {
180
+ if (!timeline && !options.deferPrompt) {
139
181
  const page = await paseo.agents.ref(sourceAgentId).timeline.refetch({ direction: "tail", limit: 500 });
140
182
  timeline = page.entries.map((entry) => entry.item);
141
183
  }
@@ -149,7 +191,7 @@ export async function continueInNewAgent(options: {
149
191
  : (source.model ?? source.runtimeInfo?.model ?? (await defaultModel(paseo, provider)));
150
192
  if (!model) throw new Error(`Couldn't tell which ${provider} model to use for the new agent.`);
151
193
 
152
- const agentId = randomUUID();
194
+ const agentId = options.agentId ?? randomUUID();
153
195
  await options.bind(agentId);
154
196
  const title = target
155
197
  ? `${source.title?.trim() || "Task"} (continued on ${target.label})`
@@ -161,12 +203,14 @@ export async function continueInNewAgent(options: {
161
203
  provider: `${provider}/${model}`,
162
204
  ...(source.currentModeId ? { modeId: source.currentModeId } : {}),
163
205
  ...(source.thinkingOptionId ? { thinkingOptionId: source.thinkingOptionId } : {}),
206
+ ...(source.features ? { featureValues: Object.fromEntries(source.features.map((feature) => [feature.id, feature.value])) } : {}),
164
207
  };
165
208
  const request = {
166
209
  agentId,
210
+ ...(options.agentId ? { idempotencyKey: options.agentId } : {}),
167
211
  config,
168
212
  title,
169
- prompt: continuationPrompt(buildTranscript(timeline), options.why, options.previous),
213
+ ...(!options.deferPrompt ? { prompt: continuationPrompt(buildTranscript(timeline ?? []), options.why, options.previous) } : {}),
170
214
  labels: { [CONTINUED_FROM_LABEL]: sourceAgentId },
171
215
  };
172
216
  if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
package/server/limits.ts CHANGED
@@ -1,21 +1,24 @@
1
- import type { LimitHit, LimitKind, TurnEvent } from "./adapter";
1
+ import type { AgentTimelineItem, LimitHit, LimitKind, TurnEvent } from "./adapter";
2
2
 
3
3
  /**
4
4
  * Claude Code's exact wording for hard limits (2.1.x templates: `You've hit your ${limit}${suffix}`),
5
5
  * plus the legacy `Claude AI usage limit reached|<epoch>`. Each must be followed by the CLI's own
6
6
  * separator (" · …", ".") or end the line, so prose like "You've hit your GitHub API rate limit"
7
7
  * never matches. Warnings ("You've used 80%…") and capacity 429s ("…not your usage limit") are
8
- * deliberately absent: switching accounts doesn't help with those.
8
+ * deliberately absent: switching accounts doesn't help with those. Claude Code 2.1.312 renamed the
9
+ * session limit the "5-hour limit"; older builds still print "session limit". A plain "usage limit"
10
+ * is a budget: Claude Code prints it for an org on usage-based billing, and as its fallback when the
11
+ * API names no window it knows. Usage readings show neither.
9
12
  */
10
13
  const END = String.raw`(?=\s*(?:·|\.|$))`;
11
14
  const APOSTROPHE = "['’]";
12
15
  const CLAUDE_LIMITS: ReadonlyArray<{ pattern: RegExp; kind: LimitKind }> = [
13
- { pattern: new RegExp(`^You${APOSTROPHE}ve hit your (?:session |weekly |Opus |Sonnet |Fable )?limit${END}`, "i"), kind: "window" },
16
+ { pattern: new RegExp(`^You${APOSTROPHE}ve hit your (?:5-hour |session |weekly |Opus |Sonnet |Fable )?limit${END}`, "i"), kind: "window" },
14
17
  { pattern: new RegExp(`^You${APOSTROPHE}ve reached your (?:Fable|Opus|Sonnet|Haiku)(?: [\\w.]{1,10})? limit${END}`), kind: "window" },
15
18
  { pattern: /Claude AI usage limit reached\|\d{9,}/, kind: "window" },
16
19
  {
17
20
  pattern: new RegExp(
18
- `^You${APOSTROPHE}ve hit your (?:usage credit limit|team${APOSTROPHE}s shared budget|(?:monthly|individual) spend limit|(?:org|channel)${APOSTROPHE}s monthly (?:usage|spend) limit)${END}`,
21
+ `^You${APOSTROPHE}ve hit your (?:usage limit|usage credit limit|team${APOSTROPHE}s shared budget|(?:monthly|individual) spend limit|individual usage limit|(?:org|channel)${APOSTROPHE}s monthly (?:usage|spend) limit)${END}`,
19
22
  "i",
20
23
  ),
21
24
  kind: "budget",
@@ -49,6 +52,23 @@ function clean(text: string): string {
49
52
  return text.replace(SYSTEM_ERROR, "").replace(/^API Error:\s*/i, "").trim();
50
53
  }
51
54
 
55
+ /**
56
+ * A turn's rows in a page of the agent's timeline (oldest first), to read as that turn. Paseo 0.13
57
+ * tags each row of a live turn with the turn's id, but providers count turns per session, so an
58
+ * earlier turn can carry the same id. Reading back from the turn's last row, another turn's prompt
59
+ * is where this one began. Rows of other turns, and rows without an id, are left out.
60
+ */
61
+ export function turnRows(entries: ReadonlyArray<{ item: AgentTimelineItem; turnId?: string }>, turnId: string): AgentTimelineItem[] {
62
+ const rows: AgentTimelineItem[] = [];
63
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
64
+ const entry = entries[index];
65
+ if (!entry) continue;
66
+ if (entry.turnId === turnId) rows.push(entry.item);
67
+ else if (rows.length > 0 && entry.turnId && entry.item.type === "user_message") break;
68
+ }
69
+ return rows.reverse();
70
+ }
71
+
52
72
  /**
53
73
  * Where a CLI-generated notice can appear in a finished turn: the failure message, error items,
54
74
  * Paseo's `[System Error]` rows, and — for Claude, which reports limits as a synthetic reply — the
package/server/routing.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { peakUsage } from "../shared/format";
2
2
  import type { Family, Usage } from "../shared/model";
3
+ import { FIVE_HOUR_MINUTES, WEEK_MINUTES } from "./codex";
3
4
  import {
4
5
  accountsOf,
5
6
  defaultAccount,
@@ -10,6 +11,13 @@ import {
10
11
  type StoredState,
11
12
  } from "./state";
12
13
 
14
+ /** Weekly resets only steer a new agent when every account it could use was read this recently. */
15
+ const FRESH_READING_MS = 30 * 60_000;
16
+ /** How soon a weekly reset has to be for its account to be preferred. */
17
+ const NEAR_RESET_MS = 24 * 60 * 60_000;
18
+ /** The most a near-reset account may have used of any window, so it still has room to spare. */
19
+ const NEAR_RESET_MAX_USED_PERCENT = 80;
20
+
13
21
  export function isLimited(account: StoredAccount, now: number): boolean {
14
22
  if (!account.limitedUntil) return false;
15
23
  const until = Date.parse(account.limitedUntil);
@@ -56,6 +64,28 @@ export function mostAvailable(
56
64
  return candidates[0];
57
65
  }
58
66
 
67
+ /** Prefer a weekly reset within a day only when every usable account has fresh, complete usage. */
68
+ function soonestWeeklyReset(state: StoredState, family: Family, usageOf: RouteInput["usageOf"], now: number): StoredAccount | undefined {
69
+ const candidates = accountsOf(state, family).filter((account) => isUsable(account, now));
70
+ const readings = candidates.map((account) => ({ account, usage: usageOf(account.id) }));
71
+ const complete = readings.every(({ usage }) => {
72
+ if (!usage || usage.error || usage.cached) return false;
73
+ const age = now - Date.parse(usage.fetchedAt);
74
+ const short = usage.windows.find((window) => window.minutes === FIVE_HOUR_MINUTES);
75
+ const weekly = usage.windows.find((window) => window.minutes === WEEK_MINUTES);
76
+ return Number.isFinite(age) && age >= 0 && age <= FRESH_READING_MS && !!short && !!weekly &&
77
+ [short, weekly].every((window) => Number.isFinite(window.usedPercent) && window.usedPercent >= 0 &&
78
+ window.usedPercent <= 100 && window.resetsAt !== null && Date.parse(window.resetsAt) > now);
79
+ });
80
+ if (!complete) return undefined;
81
+ return readings.filter(({ usage }) => {
82
+ const weekly = usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!;
83
+ return usage!.windows.every((window) => window.usedPercent <= NEAR_RESET_MAX_USED_PERCENT) &&
84
+ Date.parse(weekly.resetsAt!) - now <= NEAR_RESET_MS;
85
+ }).sort((a, b) => Date.parse(a.usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!.resetsAt!) -
86
+ Date.parse(b.usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!.resetsAt!))[0]?.account;
87
+ }
88
+
59
89
  export interface RouteInput {
60
90
  agentId: string;
61
91
  family: Family;
@@ -98,8 +128,9 @@ export function chooseAccount(state: StoredState, input: RouteInput): RouteDecis
98
128
  let bind: Binding | null = null;
99
129
 
100
130
  if (!account && fresh && input.balanceNewAgents && accounts.length > 1) {
101
- account = mostAvailable(state, input.family, input.usageOf, input.now);
102
- if (account) bind = { accountId: account.id, source: "balance", at };
131
+ const nearReset = input.family === "codex" ? soonestWeeklyReset(state, input.family, input.usageOf, input.now) : undefined;
132
+ account = nearReset ?? mostAvailable(state, input.family, input.usageOf, input.now);
133
+ if (account) bind = { accountId: account.id, source: "balance", at, selectionReason: nearReset ? "weekly_reset" : "headroom" };
103
134
  }
104
135
  if (!account) {
105
136
  // An imported Codex thread most likely came from the user's own CLI, so it belongs to that login.