@paigy/harness 0.3.49 → 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 (4) hide show
  1. package/README.md +23 -5
  2. package/dist/cli.js +854 -153
  3. package/dist/main.js +811 -183
  4. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4580,7 +4580,7 @@ import { app, BrowserWindow, dialog, ipcMain } from "electron";
4580
4580
  import { spawn as spawn2 } from "child_process";
4581
4581
  import { readFileSync as readFileSync7 } from "fs";
4582
4582
  import { fileURLToPath } from "url";
4583
- import { dirname as dirname4, join as join12 } from "path";
4583
+ import { dirname as dirname4, join as join14 } from "path";
4584
4584
 
4585
4585
  // ../../packages/sdk/dist/index.js
4586
4586
  import { createRequire as __sdkCreateRequire } from "module";
@@ -8754,6 +8754,9 @@ function reachAs(session, instance) {
8754
8754
  return (url, init) => send(url, init, session, instance);
8755
8755
  }
8756
8756
  var CLIENT;
8757
+ function setClient(name) {
8758
+ CLIENT = name;
8759
+ }
8757
8760
  async function send(url, init, session, instance = envSession("PAIGY_INSTANCE_ID") ?? INSTANCE_ID) {
8758
8761
  try {
8759
8762
  const headers = {
@@ -10252,6 +10255,12 @@ var questionFields = {
10252
10255
  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(
10253
10256
  "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."
10254
10257
  ),
10258
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
10259
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
10260
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
10261
+ causedBy: causedBy.describe(
10262
+ "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."
10263
+ ),
10255
10264
  userExplicitlyRequested
10256
10265
  };
10257
10266
  var refineQuestion = (q, ctx) => {
@@ -10494,6 +10503,21 @@ var SendFeedbackSchema = external_exports.object({
10494
10503
  kind: external_exports.enum(["bug", "idea", "other"]).default("other").describe("bug: something Paigy does wrong. idea: something it should do. other: anything else.")
10495
10504
  }).strict();
10496
10505
  var SEND_FEEDBACK_DESCRIPTION = "Send feedback about Paigy itself (a bug report, an idea) straight to the Paigy team. Send it only when the person asked you to, or agreed when you offered: it goes to Paigy, never to the person, and nobody answers it here. Not for your work or a question for the person: use contact for those. Returns whether it was stored.";
10506
+ var LAUNCH_HARNESSES = ["claude", "codex", "grok", "agy"];
10507
+ var LaunchToolSchema = external_exports.object({
10508
+ name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
10509
+ harness: external_exports.enum(LAUNCH_HARNESSES).describe("What runs it."),
10510
+ brief: goalOutcome.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX} characters.`),
10511
+ 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."),
10512
+ 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."),
10513
+ workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
10514
+ repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
10515
+ model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
10516
+ mode: external_exports.enum(["ask", "bypass"]).optional().describe("bypass (default): every tool call allowed. ask: each blocked action goes to the person's phone."),
10517
+ parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
10518
+ hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
10519
+ }).strict();
10520
+ 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.";
10497
10521
  var AGENT_TOOLS = [
10498
10522
  { name: "configure", title: "Who am I", annotations: READS, description: CONFIGURE_IDENTITY_DESCRIPTION, inputSchema: mcpInputSchema(ConfigureIdentitySchema) },
10499
10523
  { name: "contact", title: "Contact the person", annotations: SENDS, description: CONTACT_DESCRIPTION, inputSchema: CONTACT_SCHEMA },
@@ -10503,6 +10527,7 @@ var AGENT_TOOLS = [
10503
10527
  { name: "search", title: "Search history", annotations: READS, description: SEARCH_DESCRIPTION, inputSchema: mcpInputSchema(SearchToolSchema) },
10504
10528
  { name: "check_activity", title: "Recent agent activity", annotations: READS, description: "Read your person's agents that contributed in the last 24 hours, newest first: at most 30 agents and their five most recently touched Goals, with their latest entry headline and time. Use get_goals to read a Goal and its other contributors before starting overlapping work. Read-only; no arguments.", inputSchema: mcpInputSchema(CheckActivitySchema) },
10505
10529
  { name: "send_feedback", title: "Send feedback to Paigy", annotations: SENDS, description: SEND_FEEDBACK_DESCRIPTION, inputSchema: mcpInputSchema(SendFeedbackSchema) },
10530
+ { name: "launch", title: "Launch a session", annotations: SENDS, description: LAUNCH_DESCRIPTION, inputSchema: mcpInputSchema(LaunchToolSchema) },
10506
10531
  // THE GUIDE FROM INSIDE THE MCP (owner, 2026-10-27): the skill's text, needing no identity (`help.ts`).
10507
10532
  { name: "help", title: "Paigy guide", annotations: READS, description: HELP_DESCRIPTION, inputSchema: mcpInputSchema(HelpSchema) }
10508
10533
  ];
@@ -11370,6 +11395,9 @@ var InboxItemSchema = external_exports.object({
11370
11395
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
11371
11396
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
11372
11397
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
11398
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
11399
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
11400
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
11373
11401
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
11374
11402
  * the person to notice it again, and For you puts it first, the latest bump on top
11375
11403
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -11672,6 +11700,59 @@ var ReassignResultSchema = external_exports.object({
11672
11700
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
11673
11701
  parentId: external_exports.string().nullable()
11674
11702
  });
11703
+ var TeamSessionSchema = external_exports.object({
11704
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
11705
+ * agent's own page opens. The row's identity, so never null. */
11706
+ tokenId: external_exports.string(),
11707
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
11708
+ name: external_exports.string().nullable(),
11709
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
11710
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
11711
+ * session is doing is its step's `goalTitle`. */
11712
+ role: external_exports.string().nullable(),
11713
+ /** Its step under the project: the one it worked most recently. */
11714
+ goalId: external_exports.string(),
11715
+ goalTitle: external_exports.string().nullable(),
11716
+ goalState: external_exports.string(),
11717
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
11718
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
11719
+ * as it advertised it on its heartbeat. */
11720
+ harness: external_exports.string().nullable(),
11721
+ harnessLabel: external_exports.string().nullable(),
11722
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
11723
+ model: external_exports.string().nullable(),
11724
+ mode: external_exports.string().nullable(),
11725
+ workspace: external_exports.string().nullable(),
11726
+ worktree: external_exports.boolean().nullable(),
11727
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
11728
+ lastAt: external_exports.string().nullable(),
11729
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
11730
+ * that has written nothing yet can say for itself. */
11731
+ lastLine: external_exports.string().nullable(),
11732
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
11733
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
11734
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
11735
+ live: external_exports.boolean(),
11736
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
11737
+ * it is taking its work rather than merely still running. */
11738
+ working: external_exports.boolean(),
11739
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
11740
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
11741
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
11742
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
11743
+ waitingOn: external_exports.object({
11744
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
11745
+ text: external_exports.string(),
11746
+ id: external_exports.string().nullable(),
11747
+ at: external_exports.string().nullable()
11748
+ }),
11749
+ /** Its credential was revoked, or the person's end of it was carried out and said so
11750
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
11751
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
11752
+ * reads as a team rather than an empty page. */
11753
+ endedAt: external_exports.string().nullable()
11754
+ });
11755
+ var TeamReadSchema = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema) });
11675
11756
  var LessonStateSchema = external_exports.enum(["active", "proposed", "retired"]);
11676
11757
  var LessonViewSchema = external_exports.object({
11677
11758
  id: external_exports.string(),
@@ -11964,6 +12045,9 @@ var DeviceTokenSchema = external_exports.object({
11964
12045
  /** Local host recovery must preserve the launch's runtime and Paigy identity. */
11965
12046
  harness: external_exports.enum(["claude", "codex", "agy", "grok"]).optional(),
11966
12047
  session_id: external_exports.string().uuid().optional(),
12048
+ /** How the launch asked for it to run (`GET /api/sessions/claim` `mode`), so every wake of this slot
12049
+ * runs it the same way. Absent is bypass (owner, 2026-11-13), as every slot written before it. */
12050
+ mode: external_exports.enum(["ask", "bypass"]).optional(),
11967
12051
  /** A conversation the host must not resume: its context is full, so every turn fails
11968
12052
  * ("Prompt is too long"). Written when a run hits it (`run.ts` `onFull`); the host skips a slot
11969
12053
  * whose resumable session is this one, so its Goals reach the dead-agent handoff instead of a
@@ -12276,7 +12360,7 @@ function updateSlot(agent2, patch) {
12276
12360
  }
12277
12361
  function slotIdentity(agent2) {
12278
12362
  const t = readTokenFile()[agent2];
12279
- return { name: t?.name ?? null, voice: t?.voice ?? null, tokenId: t?.token_id ?? null, workspace: t?.workspace ?? null, harness: t?.harness ?? null, sessionId: t?.session_id ?? null, fullSession: t?.full_session ?? null };
12363
+ return { name: t?.name ?? null, voice: t?.voice ?? null, tokenId: t?.token_id ?? null, workspace: t?.workspace ?? null, harness: t?.harness ?? null, sessionId: t?.session_id ?? null, fullSession: t?.full_session ?? null, mode: t?.mode ?? null };
12280
12364
  }
12281
12365
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12282
12366
  function readToken(agent2 = agentName()) {
@@ -12403,6 +12487,16 @@ async function readIdentity(opts = {}) {
12403
12487
  if (!res.ok) await fail("read_identity", res);
12404
12488
  return await res.json();
12405
12489
  }
12490
+ async function launchSession(input, opts = {}) {
12491
+ const { brief, ...rest } = input;
12492
+ const res = await ensureAuthed(await (opts.reach ?? reach)(`${BACKEND_URL}/api/sessions`, {
12493
+ method: "POST",
12494
+ headers: { "content-type": "application/json", authorization: `Bearer ${authToken(opts.token) ?? ""}` },
12495
+ body: JSON.stringify({ ...rest, prompt: brief })
12496
+ }));
12497
+ if (!res.ok) await fail("launch", res);
12498
+ return await res.json();
12499
+ }
12406
12500
  async function claimSessions(opts = {}) {
12407
12501
  const res = await ensureAuthed(await reach(`${BACKEND_URL}/api/sessions/claim`, {
12408
12502
  headers: { authorization: `Bearer ${authToken(opts.token)}` }
@@ -12734,15 +12828,95 @@ async function subscribeWake(onNudge, opts = {}) {
12734
12828
  };
12735
12829
  }
12736
12830
 
12831
+ // src/update.ts
12832
+ import { execFile } from "child_process";
12833
+ import { createRequire } from "module";
12834
+ import { dirname, join as join4 } from "path";
12835
+ import { promisify } from "util";
12836
+ var SERVICE_LABEL = "ai.paigy.harness";
12837
+ var VERSION = createRequire(import.meta.url)("../package.json").version;
12838
+ var REGISTRY = "https://registry.npmjs.org/@paigy/harness/latest";
12839
+ var CHECK_MS = 60 * 6e4;
12840
+ function newer(latest, current) {
12841
+ const parts = (v) => /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null;
12842
+ const [a, b] = [parts(latest), parts(current)];
12843
+ if (!a || !b) return false;
12844
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
12845
+ return false;
12846
+ }
12847
+ var WAIT_CAP_MS = 6 * 36e5;
12848
+ function updateAction(o) {
12849
+ if (!o.service || !o.latest || o.latest === o.failed || !newer(o.latest, o.current)) return "none";
12850
+ if (o.sessions <= 0) return "install";
12851
+ const working = o.working ?? o.sessions;
12852
+ if (working > 0) return "wait";
12853
+ return (o.waited ?? 0) >= WAIT_CAP_MS ? "install" : "wait";
12854
+ }
12855
+ async function latestVersion() {
12856
+ const res = await fetch(REGISTRY, { signal: AbortSignal.timeout(1e4) });
12857
+ return res.ok ? (await res.json()).version ?? null : null;
12858
+ }
12859
+ async function install(version) {
12860
+ const bin = dirname(process.execPath);
12861
+ await promisify(execFile)(join4(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
12862
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}`, npm_config_update_notifier: "false" },
12863
+ timeout: 5 * 6e4
12864
+ });
12865
+ }
12866
+ function selfUpdater(deps) {
12867
+ const service = deps.service ?? process.env.XPC_SERVICE_NAME === SERVICE_LABEL;
12868
+ let latest = null;
12869
+ let checkedAt = -Infinity;
12870
+ let failed;
12871
+ let waiting = false;
12872
+ let waitingSince = null;
12873
+ return async () => {
12874
+ if (!service) return;
12875
+ const now = (deps.now ?? Date.now)();
12876
+ if (now - checkedAt >= CHECK_MS) {
12877
+ checkedAt = now;
12878
+ latest = await (deps.latest ?? latestVersion)().catch(() => latest);
12879
+ }
12880
+ const sessions = deps.sessions();
12881
+ const working = deps.working?.();
12882
+ if (latest && newer(latest, VERSION) && latest !== failed && waitingSince === null) waitingSince = now;
12883
+ const action = updateAction({
12884
+ current: VERSION,
12885
+ latest,
12886
+ service,
12887
+ sessions,
12888
+ failed,
12889
+ ...working === void 0 ? {} : { working },
12890
+ waited: waitingSince === null ? 0 : now - waitingSince
12891
+ });
12892
+ if (action === "wait" && !waiting) {
12893
+ deps.log(working ? `\u21E1 @paigy/harness ${latest} is out \u2014 updating once the turn in flight finishes` : `\u21E1 @paigy/harness ${latest} is out \u2014 updating once no session is running (at most ${Math.round(WAIT_CAP_MS / 36e5)}h)`);
12894
+ }
12895
+ waiting = action === "wait";
12896
+ if (action === "install" && sessions > 0) {
12897
+ deps.log(`\u21E1 @paigy/harness ${latest} is out and ${sessions} resting session(s) have held it for ${Math.round((now - (waitingSince ?? now)) / 36e5)}h \u2014 restarting over them`);
12898
+ }
12899
+ if (action !== "install" || !latest) return;
12900
+ try {
12901
+ await (deps.install ?? install)(latest);
12902
+ deps.log(`\u21E1 updated @paigy/harness ${VERSION} \u2192 ${latest} \u2014 restarting`);
12903
+ (deps.exit ?? (() => process.exit(0)))();
12904
+ } catch (e) {
12905
+ failed = latest;
12906
+ deps.log(`\u26A0 could not update to @paigy/harness ${latest}: ${e.message.split("\n")[0]} \u2014 run: npm install -g @paigy/harness`);
12907
+ }
12908
+ };
12909
+ }
12910
+
12737
12911
  // src/main.ts
12738
12912
  var import_qrcode = __toESM(require_lib(), 1);
12739
- import { homedir as homedir10, hostname } from "os";
12913
+ import { homedir as homedir12, hostname } from "os";
12740
12914
 
12741
12915
  // src/harness/catalog.ts
12742
12916
  import { spawnSync } from "child_process";
12743
12917
  import { existsSync as existsSync2 } from "fs";
12744
12918
  import { homedir as homedir3 } from "os";
12745
- import { delimiter, dirname, join as join4 } from "path";
12919
+ import { delimiter, dirname as dirname2, join as join5 } from "path";
12746
12920
  var CATALOG = [
12747
12921
  {
12748
12922
  name: "claude",
@@ -12753,7 +12927,7 @@ var CATALOG = [
12753
12927
  loginHint: "Run `claude` once in a terminal and sign in.",
12754
12928
  installCli: "curl -fsSL https://claude.ai/install.sh | bash",
12755
12929
  installAdapter: "npm install -g @agentclientprotocol/claude-agent-acp",
12756
- models: ["claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-opus-20240229"]
12930
+ models: ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5-20251001"]
12757
12931
  },
12758
12932
  {
12759
12933
  name: "codex",
@@ -12763,8 +12937,20 @@ var CATALOG = [
12763
12937
  authProbe: ["codex", "login", "status"],
12764
12938
  loginHint: "Run `codex login` to authenticate.",
12765
12939
  installCli: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",
12940
+ // UNPINNED AGAIN (2026-11-20, Goal ae096b5d, the owner's "Build SDK 2 turn support"). It was
12941
+ // pinned to 2.2.2 for a day because from 2.3.0 the adapter answers `session/prompt` with
12942
+ // `{messageId}` at once instead of `{stopReason}` at the end; `acp.ts` now settles a turn on
12943
+ // SDK 2's idle `state_update` as well, so the current adapter is the right one to install. It
12944
+ // has to be: the adapter runs its OWN bundled codex, and the one in 2.2.2 (0.160.1) is refused
12945
+ // by an account whose entitlement needs a current client.
12766
12946
  installAdapter: "npm install -g @agentclientprotocol/codex-acp",
12767
- models: ["gpt-4o", "gpt-4o-mini", "o1", "o1-mini"]
12947
+ // ONE ID, BECAUSE ONE IS WHAT A CHATGPT ACCOUNT TAKES (2026-11-23/24, Goal 04549742). The
12948
+ // whole previous list -- and `gpt-5.1-codex`, `gpt-5.1-codex-max` and the `gpt-6.2-astra`
12949
+ // that `~/.codex/config.toml` sets -- answer `400 model_not_found`: "not supported when
12950
+ // using Codex with a ChatGPT account". A Codex launch that took this list's head therefore
12951
+ // died on its first turn, and a dead turn marks its Goal done with the work untouched
12952
+ // (`afterTurn` -> `finish`, `paigy/bridge.ts`), which is how it read as a working session.
12953
+ models: ["gpt-6.1-sol"]
12768
12954
  },
12769
12955
  {
12770
12956
  name: "agy",
@@ -12775,7 +12961,9 @@ var CATALOG = [
12775
12961
  authProbe: ["agy", "help"],
12776
12962
  loginHint: "Install and set up Antigravity (`agy`).",
12777
12963
  installCli: "curl -fsSL https://antigravity.dev/install.sh | bash",
12778
- models: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.0-pro-exp"]
12964
+ // `agy models` order, high-effort variant of each family it offers (the suffix IS the
12965
+ // reasoning effort: `gemini-4-neon-low` and `-xhigh` are the same model turned down or up).
12966
+ models: ["gemini-4-neon-high", "gemini-4-argon-high", "gemini-4-carbon-high", "gemini-4-hydrogen-high"]
12779
12967
  },
12780
12968
  {
12781
12969
  name: "grok",
@@ -12785,17 +12973,25 @@ var CATALOG = [
12785
12973
  // to miss, and detection would report adapter-missing on a machine that can already launch.
12786
12974
  authProbe: ["sh", "-c", 'test -s "$HOME/.grok/auth.json"'],
12787
12975
  loginHint: "Run `grok` once in a terminal and sign in.",
12788
- installCli: "curl -fsSL https://x.ai/cli/install.sh | bash"
12976
+ installCli: "curl -fsSL https://x.ai/cli/install.sh | bash",
12977
+ // Grok was the one vendor with NO list, so a Grok session could only ever be started on
12978
+ // whatever the CLI defaulted to and the phone could offer no choice. `grok models` answers
12979
+ // without a login, so writing one cost the pending sign-in nothing.
12980
+ // BUT SIGNED OUT IT ANSWERS A SUBSET (2026-11-24). Before the owner's browser login `grok
12981
+ // models` named "grok-4.6 (default), grok-4.5", which is what this list said. The moment
12982
+ // ~/.grok/auth.json existed the same command answered grok-4.7 as the default and added
12983
+ // grok-4.7-build-fast — so a signed-out reading is a floor, not the menu. Re-read it signed in.
12984
+ models: ["grok-4.7", "grok-4.7-build-fast", "grok-4.6", "grok-4.5"]
12789
12985
  }
12790
12986
  ];
12791
12987
  function probeDirs(home = homedir3()) {
12792
12988
  return [
12793
- dirname(process.execPath),
12794
- join4(home, ".local", "bin"),
12795
- join4(home, ".grok", "bin"),
12989
+ dirname2(process.execPath),
12990
+ join5(home, ".local", "bin"),
12991
+ join5(home, ".grok", "bin"),
12796
12992
  "/usr/local/bin",
12797
12993
  "/opt/homebrew/bin",
12798
- join4(home, ".npm-global", "bin")
12994
+ join5(home, ".npm-global", "bin")
12799
12995
  ];
12800
12996
  }
12801
12997
  function which(bin) {
@@ -12803,7 +12999,7 @@ function which(bin) {
12803
12999
  const fromPath = hit.status === 0 ? hit.stdout.trim() : "";
12804
13000
  if (fromPath) return fromPath;
12805
13001
  for (const dir of probeDirs()) {
12806
- const candidate = join4(dir, bin);
13002
+ const candidate = join5(dir, bin);
12807
13003
  if (existsSync2(candidate)) return candidate;
12808
13004
  }
12809
13005
  return null;
@@ -14402,6 +14598,12 @@ var questionFields2 = {
14402
14598
  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(
14403
14599
  "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."
14404
14600
  ),
14601
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
14602
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
14603
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
14604
+ causedBy: causedBy2.describe(
14605
+ "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."
14606
+ ),
14405
14607
  userExplicitlyRequested: userExplicitlyRequested2
14406
14608
  };
14407
14609
  var refineQuestion2 = (q, ctx) => {
@@ -14644,6 +14846,21 @@ var SendFeedbackSchema2 = external_exports.object({
14644
14846
  kind: external_exports.enum(["bug", "idea", "other"]).default("other").describe("bug: something Paigy does wrong. idea: something it should do. other: anything else.")
14645
14847
  }).strict();
14646
14848
  var SEND_FEEDBACK_DESCRIPTION2 = "Send feedback about Paigy itself (a bug report, an idea) straight to the Paigy team. Send it only when the person asked you to, or agreed when you offered: it goes to Paigy, never to the person, and nobody answers it here. Not for your work or a question for the person: use contact for those. Returns whether it was stored.";
14849
+ var LAUNCH_HARNESSES2 = ["claude", "codex", "grok", "agy"];
14850
+ var LaunchToolSchema2 = external_exports.object({
14851
+ name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
14852
+ harness: external_exports.enum(LAUNCH_HARNESSES2).describe("What runs it."),
14853
+ brief: goalOutcome2.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX2} characters.`),
14854
+ 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."),
14855
+ 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."),
14856
+ workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
14857
+ repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
14858
+ model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
14859
+ mode: external_exports.enum(["ask", "bypass"]).optional().describe("bypass (default): every tool call allowed. ask: each blocked action goes to the person's phone."),
14860
+ parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
14861
+ hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
14862
+ }).strict();
14863
+ 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.";
14647
14864
  var AGENT_TOOLS2 = [
14648
14865
  { name: "configure", title: "Who am I", annotations: READS2, description: CONFIGURE_IDENTITY_DESCRIPTION2, inputSchema: mcpInputSchema2(ConfigureIdentitySchema2) },
14649
14866
  { name: "contact", title: "Contact the person", annotations: SENDS2, description: CONTACT_DESCRIPTION2, inputSchema: CONTACT_SCHEMA2 },
@@ -14653,6 +14870,7 @@ var AGENT_TOOLS2 = [
14653
14870
  { name: "search", title: "Search history", annotations: READS2, description: SEARCH_DESCRIPTION2, inputSchema: mcpInputSchema2(SearchToolSchema2) },
14654
14871
  { name: "check_activity", title: "Recent agent activity", annotations: READS2, description: "Read your person's agents that contributed in the last 24 hours, newest first: at most 30 agents and their five most recently touched Goals, with their latest entry headline and time. Use get_goals to read a Goal and its other contributors before starting overlapping work. Read-only; no arguments.", inputSchema: mcpInputSchema2(CheckActivitySchema2) },
14655
14872
  { name: "send_feedback", title: "Send feedback to Paigy", annotations: SENDS2, description: SEND_FEEDBACK_DESCRIPTION2, inputSchema: mcpInputSchema2(SendFeedbackSchema2) },
14873
+ { name: "launch", title: "Launch a session", annotations: SENDS2, description: LAUNCH_DESCRIPTION2, inputSchema: mcpInputSchema2(LaunchToolSchema2) },
14656
14874
  // THE GUIDE FROM INSIDE THE MCP (owner, 2026-10-27): the skill's text, needing no identity (`help.ts`).
14657
14875
  { name: "help", title: "Paigy guide", annotations: READS2, description: HELP_DESCRIPTION2, inputSchema: mcpInputSchema2(HelpSchema2) }
14658
14876
  ];
@@ -15531,6 +15749,9 @@ var InboxItemSchema2 = external_exports.object({
15531
15749
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
15532
15750
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
15533
15751
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
15752
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
15753
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
15754
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
15534
15755
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
15535
15756
  * the person to notice it again, and For you puts it first, the latest bump on top
15536
15757
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -15833,6 +16054,59 @@ var ReassignResultSchema2 = external_exports.object({
15833
16054
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
15834
16055
  parentId: external_exports.string().nullable()
15835
16056
  });
16057
+ var TeamSessionSchema2 = external_exports.object({
16058
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
16059
+ * agent's own page opens. The row's identity, so never null. */
16060
+ tokenId: external_exports.string(),
16061
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
16062
+ name: external_exports.string().nullable(),
16063
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
16064
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
16065
+ * session is doing is its step's `goalTitle`. */
16066
+ role: external_exports.string().nullable(),
16067
+ /** Its step under the project: the one it worked most recently. */
16068
+ goalId: external_exports.string(),
16069
+ goalTitle: external_exports.string().nullable(),
16070
+ goalState: external_exports.string(),
16071
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
16072
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
16073
+ * as it advertised it on its heartbeat. */
16074
+ harness: external_exports.string().nullable(),
16075
+ harnessLabel: external_exports.string().nullable(),
16076
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
16077
+ model: external_exports.string().nullable(),
16078
+ mode: external_exports.string().nullable(),
16079
+ workspace: external_exports.string().nullable(),
16080
+ worktree: external_exports.boolean().nullable(),
16081
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
16082
+ lastAt: external_exports.string().nullable(),
16083
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
16084
+ * that has written nothing yet can say for itself. */
16085
+ lastLine: external_exports.string().nullable(),
16086
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
16087
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
16088
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
16089
+ live: external_exports.boolean(),
16090
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
16091
+ * it is taking its work rather than merely still running. */
16092
+ working: external_exports.boolean(),
16093
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
16094
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
16095
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
16096
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
16097
+ waitingOn: external_exports.object({
16098
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
16099
+ text: external_exports.string(),
16100
+ id: external_exports.string().nullable(),
16101
+ at: external_exports.string().nullable()
16102
+ }),
16103
+ /** Its credential was revoked, or the person's end of it was carried out and said so
16104
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
16105
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
16106
+ * reads as a team rather than an empty page. */
16107
+ endedAt: external_exports.string().nullable()
16108
+ });
16109
+ var TeamReadSchema2 = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema2) });
15836
16110
  var LessonStateSchema2 = external_exports.enum(["active", "proposed", "retired"]);
15837
16111
  var LessonViewSchema2 = external_exports.object({
15838
16112
  id: external_exports.string(),
@@ -16123,6 +16397,9 @@ var DeviceTokenSchema2 = external_exports.object({
16123
16397
  /** Local host recovery must preserve the launch's runtime and Paigy identity. */
16124
16398
  harness: external_exports.enum(["claude", "codex", "agy", "grok"]).optional(),
16125
16399
  session_id: external_exports.string().uuid().optional(),
16400
+ /** How the launch asked for it to run (`GET /api/sessions/claim` `mode`), so every wake of this slot
16401
+ * runs it the same way. Absent is bypass (owner, 2026-11-13), as every slot written before it. */
16402
+ mode: external_exports.enum(["ask", "bypass"]).optional(),
16126
16403
  /** A conversation the host must not resume: its context is full, so every turn fails
16127
16404
  * ("Prompt is too long"). Written when a run hits it (`run.ts` `onFull`); the host skips a slot
16128
16405
  * whose resumable session is this one, so its Goals reach the dead-agent handoff instead of a
@@ -16378,11 +16655,11 @@ var CallRecapSchema2 = external_exports.object({
16378
16655
  });
16379
16656
 
16380
16657
  // src/host.ts
16381
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
16658
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
16382
16659
  import { execSync } from "child_process";
16383
16660
  import { randomBytes } from "crypto";
16384
- import { homedir as homedir9 } from "os";
16385
- import { join as join11 } from "path";
16661
+ import { homedir as homedir11 } from "os";
16662
+ import { join as join13 } from "path";
16386
16663
 
16387
16664
  // src/ago.ts
16388
16665
  var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
@@ -16398,10 +16675,10 @@ function ago(iso, now) {
16398
16675
 
16399
16676
  // src/workspaces.ts
16400
16677
  import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
16401
- import { dirname as dirname2, join as join5, resolve } from "path";
16678
+ import { dirname as dirname3, join as join6, resolve } from "path";
16402
16679
  import { homedir as homedir4 } from "os";
16403
16680
  function workspacesFile() {
16404
- return join5(homedir4(), ".paigy", "workspaces.json");
16681
+ return join6(homedir4(), ".paigy", "workspaces.json");
16405
16682
  }
16406
16683
  function listWorkspaces(deps) {
16407
16684
  try {
@@ -16416,14 +16693,14 @@ function addWorkspace(dir, deps) {
16416
16693
  const all = listWorkspaces(deps);
16417
16694
  if (!all.includes(next)) {
16418
16695
  all.push(next);
16419
- mkdirSync2(dirname2(deps.file), { recursive: true });
16696
+ mkdirSync2(dirname3(deps.file), { recursive: true });
16420
16697
  writeFileSync2(deps.file, JSON.stringify(all, null, 2));
16421
16698
  }
16422
16699
  return all;
16423
16700
  }
16424
16701
  function removeWorkspace(dir, deps) {
16425
16702
  const all = listWorkspaces(deps).filter((w) => w !== dir);
16426
- mkdirSync2(dirname2(deps.file), { recursive: true });
16703
+ mkdirSync2(dirname3(deps.file), { recursive: true });
16427
16704
  writeFileSync2(deps.file, JSON.stringify(all, null, 2));
16428
16705
  return all;
16429
16706
  }
@@ -16440,8 +16717,8 @@ function resolveWakeDir(pinned, deps) {
16440
16717
  }
16441
16718
  function originOf(dir) {
16442
16719
  try {
16443
- if (!statSync2(join5(dir, ".git")).isDirectory()) return null;
16444
- const config = readFileSync3(join5(dir, ".git", "config"), "utf8");
16720
+ if (!statSync2(join6(dir, ".git")).isDirectory()) return null;
16721
+ const config = readFileSync3(join6(dir, ".git", "config"), "utf8");
16445
16722
  const section = config.split(/^\[/m).find((s) => /^remote\s+"origin"\]/.test(s));
16446
16723
  return section?.match(/^\s*url\s*=\s*(.+)$/m)?.[1]?.trim() ?? null;
16447
16724
  } catch {
@@ -16462,7 +16739,7 @@ function listRepos(deps) {
16462
16739
  }
16463
16740
  for (const name of children) {
16464
16741
  if (repos.length >= MAX_REPOS) return repos;
16465
- const path = join5(root, name);
16742
+ const path = join6(root, name);
16466
16743
  const remote = originOf(path);
16467
16744
  if (remote) repos.push({ path, remote });
16468
16745
  }
@@ -16474,7 +16751,7 @@ function listRepos(deps) {
16474
16751
  import { execFileSync as execFileSync2 } from "child_process";
16475
16752
  import { readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
16476
16753
  import { homedir as homedir5 } from "os";
16477
- import { join as join6 } from "path";
16754
+ import { join as join7 } from "path";
16478
16755
  function isAlive(pid) {
16479
16756
  try {
16480
16757
  process.kill(pid, 0);
@@ -16512,7 +16789,7 @@ function proven(pid, procStart, deps) {
16512
16789
  });
16513
16790
  }
16514
16791
  function localHolderPids(deps = {}) {
16515
- const dir = deps.dir ?? join6(process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude"), "sessions");
16792
+ const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir5(), ".claude"), "sessions");
16516
16793
  const list = deps.list ?? ((d) => readdirSync2(d));
16517
16794
  const read3 = deps.read ?? ((f) => readFileSync4(f, "utf8"));
16518
16795
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
@@ -16527,7 +16804,7 @@ function localHolderPids(deps = {}) {
16527
16804
  if (!/^\d+\.json$/.test(file)) continue;
16528
16805
  let row;
16529
16806
  try {
16530
- row = parseSessionRecord(read3(join6(dir, file)));
16807
+ row = parseSessionRecord(read3(join7(dir, file)));
16531
16808
  } catch {
16532
16809
  continue;
16533
16810
  }
@@ -16561,7 +16838,7 @@ function descendsFrom(pid, ancestor, parent = psParent) {
16561
16838
  return false;
16562
16839
  }
16563
16840
  function localHolders(deps = {}) {
16564
- const dir = deps.dir ?? join6(process.env.CLAUDE_CONFIG_DIR?.trim() || join6(homedir5(), ".claude"), "sessions");
16841
+ const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir5(), ".claude"), "sessions");
16565
16842
  const list = deps.list ?? ((d) => readdirSync2(d));
16566
16843
  const read3 = deps.read ?? ((f) => readFileSync4(f, "utf8"));
16567
16844
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
@@ -16576,7 +16853,7 @@ function localHolders(deps = {}) {
16576
16853
  if (!/^\d+\.json$/.test(file)) continue;
16577
16854
  let row;
16578
16855
  try {
16579
- row = parseSessionRecord(read3(join6(dir, file)));
16856
+ row = parseSessionRecord(read3(join7(dir, file)));
16580
16857
  } catch {
16581
16858
  continue;
16582
16859
  }
@@ -16655,7 +16932,7 @@ async function endSession(end, deps) {
16655
16932
  // src/owner.ts
16656
16933
  import { closeSync as closeSync2, openSync as openSync2, readSync, readdirSync as readdirSync3 } from "fs";
16657
16934
  import { homedir as homedir6 } from "os";
16658
- import { join as join7 } from "path";
16935
+ import { join as join8 } from "path";
16659
16936
  var HEAD_BYTES = 64e3;
16660
16937
  function readHead(file) {
16661
16938
  const fd = openSync2(file, "r");
@@ -16671,7 +16948,7 @@ function ownerSession(slot, deps = {}) {
16671
16948
  const m = /^session:([0-9a-f]{8})$/.exec(slot);
16672
16949
  if (!m) return null;
16673
16950
  const prefix = m[1];
16674
- const root = deps.projectsDir ?? join7(homedir6(), ".claude", "projects");
16951
+ const root = deps.projectsDir ?? join8(homedir6(), ".claude", "projects");
16675
16952
  const list = deps.list ?? ((dir) => readdirSync3(dir));
16676
16953
  const head2 = deps.head ?? readHead;
16677
16954
  let folders;
@@ -16683,7 +16960,7 @@ function ownerSession(slot, deps = {}) {
16683
16960
  for (const folder of folders) {
16684
16961
  let files;
16685
16962
  try {
16686
- files = list(join7(root, folder));
16963
+ files = list(join8(root, folder));
16687
16964
  } catch {
16688
16965
  continue;
16689
16966
  }
@@ -16691,7 +16968,7 @@ function ownerSession(slot, deps = {}) {
16691
16968
  if (!file) continue;
16692
16969
  let text;
16693
16970
  try {
16694
- text = head2(join7(root, folder, file));
16971
+ text = head2(join8(root, folder, file));
16695
16972
  } catch {
16696
16973
  continue;
16697
16974
  }
@@ -16735,7 +17012,7 @@ import { randomUUID as randomUUID4 } from "crypto";
16735
17012
  import { spawn } from "child_process";
16736
17013
  import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
16737
17014
  import { homedir as homedir8 } from "os";
16738
- import { resolve as resolve2, delimiter as delimiter2, join as join9 } from "path";
17015
+ import { resolve as resolve2, delimiter as delimiter2, join as join10 } from "path";
16739
17016
 
16740
17017
  // src/harness/acp.ts
16741
17018
  var none = { events: [], writes: [] };
@@ -16791,6 +17068,17 @@ var AcpDriver = class {
16791
17068
  running = /* @__PURE__ */ new Set();
16792
17069
  /** The prompt in flight was already cancelled for silence: once is the whole remedy. */
16793
17070
  cancelled = false;
17071
+ /** ACP SDK 2 ANSWERED THE PROMPT AND THE TURN GOES ON (2026-11-20, Goal ae096b5d). SDK 1 keeps
17072
+ * the prompt response until the turn ends and puts `stopReason` on it. SDK 2 answers at once with
17073
+ * `{messageId}` — an acknowledgement, 2.3 seconds before the agent's first word in a live
17074
+ * capture — and ends the turn with `state_update: {state:"idle"}`. Settling on that response
17075
+ * would end every turn instantly and empty, so the turn stays in flight here: `promptId` is kept,
17076
+ * which is what `quiet` cancels against and what `flush` queues behind, and only an idle
17077
+ * `state_update` settles it. */
17078
+ ackedAwaitingIdle = false;
17079
+ /** The model the adapter last said a turn ran on (`claude-opus-5[1m]`), carried on every idle so
17080
+ * the run can tell a 200k window from a million (`fill.ts`). */
17081
+ model;
16794
17082
  /** The opening frame. Everything after is driven by responses in `handleLine`. */
16795
17083
  open() {
16796
17084
  this.initId = this.nextId++;
@@ -16802,7 +17090,17 @@ var AcpDriver = class {
16802
17090
  protocolVersion: 2,
16803
17091
  // We are not an editor: no file services offered, the agent uses its own.
16804
17092
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
16805
- clientInfo: { name: "paigy-desktop", version: "0.0.0" }
17093
+ // WHO WE ARE, UNDER BOTH NAMES (2026-11-20, Goal ae096b5d). ACP SDK 1 reads
17094
+ // `clientInfo`; SDK 2 requires `info` and REFUSES the frame without it
17095
+ // (`-32602 invalid initialize params`, path ["info"]), so a `clientInfo`-only
17096
+ // opening cannot start any adapter built on the newer SDK — and the catalog
17097
+ // installs adapters unpinned, so that is what a fresh machine gets. Sending both
17098
+ // was probed against every adapter we spawn: codex-acp 2.8.0 (SDK 2) and 2.2.2,
17099
+ // claude-agent-acp 0.76.0 and paigy-agy-acp all accept it, and the old ones keep
17100
+ // reading the field they already read. Drop `clientInfo` only once no adapter we
17101
+ // spawn is on SDK 1.
17102
+ clientInfo: { name: "paigy-desktop", version: "0.0.0" },
17103
+ info: { name: "paigy-desktop", version: "0.0.0" }
16806
17104
  }
16807
17105
  })
16808
17106
  ];
@@ -16910,33 +17208,12 @@ var AcpDriver = class {
16910
17208
  return { events: [], writes };
16911
17209
  }
16912
17210
  if (msg.id === this.promptId) {
16913
- this.promptId = void 0;
16914
- this.running.clear();
16915
- this.cancelled = false;
16916
- const events = [];
16917
- const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
16918
- if (report || this.tools.length) {
16919
- events.push({
16920
- kind: "turn",
16921
- role: "agent",
16922
- text: report,
16923
- ...this.tools.length ? { tools: [...this.tools] } : {}
16924
- });
16925
- }
16926
- const result = report;
16927
- const failed = msg.error !== void 0 || msg.result?.stopReason === "refusal";
16928
- this.text = "";
16929
- this.tools = [];
16930
- this.reportFrom = 0;
16931
- const writes = this.flush();
16932
- if (!writes.length) {
16933
- events.push({
16934
- kind: "idle",
16935
- ...result ? { result } : {},
16936
- ...failed ? { failed: true } : {}
16937
- });
17211
+ this.model = msg.result?._meta?.quota?.model_usage?.[0]?.model ?? this.model;
17212
+ if (msg.error === void 0 && msg.result?.stopReason === void 0 && msg.result?.messageId !== void 0) {
17213
+ this.ackedAwaitingIdle = true;
17214
+ return none;
16938
17215
  }
16939
- return { events, writes };
17216
+ return this.settle(msg.error !== void 0 || msg.result?.stopReason === "refusal");
16940
17217
  }
16941
17218
  return none;
16942
17219
  }
@@ -16952,6 +17229,11 @@ var AcpDriver = class {
16952
17229
  case "agent_message_chunk":
16953
17230
  this.text += update.content?.text ?? "";
16954
17231
  return none;
17232
+ // SDK 2'S END OF TURN. Only settles a turn whose prompt was acknowledged and is still in
17233
+ // flight: an SDK 1 adapter never sends this at all, `state: "running"` is the turn starting,
17234
+ // and an idle outside a turn (a session just opened) has nothing to settle.
17235
+ case "state_update":
17236
+ return update.state === "idle" && this.promptId !== void 0 && this.ackedAwaitingIdle ? this.settle(false) : none;
16955
17237
  case "tool_call": {
16956
17238
  const title = update.title?.trim() || update.kind || "tool";
16957
17239
  this.tools.push(title);
@@ -16998,6 +17280,42 @@ var AcpDriver = class {
16998
17280
  return this.resume ? { id: id3, method: "session/resume", params: { sessionId: this.resume, ...params } } : { id: id3, method: "session/new", params };
16999
17281
  }
17000
17282
  /** Send the queued prompts as one turn, if the agent can take one right now. */
17283
+ /** THE TURN IS OVER. The accumulated report lands first, then idle — the same order the line
17284
+ * adapters emit — and anything queued meanwhile goes out. Reached from SDK 1's prompt response
17285
+ * and from SDK 2's idle `state_update`, so both generations end a turn the same way. */
17286
+ settle(failed) {
17287
+ this.promptId = void 0;
17288
+ this.ackedAwaitingIdle = false;
17289
+ this.running.clear();
17290
+ this.cancelled = false;
17291
+ const events = [];
17292
+ const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
17293
+ if (report || this.tools.length) {
17294
+ events.push({
17295
+ kind: "turn",
17296
+ role: "agent",
17297
+ text: report,
17298
+ ...this.tools.length ? { tools: [...this.tools] } : {}
17299
+ });
17300
+ }
17301
+ const result = report;
17302
+ this.text = "";
17303
+ this.tools = [];
17304
+ this.reportFrom = 0;
17305
+ const writes = this.flush();
17306
+ if (!writes.length) {
17307
+ events.push({
17308
+ kind: "idle",
17309
+ ...result ? { result } : {},
17310
+ ...failed ? { failed: true } : {},
17311
+ // WHOSE conversation this was: its transcript is named by this id, and that transcript is
17312
+ // all a session's context amounts to once it can no longer write (`handoff.ts`).
17313
+ ...this.sessionId ? { session: this.sessionId } : {},
17314
+ ...this.model ? { model: this.model } : {}
17315
+ });
17316
+ }
17317
+ return { events, writes };
17318
+ }
17001
17319
  flush() {
17002
17320
  if (!this.sessionId || this.promptId !== void 0 || !this.queued.length) return [];
17003
17321
  const blocks = this.queued.map((text) => ({ type: "text", text }));
@@ -17016,7 +17334,7 @@ var frame2 = (body) => JSON.stringify({ jsonrpc: "2.0", ...body });
17016
17334
 
17017
17335
  // src/paigy/inbox.ts
17018
17336
  import { mkdirSync as mkdirSync3, readdirSync as readdirSync4, renameSync, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
17019
- import { join as join8 } from "path";
17337
+ import { join as join9 } from "path";
17020
17338
  import { homedir as homedir7 } from "os";
17021
17339
  import { randomUUID as randomUUID3 } from "crypto";
17022
17340
  var MIDTURN_HOOK = `d="$PAIGY_INBOX"; [ -n "$d" ] || { cat >/dev/null; exit 0; }; set -- "$d"/*.note; [ -e "$1" ] || { cat >/dev/null; exit 0; }; grep '"agent_id"' >/dev/null && exit 0; mkdir -p "$d/taken"; o=""; for f in "$@"; do n=\${f##*/}; mv "$f" "$d/taken/$n" 2>/dev/null || continue; touch "$d/taken/$n"; o="$o\${o:+\\n\\n}$(cat "$d/taken/$n")"; done; [ -n "$o" ] || exit 0; printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"%s"}}' "$o"`;
@@ -17024,7 +17342,7 @@ var missing = (error) => error.code === "ENOENT";
17024
17342
  function openInbox(dir) {
17025
17343
  mkdirSync3(dir, { recursive: true });
17026
17344
  let written = 0;
17027
- const receipt = (name) => join8(dir, "taken", `${name}.note`);
17345
+ const receipt = (name) => join9(dir, "taken", `${name}.note`);
17028
17346
  const taken = (name) => {
17029
17347
  try {
17030
17348
  return statSync3(receipt(name)).mtimeMs;
@@ -17037,16 +17355,16 @@ function openInbox(dir) {
17037
17355
  dir,
17038
17356
  put(text) {
17039
17357
  const name = `${Date.now()}-${String(++written).padStart(6, "0")}`;
17040
- const tmp = join8(dir, `${name}.tmp`);
17358
+ const tmp = join9(dir, `${name}.tmp`);
17041
17359
  writeFileSync3(tmp, JSON.stringify(text).slice(1, -1));
17042
- renameSync(tmp, join8(dir, `${name}.note`));
17360
+ renameSync(tmp, join9(dir, `${name}.note`));
17043
17361
  return name;
17044
17362
  },
17045
17363
  taken,
17046
17364
  settle(name) {
17047
17365
  try {
17048
- renameSync(join8(dir, `${name}.note`), join8(dir, `${name}.back`));
17049
- rmSync2(join8(dir, `${name}.back`), { force: true });
17366
+ renameSync(join9(dir, `${name}.note`), join9(dir, `${name}.back`));
17367
+ rmSync2(join9(dir, `${name}.back`), { force: true });
17050
17368
  return "retracted";
17051
17369
  } catch (error) {
17052
17370
  if (!missing(error)) throw error;
@@ -17060,7 +17378,7 @@ function openInbox(dir) {
17060
17378
  }
17061
17379
  };
17062
17380
  }
17063
- var INBOX_ROOT = join8(homedir7(), ".paigy", "inbox");
17381
+ var INBOX_ROOT = join9(homedir7(), ".paigy", "inbox");
17064
17382
  var alive = (pid) => {
17065
17383
  try {
17066
17384
  process.kill(pid, 0);
@@ -17073,12 +17391,12 @@ function inboxFor(root = INBOX_ROOT) {
17073
17391
  try {
17074
17392
  for (const name of readdirSync4(root)) {
17075
17393
  const pid = Number(name.split("-")[0]);
17076
- if (!Number.isInteger(pid) || !alive(pid)) rmSync2(join8(root, name), { recursive: true, force: true });
17394
+ if (!Number.isInteger(pid) || !alive(pid)) rmSync2(join9(root, name), { recursive: true, force: true });
17077
17395
  }
17078
17396
  } catch (error) {
17079
17397
  if (!missing(error)) throw error;
17080
17398
  }
17081
- return openInbox(join8(root, `${process.pid}-${randomUUID3().slice(0, 8)}`));
17399
+ return openInbox(join9(root, `${process.pid}-${randomUUID3().slice(0, 8)}`));
17082
17400
  }
17083
17401
 
17084
17402
  // src/harness/session.ts
@@ -17123,7 +17441,7 @@ function startSession(opts) {
17123
17441
  if (opts.model && opts.harness === "codex") codexConfig = { ...codexConfig, model: opts.model };
17124
17442
  if (codexConfig) {
17125
17443
  const key3 = "mcp_servers.paigy.env_vars";
17126
- const configPath = join9(process.env.CODEX_HOME || join9(homedir8(), ".codex"), "config.toml");
17444
+ const configPath = join10(process.env.CODEX_HOME || join10(homedir8(), ".codex"), "config.toml");
17127
17445
  const saved = existsSync4(configPath) ? readFileSync5(configPath, "utf8") : "";
17128
17446
  const registered = /\[mcp_servers\.paigy\][\s\S]*?(?=\n\[|$)/.exec(saved)?.[0];
17129
17447
  const configured = codexConfig["mcp_servers.paigy.command"] || codexConfig["mcp_servers.paigy.url"] || codexConfig.mcp_servers?.paigy?.command || codexConfig.mcp_servers?.paigy?.url;
@@ -17311,15 +17629,23 @@ var LIMIT_PREFIXES = [
17311
17629
  var RETRY_MS2 = 15 * 6e4;
17312
17630
  var MARGIN_MS = 6e4;
17313
17631
  var FARTHEST_MS = 8 * 24 * 60 * 6e4;
17632
+ function handsOver(limit) {
17633
+ return limit.kind !== "session";
17634
+ }
17314
17635
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
17315
17636
  function limitIn(text, now) {
17316
17637
  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)));
17317
17638
  if (!line) return null;
17639
+ const weekly = /\b(weekly|daily)\b/i.test(line);
17318
17640
  const reset = resetOf(line, now);
17319
17641
  if (reset !== null && reset > now && reset - now <= FARTHEST_MS) {
17320
- return { until: reset + MARGIN_MS, resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset) };
17642
+ return {
17643
+ until: reset + MARGIN_MS,
17644
+ resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset),
17645
+ kind: weekly ? "weekly" : "session"
17646
+ };
17321
17647
  }
17322
- return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2) };
17648
+ return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2), kind: weekly ? "weekly" : "credits" };
17323
17649
  }
17324
17650
  function resetOf(line, now) {
17325
17651
  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);
@@ -17494,6 +17820,12 @@ async function askPermission(event, state, rail) {
17494
17820
  ]
17495
17821
  }));
17496
17822
  }
17823
+ function wroteOn(held) {
17824
+ if (held.ownerParticipant) {
17825
+ return held.workedBy === held.ownerParticipant || (held.entries ?? []).some((e) => e.authorParticipant === held.ownerParticipant) || (held.earlier?.omitted ?? 0) > 0;
17826
+ }
17827
+ return held.state !== "ready" || Boolean(held.workedBy) || (held.entries ?? []).some((e) => e.authorParticipant.startsWith("agent:"));
17828
+ }
17497
17829
  async function finish(state, rail, opts) {
17498
17830
  const goal = state.goal;
17499
17831
  if (!goal) return;
@@ -17504,7 +17836,7 @@ async function finish(state, rail, opts) {
17504
17836
  if (!owed) state.goal = void 0;
17505
17837
  return;
17506
17838
  }
17507
- if (!held.openDecisionNeedIds?.length && !owed) {
17839
+ if (!held.openDecisionNeedIds?.length && !owed && wroteOn(held)) {
17508
17840
  await rail.complete(goal.id, held.revision ?? goal.revision);
17509
17841
  state.goal = void 0;
17510
17842
  }
@@ -17546,9 +17878,19 @@ function conversationFull(result) {
17546
17878
  return /prompt is too long/i.test(result ?? "");
17547
17879
  }
17548
17880
  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.";
17881
+ 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.`;
17882
+ function providerFailed(result) {
17883
+ if (!result) return false;
17884
+ if (/"type"\s*:\s*"error"[\s\S]*?"error"\s*:\s*\{/i.test(result)) return true;
17885
+ return result.split("\n").some((raw) => {
17886
+ const line = raw.trim();
17887
+ 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);
17888
+ });
17889
+ }
17549
17890
  async function afterTurn(event, state, rail, opts) {
17550
- if (event.failed) {
17551
- const limit = limitIn(event.result, (opts?.now ?? Date.now)());
17891
+ const now = (opts?.now ?? Date.now)();
17892
+ if (event.failed || providerFailed(event.result) || limitIn(event.result, now) || conversationFull(event.result)) {
17893
+ const limit = limitIn(event.result, now);
17552
17894
  if (limit) {
17553
17895
  state.paused = limit;
17554
17896
  if (state.typed) state.owed = state.typed;
@@ -17559,7 +17901,10 @@ async function afterTurn(event, state, rail, opts) {
17559
17901
  return limit;
17560
17902
  }
17561
17903
  if (conversationFull(event.result)) {
17562
- if (!state.full) await cannotWork(FULL_NOTICE, state, rail, opts);
17904
+ if (!state.full) {
17905
+ const dossier = opts?.dossier?.() ?? null;
17906
+ await cannotWork([FULL_NOTICE, ...dossier ? [wroteForIt(dossier)] : []].join("\n\n"), state, rail, opts);
17907
+ }
17563
17908
  state.full = true;
17564
17909
  return void 0;
17565
17910
  }
@@ -17574,6 +17919,300 @@ ${event.result?.trim() || "No result reported."}`, state, rail, opts);
17574
17919
  return void 0;
17575
17920
  }
17576
17921
 
17922
+ // src/handoff.ts
17923
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync6, writeFileSync as writeFileSync4, openSync as openSync4, readSync as readSync3, fstatSync, closeSync as closeSync4 } from "fs";
17924
+ import { homedir as homedir10 } from "os";
17925
+ import { join as join12 } from "path";
17926
+
17927
+ // src/fill.ts
17928
+ import { closeSync as closeSync3, openSync as openSync3, readSync as readSync2, readdirSync as readdirSync5, statSync as statSync4 } from "fs";
17929
+ import { homedir as homedir9 } from "os";
17930
+ import { join as join11 } from "path";
17931
+ function windowFor(model) {
17932
+ return /\[1m\]/i.test(model ?? "") ? 1e6 : 2e5;
17933
+ }
17934
+ function sizeOf(tail) {
17935
+ const lines2 = tail.split("\n");
17936
+ for (let i = lines2.length - 1; i >= 0; i--) {
17937
+ const line = lines2[i].trim();
17938
+ if (!line.startsWith("{")) continue;
17939
+ let row;
17940
+ try {
17941
+ row = JSON.parse(line);
17942
+ } catch {
17943
+ continue;
17944
+ }
17945
+ if (row.type !== "assistant" || row.isSidechain === true) continue;
17946
+ const usage = row.message?.usage;
17947
+ if (!usage) continue;
17948
+ const count = (key3) => typeof usage[key3] === "number" ? usage[key3] : 0;
17949
+ const size = count("input_tokens") + count("cache_read_input_tokens") + count("cache_creation_input_tokens");
17950
+ if (size > 0) return size;
17951
+ }
17952
+ return null;
17953
+ }
17954
+ var TAIL_BYTES = 256 * 1024;
17955
+ var TAIL_MAX = 8 * 1024 * 1024;
17956
+ function readTail(file, bytes) {
17957
+ const size = statSync4(file).size;
17958
+ const from = Math.max(0, size - bytes);
17959
+ const fd = openSync3(file, "r");
17960
+ try {
17961
+ const buf = Buffer.alloc(Math.min(bytes, size));
17962
+ const n = readSync2(fd, buf, 0, buf.length, from);
17963
+ return buf.subarray(0, n).toString("utf8");
17964
+ } finally {
17965
+ closeSync3(fd);
17966
+ }
17967
+ }
17968
+ function fillReader(deps = {}) {
17969
+ const root = deps.projectsDir ?? join11(homedir9(), ".claude", "projects");
17970
+ const list = deps.list ?? ((dir) => readdirSync5(dir));
17971
+ const tail = deps.tail ?? readTail;
17972
+ const found = /* @__PURE__ */ new Map();
17973
+ const find = (session) => {
17974
+ let folders;
17975
+ try {
17976
+ folders = list(root);
17977
+ } catch {
17978
+ return null;
17979
+ }
17980
+ for (const folder of folders) {
17981
+ let files;
17982
+ try {
17983
+ files = list(join11(root, folder));
17984
+ } catch {
17985
+ continue;
17986
+ }
17987
+ if (files.includes(`${session}.jsonl`)) return join11(root, folder, `${session}.jsonl`);
17988
+ }
17989
+ return null;
17990
+ };
17991
+ return {
17992
+ measure: (session, model) => {
17993
+ if (!session) return null;
17994
+ let path = found.get(session);
17995
+ if (!path) {
17996
+ const file = find(session);
17997
+ if (!file) return null;
17998
+ found.set(session, path = file);
17999
+ }
18000
+ let used = null;
18001
+ for (let bytes = TAIL_BYTES; used === null && bytes <= TAIL_MAX; bytes *= 4) {
18002
+ let text;
18003
+ try {
18004
+ text = tail(path, bytes);
18005
+ } catch {
18006
+ return null;
18007
+ }
18008
+ used = sizeOf(text);
18009
+ if (text.length < bytes) break;
18010
+ }
18011
+ if (used === null) return null;
18012
+ const window = windowFor(model);
18013
+ return { used, window, share: used / window };
18014
+ }
18015
+ };
18016
+ }
18017
+ function fillLine(fill) {
18018
+ const percent = Math.round(fill.share * 100);
18019
+ const used = fill.used.toLocaleString("en-US");
18020
+ const window = fill.window.toLocaleString("en-US");
18021
+ return `You are holding ${used} tokens of about ${window} \u2014 ${percent}% of this conversation's window.`;
18022
+ }
18023
+
18024
+ // src/handoff.ts
18025
+ var COMPACTION = "Compact conversation";
18026
+ function compacted(event) {
18027
+ return event.kind === "work" && event.tool.trim().toLowerCase() === COMPACTION.toLowerCase();
18028
+ }
18029
+ function dossierDir() {
18030
+ return join12(homedir10(), ".paigy", "handoff");
18031
+ }
18032
+ function dossierPath(session) {
18033
+ return join12(dossierDir(), `${session.slice(0, 8)}.md`);
18034
+ }
18035
+ function keepContext(dossier, fill) {
18036
+ return [
18037
+ "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.",
18038
+ `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.`,
18039
+ `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.`,
18040
+ // The prose names `launch` and `successor: true` in backticks, so these are quoted strings
18041
+ // joined, never one template literal.
18042
+ "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."
18043
+ ].join("\n\n");
18044
+ }
18045
+ var CARRIES_ON = ["agy", "codex", "grok", "claude"];
18046
+ function carriesOn(available, limited) {
18047
+ const ready = available.filter((a) => a.status === "ready" && a.name !== limited);
18048
+ for (const name of CARRIES_ON) {
18049
+ const hit = ready.find((a) => a.name === name);
18050
+ if (hit) return hit;
18051
+ }
18052
+ return null;
18053
+ }
18054
+ function successorName(name, label) {
18055
+ return `${name} (${label})`.slice(0, 60);
18056
+ }
18057
+ function creditsBrief(opts) {
18058
+ return [
18059
+ `Carry on ${opts.name}'s work: a usage limit stopped it until ${opts.resets}, so its open Goals are now yours.`,
18060
+ 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.",
18061
+ "Report on those Goals as you go."
18062
+ ].join(" ");
18063
+ }
18064
+ function projectSlug(cwd) {
18065
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
18066
+ }
18067
+ function transcriptOf(cwd, session, home = homedir10()) {
18068
+ const projects = join12(home, ".claude", "projects");
18069
+ const slug = projectSlug(cwd);
18070
+ const exact = join12(projects, slug, `${session}.jsonl`);
18071
+ if (existsSync5(exact)) return exact;
18072
+ let dirs = [];
18073
+ try {
18074
+ dirs = readdirSync6(projects).filter((d) => d.startsWith(slug));
18075
+ } catch {
18076
+ return null;
18077
+ }
18078
+ for (const dir of dirs) {
18079
+ const candidate = join12(projects, dir, `${session}.jsonl`);
18080
+ if (existsSync5(candidate)) return candidate;
18081
+ }
18082
+ let all = [];
18083
+ try {
18084
+ all = readdirSync6(projects);
18085
+ } catch {
18086
+ return null;
18087
+ }
18088
+ for (const dir of all) {
18089
+ const candidate = join12(projects, dir, `${session}.jsonl`);
18090
+ if (existsSync5(candidate)) return candidate;
18091
+ }
18092
+ return null;
18093
+ }
18094
+ var TAIL_BYTES2 = 2e6;
18095
+ var KEEP = { said: 6, wrote: 4, files: 20, commands: 12 };
18096
+ var COMMAND = 200;
18097
+ function tailOf(path, bytes = TAIL_BYTES2) {
18098
+ const fd = openSync4(path, "r");
18099
+ try {
18100
+ const size = fstatSync(fd).size;
18101
+ const from = Math.max(0, size - bytes);
18102
+ const buffer = Buffer.alloc(Math.min(size, bytes));
18103
+ readSync3(fd, buffer, 0, buffer.length, from);
18104
+ const text = buffer.toString("utf8");
18105
+ return from > 0 ? text.slice(text.indexOf("\n") + 1) : text;
18106
+ } finally {
18107
+ closeSync4(fd);
18108
+ }
18109
+ }
18110
+ var SCAFFOLDING = /^\s*<(task-notification|system-reminder|local-command-stdout|command-message|command-name)\b/;
18111
+ function words(content) {
18112
+ if (typeof content === "string") return content;
18113
+ if (!Array.isArray(content)) return "";
18114
+ return content.filter((b) => b.type === "text" && b.text).map((b) => b.text.trim()).join("\n\n");
18115
+ }
18116
+ function readTail2(tail) {
18117
+ const todos = [];
18118
+ const said = [];
18119
+ const wrote = [];
18120
+ const files = [];
18121
+ const commands = [];
18122
+ for (const raw of tail.split("\n")) {
18123
+ if (!raw.trim()) continue;
18124
+ let line;
18125
+ try {
18126
+ line = JSON.parse(raw);
18127
+ } catch {
18128
+ continue;
18129
+ }
18130
+ const content = line.message?.content;
18131
+ if (line.type === "user") {
18132
+ const text2 = words(content);
18133
+ if (text2 && !SCAFFOLDING.test(text2)) said.push(text2);
18134
+ continue;
18135
+ }
18136
+ if (line.type !== "assistant" || !Array.isArray(content)) continue;
18137
+ const text = words(content);
18138
+ if (text) wrote.push(text);
18139
+ for (const block2 of content) {
18140
+ if (block2.type !== "tool_use" || !block2.input) continue;
18141
+ const input = block2.input;
18142
+ if (block2.name === "TodoWrite" && Array.isArray(input["todos"])) {
18143
+ todos.length = 0;
18144
+ todos.push(...input["todos"]);
18145
+ }
18146
+ const file = input["file_path"];
18147
+ if (typeof file === "string" && !files.includes(file)) files.push(file);
18148
+ const command = input["command"];
18149
+ if (typeof command === "string") commands.push(command.split("\n")[0].trim().slice(0, COMMAND));
18150
+ }
18151
+ }
18152
+ return {
18153
+ todos,
18154
+ said: said.slice(-KEEP.said),
18155
+ wrote: wrote.slice(-KEEP.wrote),
18156
+ files: files.slice(-KEEP.files),
18157
+ commands: commands.slice(-KEEP.commands)
18158
+ };
18159
+ }
18160
+ var QUOTE = 1200;
18161
+ var quote = (text) => text.length > QUOTE ? `${text.slice(0, QUOTE)}\u2026` : text;
18162
+ function dossierFrom(tail, meta) {
18163
+ const read3 = readTail2(tail);
18164
+ const at = (meta.at ?? /* @__PURE__ */ new Date()).toISOString();
18165
+ const open = read3.todos.filter((t) => t.status !== "completed");
18166
+ const done = read3.todos.filter((t) => t.status === "completed");
18167
+ const out = [
18168
+ `# ${meta.name} \u2014 handoff`,
18169
+ `${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.`,
18170
+ `- session: ${meta.session}`,
18171
+ `- workspace: ${meta.cwd}`,
18172
+ `- written: ${at}`
18173
+ ];
18174
+ if (open.length || done.length) {
18175
+ out.push("## Its own to-do list, as it last stood");
18176
+ for (const t of open) out.push(`- [ ] ${t.content ?? ""}${t.status && t.status !== "pending" ? ` (${t.status})` : ""}`);
18177
+ for (const t of done) out.push(`- [x] ${t.content ?? ""}`);
18178
+ }
18179
+ if (read3.said.length) {
18180
+ out.push("## The last words typed into it");
18181
+ for (const s of read3.said) out.push(`> ${quote(s).split("\n").join("\n> ")}`);
18182
+ }
18183
+ if (read3.wrote.length) {
18184
+ out.push("## The last it said");
18185
+ for (const w of read3.wrote) out.push(`> ${quote(w).split("\n").join("\n> ")}`);
18186
+ }
18187
+ if (read3.files.length) {
18188
+ out.push("## Files it had open or changed");
18189
+ for (const f of read3.files) out.push(`- ${f}`);
18190
+ }
18191
+ if (read3.commands.length) {
18192
+ out.push("## The last commands it ran");
18193
+ for (const c of read3.commands) out.push(`- \`${c}\``);
18194
+ }
18195
+ return `${out.join("\n\n")}
18196
+ `;
18197
+ }
18198
+ function writeDossier(path, body) {
18199
+ mkdirSync4(join12(path, ".."), { recursive: true });
18200
+ writeFileSync4(path, body, "utf8");
18201
+ return path;
18202
+ }
18203
+ function dossierForWall(meta) {
18204
+ try {
18205
+ const path = dossierPath(meta.session);
18206
+ if (existsSync5(path)) return path;
18207
+ const transcript = transcriptOf(meta.cwd, meta.session);
18208
+ if (!transcript) return null;
18209
+ const body = dossierFrom(tailOf(transcript), meta);
18210
+ return writeDossier(path, body);
18211
+ } catch {
18212
+ return null;
18213
+ }
18214
+ }
18215
+
17577
18216
  // src/paigy/conversation.ts
17578
18217
  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).";
17579
18218
  var SAFETY_MS = 6e4;
@@ -17612,7 +18251,7 @@ var BEAT_REPORT_MS = 10 * 6e4;
17612
18251
  var ended = (state) => state === "done" || state === "cancelled";
17613
18252
  function unheard(brief, state, since = null, after = -1, reviewSince, gathered) {
17614
18253
  const seen = state.seen ??= /* @__PURE__ */ new Set();
17615
- const words = [];
18254
+ const words2 = [];
17616
18255
  const pendingAt = reviewSince ? Date.parse(reviewSince) : null;
17617
18256
  for (const [i, e] of (brief.entries ?? []).entries()) {
17618
18257
  if (seen.has(e.entryId) || !e.authorParticipant.startsWith("human:")) continue;
@@ -17629,7 +18268,7 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
17629
18268
  seen.add(e.entryId);
17630
18269
  const text = entryWords(e).trim();
17631
18270
  if (text) {
17632
- words.push(text);
18271
+ words2.push(text);
17633
18272
  gathered?.add(e.entryId);
17634
18273
  }
17635
18274
  }
@@ -17637,9 +18276,9 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
17637
18276
  const key3 = `answer:${answer.decisionNeedId}`;
17638
18277
  if (seen.has(key3) || Date.parse(answer.acceptedAt) < pendingAt) continue;
17639
18278
  seen.add(key3);
17640
- words.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
18279
+ words2.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
17641
18280
  }
17642
- return words;
18281
+ return words2;
17643
18282
  }
