@paigy/harness 0.3.51 → 0.3.52

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.
Files changed (3) hide show
  1. package/dist/cli.js +693 -119
  2. package/dist/main.js +770 -182
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -23102,7 +23102,7 @@ var CATALOG = [
23102
23102
  loginHint: "Run `claude` once in a terminal and sign in.",
23103
23103
  installCli: "curl -fsSL https://claude.ai/install.sh | bash",
23104
23104
  installAdapter: "npm install -g @agentclientprotocol/claude-agent-acp",
23105
- models: ["claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-opus-20240229"]
23105
+ models: ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5-20251001"]
23106
23106
  },
23107
23107
  {
23108
23108
  name: "codex",
@@ -23112,8 +23112,20 @@ var CATALOG = [
23112
23112
  authProbe: ["codex", "login", "status"],
23113
23113
  loginHint: "Run `codex login` to authenticate.",
23114
23114
  installCli: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",
23115
+ // UNPINNED AGAIN (2026-11-20, Goal ae096b5d, the owner's "Build SDK 2 turn support"). It was
23116
+ // pinned to 2.2.2 for a day because from 2.3.0 the adapter answers `session/prompt` with
23117
+ // `{messageId}` at once instead of `{stopReason}` at the end; `acp.ts` now settles a turn on
23118
+ // SDK 2's idle `state_update` as well, so the current adapter is the right one to install. It
23119
+ // has to be: the adapter runs its OWN bundled codex, and the one in 2.2.2 (0.160.1) is refused
23120
+ // by an account whose entitlement needs a current client.
23115
23121
  installAdapter: "npm install -g @agentclientprotocol/codex-acp",
23116
- models: ["gpt-4o", "gpt-4o-mini", "o1", "o1-mini"]
23122
+ // ONE ID, BECAUSE ONE IS WHAT A CHATGPT ACCOUNT TAKES (2026-11-23/24, Goal 04549742). The
23123
+ // whole previous list -- and `gpt-5.1-codex`, `gpt-5.1-codex-max` and the `gpt-6.2-astra`
23124
+ // that `~/.codex/config.toml` sets -- answer `400 model_not_found`: "not supported when
23125
+ // using Codex with a ChatGPT account". A Codex launch that took this list's head therefore
23126
+ // died on its first turn, and a dead turn marks its Goal done with the work untouched
23127
+ // (`afterTurn` -> `finish`, `paigy/bridge.ts`), which is how it read as a working session.
23128
+ models: ["gpt-6.1-sol"]
23117
23129
  },
23118
23130
  {
23119
23131
  name: "agy",
@@ -23124,7 +23136,9 @@ var CATALOG = [
23124
23136
  authProbe: ["agy", "help"],
23125
23137
  loginHint: "Install and set up Antigravity (`agy`).",
23126
23138
  installCli: "curl -fsSL https://antigravity.dev/install.sh | bash",
23127
- models: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.0-pro-exp"]
23139
+ // `agy models` order, high-effort variant of each family it offers (the suffix IS the
23140
+ // reasoning effort: `gemini-4-neon-low` and `-xhigh` are the same model turned down or up).
23141
+ models: ["gemini-4-neon-high", "gemini-4-argon-high", "gemini-4-carbon-high", "gemini-4-hydrogen-high"]
23128
23142
  },
23129
23143
  {
23130
23144
  name: "grok",
@@ -23134,7 +23148,15 @@ var CATALOG = [
23134
23148
  // to miss, and detection would report adapter-missing on a machine that can already launch.
23135
23149
  authProbe: ["sh", "-c", 'test -s "$HOME/.grok/auth.json"'],
23136
23150
  loginHint: "Run `grok` once in a terminal and sign in.",
23137
- installCli: "curl -fsSL https://x.ai/cli/install.sh | bash"
23151
+ installCli: "curl -fsSL https://x.ai/cli/install.sh | bash",
23152
+ // Grok was the one vendor with NO list, so a Grok session could only ever be started on
23153
+ // whatever the CLI defaulted to and the phone could offer no choice. `grok models` answers
23154
+ // without a login, so writing one cost the pending sign-in nothing.
23155
+ // BUT SIGNED OUT IT ANSWERS A SUBSET (2026-11-24). Before the owner's browser login `grok
23156
+ // models` named "grok-4.6 (default), grok-4.5", which is what this list said. The moment
23157
+ // ~/.grok/auth.json existed the same command answered grok-4.7 as the default and added
23158
+ // grok-4.7-build-fast — so a signed-out reading is a floor, not the menu. Re-read it signed in.
23159
+ models: ["grok-4.7", "grok-4.7-build-fast", "grok-4.6", "grok-4.5"]
23138
23160
  }
23139
23161
  ];
23140
23162
  function probeDirs(home = homedir()) {
@@ -27236,7 +27258,7 @@ var NEVER = INVALID;
27236
27258
  var USAGE = "usage: paigy-harness setup | pair | host [--grant DIR]\u2026 | service | enable-tools [--scope user|project] | hatch NAME [--voice KEY] [--slot SLOT] | launch NAME [--under GOAL] [--approval QUESTION] [--voice KEY] [--harness \u2026] [--model ID] [--mode \u2026] [--cwd DIR] BRIEF\u2026 | handoff | [--harness claude|codex|agy|grok] [--model ID] [--mode bypass|ask] [--cwd DIR] [--grace SECONDS] [--doctor] PROMPT\u2026";
27237
27259
  function parseArgs(argv) {
27238
27260
  const args = { harness: "claude", mode: "bypass", cwd: process.cwd(), doctor: false, help: false, host: false, pair: false, service: false, setup: false, enableTools: false, scope: "user", grant: [], hatch: null, voice: null, slot: null, launch: null, under: null, approval: null, model: null, graceSeconds: 90, prompt: "", handoff: false };
27239
- const words = [];
27261
+ const words2 = [];
27240
27262
  let commandPosition = true;
27241
27263
  for (let i = 0; i < argv.length; i++) {
27242
27264
  const arg = argv[i];
@@ -27314,10 +27336,10 @@ function parseArgs(argv) {
27314
27336
  } else if (arg?.startsWith("--")) {
27315
27337
  return { error: `unknown flag ${arg}` };
27316
27338
  } else if (arg) {
27317
- words.push(arg);
27339
+ words2.push(arg);
27318
27340
  }
27319
27341
  }
27320
- args.prompt = words.join(" ");
27342
+ args.prompt = words2.join(" ");
27321
27343
  if (args.help) return args;
27322
27344
  if (args.under && !args.launch) return { error: "--under requires launch NAME" };
27323
27345
  if (args.approval && !args.launch) return { error: "--approval requires launch NAME" };
@@ -29068,6 +29090,12 @@ var questionFields = {
29068
29090
  workItBlocks: external_exports.array(external_exports.object({ blocked: NodeRef, action: BlockedAction, reason: reason.optional() }).strict().refine(actionFits, ACTION_FITS)).min(1).max(10).optional().describe(
29069
29091
  "The work that cannot go on until this is answered: a Goal's start or completion, or another Question's answer. Only for work truly blocked; it asks for a call. Leave it out for a question you can keep working around."
29070
29092
  ),
29093
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
29094
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
29095
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
29096
+ causedBy: causedBy.describe(
29097
+ "When this question follows something the person said, the ids (or the short ids get_goals prints) of those words. Their card quotes them above the question, so they can answer without going to look. Only words it truly follows; an id that is not their words is refused by name (cause_not_found) and nothing is sent."
29098
+ ),
29071
29099
  userExplicitlyRequested
29072
29100
  };
29073
29101
  var refineQuestion = (q, ctx) => {
@@ -29315,7 +29343,8 @@ var LaunchToolSchema = external_exports.object({
29315
29343
  name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
29316
29344
  harness: external_exports.enum(LAUNCH_HARNESSES).describe("What runs it."),
29317
29345
  brief: goalOutcome.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX} characters.`),
29318
- approvalQuestionId: external_exports.string().uuid().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first."),
29346
+ approvalQuestionId: external_exports.string().uuid().optional().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first. Required unless this is your own successor, and never with it."),
29347
+ successor: external_exports.literal(true).optional().describe("THIS SESSION'S OWN SUCCESSOR, when your context is at its window or the person told you to hand off: it takes your work and your session ends. No approval is needed for your own replacement, and you can launch only one \u2014 give it a new name."),
29319
29348
  workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
29320
29349
  repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
29321
29350
  model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
@@ -29323,7 +29352,7 @@ var LaunchToolSchema = external_exports.object({
29323
29352
  parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
29324
29353
  hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
29325
29354
  }).strict();
29326
- var LAUNCH_DESCRIPTION = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. A refusal says why. Returns sessionId, the agent, the brief's goalId and next.";
29355
+ var LAUNCH_DESCRIPTION = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. Your own successor needs none: successor: true, with a new name, hands it your work and ends your session. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. Returns sessionId, the agent and the brief's goalId; a refusal says why.";
29327
29356
  var AGENT_TOOLS = [
29328
29357
  { name: "configure", title: "Who am I", annotations: READS, description: CONFIGURE_IDENTITY_DESCRIPTION, inputSchema: mcpInputSchema(ConfigureIdentitySchema) },
29329
29358
  { name: "contact", title: "Contact the person", annotations: SENDS, description: CONTACT_DESCRIPTION, inputSchema: CONTACT_SCHEMA },
@@ -30201,6 +30230,9 @@ var InboxItemSchema = external_exports.object({
30201
30230
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
30202
30231
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
30203
30232
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
30233
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
30234
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
30235
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
30204
30236
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
30205
30237
  * the person to notice it again, and For you puts it first, the latest bump on top
30206
30238
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -30503,6 +30535,59 @@ var ReassignResultSchema = external_exports.object({
30503
30535
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
30504
30536
  parentId: external_exports.string().nullable()
30505
30537
  });
30538
+ var TeamSessionSchema = external_exports.object({
30539
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
30540
+ * agent's own page opens. The row's identity, so never null. */
30541
+ tokenId: external_exports.string(),
30542
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
30543
+ name: external_exports.string().nullable(),
30544
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
30545
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
30546
+ * session is doing is its step's `goalTitle`. */
30547
+ role: external_exports.string().nullable(),
30548
+ /** Its step under the project: the one it worked most recently. */
30549
+ goalId: external_exports.string(),
30550
+ goalTitle: external_exports.string().nullable(),
30551
+ goalState: external_exports.string(),
30552
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
30553
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
30554
+ * as it advertised it on its heartbeat. */
30555
+ harness: external_exports.string().nullable(),
30556
+ harnessLabel: external_exports.string().nullable(),
30557
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
30558
+ model: external_exports.string().nullable(),
30559
+ mode: external_exports.string().nullable(),
30560
+ workspace: external_exports.string().nullable(),
30561
+ worktree: external_exports.boolean().nullable(),
30562
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
30563
+ lastAt: external_exports.string().nullable(),
30564
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
30565
+ * that has written nothing yet can say for itself. */
30566
+ lastLine: external_exports.string().nullable(),
30567
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
30568
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
30569
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
30570
+ live: external_exports.boolean(),
30571
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
30572
+ * it is taking its work rather than merely still running. */
30573
+ working: external_exports.boolean(),
30574
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
30575
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
30576
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
30577
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
30578
+ waitingOn: external_exports.object({
30579
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
30580
+ text: external_exports.string(),
30581
+ id: external_exports.string().nullable(),
30582
+ at: external_exports.string().nullable()
30583
+ }),
30584
+ /** Its credential was revoked, or the person's end of it was carried out and said so
30585
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
30586
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
30587
+ * reads as a team rather than an empty page. */
30588
+ endedAt: external_exports.string().nullable()
30589
+ });
30590
+ var TeamReadSchema = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema) });
30506
30591
  var LessonStateSchema = external_exports.enum(["active", "proposed", "retired"]);
30507
30592
  var LessonViewSchema = external_exports.object({
30508
30593
  id: external_exports.string(),
@@ -31618,10 +31703,10 @@ ${block2}`;
31618
31703
  // src/cli.ts
31619
31704
  var import_qrcode = __toESM(require_lib(), 1);
31620
31705
  import { hostname } from "os";
31621
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
31706
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "fs";
31622
31707
  import { execFile as execFile2, execSync as execSync2 } from "child_process";
31623
- import { homedir as homedir9 } from "os";
31624
- import { join as join11 } from "path";
31708
+ import { homedir as homedir11 } from "os";
31709
+ import { join as join13 } from "path";
31625
31710
 
31626
31711
  // src/run.ts
31627
31712
  import { randomUUID as randomUUID4 } from "crypto";
@@ -31686,6 +31771,17 @@ var AcpDriver = class {
31686
31771
  running = /* @__PURE__ */ new Set();
31687
31772
  /** The prompt in flight was already cancelled for silence: once is the whole remedy. */
31688
31773
  cancelled = false;
31774
+ /** ACP SDK 2 ANSWERED THE PROMPT AND THE TURN GOES ON (2026-11-20, Goal ae096b5d). SDK 1 keeps
31775
+ * the prompt response until the turn ends and puts `stopReason` on it. SDK 2 answers at once with
31776
+ * `{messageId}` — an acknowledgement, 2.3 seconds before the agent's first word in a live
31777
+ * capture — and ends the turn with `state_update: {state:"idle"}`. Settling on that response
31778
+ * would end every turn instantly and empty, so the turn stays in flight here: `promptId` is kept,
31779
+ * which is what `quiet` cancels against and what `flush` queues behind, and only an idle
31780
+ * `state_update` settles it. */
31781
+ ackedAwaitingIdle = false;
31782
+ /** The model the adapter last said a turn ran on (`claude-opus-5[1m]`), carried on every idle so
31783
+ * the run can tell a 200k window from a million (`fill.ts`). */
31784
+ model;
31689
31785
  /** The opening frame. Everything after is driven by responses in `handleLine`. */
31690
31786
  open() {
31691
31787
  this.initId = this.nextId++;
@@ -31697,7 +31793,17 @@ var AcpDriver = class {
31697
31793
  protocolVersion: 2,
31698
31794
  // We are not an editor: no file services offered, the agent uses its own.
31699
31795
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
31700
- clientInfo: { name: "paigy-desktop", version: "0.0.0" }
31796
+ // WHO WE ARE, UNDER BOTH NAMES (2026-11-20, Goal ae096b5d). ACP SDK 1 reads
31797
+ // `clientInfo`; SDK 2 requires `info` and REFUSES the frame without it
31798
+ // (`-32602 invalid initialize params`, path ["info"]), so a `clientInfo`-only
31799
+ // opening cannot start any adapter built on the newer SDK — and the catalog
31800
+ // installs adapters unpinned, so that is what a fresh machine gets. Sending both
31801
+ // was probed against every adapter we spawn: codex-acp 2.8.0 (SDK 2) and 2.2.2,
31802
+ // claude-agent-acp 0.76.0 and paigy-agy-acp all accept it, and the old ones keep
31803
+ // reading the field they already read. Drop `clientInfo` only once no adapter we
31804
+ // spawn is on SDK 1.
31805
+ clientInfo: { name: "paigy-desktop", version: "0.0.0" },
31806
+ info: { name: "paigy-desktop", version: "0.0.0" }
31701
31807
  }
31702
31808
  })
31703
31809
  ];
@@ -31805,33 +31911,12 @@ var AcpDriver = class {
31805
31911
  return { events: [], writes };
31806
31912
  }
31807
31913
  if (msg.id === this.promptId) {
31808
- this.promptId = void 0;
31809
- this.running.clear();
31810
- this.cancelled = false;
31811
- const events = [];
31812
- const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
31813
- if (report || this.tools.length) {
31814
- events.push({
31815
- kind: "turn",
31816
- role: "agent",
31817
- text: report,
31818
- ...this.tools.length ? { tools: [...this.tools] } : {}
31819
- });
31820
- }
31821
- const result = report;
31822
- const failed = msg.error !== void 0 || msg.result?.stopReason === "refusal";
31823
- this.text = "";
31824
- this.tools = [];
31825
- this.reportFrom = 0;
31826
- const writes = this.flush();
31827
- if (!writes.length) {
31828
- events.push({
31829
- kind: "idle",
31830
- ...result ? { result } : {},
31831
- ...failed ? { failed: true } : {}
31832
- });
31914
+ this.model = msg.result?._meta?.quota?.model_usage?.[0]?.model ?? this.model;
31915
+ if (msg.error === void 0 && msg.result?.stopReason === void 0 && msg.result?.messageId !== void 0) {
31916
+ this.ackedAwaitingIdle = true;
31917
+ return none;
31833
31918
  }
31834
- return { events, writes };
31919
+ return this.settle(msg.error !== void 0 || msg.result?.stopReason === "refusal");
31835
31920
  }
31836
31921
  return none;
31837
31922
  }
@@ -31847,6 +31932,11 @@ var AcpDriver = class {
31847
31932
  case "agent_message_chunk":
31848
31933
  this.text += update.content?.text ?? "";
31849
31934
  return none;
31935
+ // SDK 2'S END OF TURN. Only settles a turn whose prompt was acknowledged and is still in
31936
+ // flight: an SDK 1 adapter never sends this at all, `state: "running"` is the turn starting,
31937
+ // and an idle outside a turn (a session just opened) has nothing to settle.
31938
+ case "state_update":
31939
+ return update.state === "idle" && this.promptId !== void 0 && this.ackedAwaitingIdle ? this.settle(false) : none;
31850
31940
  case "tool_call": {
31851
31941
  const title = update.title?.trim() || update.kind || "tool";
31852
31942
  this.tools.push(title);
@@ -31893,6 +31983,42 @@ var AcpDriver = class {
31893
31983
  return this.resume ? { id: id3, method: "session/resume", params: { sessionId: this.resume, ...params } } : { id: id3, method: "session/new", params };
31894
31984
  }
31895
31985
  /** Send the queued prompts as one turn, if the agent can take one right now. */
31986
+ /** THE TURN IS OVER. The accumulated report lands first, then idle — the same order the line
31987
+ * adapters emit — and anything queued meanwhile goes out. Reached from SDK 1's prompt response
31988
+ * and from SDK 2's idle `state_update`, so both generations end a turn the same way. */
31989
+ settle(failed) {
31990
+ this.promptId = void 0;
31991
+ this.ackedAwaitingIdle = false;
31992
+ this.running.clear();
31993
+ this.cancelled = false;
31994
+ const events = [];
31995
+ const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
31996
+ if (report || this.tools.length) {
31997
+ events.push({
31998
+ kind: "turn",
31999
+ role: "agent",
32000
+ text: report,
32001
+ ...this.tools.length ? { tools: [...this.tools] } : {}
32002
+ });
32003
+ }
32004
+ const result = report;
32005
+ this.text = "";
32006
+ this.tools = [];
32007
+ this.reportFrom = 0;
32008
+ const writes = this.flush();
32009
+ if (!writes.length) {
32010
+ events.push({
32011
+ kind: "idle",
32012
+ ...result ? { result } : {},
32013
+ ...failed ? { failed: true } : {},
32014
+ // WHOSE conversation this was: its transcript is named by this id, and that transcript is
32015
+ // all a session's context amounts to once it can no longer write (`handoff.ts`).
32016
+ ...this.sessionId ? { session: this.sessionId } : {},
32017
+ ...this.model ? { model: this.model } : {}
32018
+ });
32019
+ }
32020
+ return { events, writes };
32021
+ }
31896
32022
  flush() {
31897
32023
  if (!this.sessionId || this.promptId !== void 0 || !this.queued.length) return [];
31898
32024
  const blocks = this.queued.map((text) => ({ type: "text", text }));
@@ -33724,6 +33850,12 @@ var questionFields2 = {
33724
33850
  workItBlocks: external_exports.array(external_exports.object({ blocked: NodeRef2, action: BlockedAction2, reason: reason2.optional() }).strict().refine(actionFits2, ACTION_FITS2)).min(1).max(10).optional().describe(
33725
33851
  "The work that cannot go on until this is answered: a Goal's start or completion, or another Question's answer. Only for work truly blocked; it asks for a call. Leave it out for a question you can keep working around."
33726
33852
  ),
33853
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
33854
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
33855
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
33856
+ causedBy: causedBy2.describe(
33857
+ "When this question follows something the person said, the ids (or the short ids get_goals prints) of those words. Their card quotes them above the question, so they can answer without going to look. Only words it truly follows; an id that is not their words is refused by name (cause_not_found) and nothing is sent."
33858
+ ),
33727
33859
  userExplicitlyRequested: userExplicitlyRequested2
33728
33860
  };
33729
33861
  var refineQuestion2 = (q, ctx) => {
@@ -33971,7 +34103,8 @@ var LaunchToolSchema2 = external_exports.object({
33971
34103
  name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
33972
34104
  harness: external_exports.enum(LAUNCH_HARNESSES2).describe("What runs it."),
33973
34105
  brief: goalOutcome2.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX2} characters.`),
33974
- approvalQuestionId: external_exports.string().uuid().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first."),
34106
+ approvalQuestionId: external_exports.string().uuid().optional().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first. Required unless this is your own successor, and never with it."),
34107
+ successor: external_exports.literal(true).optional().describe("THIS SESSION'S OWN SUCCESSOR, when your context is at its window or the person told you to hand off: it takes your work and your session ends. No approval is needed for your own replacement, and you can launch only one \u2014 give it a new name."),
33975
34108
  workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
33976
34109
  repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
33977
34110
  model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
@@ -33979,7 +34112,7 @@ var LaunchToolSchema2 = external_exports.object({
33979
34112
  parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
33980
34113
  hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
33981
34114
  }).strict();
33982
- var LAUNCH_DESCRIPTION2 = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. A refusal says why. Returns sessionId, the agent, the brief's goalId and next.";
34115
+ var LAUNCH_DESCRIPTION2 = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. Your own successor needs none: successor: true, with a new name, hands it your work and ends your session. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. Returns sessionId, the agent and the brief's goalId; a refusal says why.";
33983
34116
  var AGENT_TOOLS2 = [
33984
34117
  { name: "configure", title: "Who am I", annotations: READS2, description: CONFIGURE_IDENTITY_DESCRIPTION2, inputSchema: mcpInputSchema2(ConfigureIdentitySchema2) },
33985
34118
  { name: "contact", title: "Contact the person", annotations: SENDS2, description: CONTACT_DESCRIPTION2, inputSchema: CONTACT_SCHEMA2 },
@@ -34868,6 +35001,9 @@ var InboxItemSchema2 = external_exports.object({
34868
35001
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
34869
35002
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
34870
35003
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
35004
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
35005
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
35006
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
34871
35007
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
34872
35008
  * the person to notice it again, and For you puts it first, the latest bump on top
34873
35009
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -35170,6 +35306,59 @@ var ReassignResultSchema2 = external_exports.object({
35170
35306
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
35171
35307
  parentId: external_exports.string().nullable()
35172
35308
  });
35309
+ var TeamSessionSchema2 = external_exports.object({
35310
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
35311
+ * agent's own page opens. The row's identity, so never null. */
35312
+ tokenId: external_exports.string(),
35313
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
35314
+ name: external_exports.string().nullable(),
35315
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
35316
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
35317
+ * session is doing is its step's `goalTitle`. */
35318
+ role: external_exports.string().nullable(),
35319
+ /** Its step under the project: the one it worked most recently. */
35320
+ goalId: external_exports.string(),
35321
+ goalTitle: external_exports.string().nullable(),
35322
+ goalState: external_exports.string(),
35323
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
35324
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
35325
+ * as it advertised it on its heartbeat. */
35326
+ harness: external_exports.string().nullable(),
35327
+ harnessLabel: external_exports.string().nullable(),
35328
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
35329
+ model: external_exports.string().nullable(),
35330
+ mode: external_exports.string().nullable(),
35331
+ workspace: external_exports.string().nullable(),
35332
+ worktree: external_exports.boolean().nullable(),
35333
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
35334
+ lastAt: external_exports.string().nullable(),
35335
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
35336
+ * that has written nothing yet can say for itself. */
35337
+ lastLine: external_exports.string().nullable(),
35338
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
35339
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
35340
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
35341
+ live: external_exports.boolean(),
35342
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
35343
+ * it is taking its work rather than merely still running. */
35344
+ working: external_exports.boolean(),
35345
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
35346
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
35347
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
35348
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
35349
+ waitingOn: external_exports.object({
35350
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
35351
+ text: external_exports.string(),
35352
+ id: external_exports.string().nullable(),
35353
+ at: external_exports.string().nullable()
35354
+ }),
35355
+ /** Its credential was revoked, or the person's end of it was carried out and said so
35356
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
35357
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
35358
+ * reads as a team rather than an empty page. */
35359
+ endedAt: external_exports.string().nullable()
35360
+ });
35361
+ var TeamReadSchema2 = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema2) });
35173
35362
  var LessonStateSchema2 = external_exports.enum(["active", "proposed", "retired"]);
35174
35363
  var LessonViewSchema2 = external_exports.object({
35175
35364
  id: external_exports.string(),
@@ -35779,15 +35968,23 @@ var LIMIT_PREFIXES = [
35779
35968
  var RETRY_MS2 = 15 * 6e4;
35780
35969
  var MARGIN_MS = 6e4;
35781
35970
  var FARTHEST_MS = 8 * 24 * 60 * 6e4;
35971
+ function handsOver(limit) {
35972
+ return limit.kind !== "session";
35973
+ }
35782
35974
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
35783
35975
  function limitIn(text, now) {
35784
35976
  const line = (text ?? "").split("\n").map((l) => l.trim()).reverse().find((l) => LIMIT_PREFIXES.some((p) => l.startsWith(p) || p === "requires usage credits" && l.includes(p)));
35785
35977
  if (!line) return null;
35978
+ const weekly = /\b(weekly|daily)\b/i.test(line);
35786
35979
  const reset = resetOf(line, now);
35787
35980
  if (reset !== null && reset > now && reset - now <= FARTHEST_MS) {
35788
- return { until: reset + MARGIN_MS, resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset) };
35981
+ return {
35982
+ until: reset + MARGIN_MS,
35983
+ resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset),
35984
+ kind: weekly ? "weekly" : "session"
35985
+ };
35789
35986
  }
35790
- return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2) };
35987
+ return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2), kind: weekly ? "weekly" : "credits" };
35791
35988
  }
35792
35989
  function resetOf(line, now) {
35793
35990
  const m = /resets\s+(?:at\s+)?(?:([a-z]{3})[a-z]*\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i.exec(line);
@@ -35962,6 +36159,12 @@ async function askPermission(event, state, rail) {
35962
36159
  ]
35963
36160
  }));
35964
36161
  }
36162
+ function wroteOn(held) {
36163
+ if (held.ownerParticipant) {
36164
+ return held.workedBy === held.ownerParticipant || (held.entries ?? []).some((e) => e.authorParticipant === held.ownerParticipant) || (held.earlier?.omitted ?? 0) > 0;
36165
+ }
36166
+ return held.state !== "ready" || Boolean(held.workedBy) || (held.entries ?? []).some((e) => e.authorParticipant.startsWith("agent:"));
36167
+ }
35965
36168
  async function finish(state, rail, opts) {
35966
36169
  const goal = state.goal;
35967
36170
  if (!goal) return;
@@ -35972,7 +36175,7 @@ async function finish(state, rail, opts) {
35972
36175
  if (!owed) state.goal = void 0;
35973
36176
  return;
35974
36177
  }
35975
- if (!held.openDecisionNeedIds?.length && !owed) {
36178
+ if (!held.openDecisionNeedIds?.length && !owed && wroteOn(held)) {
35976
36179
  await rail.complete(goal.id, held.revision ?? goal.revision);
35977
36180
  state.goal = void 0;
35978
36181
  }
@@ -36014,9 +36217,19 @@ function conversationFull(result) {
36014
36217
  return /prompt is too long/i.test(result ?? "");
36015
36218
  }
36016
36219
  var FULL_NOTICE = "This agent's conversation is full, so it can no longer take a turn. Its session has ended and will not be resumed; its Goals go to the dead-agent handoff.";
36220
+ var wroteForIt = (dossier) => `What it had got to, as far as its own transcript shows, is written in ${dossier} on the computer that ran it: read that before starting this work again.`;
36221
+ function providerFailed(result) {
36222
+ if (!result) return false;
36223
+ if (/"type"\s*:\s*"error"[\s\S]*?"error"\s*:\s*\{/i.test(result)) return true;
36224
+ return result.split("\n").some((raw) => {
36225
+ const line = raw.trim();
36226
+ return /^\{"type"\s*:\s*"error"\b|^\{"error"\s*:\s*\{/i.test(line) || /^(?:API Error|Internal error):\s+\S/i.test(line) || /^(?:HTTP\s+)?[45]\d\d\b.*(?:\berror\b|not_found|invalid_request|unauthorized|forbidden|unsupported)/i.test(line);
36227
+ });
36228
+ }
36017
36229
  async function afterTurn(event, state, rail, opts) {
36018
- if (event.failed) {
36019
- const limit = limitIn(event.result, (opts?.now ?? Date.now)());
36230
+ const now = (opts?.now ?? Date.now)();
36231
+ if (event.failed || providerFailed(event.result) || limitIn(event.result, now) || conversationFull(event.result)) {
36232
+ const limit = limitIn(event.result, now);
36020
36233
  if (limit) {
36021
36234
  state.paused = limit;
36022
36235
  if (state.typed) state.owed = state.typed;
@@ -36027,7 +36240,10 @@ async function afterTurn(event, state, rail, opts) {
36027
36240
  return limit;
36028
36241
  }
36029
36242
  if (conversationFull(event.result)) {
36030
- if (!state.full) await cannotWork(FULL_NOTICE, state, rail, opts);
36243
+ if (!state.full) {
36244
+ const dossier = opts?.dossier?.() ?? null;
36245
+ await cannotWork([FULL_NOTICE, ...dossier ? [wroteForIt(dossier)] : []].join("\n\n"), state, rail, opts);
36246
+ }
36031
36247
  state.full = true;
36032
36248
  return void 0;
36033
36249
  }
@@ -36042,6 +36258,300 @@ ${event.result?.trim() || "No result reported."}`, state, rail, opts);
36042
36258
  return void 0;
36043
36259
  }
36044
36260
 
36261
+ // src/handoff.ts
36262
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync3, openSync as openSync3, readSync as readSync2, fstatSync, closeSync as closeSync3 } from "fs";
36263
+ import { homedir as homedir6 } from "os";
36264
+ import { join as join7 } from "path";
36265
+
36266
+ // src/fill.ts
36267
+ import { closeSync as closeSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
36268
+ import { homedir as homedir5 } from "os";
36269
+ import { join as join6 } from "path";
36270
+ function windowFor(model) {
36271
+ return /\[1m\]/i.test(model ?? "") ? 1e6 : 2e5;
36272
+ }
36273
+ function sizeOf(tail) {
36274
+ const lines2 = tail.split("\n");
36275
+ for (let i = lines2.length - 1; i >= 0; i--) {
36276
+ const line = lines2[i].trim();
36277
+ if (!line.startsWith("{")) continue;
36278
+ let row;
36279
+ try {
36280
+ row = JSON.parse(line);
36281
+ } catch {
36282
+ continue;
36283
+ }
36284
+ if (row.type !== "assistant" || row.isSidechain === true) continue;
36285
+ const usage = row.message?.usage;
36286
+ if (!usage) continue;
36287
+ const count = (key3) => typeof usage[key3] === "number" ? usage[key3] : 0;
36288
+ const size = count("input_tokens") + count("cache_read_input_tokens") + count("cache_creation_input_tokens");
36289
+ if (size > 0) return size;
36290
+ }
36291
+ return null;
36292
+ }
36293
+ var TAIL_BYTES = 256 * 1024;
36294
+ var TAIL_MAX = 8 * 1024 * 1024;
36295
+ function readTail(file, bytes) {
36296
+ const size = statSync3(file).size;
36297
+ const from = Math.max(0, size - bytes);
36298
+ const fd = openSync2(file, "r");
36299
+ try {
36300
+ const buf = Buffer.alloc(Math.min(bytes, size));
36301
+ const n = readSync(fd, buf, 0, buf.length, from);
36302
+ return buf.subarray(0, n).toString("utf8");
36303
+ } finally {
36304
+ closeSync2(fd);
36305
+ }
36306
+ }
36307
+ function fillReader(deps = {}) {
36308
+ const root = deps.projectsDir ?? join6(homedir5(), ".claude", "projects");
36309
+ const list = deps.list ?? ((dir) => readdirSync2(dir));
36310
+ const tail = deps.tail ?? readTail;
36311
+ const found = /* @__PURE__ */ new Map();
36312
+ const find = (session) => {
36313
+ let folders;
36314
+ try {
36315
+ folders = list(root);
36316
+ } catch {
36317
+ return null;
36318
+ }
36319
+ for (const folder of folders) {
36320
+ let files;
36321
+ try {
36322
+ files = list(join6(root, folder));
36323
+ } catch {
36324
+ continue;
36325
+ }
36326
+ if (files.includes(`${session}.jsonl`)) return join6(root, folder, `${session}.jsonl`);
36327
+ }
36328
+ return null;
36329
+ };
36330
+ return {
36331
+ measure: (session, model) => {
36332
+ if (!session) return null;
36333
+ let path = found.get(session);
36334
+ if (!path) {
36335
+ const file = find(session);
36336
+ if (!file) return null;
36337
+ found.set(session, path = file);
36338
+ }
36339
+ let used = null;
36340
+ for (let bytes = TAIL_BYTES; used === null && bytes <= TAIL_MAX; bytes *= 4) {
36341
+ let text;
36342
+ try {
36343
+ text = tail(path, bytes);
36344
+ } catch {
36345
+ return null;
36346
+ }
36347
+ used = sizeOf(text);
36348
+ if (text.length < bytes) break;
36349
+ }
36350
+ if (used === null) return null;
36351
+ const window = windowFor(model);
36352
+ return { used, window, share: used / window };
36353
+ }
36354
+ };
36355
+ }
36356
+ function fillLine(fill) {
36357
+ const percent = Math.round(fill.share * 100);
36358
+ const used = fill.used.toLocaleString("en-US");
36359
+ const window = fill.window.toLocaleString("en-US");
36360
+ return `You are holding ${used} tokens of about ${window} \u2014 ${percent}% of this conversation's window.`;
36361
+ }
36362
+
36363
+ // src/handoff.ts
36364
+ var COMPACTION = "Compact conversation";
36365
+ function compacted(event) {
36366
+ return event.kind === "work" && event.tool.trim().toLowerCase() === COMPACTION.toLowerCase();
36367
+ }
36368
+ function dossierDir() {
36369
+ return join7(homedir6(), ".paigy", "handoff");
36370
+ }
36371
+ function dossierPath(session) {
36372
+ return join7(dossierDir(), `${session.slice(0, 8)}.md`);
36373
+ }
36374
+ function keepContext(dossier, fill) {
36375
+ return [
36376
+ "YOUR CONTEXT JUST TURNED OVER: Claude Code compacted this conversation, so the detail of everything before the summary is gone from it. This is not your retirement \u2014 sessions here compact several times and keep working \u2014 but spend this turn making what you know survivable, because the next turnover takes more of it.",
36377
+ `1. WRITE, or rewrite if it is already there, ${dossier}: everything a session that has never seen this work would need \u2014 what the work is, where each of your Goals stands by id, what is done, what is next, the exact paths, branches, commands, PRs and ids, the traps you learned the hard way, what you are waiting on, and every question open with the person. If a step is mid-flight, say exactly where it stands, down to the uncommitted file and the command about to run. Be generous: this file is what outlives your context.`,
36378
+ `2. NAME IT ON EVERY GOAL you hold: one contact update each, saying your context is in ${dossier} on this computer. Once per Goal \u2014 if you have already said it, rewriting the file is enough.`,
36379
+ // The prose names `launch` and `successor: true` in backticks, so these are quoted strings
36380
+ // joined, never one template literal.
36381
+ "3. THEN CARRY ON with what you were doing \u2014 unless you judge that what you are holding will not fit in what is left of your context. " + (fill ? `${fillLine(fill)} What that leaves is yours to judge: only you know what the rest of this work needs.` : "Nothing here can measure that for you, so judge it from what you can see: how much of the task is left, how many Goals you hold, how long the reading ahead is.") + " If it will not fit, hand off instead, in this order: report once to the person (what you were doing, where it stands, that your successor takes it on), then `launch` your successor with `successor: true` (no approvalQuestionId \u2014 your own replacement needs no approval), a NEW name, the same harness, model and repo, under the same parent Goal, and a brief naming this dossier and what to pick up first. That call gives it every Goal you hold and ends your session, so let it be your last."
36382
+ ].join("\n\n");
36383
+ }
36384
+ var CARRIES_ON = ["agy", "codex", "grok", "claude"];
36385
+ function carriesOn(available, limited) {
36386
+ const ready = available.filter((a) => a.status === "ready" && a.name !== limited);
36387
+ for (const name of CARRIES_ON) {
36388
+ const hit = ready.find((a) => a.name === name);
36389
+ if (hit) return hit;
36390
+ }
36391
+ return null;
36392
+ }
36393
+ function successorName(name, label) {
36394
+ return `${name} (${label})`.slice(0, 60);
36395
+ }
36396
+ function creditsBrief(opts) {
36397
+ return [
36398
+ `Carry on ${opts.name}'s work: a usage limit stopped it until ${opts.resets}, so its open Goals are now yours.`,
36399
+ opts.dossier ? `Its context is in ${opts.dossier} on this computer \u2014 read that file first, then the Goals you have just been given.` : "Nothing of its context could be written down, so read the Goals you have just been given and what was last said on them.",
36400
+ "Report on those Goals as you go."
36401
+ ].join(" ");
36402
+ }
36403
+ function projectSlug(cwd) {
36404
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
36405
+ }
36406
+ function transcriptOf(cwd, session, home = homedir6()) {
36407
+ const projects = join7(home, ".claude", "projects");
36408
+ const slug = projectSlug(cwd);
36409
+ const exact = join7(projects, slug, `${session}.jsonl`);
36410
+ if (existsSync4(exact)) return exact;
36411
+ let dirs = [];
36412
+ try {
36413
+ dirs = readdirSync3(projects).filter((d) => d.startsWith(slug));
36414
+ } catch {
36415
+ return null;
36416
+ }
36417
+ for (const dir of dirs) {
36418
+ const candidate = join7(projects, dir, `${session}.jsonl`);
36419
+ if (existsSync4(candidate)) return candidate;
36420
+ }
36421
+ let all = [];
36422
+ try {
36423
+ all = readdirSync3(projects);
36424
+ } catch {
36425
+ return null;
36426
+ }
36427
+ for (const dir of all) {
36428
+ const candidate = join7(projects, dir, `${session}.jsonl`);
36429
+ if (existsSync4(candidate)) return candidate;
36430
+ }
36431
+ return null;
36432
+ }
36433
+ var TAIL_BYTES2 = 2e6;
36434
+ var KEEP = { said: 6, wrote: 4, files: 20, commands: 12 };
36435
+ var COMMAND = 200;
36436
+ function tailOf(path, bytes = TAIL_BYTES2) {
36437
+ const fd = openSync3(path, "r");
36438
+ try {
36439
+ const size = fstatSync(fd).size;
36440
+ const from = Math.max(0, size - bytes);
36441
+ const buffer = Buffer.alloc(Math.min(size, bytes));
36442
+ readSync2(fd, buffer, 0, buffer.length, from);
36443
+ const text = buffer.toString("utf8");
36444
+ return from > 0 ? text.slice(text.indexOf("\n") + 1) : text;
36445
+ } finally {
36446
+ closeSync3(fd);
36447
+ }
36448
+ }
36449
+ var SCAFFOLDING = /^\s*<(task-notification|system-reminder|local-command-stdout|command-message|command-name)\b/;
36450
+ function words(content) {
36451
+ if (typeof content === "string") return content;
36452
+ if (!Array.isArray(content)) return "";
36453
+ return content.filter((b) => b.type === "text" && b.text).map((b) => b.text.trim()).join("\n\n");
36454
+ }
36455
+ function readTail2(tail) {
36456
+ const todos = [];
36457
+ const said = [];
36458
+ const wrote = [];
36459
+ const files = [];
36460
+ const commands = [];
36461
+ for (const raw of tail.split("\n")) {
36462
+ if (!raw.trim()) continue;
36463
+ let line;
36464
+ try {
36465
+ line = JSON.parse(raw);
36466
+ } catch {
36467
+ continue;
36468
+ }
36469
+ const content = line.message?.content;
36470
+ if (line.type === "user") {
36471
+ const text2 = words(content);
36472
+ if (text2 && !SCAFFOLDING.test(text2)) said.push(text2);
36473
+ continue;
36474
+ }
36475
+ if (line.type !== "assistant" || !Array.isArray(content)) continue;
36476
+ const text = words(content);
36477
+ if (text) wrote.push(text);
36478
+ for (const block2 of content) {
36479
+ if (block2.type !== "tool_use" || !block2.input) continue;
36480
+ const input = block2.input;
36481
+ if (block2.name === "TodoWrite" && Array.isArray(input["todos"])) {
36482
+ todos.length = 0;
36483
+ todos.push(...input["todos"]);
36484
+ }
36485
+ const file = input["file_path"];
36486
+ if (typeof file === "string" && !files.includes(file)) files.push(file);
36487
+ const command = input["command"];
36488
+ if (typeof command === "string") commands.push(command.split("\n")[0].trim().slice(0, COMMAND));
36489
+ }
36490
+ }
36491
+ return {
36492
+ todos,
36493
+ said: said.slice(-KEEP.said),
36494
+ wrote: wrote.slice(-KEEP.wrote),
36495
+ files: files.slice(-KEEP.files),
36496
+ commands: commands.slice(-KEEP.commands)
36497
+ };
36498
+ }
36499
+ var QUOTE = 1200;
36500
+ var quote = (text) => text.length > QUOTE ? `${text.slice(0, QUOTE)}\u2026` : text;
36501
+ function dossierFrom(tail, meta) {
36502
+ const read3 = readTail2(tail);
36503
+ const at = (meta.at ?? /* @__PURE__ */ new Date()).toISOString();
36504
+ const open = read3.todos.filter((t) => t.status !== "completed");
36505
+ const done = read3.todos.filter((t) => t.status === "completed");
36506
+ const out = [
36507
+ `# ${meta.name} \u2014 handoff`,
36508
+ `${meta.why} The session never wrote its own account of this work, so this is what its transcript's last ${Math.round(TAIL_BYTES2 / 1e6)} MB still show. Read the Goals it held for what the work is FOR; this says where it had got to.`,
36509
+ `- session: ${meta.session}`,
36510
+ `- workspace: ${meta.cwd}`,
36511
+ `- written: ${at}`
36512
+ ];
36513
+ if (open.length || done.length) {
36514
+ out.push("## Its own to-do list, as it last stood");
36515
+ for (const t of open) out.push(`- [ ] ${t.content ?? ""}${t.status && t.status !== "pending" ? ` (${t.status})` : ""}`);
36516
+ for (const t of done) out.push(`- [x] ${t.content ?? ""}`);
36517
+ }
36518
+ if (read3.said.length) {
36519
+ out.push("## The last words typed into it");
36520
+ for (const s of read3.said) out.push(`> ${quote(s).split("\n").join("\n> ")}`);
36521
+ }
36522
+ if (read3.wrote.length) {
36523
+ out.push("## The last it said");
36524
+ for (const w of read3.wrote) out.push(`> ${quote(w).split("\n").join("\n> ")}`);
36525
+ }
36526
+ if (read3.files.length) {
36527
+ out.push("## Files it had open or changed");
36528
+ for (const f of read3.files) out.push(`- ${f}`);
36529
+ }
36530
+ if (read3.commands.length) {
36531
+ out.push("## The last commands it ran");
36532
+ for (const c of read3.commands) out.push(`- \`${c}\``);
36533
+ }
36534
+ return `${out.join("\n\n")}
36535
+ `;
36536
+ }
36537
+ function writeDossier(path, body) {
36538
+ mkdirSync3(join7(path, ".."), { recursive: true });
36539
+ writeFileSync3(path, body, "utf8");
36540
+ return path;
36541
+ }
36542
+ function dossierForWall(meta) {
36543
+ try {
36544
+ const path = dossierPath(meta.session);
36545
+ if (existsSync4(path)) return path;
36546
+ const transcript = transcriptOf(meta.cwd, meta.session);
36547
+ if (!transcript) return null;
36548
+ const body = dossierFrom(tailOf(transcript), meta);
36549
+ return writeDossier(path, body);
36550
+ } catch {
36551
+ return null;
36552
+ }
36553
+ }
36554
+
36045
36555
  // src/paigy/conversation.ts
36046
36556
  var HARNESS_INSTRUCTION = "You are running as an unattended background harness agent; your user reaches you through Paigy and is not at this terminal. Nothing wakes you after your turn ends but the person, so wait on CI or a deploy inside the turn. The person never sees your turn's final message, and it is not kept: report where the work stands with a contact update on this Goal (one the person does not need yet is kept as its progress). Anything the person needs \u2014 a question, a result, a blocker \u2014 you send through Paigy's contact tool, once; the harness sends nothing on your behalf. What the person says later arrives with the Goal it was said on named in front of it; answer them on that Goal (its id as the contact's goalId).";
36047
36557
  var SAFETY_MS = 6e4;
@@ -36080,7 +36590,7 @@ var BEAT_REPORT_MS = 10 * 6e4;
36080
36590
  var ended = (state) => state === "done" || state === "cancelled";
36081
36591
  function unheard(brief, state, since = null, after = -1, reviewSince, gathered) {
36082
36592
  const seen = state.seen ??= /* @__PURE__ */ new Set();
36083
- const words = [];
36593
+ const words2 = [];
36084
36594
  const pendingAt = reviewSince ? Date.parse(reviewSince) : null;
36085
36595
  for (const [i, e] of (brief.entries ?? []).entries()) {
36086
36596
  if (seen.has(e.entryId) || !e.authorParticipant.startsWith("human:")) continue;
@@ -36097,7 +36607,7 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
36097
36607
  seen.add(e.entryId);
36098
36608
  const text = entryWords(e).trim();
36099
36609
  if (text) {
36100
- words.push(text);
36610
+ words2.push(text);
36101
36611
  gathered?.add(e.entryId);
36102
36612
  }
36103
36613
  }
@@ -36105,9 +36615,9 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
36105
36615
  const key3 = `answer:${answer.decisionNeedId}`;
36106
36616
  if (seen.has(key3) || Date.parse(answer.acceptedAt) < pendingAt) continue;
36107
36617
  seen.add(key3);
36108
- words.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
36618
+ words2.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
36109
36619
  }
36110
- return words;
36620
+ return words2;
36111
36621
  }
36112
36622
  function sinceTheWork(brief) {
36113
36623
  const entries = brief.entries ?? [];
@@ -36230,9 +36740,9 @@ async function hear(session, state, rail, held, opts, waiting) {
36230
36740
  const log = opts?.log;
36231
36741
  const { heard, listed, direct } = await gather(state, rail, held, waiting, log);
36232
36742
  const said = heard.filter(says);
36233
- const words = [...direct.flatMap((d) => d.words), ...said.map(block)];
36234
- if (words.length) {
36235
- const text = words.join("\n\n");
36743
+ const words2 = [...direct.flatMap((d) => d.words), ...said.map(block)];
36744
+ if (words2.length) {
36745
+ const text = words2.join("\n\n");
36236
36746
  try {
36237
36747
  await send2(session, state, text);
36238
36748
  } catch (error) {
@@ -36263,7 +36773,7 @@ async function note(state, rail, held, inbox, how, waiting) {
36263
36773
  const said = heard.filter(says);
36264
36774
  const parts = [...direct.flatMap((d) => d.words), ...said.map(block)];
36265
36775
  if (!parts.length) return 0;
36266
- const words = parts.join("\n\n");
36776
+ const words2 = parts.join("\n\n");
36267
36777
  const goals = said.map((h) => h.goalId);
36268
36778
  const assigned = given(said);
36269
36779
  if (how.tally) how.tally.announced += assigned.length;
@@ -36271,13 +36781,13 @@ async function note(state, rail, held, inbox, how, waiting) {
36271
36781
  try {
36272
36782
  name = inbox.put(`${NOTED}
36273
36783
 
36274
- ${words}`);
36784
+ ${words2}`);
36275
36785
  how.log?.(`\u25B9 noted mid-turn: ${short(goals)}`);
36276
36786
  if (assigned.length) how.log?.(`\u25B8 announced assigned ${short(assigned)} (via hook)`);
36277
36787
  } catch (error) {
36278
36788
  how.log?.(`\u26A0 could not note mid-turn (${error.message}): ${short(goals)} wait for the turn's end`);
36279
36789
  }
36280
- (state.noted ??= []).push({ name, goals, words, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
36790
+ (state.noted ??= []).push({ name, goals, words: words2, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
36281
36791
  for (const d of direct) for (const id3 of d.entryIds) (state.seen ??= /* @__PURE__ */ new Set()).add(id3);
36282
36792
  return 1;
36283
36793
  }
@@ -36344,6 +36854,24 @@ async function step(session, state, rail, opts) {
36344
36854
  state.paused = void 0;
36345
36855
  state.carryOn = true;
36346
36856
  }
36857
+ if (state.handoff && !state.handoff.said && !state.asks?.size) {
36858
+ const words2 = keepContext(state.handoff.dossier, opts?.fill?.() ?? void 0);
36859
+ if (state.resting) {
36860
+ await send2(session, state, words2);
36861
+ state.handoff.said = true;
36862
+ opts?.log?.(`\u25B8 context turned over: told to write it down and judge whether to hand off (dossier ${state.handoff.dossier})`);
36863
+ return;
36864
+ }
36865
+ if (opts?.inbox && !state.handoff.noted) {
36866
+ try {
36867
+ opts.inbox.put(words2);
36868
+ state.handoff.noted = true;
36869
+ opts.log?.("\u25B9 context turned over: the note is in its inbox for this turn's next tool call");
36870
+ } catch (error) {
36871
+ opts.log?.(`\u26A0 could not note the turnover (${error.message}): it is typed in when the turn ends`);
36872
+ }
36873
+ }
36874
+ }
36347
36875
  await look(session, state, rail, opts);
36348
36876
  if (state.carryOn && state.resting && !state.asks?.size) await send2(session, state, "");
36349
36877
  }
@@ -36418,10 +36946,10 @@ async function look(session, state, rail, opts) {
36418
36946
  await hear(session, state, rail, brief, { ...opts?.log ? { log: opts.log } : {}, ...opts?.tally ? { tally: opts.tally } : {} });
36419
36947
  }
36420
36948
  async function send2(session, state, text) {
36421
- let words = text;
36949
+ let words2 = text;
36422
36950
  if (state.carryOn) {
36423
36951
  const owed = state.owed;
36424
- words = [owed, text].filter(Boolean).join("\n\n");
36952
+ words2 = [owed, text].filter(Boolean).join("\n\n");
36425
36953
  text = [CARRY_ON, ...owed ? [OWED, owed] : [], text].filter(Boolean).join("\n\n");
36426
36954
  }
36427
36955
  const resting = state.resting;
@@ -36432,7 +36960,7 @@ async function send2(session, state, text) {
36432
36960
  state.resting = resting;
36433
36961
  throw error;
36434
36962
  }
36435
- state.typed = words || void 0;
36963
+ state.typed = words2 || void 0;
36436
36964
  if (state.carryOn) {
36437
36965
  state.carryOn = false;
36438
36966
  state.carriedOn = true;
@@ -36448,6 +36976,7 @@ async function pump(session, state, rail, opts) {
36448
36976
  ...opts.initialPrompt ? { initialPrompt: opts.initialPrompt } : {},
36449
36977
  ...opts.log ? { log: opts.log } : {},
36450
36978
  ...opts.inbox ? { inbox: opts.inbox } : {},
36979
+ ...opts.fill ? { fill: opts.fill } : {},
36451
36980
  now,
36452
36981
  tally
36453
36982
  };
@@ -36485,6 +37014,10 @@ function runHarness(opts) {
36485
37014
  const clock4 = beat();
36486
37015
  let session = null;
36487
37016
  const speaksAs = opts.session ?? opts.resume ?? sessionId();
37017
+ let conversation;
37018
+ let model;
37019
+ const filled = fillReader();
37020
+ const fill = () => filled.measure(conversation, model ?? opts.model);
36488
37021
  const instance = randomUUID4();
36489
37022
  const rail = railFor({ token: opts.token, reach: reachAs(speaksAs, instance) });
36490
37023
  let inbox;
@@ -36496,6 +37029,36 @@ function runHarness(opts) {
36496
37029
  }
36497
37030
  }
36498
37031
  const name = opts.name ?? "The agent";
37032
+ let handedOn = false;
37033
+ async function handOnCredits(limit) {
37034
+ if (handedOn) return;
37035
+ if (!handsOver(limit)) return;
37036
+ handedOn = true;
37037
+ const dossier = dossierForWall({
37038
+ name,
37039
+ session: conversation ?? speaksAs,
37040
+ cwd: opts.cwd,
37041
+ why: `A usage limit stopped this session until ${limit.resets}, so its work was handed on.`
37042
+ });
37043
+ const to = carriesOn(detectAll(), opts.harness);
37044
+ if (!to) {
37045
+ opts.log(`\u23F8 nothing else here can take this work, so it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
37046
+ return;
37047
+ }
37048
+ try {
37049
+ const launched = await launchSession({
37050
+ name: successorName(name, to.label),
37051
+ harness: to.name,
37052
+ brief: creditsBrief({ name, dossier, resets: limit.resets }),
37053
+ workspace: opts.cwd,
37054
+ mode: opts.mode,
37055
+ successor: true
37056
+ }, { ...opts.token ? { token: opts.token } : {} });
37057
+ opts.log(`\u25B6 out of credits until ${limit.resets}: ${to.label} session ${launched.sessionId} takes this work on${dossier ? `, with its context in ${dossier}` : ""}`);
37058
+ } catch (error) {
37059
+ opts.log(`\u26A0 could not hand this work on (${error.message}): it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
37060
+ }
37061
+ }
36499
37062
  function runningAgain() {
36500
37063
  state.carriedOn = false;
36501
37064
  opts.log("\u25B6 running again after the limit");
@@ -36528,6 +37091,11 @@ ${event.message}`, state, rail, { log: opts.log });
36528
37091
  }
36529
37092
  if (event.kind === "work") {
36530
37093
  if (state.carriedOn) runningAgain();
37094
+ if (compacted(event)) {
37095
+ state.handoff = { dossier: dossierPath(conversation ?? speaksAs) };
37096
+ opts.log(`\u25C6 ${name}'s context turned over \u2014 writing it to ${state.handoff.dossier}`);
37097
+ clock4.nudge("wake");
37098
+ }
36531
37099
  opts.log(`\u2699 ${event.tool}${event.note ? ` \u2014 ${event.note.split("\n")[0] ?? ""}` : ""}`);
36532
37100
  tail = pushWork(tail, workLine(event));
36533
37101
  return;
@@ -36535,9 +37103,15 @@ ${event.message}`, state, rail, { log: opts.log });
36535
37103
  if (event.kind === "turn") opts.log(`${event.role}: ${event.text.split("\n")[0] ?? ""}`);
36536
37104
  if (event.kind === "idle") {
36537
37105
  tail = [];
37106
+ conversation = event.session ?? conversation;
37107
+ model = event.model ?? model;
36538
37108
  const carried = state.carriedOn && !event.failed;
36539
- if (await afterTurn(event, state, rail, { log: opts.log })) LIMITS.paused(name, Date.now());
36540
- else if (state.full) {
37109
+ const dossier = () => dossierForWall({ name, session: conversation ?? speaksAs, cwd: opts.cwd, why: 'This session reached the wall: every prompt in it came back "Prompt is too long".' });
37110
+ const limit = await afterTurn(event, state, rail, { log: opts.log, dossier });
37111
+ if (limit) {
37112
+ LIMITS.paused(name, Date.now());
37113
+ await handOnCredits(limit);
37114
+ } else if (state.full) {
36541
37115
  opts.log(`\u25A0 ${name}'s conversation is full \u2014 ending this run; it will not be resumed`);
36542
37116
  opts.onFull?.(speaksAs);
36543
37117
  stop2();
@@ -36563,7 +37137,7 @@ ${event.message}`, state, rail, { log: opts.log });
36563
37137
  },
36564
37138
  onEvent: (event) => void handle3(event).catch((err) => opts.log(`\u26A0 ${err.message}`))
36565
37139
  });
36566
- void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, ...inbox ? { inbox } : {} }).catch(
37140
+ void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, fill, ...inbox ? { inbox } : {} }).catch(
36567
37141
  (e) => opts.log(`\u26A0 conversation loop stopped: ${e.message}`)
36568
37142
  );
36569
37143
  opts.log(`\u25B6 started ${opts.harness} in ${opts.cwd} (${opts.mode} mode)`);
@@ -36587,11 +37161,11 @@ ${event.message}`, state, rail, { log: opts.log });
36587
37161
  }
36588
37162
 
36589
37163
  // src/host.ts
36590
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
37164
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
36591
37165
  import { execSync } from "child_process";
36592
37166
  import { randomBytes } from "crypto";
36593
- import { homedir as homedir8 } from "os";
36594
- import { join as join10 } from "path";
37167
+ import { homedir as homedir10 } from "os";
37168
+ import { join as join12 } from "path";
36595
37169
 
36596
37170
  // src/ago.ts
36597
37171
  var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
@@ -36606,11 +37180,11 @@ function ago(iso, now) {
36606
37180
  }
36607
37181
 
36608
37182
  // src/workspaces.ts
36609
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
36610
- import { dirname as dirname2, join as join6, resolve as resolve2 } from "path";
36611
- import { homedir as homedir5 } from "os";
37183
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync4, writeFileSync as writeFileSync4 } from "fs";
37184
+ import { dirname as dirname2, join as join8, resolve as resolve2 } from "path";
37185
+ import { homedir as homedir7 } from "os";
36612
37186
  function workspacesFile() {
36613
- return join6(homedir5(), ".paigy", "workspaces.json");
37187
+ return join8(homedir7(), ".paigy", "workspaces.json");
36614
37188
  }
36615
37189
  function listWorkspaces(deps) {
36616
37190
  try {
@@ -36621,30 +37195,30 @@ function listWorkspaces(deps) {
36621
37195
  }
36622
37196
  }
36623
37197
  function addWorkspace(dir, deps) {
36624
- const next = resolve2(dir.replace(/^~(?=$|\/)/, homedir5()));
37198
+ const next = resolve2(dir.replace(/^~(?=$|\/)/, homedir7()));
36625
37199
  const all = listWorkspaces(deps);
36626
37200
  if (!all.includes(next)) {
36627
37201
  all.push(next);
36628
- mkdirSync3(dirname2(deps.file), { recursive: true });
36629
- writeFileSync3(deps.file, JSON.stringify(all, null, 2));
37202
+ mkdirSync4(dirname2(deps.file), { recursive: true });
37203
+ writeFileSync4(deps.file, JSON.stringify(all, null, 2));
36630
37204
  }
36631
37205
  return all;
36632
37206
  }
36633
37207
  function allowed(cwd, deps) {
36634
- const target = resolve2(cwd.replace(/^~(?=$|\/)/, homedir5()));
37208
+ const target = resolve2(cwd.replace(/^~(?=$|\/)/, homedir7()));
36635
37209
  return listWorkspaces(deps).some((w) => target === w || target.startsWith(`${w}/`));
36636
37210
  }
36637
37211
  function resolveWakeDir(pinned, deps) {
36638
37212
  if (pinned && allowed(pinned, deps)) {
36639
- const dir = resolve2(pinned.replace(/^~(?=$|\/)/, homedir5()));
36640
- if ((deps.exists ?? existsSync4)(dir)) return dir;
37213
+ const dir = resolve2(pinned.replace(/^~(?=$|\/)/, homedir7()));
37214
+ if ((deps.exists ?? existsSync5)(dir)) return dir;
36641
37215
  }
36642
37216
  return listWorkspaces(deps)[0];
36643
37217
  }
36644
37218
  function originOf(dir) {
36645
37219
  try {
36646
- if (!statSync3(join6(dir, ".git")).isDirectory()) return null;
36647
- const config = readFileSync4(join6(dir, ".git", "config"), "utf8");
37220
+ if (!statSync4(join8(dir, ".git")).isDirectory()) return null;
37221
+ const config = readFileSync4(join8(dir, ".git", "config"), "utf8");
36648
37222
  const section = config.split(/^\[/m).find((s) => /^remote\s+"origin"\]/.test(s));
36649
37223
  return section?.match(/^\s*url\s*=\s*(.+)$/m)?.[1]?.trim() ?? null;
36650
37224
  } catch {
@@ -36660,12 +37234,12 @@ function listRepos(deps) {
36660
37234
  if (own) repos.push({ path: root, remote: own });
36661
37235
  let children = [];
36662
37236
  try {
36663
- children = readdirSync2(root, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name).sort().slice(0, MAX_CHILDREN);
37237
+ children = readdirSync4(root, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name).sort().slice(0, MAX_CHILDREN);
36664
37238
  } catch {
36665
37239
  }
36666
37240
  for (const name of children) {
36667
37241
  if (repos.length >= MAX_REPOS) return repos;
36668
- const path = join6(root, name);
37242
+ const path = join8(root, name);
36669
37243
  const remote = originOf(path);
36670
37244
  if (remote) repos.push({ path, remote });
36671
37245
  }
@@ -36675,9 +37249,9 @@ function listRepos(deps) {
36675
37249
 
36676
37250
  // src/holder.ts
36677
37251
  import { execFileSync as execFileSync2 } from "child_process";
36678
- import { readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
36679
- import { homedir as homedir6 } from "os";
36680
- import { join as join7 } from "path";
37252
+ import { readFileSync as readFileSync5, readdirSync as readdirSync5 } from "fs";
37253
+ import { homedir as homedir8 } from "os";
37254
+ import { join as join9 } from "path";
36681
37255
  function isAlive(pid) {
36682
37256
  try {
36683
37257
  process.kill(pid, 0);
@@ -36715,8 +37289,8 @@ function proven(pid, procStart, deps) {
36715
37289
  });
36716
37290
  }
36717
37291
  function localHolderPids(deps = {}) {
36718
- const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude"), "sessions");
36719
- const list = deps.list ?? ((d) => readdirSync3(d));
37292
+ const dir = deps.dir ?? join9(process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir8(), ".claude"), "sessions");
37293
+ const list = deps.list ?? ((d) => readdirSync5(d));
36720
37294
  const read3 = deps.read ?? ((f) => readFileSync5(f, "utf8"));
36721
37295
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
36722
37296
  const held = /* @__PURE__ */ new Map();
@@ -36730,7 +37304,7 @@ function localHolderPids(deps = {}) {
36730
37304
  if (!/^\d+\.json$/.test(file)) continue;
36731
37305
  let row;
36732
37306
  try {
36733
- row = parseSessionRecord(read3(join7(dir, file)));
37307
+ row = parseSessionRecord(read3(join9(dir, file)));
36734
37308
  } catch {
36735
37309
  continue;
36736
37310
  }
@@ -36764,8 +37338,8 @@ function descendsFrom(pid, ancestor, parent = psParent) {
36764
37338
  return false;
36765
37339
  }
36766
37340
  function localHolders(deps = {}) {
36767
- const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude"), "sessions");
36768
- const list = deps.list ?? ((d) => readdirSync3(d));
37341
+ const dir = deps.dir ?? join9(process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir8(), ".claude"), "sessions");
37342
+ const list = deps.list ?? ((d) => readdirSync5(d));
36769
37343
  const read3 = deps.read ?? ((f) => readFileSync5(f, "utf8"));
36770
37344
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
36771
37345
  const held = /* @__PURE__ */ new Map();
@@ -36779,7 +37353,7 @@ function localHolders(deps = {}) {
36779
37353
  if (!/^\d+\.json$/.test(file)) continue;
36780
37354
  let row;
36781
37355
  try {
36782
- row = parseSessionRecord(read3(join7(dir, file)));
37356
+ row = parseSessionRecord(read3(join9(dir, file)));
36783
37357
  } catch {
36784
37358
  continue;
36785
37359
  }
@@ -36856,26 +37430,26 @@ async function endSession(end, deps) {
36856
37430
  }
36857
37431
 
36858
37432
  // src/owner.ts
36859
- import { closeSync as closeSync2, openSync as openSync2, readSync, readdirSync as readdirSync4 } from "fs";
36860
- import { homedir as homedir7 } from "os";
36861
- import { join as join8 } from "path";
37433
+ import { closeSync as closeSync4, openSync as openSync4, readSync as readSync3, readdirSync as readdirSync6 } from "fs";
37434
+ import { homedir as homedir9 } from "os";
37435
+ import { join as join10 } from "path";
36862
37436
  var HEAD_BYTES = 64e3;
36863
37437
  function readHead(file) {
36864
- const fd = openSync2(file, "r");
37438
+ const fd = openSync4(file, "r");
36865
37439
  try {
36866
37440
  const buf = Buffer.alloc(HEAD_BYTES);
36867
- const n = readSync(fd, buf, 0, HEAD_BYTES, 0);
37441
+ const n = readSync3(fd, buf, 0, HEAD_BYTES, 0);
36868
37442
  return buf.subarray(0, n).toString("utf8");
36869
37443
  } finally {
36870
- closeSync2(fd);
37444
+ closeSync4(fd);
36871
37445
  }
36872
37446
  }
36873
37447
  function ownerSession(slot, deps = {}) {
36874
37448
  const m = /^session:([0-9a-f]{8})$/.exec(slot);
36875
37449
  if (!m) return null;
36876
37450
  const prefix = m[1];
36877
- const root = deps.projectsDir ?? join8(homedir7(), ".claude", "projects");
36878
- const list = deps.list ?? ((dir) => readdirSync4(dir));
37451
+ const root = deps.projectsDir ?? join10(homedir9(), ".claude", "projects");
37452
+ const list = deps.list ?? ((dir) => readdirSync6(dir));
36879
37453
  const head2 = deps.head ?? readHead;
36880
37454
  let folders;
36881
37455
  try {
@@ -36886,7 +37460,7 @@ function ownerSession(slot, deps = {}) {
36886
37460
  for (const folder of folders) {
36887
37461
  let files;
36888
37462
  try {
36889
- files = list(join8(root, folder));
37463
+ files = list(join10(root, folder));
36890
37464
  } catch {
36891
37465
  continue;
36892
37466
  }
@@ -36894,7 +37468,7 @@ function ownerSession(slot, deps = {}) {
36894
37468
  if (!file) continue;
36895
37469
  let text;
36896
37470
  try {
36897
- text = head2(join8(root, folder, file));
37471
+ text = head2(join10(root, folder, file));
36898
37472
  } catch {
36899
37473
  continue;
36900
37474
  }
@@ -36914,7 +37488,7 @@ function ownerSession(slot, deps = {}) {
36914
37488
  // src/update.ts
36915
37489
  import { execFile } from "child_process";
36916
37490
  import { createRequire } from "module";
36917
- import { dirname as dirname3, join as join9 } from "path";
37491
+ import { dirname as dirname3, join as join11 } from "path";
36918
37492
  import { promisify } from "util";
36919
37493
  var SERVICE_LABEL = "ai.paigy.harness";
36920
37494
  var VERSION = createRequire(import.meta.url)("../package.json").version;
@@ -36941,7 +37515,7 @@ async function latestVersion() {
36941
37515
  }
36942
37516
  async function install(version) {
36943
37517
  const bin = dirname3(process.execPath);
36944
- await promisify(execFile)(join9(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
37518
+ await promisify(execFile)(join11(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
36945
37519
  env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}`, npm_config_update_notifier: "false" },
36946
37520
  timeout: 5 * 6e4
36947
37521
  });
@@ -36992,7 +37566,7 @@ function selfUpdater(deps) {
36992
37566
  }
36993
37567
 
36994
37568
  // src/host.ts
36995
- var HOST_FILE = join10(homedir8(), ".paigy", "host.json");
37569
+ var HOST_FILE = join12(homedir10(), ".paigy", "host.json");
36996
37570
  function wakeHarness(slot, saved, claudeTranscript) {
36997
37571
  if (slot === "Desktop") return void 0;
36998
37572
  if (saved !== null) return saved === "agy" || saved === "codex" || saved === "claude" || saved === "grok" ? saved : void 0;
@@ -37420,7 +37994,7 @@ function startHost(opts) {
37420
37994
  };
37421
37995
  const publish = () => {
37422
37996
  try {
37423
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
37997
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
37424
37998
  } catch {
37425
37999
  }
37426
38000
  };
@@ -37487,7 +38061,7 @@ function startHost(opts) {
37487
38061
  streamActivity();
37488
38062
  clearInterval(activityTick);
37489
38063
  try {
37490
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
38064
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
37491
38065
  } catch {
37492
38066
  }
37493
38067
  }
@@ -37592,11 +38166,11 @@ async function pairThisMachine() {
37592
38166
  }
37593
38167
  }
37594
38168
  function forwardCodexThreadId() {
37595
- const cfg = join11(process.env.CODEX_HOME || join11(homedir9(), ".codex"), "config.toml");
37596
- if (!existsSync5(cfg)) return;
38169
+ const cfg = join13(process.env.CODEX_HOME || join13(homedir11(), ".codex"), "config.toml");
38170
+ if (!existsSync6(cfg)) return;
37597
38171
  const text = readFileSync7(cfg, "utf8");
37598
38172
  const updated = withCodexEnv(text);
37599
- if (updated !== null && updated !== text) writeFileSync5(cfg, updated);
38173
+ if (updated !== null && updated !== text) writeFileSync6(cfg, updated);
37600
38174
  }
37601
38175
  async function main() {
37602
38176
  setClient(`harness@${VERSION}`);
@@ -37676,8 +38250,8 @@ async function main() {
37676
38250
  const wsDeps = { file: workspacesFile() };
37677
38251
  for (const dir of parsed.grant) addWorkspace(dir, wsDeps);
37678
38252
  if (!listWorkspaces(wsDeps).length) {
37679
- const guess = join11(homedir9(), "projects");
37680
- if (existsSync5(guess)) {
38253
+ const guess = join13(homedir11(), "projects");
38254
+ if (existsSync6(guess)) {
37681
38255
  addWorkspace(guess, wsDeps);
37682
38256
  console.log(`\u2713 workspace granted: ${guess} (change with --grant DIR)`);
37683
38257
  } else console.log("no workspace granted yet \u2014 grant one with: paigy-harness host --grant DIR");
@@ -37709,12 +38283,12 @@ async function main() {
37709
38283
  }
37710
38284
  }
37711
38285
  try {
37712
- const settings = join11(homedir9(), ".claude", "settings.json");
37713
- if (which("claude") && existsSync5(settings)) {
38286
+ const settings = join13(homedir11(), ".claude", "settings.json");
38287
+ if (which("claude") && existsSync6(settings)) {
37714
38288
  const cfg = JSON.parse(readFileSync7(settings, "utf8"));
37715
38289
  if (!cfg["statusLine"]) {
37716
38290
  cfg["statusLine"] = { type: "command", command: "npx -y -p @paigy/mcp@latest paigy-statusline" };
37717
- writeFileSync5(settings, JSON.stringify(cfg, null, 2));
38291
+ writeFileSync6(settings, JSON.stringify(cfg, null, 2));
37718
38292
  console.log("\u2713 statusline wired");
37719
38293
  }
37720
38294
  }
@@ -37767,14 +38341,14 @@ async function main() {
37767
38341
  <key>SoftResourceLimits</key><dict>
37768
38342
  <key>NumberOfFiles</key><integer>65536</integer>
37769
38343
  </dict>
37770
- <key>StandardOutPath</key><string>${join11(homedir9(), ".paigy", "host.log")}</string>
37771
- <key>StandardErrorPath</key><string>${join11(homedir9(), ".paigy", "host.log")}</string>
38344
+ <key>StandardOutPath</key><string>${join13(homedir11(), ".paigy", "host.log")}</string>
38345
+ <key>StandardErrorPath</key><string>${join13(homedir11(), ".paigy", "host.log")}</string>
37772
38346
  </dict></plist>
37773
38347
  `;
37774
- const dir = join11(homedir9(), "Library", "LaunchAgents");
37775
- mkdirSync4(dir, { recursive: true });
37776
- const path = join11(dir, `${SERVICE_LABEL}.plist`);
37777
- writeFileSync5(path, plist);
38348
+ const dir = join13(homedir11(), "Library", "LaunchAgents");
38349
+ mkdirSync5(dir, { recursive: true });
38350
+ const path = join13(dir, `${SERVICE_LABEL}.plist`);
38351
+ writeFileSync6(path, plist);
37778
38352
  execSync2(`launchctl unload ${path} 2>/dev/null; launchctl load ${path}`, { shell: "/bin/sh" });
37779
38353
  console.log(`\u2713 host installed as a login service (${path}) \u2014 logs at ~/.paigy/host.log`);
37780
38354
  console.log(" file limit raised to 65536 for the host and every session it spawns");
@@ -37796,7 +38370,7 @@ async function main() {
37796
38370
  process.exit(1);
37797
38371
  }
37798
38372
  const name = slotName(slot) ?? slot;
37799
- console.log(`\u2713 ${name} is handed off \u2014 wakes in ${cwd.replace(homedir9(), "~")}`);
38373
+ console.log(`\u2713 ${name} is handed off \u2014 wakes in ${cwd.replace(homedir11(), "~")}`);
37800
38374
  if (!allowed(cwd, { file: workspacesFile() })) {
37801
38375
  console.log(` \u26A0 that folder isn't on the allow-list, so wakes will land in the first granted`);
37802
38376
  console.log(` workspace instead \u2014 add it in the desktop app, or: paigy-harness host --grant ${cwd}`);