17644
18283
  function sinceTheWork(brief) {
17645
18284
  const entries = brief.entries ?? [];
@@ -17762,9 +18401,9 @@ async function hear(session, state, rail, held, opts, waiting) {
17762
18401
  const log2 = opts?.log;
17763
18402
  const { heard, listed, direct } = await gather(state, rail, held, waiting, log2);
17764
18403
  const said = heard.filter(says);
17765
- const words = [...direct.flatMap((d) => d.words), ...said.map(block)];
17766
- if (words.length) {
17767
- const text = words.join("\n\n");
18404
+ const words2 = [...direct.flatMap((d) => d.words), ...said.map(block)];
18405
+ if (words2.length) {
18406
+ const text = words2.join("\n\n");
17768
18407
  try {
17769
18408
  await send2(session, state, text);
17770
18409
  } catch (error) {
@@ -17795,7 +18434,7 @@ async function note(state, rail, held, inbox, how, waiting) {
17795
18434
  const said = heard.filter(says);
17796
18435
  const parts = [...direct.flatMap((d) => d.words), ...said.map(block)];
17797
18436
  if (!parts.length) return 0;
17798
- const words = parts.join("\n\n");
18437
+ const words2 = parts.join("\n\n");
17799
18438
  const goals = said.map((h) => h.goalId);
17800
18439
  const assigned = given(said);
17801
18440
  if (how.tally) how.tally.announced += assigned.length;
@@ -17803,13 +18442,13 @@ async function note(state, rail, held, inbox, how, waiting) {
17803
18442
  try {
17804
18443
  name = inbox.put(`${NOTED}
17805
18444
 
17806
- ${words}`);
18445
+ ${words2}`);
17807
18446
  how.log?.(`\u25B9 noted mid-turn: ${short(goals)}`);
17808
18447
  if (assigned.length) how.log?.(`\u25B8 announced assigned ${short(assigned)} (via hook)`);
17809
18448
  } catch (error) {
17810
18449
  how.log?.(`\u26A0 could not note mid-turn (${error.message}): ${short(goals)} wait for the turn's end`);
17811
18450
  }
17812
- (state.noted ??= []).push({ name, goals, words, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
18451
+ (state.noted ??= []).push({ name, goals, words: words2, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
17813
18452
  for (const d of direct) for (const id3 of d.entryIds) (state.seen ??= /* @__PURE__ */ new Set()).add(id3);
17814
18453
  return 1;
17815
18454
  }
@@ -17876,6 +18515,24 @@ async function step(session, state, rail, opts) {
17876
18515
  state.paused = void 0;
17877
18516
  state.carryOn = true;
17878
18517
  }
18518
+ if (state.handoff && !state.handoff.said && !state.asks?.size) {
18519
+ const words2 = keepContext(state.handoff.dossier, opts?.fill?.() ?? void 0);
18520
+ if (state.resting) {
18521
+ await send2(session, state, words2);
18522
+ state.handoff.said = true;
18523
+ opts?.log?.(`\u25B8 context turned over: told to write it down and judge whether to hand off (dossier ${state.handoff.dossier})`);
18524
+ return;
18525
+ }
18526
+ if (opts?.inbox && !state.handoff.noted) {
18527
+ try {
18528
+ opts.inbox.put(words2);
18529
+ state.handoff.noted = true;
18530
+ opts.log?.("\u25B9 context turned over: the note is in its inbox for this turn's next tool call");
18531
+ } catch (error) {
18532
+ opts.log?.(`\u26A0 could not note the turnover (${error.message}): it is typed in when the turn ends`);
18533
+ }
18534
+ }
18535
+ }
17879
18536
  await look(session, state, rail, opts);
17880
18537
  if (state.carryOn && state.resting && !state.asks?.size) await send2(session, state, "");
17881
18538
  }
@@ -17950,10 +18607,10 @@ async function look(session, state, rail, opts) {
17950
18607
  await hear(session, state, rail, brief, { ...opts?.log ? { log: opts.log } : {}, ...opts?.tally ? { tally: opts.tally } : {} });
17951
18608
  }
17952
18609
  async function send2(session, state, text) {
17953
- let words = text;
18610
+ let words2 = text;
17954
18611
  if (state.carryOn) {
17955
18612
  const owed = state.owed;
17956
- words = [owed, text].filter(Boolean).join("\n\n");
18613
+ words2 = [owed, text].filter(Boolean).join("\n\n");
17957
18614
  text = [CARRY_ON, ...owed ? [OWED, owed] : [], text].filter(Boolean).join("\n\n");
17958
18615
  }
17959
18616
  const resting = state.resting;
@@ -17964,7 +18621,7 @@ async function send2(session, state, text) {
17964
18621
  state.resting = resting;
17965
18622
  throw error;
17966
18623
  }
17967
- state.typed = words || void 0;
18624
+ state.typed = words2 || void 0;
17968
18625
  if (state.carryOn) {
17969
18626
  state.carryOn = false;
17970
18627
  state.carriedOn = true;
@@ -17980,6 +18637,7 @@ async function pump(session, state, rail, opts) {
17980
18637
  ...opts.initialPrompt ? { initialPrompt: opts.initialPrompt } : {},
17981
18638
  ...opts.log ? { log: opts.log } : {},
17982
18639
  ...opts.inbox ? { inbox: opts.inbox } : {},
18640
+ ...opts.fill ? { fill: opts.fill } : {},
17983
18641
  now,
17984
18642
  tally
17985
18643
  };
@@ -18017,6 +18675,10 @@ function runHarness(opts) {
18017
18675
  const clock4 = beat();
18018
18676
  let session = null;
18019
18677
  const speaksAs = opts.session ?? opts.resume ?? sessionId();
18678
+ let conversation;
18679
+ let model;
18680
+ const filled = fillReader();
18681
+ const fill = () => filled.measure(conversation, model ?? opts.model);
18020
18682
  const instance = randomUUID4();
18021
18683
  const rail = railFor({ token: opts.token, reach: reachAs(speaksAs, instance) });
18022
18684
  let inbox;
@@ -18028,6 +18690,36 @@ function runHarness(opts) {
18028
18690
  }
18029
18691
  }
18030
18692
  const name = opts.name ?? "The agent";
18693
+ let handedOn = false;
18694
+ async function handOnCredits(limit) {
18695
+ if (handedOn) return;
18696
+ if (!handsOver(limit)) return;
18697
+ handedOn = true;
18698
+ const dossier = dossierForWall({
18699
+ name,
18700
+ session: conversation ?? speaksAs,
18701
+ cwd: opts.cwd,
18702
+ why: `A usage limit stopped this session until ${limit.resets}, so its work was handed on.`
18703
+ });
18704
+ const to = carriesOn(detectAll(), opts.harness);
18705
+ if (!to) {
18706
+ opts.log(`\u23F8 nothing else here can take this work, so it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
18707
+ return;
18708
+ }
18709
+ try {
18710
+ const launched = await launchSession({
18711
+ name: successorName(name, to.label),
18712
+ harness: to.name,
18713
+ brief: creditsBrief({ name, dossier, resets: limit.resets }),
18714
+ workspace: opts.cwd,
18715
+ mode: opts.mode,
18716
+ successor: true
18717
+ }, { ...opts.token ? { token: opts.token } : {} });
18718
+ opts.log(`\u25B6 out of credits until ${limit.resets}: ${to.label} session ${launched.sessionId} takes this work on${dossier ? `, with its context in ${dossier}` : ""}`);
18719
+ } catch (error) {
18720
+ opts.log(`\u26A0 could not hand this work on (${error.message}): it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
18721
+ }
18722
+ }
18031
18723
  function runningAgain() {
18032
18724
  state.carriedOn = false;
18033
18725
  opts.log("\u25B6 running again after the limit");
@@ -18060,6 +18752,11 @@ ${event.message}`, state, rail, { log: opts.log });
18060
18752
  }
18061
18753
  if (event.kind === "work") {
18062
18754
  if (state.carriedOn) runningAgain();
18755
+ if (compacted(event)) {
18756
+ state.handoff = { dossier: dossierPath(conversation ?? speaksAs) };
18757
+ opts.log(`\u25C6 ${name}'s context turned over \u2014 writing it to ${state.handoff.dossier}`);
18758
+ clock4.nudge("wake");
18759
+ }
18063
18760
  opts.log(`\u2699 ${event.tool}${event.note ? ` \u2014 ${event.note.split("\n")[0] ?? ""}` : ""}`);
18064
18761
  tail = pushWork(tail, workLine(event));
18065
18762
  return;
@@ -18067,9 +18764,15 @@ ${event.message}`, state, rail, { log: opts.log });
18067
18764
  if (event.kind === "turn") opts.log(`${event.role}: ${event.text.split("\n")[0] ?? ""}`);
18068
18765
  if (event.kind === "idle") {
18069
18766
  tail = [];
18767
+ conversation = event.session ?? conversation;
18768
+ model = event.model ?? model;
18070
18769
  const carried = state.carriedOn && !event.failed;
18071
- if (await afterTurn(event, state, rail, { log: opts.log })) LIMITS.paused(name, Date.now());
18072
- else if (state.full) {
18770
+ 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".' });
18771
+ const limit = await afterTurn(event, state, rail, { log: opts.log, dossier });
18772
+ if (limit) {
18773
+ LIMITS.paused(name, Date.now());
18774
+ await handOnCredits(limit);
18775
+ } else if (state.full) {
18073
18776
  opts.log(`\u25A0 ${name}'s conversation is full \u2014 ending this run; it will not be resumed`);
18074
18777
  opts.onFull?.(speaksAs);
18075
18778
  stop2();
@@ -18086,6 +18789,7 @@ ${event.message}`, state, rail, { log: opts.log });
18086
18789
  ...opts.token ? { token: opts.token } : {},
18087
18790
  ...opts.resume ? { resume: opts.resume } : {},
18088
18791
  ...opts.session ? { session: opts.session } : {},
18792
+ ...opts.model ? { model: opts.model } : {},
18089
18793
  ...opts.bin ? { bin: opts.bin } : {},
18090
18794
  ...inbox ? { inbox: inbox.dir } : {},
18091
18795
  onExit: () => {
@@ -18094,7 +18798,7 @@ ${event.message}`, state, rail, { log: opts.log });
18094
18798
  },
18095
18799
  onEvent: (event) => void handle3(event).catch((err) => opts.log(`\u26A0 ${err.message}`))
18096
18800
  });
18097
- void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, ...inbox ? { inbox } : {} }).catch(
18801
+ void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, fill, ...inbox ? { inbox } : {} }).catch(
18098
18802
  (e) => opts.log(`\u26A0 conversation loop stopped: ${e.message}`)
18099
18803
  );
18100
18804
  opts.log(`\u25B6 started ${opts.harness} in ${opts.cwd} (${opts.mode} mode)`);
@@ -18117,88 +18821,8 @@ ${event.message}`, state, rail, { log: opts.log });
18117
18821
  };
18118
18822
  }
18119
18823
 
18120
- // src/update.ts
18121
- import { execFile } from "child_process";
18122
- import { createRequire } from "module";
18123
- import { dirname as dirname3, join as join10 } from "path";
18124
- import { promisify } from "util";
18125
- var SERVICE_LABEL = "ai.paigy.harness";
18126
- var VERSION = createRequire(import.meta.url)("../package.json").version;
18127
- var REGISTRY = "https://registry.npmjs.org/@paigy/harness/latest";
18128
- var CHECK_MS = 60 * 6e4;
18129
- function newer(latest, current) {
18130
- const parts = (v) => /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null;
18131
- const [a, b] = [parts(latest), parts(current)];
18132
- if (!a || !b) return false;
18133
- for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
18134
- return false;
18135
- }
18136
- var WAIT_CAP_MS = 6 * 36e5;
18137
- function updateAction(o) {
18138
- if (!o.service || !o.latest || o.latest === o.failed || !newer(o.latest, o.current)) return "none";
18139
- if (o.sessions <= 0) return "install";
18140
- const working = o.working ?? o.sessions;
18141
- if (working > 0) return "wait";
18142
- return (o.waited ?? 0) >= WAIT_CAP_MS ? "install" : "wait";
18143
- }
18144
- async function latestVersion() {
18145
- const res = await fetch(REGISTRY, { signal: AbortSignal.timeout(1e4) });
18146
- return res.ok ? (await res.json()).version ?? null : null;
18147
- }
18148
- async function install(version) {
18149
- const bin = dirname3(process.execPath);
18150
- await promisify(execFile)(join10(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
18151
- env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}`, npm_config_update_notifier: "false" },
18152
- timeout: 5 * 6e4
18153
- });
18154
- }
18155
- function selfUpdater(deps) {
18156
- const service = deps.service ?? process.env.XPC_SERVICE_NAME === SERVICE_LABEL;
18157
- let latest = null;
18158
- let checkedAt = -Infinity;
18159
- let failed;
18160
- let waiting = false;
18161
- let waitingSince = null;
18162
- return async () => {
18163
- if (!service) return;
18164
- const now = (deps.now ?? Date.now)();
18165
- if (now - checkedAt >= CHECK_MS) {
18166
- checkedAt = now;
18167
- latest = await (deps.latest ?? latestVersion)().catch(() => latest);
18168
- }
18169
- const sessions = deps.sessions();
18170
- const working = deps.working?.();
18171
- if (latest && newer(latest, VERSION) && latest !== failed && waitingSince === null) waitingSince = now;
18172
- const action = updateAction({
18173
- current: VERSION,
18174
- latest,
18175
- service,
18176
- sessions,
18177
- failed,
18178
- ...working === void 0 ? {} : { working },
18179
- waited: waitingSince === null ? 0 : now - waitingSince
18180
- });
18181
- if (action === "wait" && !waiting) {
18182
- deps.log(working ? `\u21E1 @paigy/harness ${latest} is out \u2014 updating once the turn in flight finishes` : `\u21E1 @paigy/harness ${latest} is out \u2014 updating once no session is running (at most ${Math.round(WAIT_CAP_MS / 36e5)}h)`);
18183
- }
18184
- waiting = action === "wait";
18185
- if (action === "install" && sessions > 0) {
18186
- deps.log(`\u21E1 @paigy/harness ${latest} is out and ${sessions} resting session(s) have held it for ${Math.round((now - (waitingSince ?? now)) / 36e5)}h \u2014 restarting over them`);
18187
- }
18188
- if (action !== "install" || !latest) return;
18189
- try {
18190
- await (deps.install ?? install)(latest);
18191
- deps.log(`\u21E1 updated @paigy/harness ${VERSION} \u2192 ${latest} \u2014 restarting`);
18192
- (deps.exit ?? (() => process.exit(0)))();
18193
- } catch (e) {
18194
- failed = latest;
18195
- deps.log(`\u26A0 could not update to @paigy/harness ${latest}: ${e.message.split("\n")[0]} \u2014 run: npm install -g @paigy/harness`);
18196
- }
18197
- };
18198
- }
18199
-
18200
18824
  // src/host.ts
18201
- var HOST_FILE = join11(homedir9(), ".paigy", "host.json");
18825
+ var HOST_FILE = join13(homedir11(), ".paigy", "host.json");
18202
18826
  function wakeHarness(slot, saved, claudeTranscript) {
18203
18827
  if (slot === "Desktop") return void 0;
18204
18828
  if (saved !== null) return saved === "agy" || saved === "codex" || saved === "claude" || saved === "grok" ? saved : void 0;
@@ -18237,6 +18861,7 @@ var claimedRun = (sessionId2) => {
18237
18861
  return { slot, key: runKey(slot) };
18238
18862
  };
18239
18863
  var launchRun = (spec) => ({ session: spec.sessionId, model: spec.model });
18864
+ var launchMode = (mode) => mode === "ask" ? "ask" : "bypass";
18240
18865
  var BOUND_ELSEWHERE_MS = 10 * 6e4;
18241
18866
  var boundElsewhere = /* @__PURE__ */ new Map();
18242
18867
  var BOUND_SKIP = "is bound to the session it was paired in, which this host cannot name \u2014 run `paigy-harness handoff` as it, in its folder, to record it";
@@ -18377,7 +19002,8 @@ function startHost(opts) {
18377
19002
  device: null,
18378
19003
  workspace: spec.workspace,
18379
19004
  harness: spec.harness,
18380
- session_id: spec.sessionId
19005
+ session_id: spec.sessionId,
19006
+ mode: launchMode(spec.mode)
18381
19007
  }, slot);
18382
19008
  } catch {
18383
19009
  log2("Cannot persist launch identity/runtime; session was not started. Check local storage and relaunch.");
@@ -18386,7 +19012,7 @@ function startHost(opts) {
18386
19012
  const run = runHarness({
18387
19013
  harness: spec.harness,
18388
19014
  cwd: workspace,
18389
- mode: "bypass",
19015
+ mode: launchMode(spec.mode),
18390
19016
  prompt: "",
18391
19017
  token: spec.token,
18392
19018
  ...launchRun(spec),
@@ -18405,7 +19031,7 @@ function startHost(opts) {
18405
19031
  void heartbeat(void 0, { token: spec.token }).catch(() => {
18406
19032
  });
18407
19033
  void refreshIdentities();
18408
- opts.log(`\u25B6 phone-launched ${label} (${spec.harness}) in ${spec.workspace}`);
19034
+ opts.log(`\u25B6 launched ${label} (${spec.harness}, ${launchMode(spec.mode)}) in ${spec.workspace}`);
18409
19035
  }
18410
19036
  const ends = await claimSessionEnds(asHost).catch(() => []);
18411
19037
  for (const end of ends) {
@@ -18552,9 +19178,10 @@ function startHost(opts) {
18552
19178
  }
18553
19179
  const log2 = (line) => opts.log(`[${label}] ${line}`);
18554
19180
  const run = runHarness({
19181
+ // A wake runs the session the way its launch asked (the slot keeps it), bypass when it named none.
18555
19182
  harness,
18556
19183
  cwd: workspace,
18557
- mode: "bypass",
19184
+ mode: launchMode(identity.mode),
18558
19185
  prompt: "",
18559
19186
  token,
18560
19187
  ...identity.sessionId ? { session: identity.sessionId } : {},
@@ -18641,7 +19268,7 @@ function startHost(opts) {
18641
19268
  };
18642
19269
  const publish = () => {
18643
19270
  try {
18644
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
19271
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
18645
19272
  } catch {
18646
19273
  }
18647
19274
  };
@@ -18708,7 +19335,7 @@ function startHost(opts) {
18708
19335
  streamActivity();
18709
19336
  clearInterval(activityTick);
18710
19337
  try {
18711
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
19338
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
18712
19339
  } catch {
18713
19340
  }
18714
19341
  }
@@ -18721,6 +19348,7 @@ function startHost(opts) {
18721
19348
 
18722
19349
  // src/main.ts
18723
19350
  var here = dirname4(fileURLToPath(import.meta.url));
19351
+ setClient(`desktop@${VERSION}`);
18724
19352
  var wsDeps = { file: workspacesFile() };
18725
19353
  var DEVICE_SLOT = "Desktop";
18726
19354
  var deviceToken = () => readToken(DEVICE_SLOT);
@@ -18728,7 +19356,7 @@ var win = null;
18728
19356
  function log(message) {
18729
19357
  win?.webContents.send("paigy:log", message);
18730
19358
  }
18731
- var ICON = join12(here, "..", "assets", "icon.png");
19359
+ var ICON = join14(here, "..", "assets", "icon.png");
18732
19360
  function createWindow() {
18733
19361
  win = new BrowserWindow({
18734
19362
  // Sized for the working log, which is now the window's centerpiece; the layout is a
@@ -18740,9 +19368,9 @@ function createWindow() {
18740
19368
  minHeight: 520,
18741
19369
  icon: ICON,
18742
19370
  // Windows/Linux window icon; macOS uses the dock icon below
18743
- webPreferences: { preload: join12(here, "preload.cjs"), contextIsolation: true, nodeIntegration: false }
19371
+ webPreferences: { preload: join14(here, "preload.cjs"), contextIsolation: true, nodeIntegration: false }
18744
19372
  });
18745
- void win.loadFile(join12(here, "..", "renderer", "index.html"));
19373
+ void win.loadFile(join14(here, "..", "renderer", "index.html"));
18746
19374
  }
18747
19375
  var host = null;
18748
19376
  app.whenReady().then(() => {
@@ -18811,7 +19439,7 @@ ipcMain.handle("paigy:agent", async (_e, name) => {
18811
19439
  });
18812
19440
  ipcMain.handle("paigy:agent-log", (_e, name) => {
18813
19441
  try {
18814
- const all = readFileSync7(join12(homedir10(), ".paigy", "host.log"), "utf8").split("\n");
19442
+ const all = readFileSync7(join14(homedir12(), ".paigy", "host.log"), "utf8").split("\n");
18815
19443
  const mine = all.filter((l) => l.includes(`[${name}]`) || /[▶✖◉⚠]/.test(l) && l.includes(name));
18816
19444
  return mine.slice(-500).join("\n");
18817
19445
  } catch {