@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/cli.js CHANGED
@@ -23102,7 +23102,7 @@ var CATALOG = [
23102
23102
  loginHint: "Run `claude` once in a terminal and sign in.",
23103
23103
  installCli: "curl -fsSL https://claude.ai/install.sh | bash",
23104
23104
  installAdapter: "npm install -g @agentclientprotocol/claude-agent-acp",
23105
- models: ["claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-opus-20240229"]
23105
+ models: ["claude-opus-5", "claude-sonnet-5", "claude-haiku-4-5-20251001"]
23106
23106
  },
23107
23107
  {
23108
23108
  name: "codex",
@@ -23112,8 +23112,20 @@ var CATALOG = [
23112
23112
  authProbe: ["codex", "login", "status"],
23113
23113
  loginHint: "Run `codex login` to authenticate.",
23114
23114
  installCli: "curl -fsSL https://chatgpt.com/codex/install.sh | sh",
23115
+ // UNPINNED AGAIN (2026-11-20, Goal ae096b5d, the owner's "Build SDK 2 turn support"). It was
23116
+ // pinned to 2.2.2 for a day because from 2.3.0 the adapter answers `session/prompt` with
23117
+ // `{messageId}` at once instead of `{stopReason}` at the end; `acp.ts` now settles a turn on
23118
+ // SDK 2's idle `state_update` as well, so the current adapter is the right one to install. It
23119
+ // has to be: the adapter runs its OWN bundled codex, and the one in 2.2.2 (0.160.1) is refused
23120
+ // by an account whose entitlement needs a current client.
23115
23121
  installAdapter: "npm install -g @agentclientprotocol/codex-acp",
23116
- models: ["gpt-4o", "gpt-4o-mini", "o1", "o1-mini"]
23122
+ // ONE ID, BECAUSE ONE IS WHAT A CHATGPT ACCOUNT TAKES (2026-11-23/24, Goal 04549742). The
23123
+ // whole previous list -- and `gpt-5.1-codex`, `gpt-5.1-codex-max` and the `gpt-6.2-astra`
23124
+ // that `~/.codex/config.toml` sets -- answer `400 model_not_found`: "not supported when
23125
+ // using Codex with a ChatGPT account". A Codex launch that took this list's head therefore
23126
+ // died on its first turn, and a dead turn marks its Goal done with the work untouched
23127
+ // (`afterTurn` -> `finish`, `paigy/bridge.ts`), which is how it read as a working session.
23128
+ models: ["gpt-6.1-sol"]
23117
23129
  },
23118
23130
  {
23119
23131
  name: "agy",
@@ -23124,7 +23136,9 @@ var CATALOG = [
23124
23136
  authProbe: ["agy", "help"],
23125
23137
  loginHint: "Install and set up Antigravity (`agy`).",
23126
23138
  installCli: "curl -fsSL https://antigravity.dev/install.sh | bash",
23127
- models: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.0-pro-exp"]
23139
+ // `agy models` order, high-effort variant of each family it offers (the suffix IS the
23140
+ // reasoning effort: `gemini-4-neon-low` and `-xhigh` are the same model turned down or up).
23141
+ models: ["gemini-4-neon-high", "gemini-4-argon-high", "gemini-4-carbon-high", "gemini-4-hydrogen-high"]
23128
23142
  },
23129
23143
  {
23130
23144
  name: "grok",
@@ -23134,7 +23148,15 @@ var CATALOG = [
23134
23148
  // to miss, and detection would report adapter-missing on a machine that can already launch.
23135
23149
  authProbe: ["sh", "-c", 'test -s "$HOME/.grok/auth.json"'],
23136
23150
  loginHint: "Run `grok` once in a terminal and sign in.",
23137
- installCli: "curl -fsSL https://x.ai/cli/install.sh | bash"
23151
+ installCli: "curl -fsSL https://x.ai/cli/install.sh | bash",
23152
+ // Grok was the one vendor with NO list, so a Grok session could only ever be started on
23153
+ // whatever the CLI defaulted to and the phone could offer no choice. `grok models` answers
23154
+ // without a login, so writing one cost the pending sign-in nothing.
23155
+ // BUT SIGNED OUT IT ANSWERS A SUBSET (2026-11-24). Before the owner's browser login `grok
23156
+ // models` named "grok-4.6 (default), grok-4.5", which is what this list said. The moment
23157
+ // ~/.grok/auth.json existed the same command answered grok-4.7 as the default and added
23158
+ // grok-4.7-build-fast — so a signed-out reading is a floor, not the menu. Re-read it signed in.
23159
+ models: ["grok-4.7", "grok-4.7-build-fast", "grok-4.6", "grok-4.5"]
23138
23160
  }
23139
23161
  ];
23140
23162
  function probeDirs(home = homedir()) {
@@ -27233,10 +27255,10 @@ var coerce = {
27233
27255
  var NEVER = INVALID;
27234
27256
 
27235
27257
  // src/cli-args.ts
27236
- var USAGE = "usage: paigy-harness setup | pair | host [--grant DIR]\u2026 | service | enable-tools [--scope user|project] | hatch NAME [--voice KEY] [--slot SLOT] | launch NAME [--under GOAL] [--voice KEY] [--harness \u2026] [--mode \u2026] [--cwd DIR] BRIEF\u2026 | handoff | [--harness claude|codex|agy|grok] [--mode bypass|ask] [--cwd DIR] [--grace SECONDS] [--doctor] PROMPT\u2026";
27258
+ var USAGE = "usage: paigy-harness setup | pair | host [--grant DIR]\u2026 | service | enable-tools [--scope user|project] | hatch NAME [--voice KEY] [--slot SLOT] | launch NAME [--under GOAL] [--approval QUESTION] [--voice KEY] [--harness \u2026] [--model ID] [--mode \u2026] [--cwd DIR] BRIEF\u2026 | handoff | [--harness claude|codex|agy|grok] [--model ID] [--mode bypass|ask] [--cwd DIR] [--grace SECONDS] [--doctor] PROMPT\u2026";
27237
27259
  function parseArgs(argv) {
27238
- const args = { harness: "claude", mode: "bypass", cwd: process.cwd(), doctor: false, help: false, host: false, pair: false, service: false, setup: false, enableTools: false, scope: "user", grant: [], hatch: null, voice: null, slot: null, launch: null, under: null, graceSeconds: 90, prompt: "", handoff: false };
27239
- const words = [];
27260
+ const args = { harness: "claude", mode: "bypass", cwd: process.cwd(), doctor: false, help: false, host: false, pair: false, service: false, setup: false, enableTools: false, scope: "user", grant: [], hatch: null, voice: null, slot: null, launch: null, under: null, approval: null, model: null, graceSeconds: 90, prompt: "", handoff: false };
27261
+ const words2 = [];
27240
27262
  let commandPosition = true;
27241
27263
  for (let i = 0; i < argv.length; i++) {
27242
27264
  const arg = argv[i];
@@ -27247,6 +27269,10 @@ function parseArgs(argv) {
27247
27269
  const v = next();
27248
27270
  if (v !== "claude" && v !== "codex" && v !== "agy" && v !== "grok") return { error: `--harness must be claude, codex, agy, or grok, got ${v ?? "nothing"}` };
27249
27271
  args.harness = v;
27272
+ } else if (arg === "--model") {
27273
+ const v = next();
27274
+ if (!v || v.startsWith("-")) return { error: "--model needs a model id, as your harness names it" };
27275
+ args.model = v;
27250
27276
  } else if (arg === "--mode") {
27251
27277
  const v = next();
27252
27278
  if (v !== "bypass" && v !== "ask") return { error: `--mode must be bypass or ask, got ${v ?? "nothing"}` };
@@ -27303,15 +27329,20 @@ function parseArgs(argv) {
27303
27329
  const v = next();
27304
27330
  if (!v || !external_exports.string().uuid().safeParse(v).success) return { error: "--under needs a Goal UUID" };
27305
27331
  args.under = v;
27332
+ } else if (arg === "--approval") {
27333
+ const v = next();
27334
+ if (!v || !external_exports.string().uuid().safeParse(v).success) return { error: "--approval needs the answered question's id (its whole UUID)" };
27335
+ args.approval = v;
27306
27336
  } else if (arg?.startsWith("--")) {
27307
27337
  return { error: `unknown flag ${arg}` };
27308
27338
  } else if (arg) {
27309
- words.push(arg);
27339
+ words2.push(arg);
27310
27340
  }
27311
27341
  }
27312
- args.prompt = words.join(" ");
27342
+ args.prompt = words2.join(" ");
27313
27343
  if (args.help) return args;
27314
27344
  if (args.under && !args.launch) return { error: "--under requires launch NAME" };
27345
+ if (args.approval && !args.launch) return { error: "--approval requires launch NAME" };
27315
27346
  if (args.launch && !args.prompt) return { error: 'launch needs a brief: paigy-harness launch "Deploy check" "brief"' };
27316
27347
  if (!args.doctor && !args.handoff && !args.hatch && !args.host && !args.pair && !args.service && !args.setup && !args.enableTools && !args.prompt) return { error: "a prompt is required (or setup / --doctor / pair / host / service / enable-tools / hatch NAME / handoff)" };
27317
27348
  return args;
@@ -27361,6 +27392,74 @@ function lineageName(parent, name, max = NAME_MAX) {
27361
27392
  return own.slice(0, max);
27362
27393
  }
27363
27394
 
27395
+ // src/launch.ts
27396
+ async function launchViaHost(args, deps) {
27397
+ const asAgent = !!deps.agentToken;
27398
+ const name = lineageName(asAgent ? deps.parentName : null, args.launch);
27399
+ const spec = {
27400
+ name,
27401
+ harness: args.harness,
27402
+ brief: args.prompt,
27403
+ workspace: args.cwd,
27404
+ mode: args.mode,
27405
+ ...args.model ? { model: args.model } : {},
27406
+ ...args.under ? { parentGoalId: args.under } : {},
27407
+ ...deps.deviceTokenId ? { hostTokenId: deps.deviceTokenId } : {}
27408
+ };
27409
+ let token;
27410
+ let input;
27411
+ if (asAgent) {
27412
+ if (!args.approval) {
27413
+ deps.error(`\u270B ${name} was not launched: an agent launches only a session the person approved.`);
27414
+ deps.error(" Ask them first: one question, on the Goal it is for, naming the session, its role, model and mode.");
27415
+ deps.error(" Once they answer, launch again with that question's id: --approval QUESTION_ID");
27416
+ return 1;
27417
+ }
27418
+ token = deps.agentToken;
27419
+ input = { ...spec, approvalQuestionId: args.approval };
27420
+ } else {
27421
+ if (!deps.deviceToken) {
27422
+ deps.error(`\u270B ${name} was not launched: this computer is not connected to Paigy. Connect it with: paigy-harness pair`);
27423
+ return 1;
27424
+ }
27425
+ if (!deps.isTTY) {
27426
+ deps.error(`\u270B ${name} was not launched: there is no agent identity here and nobody at a terminal to confirm it.`);
27427
+ deps.error(" Start it from the app instead: Agents \u2192 New session.");
27428
+ return 1;
27429
+ }
27430
+ if (args.approval) deps.log(" (--approval is for an agent's launch; at your own computer you confirm it here instead)");
27431
+ if (!await deps.confirm(`Start ${name} on ${args.harness} in ${args.cwd}? [y/N] `)) {
27432
+ deps.error(`\u270B ${name} was not launched.`);
27433
+ return 1;
27434
+ }
27435
+ token = deps.deviceToken;
27436
+ input = spec;
27437
+ }
27438
+ let launched;
27439
+ try {
27440
+ launched = await deps.launch(input, { token });
27441
+ } catch (e) {
27442
+ const body = e.body ?? {};
27443
+ deps.error(`\u270B ${name} was not launched: ${typeof body.error === "string" ? body.error : e.message}${typeof body.why === "string" ? ` (${body.why})` : ""}`);
27444
+ if (typeof body.message === "string") deps.error(` ${body.message}`);
27445
+ for (const offer of body.offers ?? []) {
27446
+ deps.error(` ${offer.name ?? "a computer"}: ${(offer.harnesses ?? []).join(", ") || "no harness ready"} in ${[...offer.workspaces ?? [], ...offer.repos ?? []].join(", ") || "no granted folder"}`);
27447
+ }
27448
+ return 1;
27449
+ }
27450
+ const goal = launched.placed?.goalId;
27451
+ deps.log(`\u2713 launched "${launched.name ?? name}"${launched.name ? "" : " (unnamed: you already have an agent with that name)"} \u2014 session ${launched.sessionId}${goal ? `, its brief is Goal ${goal}` : ""}.`);
27452
+ if (launched.hostLive === false) {
27453
+ deps.log(" \u26A0 This computer's Paigy host is not running, so the session waits until it is. Start it with:");
27454
+ deps.log(" paigy-harness host (or keep it running as a service: paigy-harness service)");
27455
+ } else if (launched.hostLive === true) {
27456
+ deps.log(" The host runs it; it shows on your phone's Agents screen and ends from there.");
27457
+ } else {
27458
+ deps.log(" The host runs it once it claims it (Paigy could not tell whether the host is running).");
27459
+ }
27460
+ return 0;
27461
+ }
27462
+
27364
27463
  // ../../packages/sdk/dist/index.js
27365
27464
  import { createRequire as __sdkCreateRequire } from "module";
27366
27465
  import { execFileSync } from "child_process";
@@ -28991,6 +29090,12 @@ var questionFields = {
28991
29090
  workItBlocks: external_exports.array(external_exports.object({ blocked: NodeRef, action: BlockedAction, reason: reason.optional() }).strict().refine(actionFits, ACTION_FITS)).min(1).max(10).optional().describe(
28992
29091
  "The work that cannot go on until this is answered: a Goal's start or completion, or another Question's answer. Only for work truly blocked; it asks for a call. Leave it out for a question you can keep working around."
28993
29092
  ),
29093
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
29094
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
29095
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
29096
+ causedBy: causedBy.describe(
29097
+ "When this question follows something the person said, the ids (or the short ids get_goals prints) of those words. Their card quotes them above the question, so they can answer without going to look. Only words it truly follows; an id that is not their words is refused by name (cause_not_found) and nothing is sent."
29098
+ ),
28994
29099
  userExplicitlyRequested
28995
29100
  };
28996
29101
  var refineQuestion = (q, ctx) => {
@@ -29233,6 +29338,21 @@ var SendFeedbackSchema = external_exports.object({
29233
29338
  kind: external_exports.enum(["bug", "idea", "other"]).default("other").describe("bug: something Paigy does wrong. idea: something it should do. other: anything else.")
29234
29339
  }).strict();
29235
29340
  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.";
29341
+ var LAUNCH_HARNESSES = ["claude", "codex", "grok", "agy"];
29342
+ var LaunchToolSchema = external_exports.object({
29343
+ name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
29344
+ harness: external_exports.enum(LAUNCH_HARNESSES).describe("What runs it."),
29345
+ brief: goalOutcome.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX} characters.`),
29346
+ approvalQuestionId: external_exports.string().uuid().optional().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first. Required unless this is your own successor, and never with it."),
29347
+ successor: external_exports.literal(true).optional().describe("THIS SESSION'S OWN SUCCESSOR, when your context is at its window or the person told you to hand off: it takes your work and your session ends. No approval is needed for your own replacement, and you can launch only one \u2014 give it a new name."),
29348
+ workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
29349
+ repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
29350
+ model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
29351
+ mode: external_exports.enum(["ask", "bypass"]).optional().describe("bypass (default): every tool call allowed. ask: each blocked action goes to the person's phone."),
29352
+ parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
29353
+ hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
29354
+ }).strict();
29355
+ var LAUNCH_DESCRIPTION = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. Your own successor needs none: successor: true, with a new name, hands it your work and ends your session. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. Returns sessionId, the agent and the brief's goalId; a refusal says why.";
29236
29356
  var AGENT_TOOLS = [
29237
29357
  { name: "configure", title: "Who am I", annotations: READS, description: CONFIGURE_IDENTITY_DESCRIPTION, inputSchema: mcpInputSchema(ConfigureIdentitySchema) },
29238
29358
  { name: "contact", title: "Contact the person", annotations: SENDS, description: CONTACT_DESCRIPTION, inputSchema: CONTACT_SCHEMA },
@@ -29242,6 +29362,7 @@ var AGENT_TOOLS = [
29242
29362
  { name: "search", title: "Search history", annotations: READS, description: SEARCH_DESCRIPTION, inputSchema: mcpInputSchema(SearchToolSchema) },
29243
29363
  { 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) },
29244
29364
  { name: "send_feedback", title: "Send feedback to Paigy", annotations: SENDS, description: SEND_FEEDBACK_DESCRIPTION, inputSchema: mcpInputSchema(SendFeedbackSchema) },
29365
+ { name: "launch", title: "Launch a session", annotations: SENDS, description: LAUNCH_DESCRIPTION, inputSchema: mcpInputSchema(LaunchToolSchema) },
29245
29366
  // THE GUIDE FROM INSIDE THE MCP (owner, 2026-10-27): the skill's text, needing no identity (`help.ts`).
29246
29367
  { name: "help", title: "Paigy guide", annotations: READS, description: HELP_DESCRIPTION, inputSchema: mcpInputSchema(HelpSchema) }
29247
29368
  ];
@@ -30109,6 +30230,9 @@ var InboxItemSchema = external_exports.object({
30109
30230
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
30110
30231
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
30111
30232
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
30233
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
30234
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
30235
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
30112
30236
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
30113
30237
  * the person to notice it again, and For you puts it first, the latest bump on top
30114
30238
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -30411,6 +30535,59 @@ var ReassignResultSchema = external_exports.object({
30411
30535
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
30412
30536
  parentId: external_exports.string().nullable()
30413
30537
  });
30538
+ var TeamSessionSchema = external_exports.object({
30539
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
30540
+ * agent's own page opens. The row's identity, so never null. */
30541
+ tokenId: external_exports.string(),
30542
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
30543
+ name: external_exports.string().nullable(),
30544
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
30545
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
30546
+ * session is doing is its step's `goalTitle`. */
30547
+ role: external_exports.string().nullable(),
30548
+ /** Its step under the project: the one it worked most recently. */
30549
+ goalId: external_exports.string(),
30550
+ goalTitle: external_exports.string().nullable(),
30551
+ goalState: external_exports.string(),
30552
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
30553
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
30554
+ * as it advertised it on its heartbeat. */
30555
+ harness: external_exports.string().nullable(),
30556
+ harnessLabel: external_exports.string().nullable(),
30557
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
30558
+ model: external_exports.string().nullable(),
30559
+ mode: external_exports.string().nullable(),
30560
+ workspace: external_exports.string().nullable(),
30561
+ worktree: external_exports.boolean().nullable(),
30562
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
30563
+ lastAt: external_exports.string().nullable(),
30564
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
30565
+ * that has written nothing yet can say for itself. */
30566
+ lastLine: external_exports.string().nullable(),
30567
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
30568
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
30569
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
30570
+ live: external_exports.boolean(),
30571
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
30572
+ * it is taking its work rather than merely still running. */
30573
+ working: external_exports.boolean(),
30574
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
30575
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
30576
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
30577
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
30578
+ waitingOn: external_exports.object({
30579
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
30580
+ text: external_exports.string(),
30581
+ id: external_exports.string().nullable(),
30582
+ at: external_exports.string().nullable()
30583
+ }),
30584
+ /** Its credential was revoked, or the person's end of it was carried out and said so
30585
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
30586
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
30587
+ * reads as a team rather than an empty page. */
30588
+ endedAt: external_exports.string().nullable()
30589
+ });
30590
+ var TeamReadSchema = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema) });
30414
30591
  var LessonStateSchema = external_exports.enum(["active", "proposed", "retired"]);
30415
30592
  var LessonViewSchema = external_exports.object({
30416
30593
  id: external_exports.string(),
@@ -30703,6 +30880,9 @@ var DeviceTokenSchema = external_exports.object({
30703
30880
  /** Local host recovery must preserve the launch's runtime and Paigy identity. */
30704
30881
  harness: external_exports.enum(["claude", "codex", "agy", "grok"]).optional(),
30705
30882
  session_id: external_exports.string().uuid().optional(),
30883
+ /** How the launch asked for it to run (`GET /api/sessions/claim` `mode`), so every wake of this slot
30884
+ * runs it the same way. Absent is bypass (owner, 2026-11-13), as every slot written before it. */
30885
+ mode: external_exports.enum(["ask", "bypass"]).optional(),
30706
30886
  /** A conversation the host must not resume: its context is full, so every turn fails
30707
30887
  * ("Prompt is too long"). Written when a run hits it (`run.ts` `onFull`); the host skips a slot
30708
30888
  * whose resumable session is this one, so its Goals reach the dead-agent handoff instead of a
@@ -31015,7 +31195,7 @@ function updateSlot(agent2, patch) {
31015
31195
  }
31016
31196
  function slotIdentity(agent2) {
31017
31197
  const t = readTokenFile()[agent2];
31018
- 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 };
31198
+ 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 };
31019
31199
  }
31020
31200
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
31021
31201
  function readToken(agent2 = agentName()) {
@@ -31134,16 +31314,11 @@ async function getGoals(goalIds, opts = {}, read3 = {}) {
31134
31314
  return (await res.json()).goals;
31135
31315
  }
31136
31316
  var AWAIT_WINDOW_MS = 45e3;
31137
- async function hatch(name, voice = null, opts = {}) {
31138
- const res = await ensureAuthed(await (opts.reach ?? reach)(`${BACKEND_URL}/api/hatch`, {
31317
+ async function hatch(name, voice = null) {
31318
+ const res = await ensureAuthed(await reach(`${BACKEND_URL}/api/hatch`, {
31139
31319
  method: "POST",
31140
31320
  headers: { "content-type": "application/json", authorization: `Bearer ${authToken()}` },
31141
- body: JSON.stringify({
31142
- name,
31143
- voice,
31144
- ...opts.brief ? { brief: opts.brief } : {},
31145
- ...opts.parentGoalId ? { parentGoalId: opts.parentGoalId } : {}
31146
- })
31321
+ body: JSON.stringify({ name, voice })
31147
31322
  }));
31148
31323
  if (!res.ok) throw new Error(`hatch failed: ${res.status} ${await res.text()}`);
31149
31324
  return await res.json();
@@ -31162,6 +31337,16 @@ async function readIdentity(opts = {}) {
31162
31337
  if (!res.ok) await fail("read_identity", res);
31163
31338
  return await res.json();
31164
31339
  }
31340
+ async function launchSession(input, opts = {}) {
31341
+ const { brief, ...rest } = input;
31342
+ const res = await ensureAuthed(await (opts.reach ?? reach)(`${BACKEND_URL}/api/sessions`, {
31343
+ method: "POST",
31344
+ headers: { "content-type": "application/json", authorization: `Bearer ${authToken(opts.token) ?? ""}` },
31345
+ body: JSON.stringify({ ...rest, prompt: brief })
31346
+ }));
31347
+ if (!res.ok) await fail("launch", res);
31348
+ return await res.json();
31349
+ }
31165
31350
  async function claimSessions(opts = {}) {
31166
31351
  const res = await ensureAuthed(await reach(`${BACKEND_URL}/api/sessions/claim`, {
31167
31352
  headers: { authorization: `Bearer ${authToken(opts.token)}` }
@@ -31517,12 +31702,11 @@ ${block2}`;
31517
31702
 
31518
31703
  // src/cli.ts
31519
31704
  var import_qrcode = __toESM(require_lib(), 1);
31520
- import { randomUUID as randomUUID5 } from "crypto";
31521
31705
  import { hostname } from "os";
31522
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
31706
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "fs";
31523
31707
  import { execFile as execFile2, execSync as execSync2 } from "child_process";
31524
- import { homedir as homedir9 } from "os";
31525
- import { join as join11 } from "path";
31708
+ import { homedir as homedir11 } from "os";
31709
+ import { join as join13 } from "path";
31526
31710
 
31527
31711
  // src/run.ts
31528
31712
  import { randomUUID as randomUUID4 } from "crypto";
@@ -31587,6 +31771,17 @@ var AcpDriver = class {
31587
31771
  running = /* @__PURE__ */ new Set();
31588
31772
  /** The prompt in flight was already cancelled for silence: once is the whole remedy. */
31589
31773
  cancelled = false;
31774
+ /** ACP SDK 2 ANSWERED THE PROMPT AND THE TURN GOES ON (2026-11-20, Goal ae096b5d). SDK 1 keeps
31775
+ * the prompt response until the turn ends and puts `stopReason` on it. SDK 2 answers at once with
31776
+ * `{messageId}` — an acknowledgement, 2.3 seconds before the agent's first word in a live
31777
+ * capture — and ends the turn with `state_update: {state:"idle"}`. Settling on that response
31778
+ * would end every turn instantly and empty, so the turn stays in flight here: `promptId` is kept,
31779
+ * which is what `quiet` cancels against and what `flush` queues behind, and only an idle
31780
+ * `state_update` settles it. */
31781
+ ackedAwaitingIdle = false;
31782
+ /** The model the adapter last said a turn ran on (`claude-opus-5[1m]`), carried on every idle so
31783
+ * the run can tell a 200k window from a million (`fill.ts`). */
31784
+ model;
31590
31785
  /** The opening frame. Everything after is driven by responses in `handleLine`. */
31591
31786
  open() {
31592
31787
  this.initId = this.nextId++;
@@ -31598,7 +31793,17 @@ var AcpDriver = class {
31598
31793
  protocolVersion: 2,
31599
31794
  // We are not an editor: no file services offered, the agent uses its own.
31600
31795
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
31601
- clientInfo: { name: "paigy-desktop", version: "0.0.0" }
31796
+ // WHO WE ARE, UNDER BOTH NAMES (2026-11-20, Goal ae096b5d). ACP SDK 1 reads
31797
+ // `clientInfo`; SDK 2 requires `info` and REFUSES the frame without it
31798
+ // (`-32602 invalid initialize params`, path ["info"]), so a `clientInfo`-only
31799
+ // opening cannot start any adapter built on the newer SDK — and the catalog
31800
+ // installs adapters unpinned, so that is what a fresh machine gets. Sending both
31801
+ // was probed against every adapter we spawn: codex-acp 2.8.0 (SDK 2) and 2.2.2,
31802
+ // claude-agent-acp 0.76.0 and paigy-agy-acp all accept it, and the old ones keep
31803
+ // reading the field they already read. Drop `clientInfo` only once no adapter we
31804
+ // spawn is on SDK 1.
31805
+ clientInfo: { name: "paigy-desktop", version: "0.0.0" },
31806
+ info: { name: "paigy-desktop", version: "0.0.0" }
31602
31807
  }
31603
31808
  })
31604
31809
  ];
@@ -31706,33 +31911,12 @@ var AcpDriver = class {
31706
31911
  return { events: [], writes };
31707
31912
  }
31708
31913
  if (msg.id === this.promptId) {
31709
- this.promptId = void 0;
31710
- this.running.clear();
31711
- this.cancelled = false;
31712
- const events = [];
31713
- const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
31714
- if (report || this.tools.length) {
31715
- events.push({
31716
- kind: "turn",
31717
- role: "agent",
31718
- text: report,
31719
- ...this.tools.length ? { tools: [...this.tools] } : {}
31720
- });
31721
- }
31722
- const result = report;
31723
- const failed = msg.error !== void 0 || msg.result?.stopReason === "refusal";
31724
- this.text = "";
31725
- this.tools = [];
31726
- this.reportFrom = 0;
31727
- const writes = this.flush();
31728
- if (!writes.length) {
31729
- events.push({
31730
- kind: "idle",
31731
- ...result ? { result } : {},
31732
- ...failed ? { failed: true } : {}
31733
- });
31914
+ this.model = msg.result?._meta?.quota?.model_usage?.[0]?.model ?? this.model;
31915
+ if (msg.error === void 0 && msg.result?.stopReason === void 0 && msg.result?.messageId !== void 0) {
31916
+ this.ackedAwaitingIdle = true;
31917
+ return none;
31734
31918
  }
31735
- return { events, writes };
31919
+ return this.settle(msg.error !== void 0 || msg.result?.stopReason === "refusal");
31736
31920
  }
31737
31921
  return none;
31738
31922
  }
@@ -31748,6 +31932,11 @@ var AcpDriver = class {
31748
31932
  case "agent_message_chunk":
31749
31933
  this.text += update.content?.text ?? "";
31750
31934
  return none;
31935
+ // SDK 2'S END OF TURN. Only settles a turn whose prompt was acknowledged and is still in
31936
+ // flight: an SDK 1 adapter never sends this at all, `state: "running"` is the turn starting,
31937
+ // and an idle outside a turn (a session just opened) has nothing to settle.
31938
+ case "state_update":
31939
+ return update.state === "idle" && this.promptId !== void 0 && this.ackedAwaitingIdle ? this.settle(false) : none;
31751
31940
  case "tool_call": {
31752
31941
  const title = update.title?.trim() || update.kind || "tool";
31753
31942
  this.tools.push(title);
@@ -31794,6 +31983,42 @@ var AcpDriver = class {
31794
31983
  return this.resume ? { id: id3, method: "session/resume", params: { sessionId: this.resume, ...params } } : { id: id3, method: "session/new", params };
31795
31984
  }
31796
31985
  /** Send the queued prompts as one turn, if the agent can take one right now. */
31986
+ /** THE TURN IS OVER. The accumulated report lands first, then idle — the same order the line
31987
+ * adapters emit — and anything queued meanwhile goes out. Reached from SDK 1's prompt response
31988
+ * and from SDK 2's idle `state_update`, so both generations end a turn the same way. */
31989
+ settle(failed) {
31990
+ this.promptId = void 0;
31991
+ this.ackedAwaitingIdle = false;
31992
+ this.running.clear();
31993
+ this.cancelled = false;
31994
+ const events = [];
31995
+ const report = this.text.slice(this.reportFrom).trim() || this.text.trim();
31996
+ if (report || this.tools.length) {
31997
+ events.push({
31998
+ kind: "turn",
31999
+ role: "agent",
32000
+ text: report,
32001
+ ...this.tools.length ? { tools: [...this.tools] } : {}
32002
+ });
32003
+ }
32004
+ const result = report;
32005
+ this.text = "";
32006
+ this.tools = [];
32007
+ this.reportFrom = 0;
32008
+ const writes = this.flush();
32009
+ if (!writes.length) {
32010
+ events.push({
32011
+ kind: "idle",
32012
+ ...result ? { result } : {},
32013
+ ...failed ? { failed: true } : {},
32014
+ // WHOSE conversation this was: its transcript is named by this id, and that transcript is
32015
+ // all a session's context amounts to once it can no longer write (`handoff.ts`).
32016
+ ...this.sessionId ? { session: this.sessionId } : {},
32017
+ ...this.model ? { model: this.model } : {}
32018
+ });
32019
+ }
32020
+ return { events, writes };
32021
+ }
31797
32022
  flush() {
31798
32023
  if (!this.sessionId || this.promptId !== void 0 || !this.queued.length) return [];
31799
32024
  const blocks = this.queued.map((text) => ({ type: "text", text }));
@@ -33625,6 +33850,12 @@ var questionFields2 = {
33625
33850
  workItBlocks: external_exports.array(external_exports.object({ blocked: NodeRef2, action: BlockedAction2, reason: reason2.optional() }).strict().refine(actionFits2, ACTION_FITS2)).min(1).max(10).optional().describe(
33626
33851
  "The work that cannot go on until this is answered: a Goal's start or completion, or another Question's answer. Only for work truly blocked; it asks for a call. Leave it out for a question you can keep working around."
33627
33852
  ),
33853
+ // THE WORDS OF HIS IT FOLLOWS (owner, 2026-11-14: "if something that the agent is asking is in response to one of the
33854
+ // user's words somewhere"; and "Build the real link before 1.4.4"). The same marks an update's `causedBy` writes
33855
+ // (`mark_entry`), on the question's own request: his card quotes exactly these words above the question.
33856
+ causedBy: causedBy2.describe(
33857
+ "When this question follows something the person said, the ids (or the short ids get_goals prints) of those words. Their card quotes them above the question, so they can answer without going to look. Only words it truly follows; an id that is not their words is refused by name (cause_not_found) and nothing is sent."
33858
+ ),
33628
33859
  userExplicitlyRequested: userExplicitlyRequested2
33629
33860
  };
33630
33861
  var refineQuestion2 = (q, ctx) => {
@@ -33867,6 +34098,21 @@ var SendFeedbackSchema2 = external_exports.object({
33867
34098
  kind: external_exports.enum(["bug", "idea", "other"]).default("other").describe("bug: something Paigy does wrong. idea: something it should do. other: anything else.")
33868
34099
  }).strict();
33869
34100
  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.";
34101
+ var LAUNCH_HARNESSES2 = ["claude", "codex", "grok", "agy"];
34102
+ var LaunchToolSchema2 = external_exports.object({
34103
+ name: external_exports.string().trim().min(1).max(60).describe("The session's role name, as the person will see it."),
34104
+ harness: external_exports.enum(LAUNCH_HARNESSES2).describe("What runs it."),
34105
+ brief: goalOutcome2.describe(`The session's first Goal: what to do, one paragraph of at most ${GOAL_OUTCOME_MAX2} characters.`),
34106
+ approvalQuestionId: external_exports.string().uuid().optional().describe("The questionId (the whole UUID) of the question you asked the person that names this session, once they answered it: a board card's, or one you ask first. Required unless this is your own successor, and never with it."),
34107
+ successor: external_exports.literal(true).optional().describe("THIS SESSION'S OWN SUCCESSOR, when your context is at its window or the person told you to hand off: it takes your work and your session ends. No approval is needed for your own replacement, and you can launch only one \u2014 give it a new name."),
34108
+ workspace: external_exports.string().trim().min(1).optional().describe("A folder the host granted. Name it or repo."),
34109
+ repo: external_exports.string().trim().min(1).max(200).optional().describe("The repo the work is in (owner/name); the session opens in it."),
34110
+ model: external_exports.string().trim().min(1).max(100).optional().describe("The model the card approved, passed to the harness."),
34111
+ mode: external_exports.enum(["ask", "bypass"]).optional().describe("bypass (default): every tool call allowed. ask: each blocked action goes to the person's phone."),
34112
+ parentGoalId: external_exports.string().uuid().optional().describe("The Goal the brief goes under, such as the Team project."),
34113
+ hostTokenId: external_exports.string().uuid().optional().describe("The computer to run it on. Omitted: the live host that offers it.")
34114
+ }).strict();
34115
+ var LAUNCH_DESCRIPTION2 = "Start a new agent session on one of your person's computers: their host runs it as it runs a launch from their phone. Only what the person approved: a board card they answered, or else ask them first, one question on the Goal it is for naming the session, its role, model and mode; pass that question's questionId as approvalQuestionId. Your own successor needs none: successor: true, with a new name, hands it your work and ends your session. brief becomes the session's first Goal, under parentGoalId when given. Name a workspace the host granted or the repo. mode is bypass unless ask. Returns sessionId, the agent and the brief's goalId; a refusal says why.";
33870
34116
  var AGENT_TOOLS2 = [
33871
34117
  { name: "configure", title: "Who am I", annotations: READS2, description: CONFIGURE_IDENTITY_DESCRIPTION2, inputSchema: mcpInputSchema2(ConfigureIdentitySchema2) },
33872
34118
  { name: "contact", title: "Contact the person", annotations: SENDS2, description: CONTACT_DESCRIPTION2, inputSchema: CONTACT_SCHEMA2 },
@@ -33876,6 +34122,7 @@ var AGENT_TOOLS2 = [
33876
34122
  { name: "search", title: "Search history", annotations: READS2, description: SEARCH_DESCRIPTION2, inputSchema: mcpInputSchema2(SearchToolSchema2) },
33877
34123
  { 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) },
33878
34124
  { name: "send_feedback", title: "Send feedback to Paigy", annotations: SENDS2, description: SEND_FEEDBACK_DESCRIPTION2, inputSchema: mcpInputSchema2(SendFeedbackSchema2) },
34125
+ { name: "launch", title: "Launch a session", annotations: SENDS2, description: LAUNCH_DESCRIPTION2, inputSchema: mcpInputSchema2(LaunchToolSchema2) },
33879
34126
  // THE GUIDE FROM INSIDE THE MCP (owner, 2026-10-27): the skill's text, needing no identity (`help.ts`).
33880
34127
  { name: "help", title: "Paigy guide", annotations: READS2, description: HELP_DESCRIPTION2, inputSchema: mcpInputSchema2(HelpSchema2) }
33881
34128
  ];
@@ -34754,6 +35001,9 @@ var InboxItemSchema2 = external_exports.object({
34754
35001
  * words, drawn above it as "You asked" (`public.questions_answered_by`, read beside the card read).
34755
35002
  * Absent on every card that answers nothing of theirs, and on a held question, which has `freedBy`. */
34756
35003
  answering: external_exports.object({ asked: external_exports.string() }).optional(),
35004
+ /** THE WORDS OF HIS THIS QUESTION FOLLOWS (owner, 2026-11-14): exactly the words its agent cited (`causedBy` on the
35005
+ * question), oldest first. Additive: absent on every card that cites none, and from an API that predates it. */
35006
+ follows: external_exports.array(external_exports.object({ said: external_exports.string(), at: external_exports.string().datetime() })).optional(),
34757
35007
  /** WHEN ITS AGENT LAST BUMPED THIS QUESTION (#2855, `contact`'s `bumpQuestionIds`): the agent asked
34758
35008
  * the person to notice it again, and For you puts it first, the latest bump on top
34759
35009
  * (`question/order.ts`). Absent on a question never bumped, and on every card from an API older
@@ -35056,6 +35306,59 @@ var ReassignResultSchema2 = external_exports.object({
35056
35306
  moved: external_exports.object({ asks: external_exports.number(), answered: external_exports.number(), requests: external_exports.number(), goals: external_exports.number(), callbacks: external_exports.number() }),
35057
35307
  parentId: external_exports.string().nullable()
35058
35308
  });
35309
+ var TeamSessionSchema2 = external_exports.object({
35310
+ /** The session's agent token: what `POST /api/sessions/end` takes as `agentTokenId`, and what the
35311
+ * agent's own page opens. The row's identity, so never null. */
35312
+ tokenId: external_exports.string(),
35313
+ /** Null while it has not named itself yet — never a placeholder (owner, 2026-10-01). */
35314
+ name: external_exports.string().nullable(),
35315
+ /** THE NAME'S SUFFIX, because a team is a name: `Interface/Web app` is the Interface session's
35316
+ * `Web app` helper. There is no role column to read, and a flat name has no role — what that
35317
+ * session is doing is its step's `goalTitle`. */
35318
+ role: external_exports.string().nullable(),
35319
+ /** Its step under the project: the one it worked most recently. */
35320
+ goalId: external_exports.string(),
35321
+ goalTitle: external_exports.string().nullable(),
35322
+ goalState: external_exports.string(),
35323
+ /** How it runs, from its `sessions` row — all null for a session the host did not launch (a
35324
+ * terminal hatch has no such row at all). `harnessLabel` is the host's own word for the harness,
35325
+ * as it advertised it on its heartbeat. */
35326
+ harness: external_exports.string().nullable(),
35327
+ harnessLabel: external_exports.string().nullable(),
35328
+ /** The model it was launched with, else the one its identity carries (`tokens.model`). */
35329
+ model: external_exports.string().nullable(),
35330
+ mode: external_exports.string().nullable(),
35331
+ workspace: external_exports.string().nullable(),
35332
+ worktree: external_exports.boolean().nullable(),
35333
+ /** The newest of: its last Entry on its own steps, `last_worked_at`, `listened_at`, `last_seen_at`. */
35334
+ lastAt: external_exports.string().nullable(),
35335
+ /** That Entry's headline, else its working-log tail (`tokens.activity`), which is all a session
35336
+ * that has written nothing yet can say for itself. */
35337
+ lastLine: external_exports.string().nullable(),
35338
+ /** IS ANYONE STILL THERE (`sessionLive`): a listener swept inside `LISTENER_FRESH_MS`, or it
35339
+ * worked or was born inside `IDLE_MS`. NOT presence: an agent token's `last_seen_at` is the
35340
+ * desktop HOST's beat, so a dot drawn off it alone shows a working team as dead. */
35341
+ live: external_exports.boolean(),
35342
+ /** DID IT WRITE THIS HOUR (`activeAgents`, `ACTIVE_MS`) — the other clock, and the one that says
35343
+ * it is taking its work rather than merely still running. */
35344
+ working: external_exports.boolean(),
35345
+ /** What it waits on, first match wins, so one session has one answer: a question of its own the
35346
+ * person owes (`person`), one another agent owes (`agent`), a step blocked by a Goal or by a step
35347
+ * below it (`goal`), a step parked for later (`later`), or `nothing`. `text` is already the
35348
+ * sentence to print; `id` is the question's, or the blocker's Goal id; `at` is the parked time. */
35349
+ waitingOn: external_exports.object({
35350
+ kind: external_exports.enum(["person", "agent", "goal", "later", "nothing"]),
35351
+ text: external_exports.string(),
35352
+ id: external_exports.string().nullable(),
35353
+ at: external_exports.string().nullable()
35354
+ }),
35355
+ /** Its credential was revoked, or the person's end of it was carried out and said so
35356
+ * (`session_ends`). Null also covers a session that died without saying so, which is what `live`
35357
+ * answers; nothing here guesses. An ended session STAYS in the roster, so a finished team still
35358
+ * reads as a team rather than an empty page. */
35359
+ endedAt: external_exports.string().nullable()
35360
+ });
35361
+ var TeamReadSchema2 = external_exports.object({ goalId: external_exports.string(), team: external_exports.array(TeamSessionSchema2) });
35059
35362
  var LessonStateSchema2 = external_exports.enum(["active", "proposed", "retired"]);
35060
35363
  var LessonViewSchema2 = external_exports.object({
35061
35364
  id: external_exports.string(),
@@ -35346,6 +35649,9 @@ var DeviceTokenSchema2 = external_exports.object({
35346
35649
  /** Local host recovery must preserve the launch's runtime and Paigy identity. */
35347
35650
  harness: external_exports.enum(["claude", "codex", "agy", "grok"]).optional(),
35348
35651
  session_id: external_exports.string().uuid().optional(),
35652
+ /** How the launch asked for it to run (`GET /api/sessions/claim` `mode`), so every wake of this slot
35653
+ * runs it the same way. Absent is bypass (owner, 2026-11-13), as every slot written before it. */
35654
+ mode: external_exports.enum(["ask", "bypass"]).optional(),
35349
35655
  /** A conversation the host must not resume: its context is full, so every turn fails
35350
35656
  * ("Prompt is too long"). Written when a run hits it (`run.ts` `onFull`); the host skips a slot
35351
35657
  * whose resumable session is this one, so its Goals reach the dead-agent handoff instead of a
@@ -35662,15 +35968,23 @@ var LIMIT_PREFIXES = [
35662
35968
  var RETRY_MS2 = 15 * 6e4;
35663
35969
  var MARGIN_MS = 6e4;
35664
35970
  var FARTHEST_MS = 8 * 24 * 60 * 6e4;
35971
+ function handsOver(limit) {
35972
+ return limit.kind !== "session";
35973
+ }
35665
35974
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
35666
35975
  function limitIn(text, now) {
35667
35976
  const line = (text ?? "").split("\n").map((l) => l.trim()).reverse().find((l) => LIMIT_PREFIXES.some((p) => l.startsWith(p) || p === "requires usage credits" && l.includes(p)));
35668
35977
  if (!line) return null;
35978
+ const weekly = /\b(weekly|daily)\b/i.test(line);
35669
35979
  const reset = resetOf(line, now);
35670
35980
  if (reset !== null && reset > now && reset - now <= FARTHEST_MS) {
35671
- return { until: reset + MARGIN_MS, resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset) };
35981
+ return {
35982
+ until: reset + MARGIN_MS,
35983
+ resets: /resets\s+(?:at\s+)?(.+?)\s*(?:\(|$)/i.exec(line)?.[1]?.trim() ?? clock3(reset),
35984
+ kind: weekly ? "weekly" : "session"
35985
+ };
35672
35986
  }
35673
- return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2) };
35987
+ return { until: now + RETRY_MS2, resets: clock3(now + RETRY_MS2), kind: weekly ? "weekly" : "credits" };
35674
35988
  }
35675
35989
  function resetOf(line, now) {
35676
35990
  const m = /resets\s+(?:at\s+)?(?:([a-z]{3})[a-z]*\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i.exec(line);
@@ -35845,6 +36159,12 @@ async function askPermission(event, state, rail) {
35845
36159
  ]
35846
36160
  }));
35847
36161
  }
36162
+ function wroteOn(held) {
36163
+ if (held.ownerParticipant) {
36164
+ return held.workedBy === held.ownerParticipant || (held.entries ?? []).some((e) => e.authorParticipant === held.ownerParticipant) || (held.earlier?.omitted ?? 0) > 0;
36165
+ }
36166
+ return held.state !== "ready" || Boolean(held.workedBy) || (held.entries ?? []).some((e) => e.authorParticipant.startsWith("agent:"));
36167
+ }
35848
36168
  async function finish(state, rail, opts) {
35849
36169
  const goal = state.goal;
35850
36170
  if (!goal) return;
@@ -35855,7 +36175,7 @@ async function finish(state, rail, opts) {
35855
36175
  if (!owed) state.goal = void 0;
35856
36176
  return;
35857
36177
  }
35858
- if (!held.openDecisionNeedIds?.length && !owed) {
36178
+ if (!held.openDecisionNeedIds?.length && !owed && wroteOn(held)) {
35859
36179
  await rail.complete(goal.id, held.revision ?? goal.revision);
35860
36180
  state.goal = void 0;
35861
36181
  }
@@ -35897,9 +36217,19 @@ function conversationFull(result) {
35897
36217
  return /prompt is too long/i.test(result ?? "");
35898
36218
  }
35899
36219
  var FULL_NOTICE = "This agent's conversation is full, so it can no longer take a turn. Its session has ended and will not be resumed; its Goals go to the dead-agent handoff.";
36220
+ var wroteForIt = (dossier) => `What it had got to, as far as its own transcript shows, is written in ${dossier} on the computer that ran it: read that before starting this work again.`;
36221
+ function providerFailed(result) {
36222
+ if (!result) return false;
36223
+ if (/"type"\s*:\s*"error"[\s\S]*?"error"\s*:\s*\{/i.test(result)) return true;
36224
+ return result.split("\n").some((raw) => {
36225
+ const line = raw.trim();
36226
+ return /^\{"type"\s*:\s*"error"\b|^\{"error"\s*:\s*\{/i.test(line) || /^(?:API Error|Internal error):\s+\S/i.test(line) || /^(?:HTTP\s+)?[45]\d\d\b.*(?:\berror\b|not_found|invalid_request|unauthorized|forbidden|unsupported)/i.test(line);
36227
+ });
36228
+ }
35900
36229
  async function afterTurn(event, state, rail, opts) {
35901
- if (event.failed) {
35902
- const limit = limitIn(event.result, (opts?.now ?? Date.now)());
36230
+ const now = (opts?.now ?? Date.now)();
36231
+ if (event.failed || providerFailed(event.result) || limitIn(event.result, now) || conversationFull(event.result)) {
36232
+ const limit = limitIn(event.result, now);
35903
36233
  if (limit) {
35904
36234
  state.paused = limit;
35905
36235
  if (state.typed) state.owed = state.typed;
@@ -35910,7 +36240,10 @@ async function afterTurn(event, state, rail, opts) {
35910
36240
  return limit;
35911
36241
  }
35912
36242
  if (conversationFull(event.result)) {
35913
- if (!state.full) await cannotWork(FULL_NOTICE, state, rail, opts);
36243
+ if (!state.full) {
36244
+ const dossier = opts?.dossier?.() ?? null;
36245
+ await cannotWork([FULL_NOTICE, ...dossier ? [wroteForIt(dossier)] : []].join("\n\n"), state, rail, opts);
36246
+ }
35914
36247
  state.full = true;
35915
36248
  return void 0;
35916
36249
  }
@@ -35925,6 +36258,300 @@ ${event.result?.trim() || "No result reported."}`, state, rail, opts);
35925
36258
  return void 0;
35926
36259
  }
35927
36260
 
36261
+ // src/handoff.ts
36262
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync3, openSync as openSync3, readSync as readSync2, fstatSync, closeSync as closeSync3 } from "fs";
36263
+ import { homedir as homedir6 } from "os";
36264
+ import { join as join7 } from "path";
36265
+
36266
+ // src/fill.ts
36267
+ import { closeSync as closeSync2, openSync as openSync2, readSync, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
36268
+ import { homedir as homedir5 } from "os";
36269
+ import { join as join6 } from "path";
36270
+ function windowFor(model) {
36271
+ return /\[1m\]/i.test(model ?? "") ? 1e6 : 2e5;
36272
+ }
36273
+ function sizeOf(tail) {
36274
+ const lines2 = tail.split("\n");
36275
+ for (let i = lines2.length - 1; i >= 0; i--) {
36276
+ const line = lines2[i].trim();
36277
+ if (!line.startsWith("{")) continue;
36278
+ let row;
36279
+ try {
36280
+ row = JSON.parse(line);
36281
+ } catch {
36282
+ continue;
36283
+ }
36284
+ if (row.type !== "assistant" || row.isSidechain === true) continue;
36285
+ const usage = row.message?.usage;
36286
+ if (!usage) continue;
36287
+ const count = (key3) => typeof usage[key3] === "number" ? usage[key3] : 0;
36288
+ const size = count("input_tokens") + count("cache_read_input_tokens") + count("cache_creation_input_tokens");
36289
+ if (size > 0) return size;
36290
+ }
36291
+ return null;
36292
+ }
36293
+ var TAIL_BYTES = 256 * 1024;
36294
+ var TAIL_MAX = 8 * 1024 * 1024;
36295
+ function readTail(file, bytes) {
36296
+ const size = statSync3(file).size;
36297
+ const from = Math.max(0, size - bytes);
36298
+ const fd = openSync2(file, "r");
36299
+ try {
36300
+ const buf = Buffer.alloc(Math.min(bytes, size));
36301
+ const n = readSync(fd, buf, 0, buf.length, from);
36302
+ return buf.subarray(0, n).toString("utf8");
36303
+ } finally {
36304
+ closeSync2(fd);
36305
+ }
36306
+ }
36307
+ function fillReader(deps = {}) {
36308
+ const root = deps.projectsDir ?? join6(homedir5(), ".claude", "projects");
36309
+ const list = deps.list ?? ((dir) => readdirSync2(dir));
36310
+ const tail = deps.tail ?? readTail;
36311
+ const found = /* @__PURE__ */ new Map();
36312
+ const find = (session) => {
36313
+ let folders;
36314
+ try {
36315
+ folders = list(root);
36316
+ } catch {
36317
+ return null;
36318
+ }
36319
+ for (const folder of folders) {
36320
+ let files;
36321
+ try {
36322
+ files = list(join6(root, folder));
36323
+ } catch {
36324
+ continue;
36325
+ }
36326
+ if (files.includes(`${session}.jsonl`)) return join6(root, folder, `${session}.jsonl`);
36327
+ }
36328
+ return null;
36329
+ };
36330
+ return {
36331
+ measure: (session, model) => {
36332
+ if (!session) return null;
36333
+ let path = found.get(session);
36334
+ if (!path) {
36335
+ const file = find(session);
36336
+ if (!file) return null;
36337
+ found.set(session, path = file);
36338
+ }
36339
+ let used = null;
36340
+ for (let bytes = TAIL_BYTES; used === null && bytes <= TAIL_MAX; bytes *= 4) {
36341
+ let text;
36342
+ try {
36343
+ text = tail(path, bytes);
36344
+ } catch {
36345
+ return null;
36346
+ }
36347
+ used = sizeOf(text);
36348
+ if (text.length < bytes) break;
36349
+ }
36350
+ if (used === null) return null;
36351
+ const window = windowFor(model);
36352
+ return { used, window, share: used / window };
36353
+ }
36354
+ };
36355
+ }
36356
+ function fillLine(fill) {
36357
+ const percent = Math.round(fill.share * 100);
36358
+ const used = fill.used.toLocaleString("en-US");
36359
+ const window = fill.window.toLocaleString("en-US");
36360
+ return `You are holding ${used} tokens of about ${window} \u2014 ${percent}% of this conversation's window.`;
36361
+ }
36362
+
36363
+ // src/handoff.ts
36364
+ var COMPACTION = "Compact conversation";
36365
+ function compacted(event) {
36366
+ return event.kind === "work" && event.tool.trim().toLowerCase() === COMPACTION.toLowerCase();
36367
+ }
36368
+ function dossierDir() {
36369
+ return join7(homedir6(), ".paigy", "handoff");
36370
+ }
36371
+ function dossierPath(session) {
36372
+ return join7(dossierDir(), `${session.slice(0, 8)}.md`);
36373
+ }
36374
+ function keepContext(dossier, fill) {
36375
+ return [
36376
+ "YOUR CONTEXT JUST TURNED OVER: Claude Code compacted this conversation, so the detail of everything before the summary is gone from it. This is not your retirement \u2014 sessions here compact several times and keep working \u2014 but spend this turn making what you know survivable, because the next turnover takes more of it.",
36377
+ `1. WRITE, or rewrite if it is already there, ${dossier}: everything a session that has never seen this work would need \u2014 what the work is, where each of your Goals stands by id, what is done, what is next, the exact paths, branches, commands, PRs and ids, the traps you learned the hard way, what you are waiting on, and every question open with the person. If a step is mid-flight, say exactly where it stands, down to the uncommitted file and the command about to run. Be generous: this file is what outlives your context.`,
36378
+ `2. NAME IT ON EVERY GOAL you hold: one contact update each, saying your context is in ${dossier} on this computer. Once per Goal \u2014 if you have already said it, rewriting the file is enough.`,
36379
+ // The prose names `launch` and `successor: true` in backticks, so these are quoted strings
36380
+ // joined, never one template literal.
36381
+ "3. THEN CARRY ON with what you were doing \u2014 unless you judge that what you are holding will not fit in what is left of your context. " + (fill ? `${fillLine(fill)} What that leaves is yours to judge: only you know what the rest of this work needs.` : "Nothing here can measure that for you, so judge it from what you can see: how much of the task is left, how many Goals you hold, how long the reading ahead is.") + " If it will not fit, hand off instead, in this order: report once to the person (what you were doing, where it stands, that your successor takes it on), then `launch` your successor with `successor: true` (no approvalQuestionId \u2014 your own replacement needs no approval), a NEW name, the same harness, model and repo, under the same parent Goal, and a brief naming this dossier and what to pick up first. That call gives it every Goal you hold and ends your session, so let it be your last."
36382
+ ].join("\n\n");
36383
+ }
36384
+ var CARRIES_ON = ["agy", "codex", "grok", "claude"];
36385
+ function carriesOn(available, limited) {
36386
+ const ready = available.filter((a) => a.status === "ready" && a.name !== limited);
36387
+ for (const name of CARRIES_ON) {
36388
+ const hit = ready.find((a) => a.name === name);
36389
+ if (hit) return hit;
36390
+ }
36391
+ return null;
36392
+ }
36393
+ function successorName(name, label) {
36394
+ return `${name} (${label})`.slice(0, 60);
36395
+ }
36396
+ function creditsBrief(opts) {
36397
+ return [
36398
+ `Carry on ${opts.name}'s work: a usage limit stopped it until ${opts.resets}, so its open Goals are now yours.`,
36399
+ opts.dossier ? `Its context is in ${opts.dossier} on this computer \u2014 read that file first, then the Goals you have just been given.` : "Nothing of its context could be written down, so read the Goals you have just been given and what was last said on them.",
36400
+ "Report on those Goals as you go."
36401
+ ].join(" ");
36402
+ }
36403
+ function projectSlug(cwd) {
36404
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
36405
+ }
36406
+ function transcriptOf(cwd, session, home = homedir6()) {
36407
+ const projects = join7(home, ".claude", "projects");
36408
+ const slug = projectSlug(cwd);
36409
+ const exact = join7(projects, slug, `${session}.jsonl`);
36410
+ if (existsSync4(exact)) return exact;
36411
+ let dirs = [];
36412
+ try {
36413
+ dirs = readdirSync3(projects).filter((d) => d.startsWith(slug));
36414
+ } catch {
36415
+ return null;
36416
+ }
36417
+ for (const dir of dirs) {
36418
+ const candidate = join7(projects, dir, `${session}.jsonl`);
36419
+ if (existsSync4(candidate)) return candidate;
36420
+ }
36421
+ let all = [];
36422
+ try {
36423
+ all = readdirSync3(projects);
36424
+ } catch {
36425
+ return null;
36426
+ }
36427
+ for (const dir of all) {
36428
+ const candidate = join7(projects, dir, `${session}.jsonl`);
36429
+ if (existsSync4(candidate)) return candidate;
36430
+ }
36431
+ return null;
36432
+ }
36433
+ var TAIL_BYTES2 = 2e6;
36434
+ var KEEP = { said: 6, wrote: 4, files: 20, commands: 12 };
36435
+ var COMMAND = 200;
36436
+ function tailOf(path, bytes = TAIL_BYTES2) {
36437
+ const fd = openSync3(path, "r");
36438
+ try {
36439
+ const size = fstatSync(fd).size;
36440
+ const from = Math.max(0, size - bytes);
36441
+ const buffer = Buffer.alloc(Math.min(size, bytes));
36442
+ readSync2(fd, buffer, 0, buffer.length, from);
36443
+ const text = buffer.toString("utf8");
36444
+ return from > 0 ? text.slice(text.indexOf("\n") + 1) : text;
36445
+ } finally {
36446
+ closeSync3(fd);
36447
+ }
36448
+ }
36449
+ var SCAFFOLDING = /^\s*<(task-notification|system-reminder|local-command-stdout|command-message|command-name)\b/;
36450
+ function words(content) {
36451
+ if (typeof content === "string") return content;
36452
+ if (!Array.isArray(content)) return "";
36453
+ return content.filter((b) => b.type === "text" && b.text).map((b) => b.text.trim()).join("\n\n");
36454
+ }
36455
+ function readTail2(tail) {
36456
+ const todos = [];
36457
+ const said = [];
36458
+ const wrote = [];
36459
+ const files = [];
36460
+ const commands = [];
36461
+ for (const raw of tail.split("\n")) {
36462
+ if (!raw.trim()) continue;
36463
+ let line;
36464
+ try {
36465
+ line = JSON.parse(raw);
36466
+ } catch {
36467
+ continue;
36468
+ }
36469
+ const content = line.message?.content;
36470
+ if (line.type === "user") {
36471
+ const text2 = words(content);
36472
+ if (text2 && !SCAFFOLDING.test(text2)) said.push(text2);
36473
+ continue;
36474
+ }
36475
+ if (line.type !== "assistant" || !Array.isArray(content)) continue;
36476
+ const text = words(content);
36477
+ if (text) wrote.push(text);
36478
+ for (const block2 of content) {
36479
+ if (block2.type !== "tool_use" || !block2.input) continue;
36480
+ const input = block2.input;
36481
+ if (block2.name === "TodoWrite" && Array.isArray(input["todos"])) {
36482
+ todos.length = 0;
36483
+ todos.push(...input["todos"]);
36484
+ }
36485
+ const file = input["file_path"];
36486
+ if (typeof file === "string" && !files.includes(file)) files.push(file);
36487
+ const command = input["command"];
36488
+ if (typeof command === "string") commands.push(command.split("\n")[0].trim().slice(0, COMMAND));
36489
+ }
36490
+ }
36491
+ return {
36492
+ todos,
36493
+ said: said.slice(-KEEP.said),
36494
+ wrote: wrote.slice(-KEEP.wrote),
36495
+ files: files.slice(-KEEP.files),
36496
+ commands: commands.slice(-KEEP.commands)
36497
+ };
36498
+ }
36499
+ var QUOTE = 1200;
36500
+ var quote = (text) => text.length > QUOTE ? `${text.slice(0, QUOTE)}\u2026` : text;
36501
+ function dossierFrom(tail, meta) {
36502
+ const read3 = readTail2(tail);
36503
+ const at = (meta.at ?? /* @__PURE__ */ new Date()).toISOString();
36504
+ const open = read3.todos.filter((t) => t.status !== "completed");
36505
+ const done = read3.todos.filter((t) => t.status === "completed");
36506
+ const out = [
36507
+ `# ${meta.name} \u2014 handoff`,
36508
+ `${meta.why} The session never wrote its own account of this work, so this is what its transcript's last ${Math.round(TAIL_BYTES2 / 1e6)} MB still show. Read the Goals it held for what the work is FOR; this says where it had got to.`,
36509
+ `- session: ${meta.session}`,
36510
+ `- workspace: ${meta.cwd}`,
36511
+ `- written: ${at}`
36512
+ ];
36513
+ if (open.length || done.length) {
36514
+ out.push("## Its own to-do list, as it last stood");
36515
+ for (const t of open) out.push(`- [ ] ${t.content ?? ""}${t.status && t.status !== "pending" ? ` (${t.status})` : ""}`);
36516
+ for (const t of done) out.push(`- [x] ${t.content ?? ""}`);
36517
+ }
36518
+ if (read3.said.length) {
36519
+ out.push("## The last words typed into it");
36520
+ for (const s of read3.said) out.push(`> ${quote(s).split("\n").join("\n> ")}`);
36521
+ }
36522
+ if (read3.wrote.length) {
36523
+ out.push("## The last it said");
36524
+ for (const w of read3.wrote) out.push(`> ${quote(w).split("\n").join("\n> ")}`);
36525
+ }
36526
+ if (read3.files.length) {
36527
+ out.push("## Files it had open or changed");
36528
+ for (const f of read3.files) out.push(`- ${f}`);
36529
+ }
36530
+ if (read3.commands.length) {
36531
+ out.push("## The last commands it ran");
36532
+ for (const c of read3.commands) out.push(`- \`${c}\``);
36533
+ }
36534
+ return `${out.join("\n\n")}
36535
+ `;
36536
+ }
36537
+ function writeDossier(path, body) {
36538
+ mkdirSync3(join7(path, ".."), { recursive: true });
36539
+ writeFileSync3(path, body, "utf8");
36540
+ return path;
36541
+ }
36542
+ function dossierForWall(meta) {
36543
+ try {
36544
+ const path = dossierPath(meta.session);
36545
+ if (existsSync4(path)) return path;
36546
+ const transcript = transcriptOf(meta.cwd, meta.session);
36547
+ if (!transcript) return null;
36548
+ const body = dossierFrom(tailOf(transcript), meta);
36549
+ return writeDossier(path, body);
36550
+ } catch {
36551
+ return null;
36552
+ }
36553
+ }
36554
+
35928
36555
  // src/paigy/conversation.ts
35929
36556
  var HARNESS_INSTRUCTION = "You are running as an unattended background harness agent; your user reaches you through Paigy and is not at this terminal. Nothing wakes you after your turn ends but the person, so wait on CI or a deploy inside the turn. The person never sees your turn's final message, and it is not kept: report where the work stands with a contact update on this Goal (one the person does not need yet is kept as its progress). Anything the person needs \u2014 a question, a result, a blocker \u2014 you send through Paigy's contact tool, once; the harness sends nothing on your behalf. What the person says later arrives with the Goal it was said on named in front of it; answer them on that Goal (its id as the contact's goalId).";
35930
36557
  var SAFETY_MS = 6e4;
@@ -35963,7 +36590,7 @@ var BEAT_REPORT_MS = 10 * 6e4;
35963
36590
  var ended = (state) => state === "done" || state === "cancelled";
35964
36591
  function unheard(brief, state, since = null, after = -1, reviewSince, gathered) {
35965
36592
  const seen = state.seen ??= /* @__PURE__ */ new Set();
35966
- const words = [];
36593
+ const words2 = [];
35967
36594
  const pendingAt = reviewSince ? Date.parse(reviewSince) : null;
35968
36595
  for (const [i, e] of (brief.entries ?? []).entries()) {
35969
36596
  if (seen.has(e.entryId) || !e.authorParticipant.startsWith("human:")) continue;
@@ -35980,7 +36607,7 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
35980
36607
  seen.add(e.entryId);
35981
36608
  const text = entryWords(e).trim();
35982
36609
  if (text) {
35983
- words.push(text);
36610
+ words2.push(text);
35984
36611
  gathered?.add(e.entryId);
35985
36612
  }
35986
36613
  }
@@ -35988,9 +36615,9 @@ function unheard(brief, state, since = null, after = -1, reviewSince, gathered)
35988
36615
  const key3 = `answer:${answer.decisionNeedId}`;
35989
36616
  if (seen.has(key3) || Date.parse(answer.acceptedAt) < pendingAt) continue;
35990
36617
  seen.add(key3);
35991
- words.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
36618
+ words2.push(`Answer to question ${answer.decisionNeedId}: ${JSON.stringify(answer.result)}`);
35992
36619
  }
35993
- return words;
36620
+ return words2;
35994
36621
  }
35995
36622
  function sinceTheWork(brief) {
35996
36623
  const entries = brief.entries ?? [];
@@ -36113,9 +36740,9 @@ async function hear(session, state, rail, held, opts, waiting) {
36113
36740
  const log = opts?.log;
36114
36741
  const { heard, listed, direct } = await gather(state, rail, held, waiting, log);
36115
36742
  const said = heard.filter(says);
36116
- const words = [...direct.flatMap((d) => d.words), ...said.map(block)];
36117
- if (words.length) {
36118
- const text = words.join("\n\n");
36743
+ const words2 = [...direct.flatMap((d) => d.words), ...said.map(block)];
36744
+ if (words2.length) {
36745
+ const text = words2.join("\n\n");
36119
36746
  try {
36120
36747
  await send2(session, state, text);
36121
36748
  } catch (error) {
@@ -36146,7 +36773,7 @@ async function note(state, rail, held, inbox, how, waiting) {
36146
36773
  const said = heard.filter(says);
36147
36774
  const parts = [...direct.flatMap((d) => d.words), ...said.map(block)];
36148
36775
  if (!parts.length) return 0;
36149
- const words = parts.join("\n\n");
36776
+ const words2 = parts.join("\n\n");
36150
36777
  const goals = said.map((h) => h.goalId);
36151
36778
  const assigned = given(said);
36152
36779
  if (how.tally) how.tally.announced += assigned.length;
@@ -36154,13 +36781,13 @@ async function note(state, rail, held, inbox, how, waiting) {
36154
36781
  try {
36155
36782
  name = inbox.put(`${NOTED}
36156
36783
 
36157
- ${words}`);
36784
+ ${words2}`);
36158
36785
  how.log?.(`\u25B9 noted mid-turn: ${short(goals)}`);
36159
36786
  if (assigned.length) how.log?.(`\u25B8 announced assigned ${short(assigned)} (via hook)`);
36160
36787
  } catch (error) {
36161
36788
  how.log?.(`\u26A0 could not note mid-turn (${error.message}): ${short(goals)} wait for the turn's end`);
36162
36789
  }
36163
- (state.noted ??= []).push({ name, goals, words, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
36790
+ (state.noted ??= []).push({ name, goals, words: words2, eventIds: direct.map((d) => d.eventId), at: how.now(), cause: how.cause === "wake" ? "wake" : "read" });
36164
36791
  for (const d of direct) for (const id3 of d.entryIds) (state.seen ??= /* @__PURE__ */ new Set()).add(id3);
36165
36792
  return 1;
36166
36793
  }
@@ -36227,6 +36854,24 @@ async function step(session, state, rail, opts) {
36227
36854
  state.paused = void 0;
36228
36855
  state.carryOn = true;
36229
36856
  }
36857
+ if (state.handoff && !state.handoff.said && !state.asks?.size) {
36858
+ const words2 = keepContext(state.handoff.dossier, opts?.fill?.() ?? void 0);
36859
+ if (state.resting) {
36860
+ await send2(session, state, words2);
36861
+ state.handoff.said = true;
36862
+ opts?.log?.(`\u25B8 context turned over: told to write it down and judge whether to hand off (dossier ${state.handoff.dossier})`);
36863
+ return;
36864
+ }
36865
+ if (opts?.inbox && !state.handoff.noted) {
36866
+ try {
36867
+ opts.inbox.put(words2);
36868
+ state.handoff.noted = true;
36869
+ opts.log?.("\u25B9 context turned over: the note is in its inbox for this turn's next tool call");
36870
+ } catch (error) {
36871
+ opts.log?.(`\u26A0 could not note the turnover (${error.message}): it is typed in when the turn ends`);
36872
+ }
36873
+ }
36874
+ }
36230
36875
  await look(session, state, rail, opts);
36231
36876
  if (state.carryOn && state.resting && !state.asks?.size) await send2(session, state, "");
36232
36877
  }
@@ -36301,10 +36946,10 @@ async function look(session, state, rail, opts) {
36301
36946
  await hear(session, state, rail, brief, { ...opts?.log ? { log: opts.log } : {}, ...opts?.tally ? { tally: opts.tally } : {} });
36302
36947
  }
36303
36948
  async function send2(session, state, text) {
36304
- let words = text;
36949
+ let words2 = text;
36305
36950
  if (state.carryOn) {
36306
36951
  const owed = state.owed;
36307
- words = [owed, text].filter(Boolean).join("\n\n");
36952
+ words2 = [owed, text].filter(Boolean).join("\n\n");
36308
36953
  text = [CARRY_ON, ...owed ? [OWED, owed] : [], text].filter(Boolean).join("\n\n");
36309
36954
  }
36310
36955
  const resting = state.resting;
@@ -36315,7 +36960,7 @@ async function send2(session, state, text) {
36315
36960
  state.resting = resting;
36316
36961
  throw error;
36317
36962
  }
36318
- state.typed = words || void 0;
36963
+ state.typed = words2 || void 0;
36319
36964
  if (state.carryOn) {
36320
36965
  state.carryOn = false;
36321
36966
  state.carriedOn = true;
@@ -36331,6 +36976,7 @@ async function pump(session, state, rail, opts) {
36331
36976
  ...opts.initialPrompt ? { initialPrompt: opts.initialPrompt } : {},
36332
36977
  ...opts.log ? { log: opts.log } : {},
36333
36978
  ...opts.inbox ? { inbox: opts.inbox } : {},
36979
+ ...opts.fill ? { fill: opts.fill } : {},
36334
36980
  now,
36335
36981
  tally
36336
36982
  };
@@ -36368,6 +37014,10 @@ function runHarness(opts) {
36368
37014
  const clock4 = beat();
36369
37015
  let session = null;
36370
37016
  const speaksAs = opts.session ?? opts.resume ?? sessionId();
37017
+ let conversation;
37018
+ let model;
37019
+ const filled = fillReader();
37020
+ const fill = () => filled.measure(conversation, model ?? opts.model);
36371
37021
  const instance = randomUUID4();
36372
37022
  const rail = railFor({ token: opts.token, reach: reachAs(speaksAs, instance) });
36373
37023
  let inbox;
@@ -36379,6 +37029,36 @@ function runHarness(opts) {
36379
37029
  }
36380
37030
  }
36381
37031
  const name = opts.name ?? "The agent";
37032
+ let handedOn = false;
37033
+ async function handOnCredits(limit) {
37034
+ if (handedOn) return;
37035
+ if (!handsOver(limit)) return;
37036
+ handedOn = true;
37037
+ const dossier = dossierForWall({
37038
+ name,
37039
+ session: conversation ?? speaksAs,
37040
+ cwd: opts.cwd,
37041
+ why: `A usage limit stopped this session until ${limit.resets}, so its work was handed on.`
37042
+ });
37043
+ const to = carriesOn(detectAll(), opts.harness);
37044
+ if (!to) {
37045
+ opts.log(`\u23F8 nothing else here can take this work, so it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
37046
+ return;
37047
+ }
37048
+ try {
37049
+ const launched = await launchSession({
37050
+ name: successorName(name, to.label),
37051
+ harness: to.name,
37052
+ brief: creditsBrief({ name, dossier, resets: limit.resets }),
37053
+ workspace: opts.cwd,
37054
+ mode: opts.mode,
37055
+ successor: true
37056
+ }, { ...opts.token ? { token: opts.token } : {} });
37057
+ opts.log(`\u25B6 out of credits until ${limit.resets}: ${to.label} session ${launched.sessionId} takes this work on${dossier ? `, with its context in ${dossier}` : ""}`);
37058
+ } catch (error) {
37059
+ opts.log(`\u26A0 could not hand this work on (${error.message}): it waits for ${limit.resets}${dossier ? ` (its context is in ${dossier})` : ""}`);
37060
+ }
37061
+ }
36382
37062
  function runningAgain() {
36383
37063
  state.carriedOn = false;
36384
37064
  opts.log("\u25B6 running again after the limit");
@@ -36411,6 +37091,11 @@ ${event.message}`, state, rail, { log: opts.log });
36411
37091
  }
36412
37092
  if (event.kind === "work") {
36413
37093
  if (state.carriedOn) runningAgain();
37094
+ if (compacted(event)) {
37095
+ state.handoff = { dossier: dossierPath(conversation ?? speaksAs) };
37096
+ opts.log(`\u25C6 ${name}'s context turned over \u2014 writing it to ${state.handoff.dossier}`);
37097
+ clock4.nudge("wake");
37098
+ }
36414
37099
  opts.log(`\u2699 ${event.tool}${event.note ? ` \u2014 ${event.note.split("\n")[0] ?? ""}` : ""}`);
36415
37100
  tail = pushWork(tail, workLine(event));
36416
37101
  return;
@@ -36418,9 +37103,15 @@ ${event.message}`, state, rail, { log: opts.log });
36418
37103
  if (event.kind === "turn") opts.log(`${event.role}: ${event.text.split("\n")[0] ?? ""}`);
36419
37104
  if (event.kind === "idle") {
36420
37105
  tail = [];
37106
+ conversation = event.session ?? conversation;
37107
+ model = event.model ?? model;
36421
37108
  const carried = state.carriedOn && !event.failed;
36422
- if (await afterTurn(event, state, rail, { log: opts.log })) LIMITS.paused(name, Date.now());
36423
- else if (state.full) {
37109
+ const dossier = () => dossierForWall({ name, session: conversation ?? speaksAs, cwd: opts.cwd, why: 'This session reached the wall: every prompt in it came back "Prompt is too long".' });
37110
+ const limit = await afterTurn(event, state, rail, { log: opts.log, dossier });
37111
+ if (limit) {
37112
+ LIMITS.paused(name, Date.now());
37113
+ await handOnCredits(limit);
37114
+ } else if (state.full) {
36424
37115
  opts.log(`\u25A0 ${name}'s conversation is full \u2014 ending this run; it will not be resumed`);
36425
37116
  opts.onFull?.(speaksAs);
36426
37117
  stop2();
@@ -36437,6 +37128,7 @@ ${event.message}`, state, rail, { log: opts.log });
36437
37128
  ...opts.token ? { token: opts.token } : {},
36438
37129
  ...opts.resume ? { resume: opts.resume } : {},
36439
37130
  ...opts.session ? { session: opts.session } : {},
37131
+ ...opts.model ? { model: opts.model } : {},
36440
37132
  ...opts.bin ? { bin: opts.bin } : {},
36441
37133
  ...inbox ? { inbox: inbox.dir } : {},
36442
37134
  onExit: () => {
@@ -36445,7 +37137,7 @@ ${event.message}`, state, rail, { log: opts.log });
36445
37137
  },
36446
37138
  onEvent: (event) => void handle3(event).catch((err) => opts.log(`\u26A0 ${err.message}`))
36447
37139
  });
36448
- void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, ...inbox ? { inbox } : {} }).catch(
37140
+ void pump(session, state, rail, { onIdle: () => running, beat: clock4, initialPrompt: opts.prompt, log: opts.log, fill, ...inbox ? { inbox } : {} }).catch(
36449
37141
  (e) => opts.log(`\u26A0 conversation loop stopped: ${e.message}`)
36450
37142
  );
36451
37143
  opts.log(`\u25B6 started ${opts.harness} in ${opts.cwd} (${opts.mode} mode)`);
@@ -36469,11 +37161,11 @@ ${event.message}`, state, rail, { log: opts.log });
36469
37161
  }
36470
37162
 
36471
37163
  // src/host.ts
36472
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
37164
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
36473
37165
  import { execSync } from "child_process";
36474
37166
  import { randomBytes } from "crypto";
36475
- import { homedir as homedir8 } from "os";
36476
- import { join as join10 } from "path";
37167
+ import { homedir as homedir10 } from "os";
37168
+ import { join as join12 } from "path";
36477
37169
 
36478
37170
  // src/ago.ts
36479
37171
  var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
@@ -36488,11 +37180,11 @@ function ago(iso, now) {
36488
37180
  }
36489
37181
 
36490
37182
  // src/workspaces.ts
36491
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
36492
- import { dirname as dirname2, join as join6, resolve as resolve2 } from "path";
36493
- import { homedir as homedir5 } from "os";
37183
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync4, writeFileSync as writeFileSync4 } from "fs";
37184
+ import { dirname as dirname2, join as join8, resolve as resolve2 } from "path";
37185
+ import { homedir as homedir7 } from "os";
36494
37186
  function workspacesFile() {
36495
- return join6(homedir5(), ".paigy", "workspaces.json");
37187
+ return join8(homedir7(), ".paigy", "workspaces.json");
36496
37188
  }
36497
37189
  function listWorkspaces(deps) {
36498
37190
  try {
@@ -36503,30 +37195,30 @@ function listWorkspaces(deps) {
36503
37195
  }
36504
37196
  }
36505
37197
  function addWorkspace(dir, deps) {
36506
- const next = resolve2(dir.replace(/^~(?=$|\/)/, homedir5()));
37198
+ const next = resolve2(dir.replace(/^~(?=$|\/)/, homedir7()));
36507
37199
  const all = listWorkspaces(deps);
36508
37200
  if (!all.includes(next)) {
36509
37201
  all.push(next);
36510
- mkdirSync3(dirname2(deps.file), { recursive: true });
36511
- writeFileSync3(deps.file, JSON.stringify(all, null, 2));
37202
+ mkdirSync4(dirname2(deps.file), { recursive: true });
37203
+ writeFileSync4(deps.file, JSON.stringify(all, null, 2));
36512
37204
  }
36513
37205
  return all;
36514
37206
  }
36515
37207
  function allowed(cwd, deps) {
36516
- const target = resolve2(cwd.replace(/^~(?=$|\/)/, homedir5()));
37208
+ const target = resolve2(cwd.replace(/^~(?=$|\/)/, homedir7()));
36517
37209
  return listWorkspaces(deps).some((w) => target === w || target.startsWith(`${w}/`));
36518
37210
  }
36519
37211
  function resolveWakeDir(pinned, deps) {
36520
37212
  if (pinned && allowed(pinned, deps)) {
36521
- const dir = resolve2(pinned.replace(/^~(?=$|\/)/, homedir5()));
36522
- if ((deps.exists ?? existsSync4)(dir)) return dir;
37213
+ const dir = resolve2(pinned.replace(/^~(?=$|\/)/, homedir7()));
37214
+ if ((deps.exists ?? existsSync5)(dir)) return dir;
36523
37215
  }
36524
37216
  return listWorkspaces(deps)[0];
36525
37217
  }
36526
37218
  function originOf(dir) {
36527
37219
  try {
36528
- if (!statSync3(join6(dir, ".git")).isDirectory()) return null;
36529
- const config = readFileSync4(join6(dir, ".git", "config"), "utf8");
37220
+ if (!statSync4(join8(dir, ".git")).isDirectory()) return null;
37221
+ const config = readFileSync4(join8(dir, ".git", "config"), "utf8");
36530
37222
  const section = config.split(/^\[/m).find((s) => /^remote\s+"origin"\]/.test(s));
36531
37223
  return section?.match(/^\s*url\s*=\s*(.+)$/m)?.[1]?.trim() ?? null;
36532
37224
  } catch {
@@ -36542,12 +37234,12 @@ function listRepos(deps) {
36542
37234
  if (own) repos.push({ path: root, remote: own });
36543
37235
  let children = [];
36544
37236
  try {
36545
- children = readdirSync2(root, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name).sort().slice(0, MAX_CHILDREN);
37237
+ children = readdirSync4(root, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name).sort().slice(0, MAX_CHILDREN);
36546
37238
  } catch {
36547
37239
  }
36548
37240
  for (const name of children) {
36549
37241
  if (repos.length >= MAX_REPOS) return repos;
36550
- const path = join6(root, name);
37242
+ const path = join8(root, name);
36551
37243
  const remote = originOf(path);
36552
37244
  if (remote) repos.push({ path, remote });
36553
37245
  }
@@ -36557,9 +37249,9 @@ function listRepos(deps) {
36557
37249
 
36558
37250
  // src/holder.ts
36559
37251
  import { execFileSync as execFileSync2 } from "child_process";
36560
- import { readFileSync as readFileSync5, readdirSync as readdirSync3 } from "fs";
36561
- import { homedir as homedir6 } from "os";
36562
- import { join as join7 } from "path";
37252
+ import { readFileSync as readFileSync5, readdirSync as readdirSync5 } from "fs";
37253
+ import { homedir as homedir8 } from "os";
37254
+ import { join as join9 } from "path";
36563
37255
  function isAlive(pid) {
36564
37256
  try {
36565
37257
  process.kill(pid, 0);
@@ -36597,8 +37289,8 @@ function proven(pid, procStart, deps) {
36597
37289
  });
36598
37290
  }
36599
37291
  function localHolderPids(deps = {}) {
36600
- const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude"), "sessions");
36601
- const list = deps.list ?? ((d) => readdirSync3(d));
37292
+ const dir = deps.dir ?? join9(process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir8(), ".claude"), "sessions");
37293
+ const list = deps.list ?? ((d) => readdirSync5(d));
36602
37294
  const read3 = deps.read ?? ((f) => readFileSync5(f, "utf8"));
36603
37295
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
36604
37296
  const held = /* @__PURE__ */ new Map();
@@ -36612,7 +37304,7 @@ function localHolderPids(deps = {}) {
36612
37304
  if (!/^\d+\.json$/.test(file)) continue;
36613
37305
  let row;
36614
37306
  try {
36615
- row = parseSessionRecord(read3(join7(dir, file)));
37307
+ row = parseSessionRecord(read3(join9(dir, file)));
36616
37308
  } catch {
36617
37309
  continue;
36618
37310
  }
@@ -36646,8 +37338,8 @@ function descendsFrom(pid, ancestor, parent = psParent) {
36646
37338
  return false;
36647
37339
  }
36648
37340
  function localHolders(deps = {}) {
36649
- const dir = deps.dir ?? join7(process.env.CLAUDE_CONFIG_DIR?.trim() || join7(homedir6(), ".claude"), "sessions");
36650
- const list = deps.list ?? ((d) => readdirSync3(d));
37341
+ const dir = deps.dir ?? join9(process.env.CLAUDE_CONFIG_DIR?.trim() || join9(homedir8(), ".claude"), "sessions");
37342
+ const list = deps.list ?? ((d) => readdirSync5(d));
36651
37343
  const read3 = deps.read ?? ((f) => readFileSync5(f, "utf8"));
36652
37344
  const check = { alive: deps.alive ?? isAlive, started: deps.started ?? psStart };
36653
37345
  const held = /* @__PURE__ */ new Map();
@@ -36661,7 +37353,7 @@ function localHolders(deps = {}) {
36661
37353
  if (!/^\d+\.json$/.test(file)) continue;
36662
37354
  let row;
36663
37355
  try {
36664
- row = parseSessionRecord(read3(join7(dir, file)));
37356
+ row = parseSessionRecord(read3(join9(dir, file)));
36665
37357
  } catch {
36666
37358
  continue;
36667
37359
  }
@@ -36738,26 +37430,26 @@ async function endSession(end, deps) {
36738
37430
  }
36739
37431
 
36740
37432
  // src/owner.ts
36741
- import { closeSync as closeSync2, openSync as openSync2, readSync, readdirSync as readdirSync4 } from "fs";
36742
- import { homedir as homedir7 } from "os";
36743
- import { join as join8 } from "path";
37433
+ import { closeSync as closeSync4, openSync as openSync4, readSync as readSync3, readdirSync as readdirSync6 } from "fs";
37434
+ import { homedir as homedir9 } from "os";
37435
+ import { join as join10 } from "path";
36744
37436
  var HEAD_BYTES = 64e3;
36745
37437
  function readHead(file) {
36746
- const fd = openSync2(file, "r");
37438
+ const fd = openSync4(file, "r");
36747
37439
  try {
36748
37440
  const buf = Buffer.alloc(HEAD_BYTES);
36749
- const n = readSync(fd, buf, 0, HEAD_BYTES, 0);
37441
+ const n = readSync3(fd, buf, 0, HEAD_BYTES, 0);
36750
37442
  return buf.subarray(0, n).toString("utf8");
36751
37443
  } finally {
36752
- closeSync2(fd);
37444
+ closeSync4(fd);
36753
37445
  }
36754
37446
  }
36755
37447
  function ownerSession(slot, deps = {}) {
36756
37448
  const m = /^session:([0-9a-f]{8})$/.exec(slot);
36757
37449
  if (!m) return null;
36758
37450
  const prefix = m[1];
36759
- const root = deps.projectsDir ?? join8(homedir7(), ".claude", "projects");
36760
- const list = deps.list ?? ((dir) => readdirSync4(dir));
37451
+ const root = deps.projectsDir ?? join10(homedir9(), ".claude", "projects");
37452
+ const list = deps.list ?? ((dir) => readdirSync6(dir));
36761
37453
  const head2 = deps.head ?? readHead;
36762
37454
  let folders;
36763
37455
  try {
@@ -36768,7 +37460,7 @@ function ownerSession(slot, deps = {}) {
36768
37460
  for (const folder of folders) {
36769
37461
  let files;
36770
37462
  try {
36771
- files = list(join8(root, folder));
37463
+ files = list(join10(root, folder));
36772
37464
  } catch {
36773
37465
  continue;
36774
37466
  }
@@ -36776,7 +37468,7 @@ function ownerSession(slot, deps = {}) {
36776
37468
  if (!file) continue;
36777
37469
  let text;
36778
37470
  try {
36779
- text = head2(join8(root, folder, file));
37471
+ text = head2(join10(root, folder, file));
36780
37472
  } catch {
36781
37473
  continue;
36782
37474
  }
@@ -36796,7 +37488,7 @@ function ownerSession(slot, deps = {}) {
36796
37488
  // src/update.ts
36797
37489
  import { execFile } from "child_process";
36798
37490
  import { createRequire } from "module";
36799
- import { dirname as dirname3, join as join9 } from "path";
37491
+ import { dirname as dirname3, join as join11 } from "path";
36800
37492
  import { promisify } from "util";
36801
37493
  var SERVICE_LABEL = "ai.paigy.harness";
36802
37494
  var VERSION = createRequire(import.meta.url)("../package.json").version;
@@ -36823,7 +37515,7 @@ async function latestVersion() {
36823
37515
  }
36824
37516
  async function install(version) {
36825
37517
  const bin = dirname3(process.execPath);
36826
- await promisify(execFile)(join9(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
37518
+ await promisify(execFile)(join11(bin, "npm"), ["install", "-g", `@paigy/harness@${version}`], {
36827
37519
  env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}`, npm_config_update_notifier: "false" },
36828
37520
  timeout: 5 * 6e4
36829
37521
  });
@@ -36874,7 +37566,7 @@ function selfUpdater(deps) {
36874
37566
  }
36875
37567
 
36876
37568
  // src/host.ts
36877
- var HOST_FILE = join10(homedir8(), ".paigy", "host.json");
37569
+ var HOST_FILE = join12(homedir10(), ".paigy", "host.json");
36878
37570
  function wakeHarness(slot, saved, claudeTranscript) {
36879
37571
  if (slot === "Desktop") return void 0;
36880
37572
  if (saved !== null) return saved === "agy" || saved === "codex" || saved === "claude" || saved === "grok" ? saved : void 0;
@@ -36895,6 +37587,7 @@ var claimedRun = (sessionId2) => {
36895
37587
  return { slot, key: runKey(slot) };
36896
37588
  };
36897
37589
  var launchRun = (spec) => ({ session: spec.sessionId, model: spec.model });
37590
+ var launchMode = (mode) => mode === "ask" ? "ask" : "bypass";
36898
37591
  var BOUND_ELSEWHERE_MS = 10 * 6e4;
36899
37592
  var boundElsewhere = /* @__PURE__ */ new Map();
36900
37593
  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";
@@ -37035,7 +37728,8 @@ function startHost(opts) {
37035
37728
  device: null,
37036
37729
  workspace: spec.workspace,
37037
37730
  harness: spec.harness,
37038
- session_id: spec.sessionId
37731
+ session_id: spec.sessionId,
37732
+ mode: launchMode(spec.mode)
37039
37733
  }, slot);
37040
37734
  } catch {
37041
37735
  log("Cannot persist launch identity/runtime; session was not started. Check local storage and relaunch.");
@@ -37044,7 +37738,7 @@ function startHost(opts) {
37044
37738
  const run = runHarness({
37045
37739
  harness: spec.harness,
37046
37740
  cwd: workspace,
37047
- mode: "bypass",
37741
+ mode: launchMode(spec.mode),
37048
37742
  prompt: "",
37049
37743
  token: spec.token,
37050
37744
  ...launchRun(spec),
@@ -37063,7 +37757,7 @@ function startHost(opts) {
37063
37757
  void heartbeat(void 0, { token: spec.token }).catch(() => {
37064
37758
  });
37065
37759
  void refreshIdentities();
37066
- opts.log(`\u25B6 phone-launched ${label} (${spec.harness}) in ${spec.workspace}`);
37760
+ opts.log(`\u25B6 launched ${label} (${spec.harness}, ${launchMode(spec.mode)}) in ${spec.workspace}`);
37067
37761
  }
37068
37762
  const ends = await claimSessionEnds(asHost).catch(() => []);
37069
37763
  for (const end of ends) {
@@ -37210,9 +37904,10 @@ function startHost(opts) {
37210
37904
  }
37211
37905
  const log = (line) => opts.log(`[${label}] ${line}`);
37212
37906
  const run = runHarness({
37907
+ // A wake runs the session the way its launch asked (the slot keeps it), bypass when it named none.
37213
37908
  harness,
37214
37909
  cwd: workspace,
37215
- mode: "bypass",
37910
+ mode: launchMode(identity.mode),
37216
37911
  prompt: "",
37217
37912
  token,
37218
37913
  ...identity.sessionId ? { session: identity.sessionId } : {},
@@ -37299,7 +37994,7 @@ function startHost(opts) {
37299
37994
  };
37300
37995
  const publish = () => {
37301
37996
  try {
37302
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
37997
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: Date.now(), roster: api.roster() }));
37303
37998
  } catch {
37304
37999
  }
37305
38000
  };
@@ -37366,7 +38061,7 @@ function startHost(opts) {
37366
38061
  streamActivity();
37367
38062
  clearInterval(activityTick);
37368
38063
  try {
37369
- writeFileSync4(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
38064
+ writeFileSync5(HOST_FILE, JSON.stringify({ pid: process.pid, at: 0, roster: [] }));
37370
38065
  } catch {
37371
38066
  }
37372
38067
  }
@@ -37471,11 +38166,11 @@ async function pairThisMachine() {
37471
38166
  }
37472
38167
  }
37473
38168
  function forwardCodexThreadId() {
37474
- const cfg = join11(process.env.CODEX_HOME || join11(homedir9(), ".codex"), "config.toml");
37475
- if (!existsSync5(cfg)) return;
38169
+ const cfg = join13(process.env.CODEX_HOME || join13(homedir11(), ".codex"), "config.toml");
38170
+ if (!existsSync6(cfg)) return;
37476
38171
  const text = readFileSync7(cfg, "utf8");
37477
38172
  const updated = withCodexEnv(text);
37478
- if (updated !== null && updated !== text) writeFileSync5(cfg, updated);
38173
+ if (updated !== null && updated !== text) writeFileSync6(cfg, updated);
37479
38174
  }
37480
38175
  async function main() {
37481
38176
  setClient(`harness@${VERSION}`);
@@ -37494,7 +38189,7 @@ async function main() {
37494
38189
  console.log(" service install the host as a login service (macOS)");
37495
38190
  console.log(" enable-tools allowlist Paigy's tools in Claude Code so they don't prompt each time");
37496
38191
  console.log(" hatch NAME mint a sibling identity from this machine's credential");
37497
- console.log(' launch NAME "brief" start a helper session with its own identity and its brief as its first Goal [--under GOAL]');
38192
+ console.log(` launch NAME "brief" ask this computer's host to run a helper session, its brief as its first Goal [--under GOAL] [--approval QUESTION]`);
37498
38193
  console.log(" handoff pin this terminal's identity here so your phone can resume it");
37499
38194
  console.log(" --doctor report which agent CLIs are installed and ready");
37500
38195
  console.log("");
@@ -37555,8 +38250,8 @@ async function main() {
37555
38250
  const wsDeps = { file: workspacesFile() };
37556
38251
  for (const dir of parsed.grant) addWorkspace(dir, wsDeps);
37557
38252
  if (!listWorkspaces(wsDeps).length) {
37558
- const guess = join11(homedir9(), "projects");
37559
- if (existsSync5(guess)) {
38253
+ const guess = join13(homedir11(), "projects");
38254
+ if (existsSync6(guess)) {
37560
38255
  addWorkspace(guess, wsDeps);
37561
38256
  console.log(`\u2713 workspace granted: ${guess} (change with --grant DIR)`);
37562
38257
  } else console.log("no workspace granted yet \u2014 grant one with: paigy-harness host --grant DIR");
@@ -37588,12 +38283,12 @@ async function main() {
37588
38283
  }
37589
38284
  }
37590
38285
  try {
37591
- const settings = join11(homedir9(), ".claude", "settings.json");
37592
- if (which("claude") && existsSync5(settings)) {
38286
+ const settings = join13(homedir11(), ".claude", "settings.json");
38287
+ if (which("claude") && existsSync6(settings)) {
37593
38288
  const cfg = JSON.parse(readFileSync7(settings, "utf8"));
37594
38289
  if (!cfg["statusLine"]) {
37595
38290
  cfg["statusLine"] = { type: "command", command: "npx -y -p @paigy/mcp@latest paigy-statusline" };
37596
- writeFileSync5(settings, JSON.stringify(cfg, null, 2));
38291
+ writeFileSync6(settings, JSON.stringify(cfg, null, 2));
37597
38292
  console.log("\u2713 statusline wired");
37598
38293
  }
37599
38294
  }
@@ -37646,14 +38341,14 @@ async function main() {
37646
38341
  <key>SoftResourceLimits</key><dict>
37647
38342
  <key>NumberOfFiles</key><integer>65536</integer>
37648
38343
  </dict>
37649
- <key>StandardOutPath</key><string>${join11(homedir9(), ".paigy", "host.log")}</string>
37650
- <key>StandardErrorPath</key><string>${join11(homedir9(), ".paigy", "host.log")}</string>
38344
+ <key>StandardOutPath</key><string>${join13(homedir11(), ".paigy", "host.log")}</string>
38345
+ <key>StandardErrorPath</key><string>${join13(homedir11(), ".paigy", "host.log")}</string>
37651
38346
  </dict></plist>
37652
38347
  `;
37653
- const dir = join11(homedir9(), "Library", "LaunchAgents");
37654
- mkdirSync4(dir, { recursive: true });
37655
- const path = join11(dir, `${SERVICE_LABEL}.plist`);
37656
- writeFileSync5(path, plist);
38348
+ const dir = join13(homedir11(), "Library", "LaunchAgents");
38349
+ mkdirSync5(dir, { recursive: true });
38350
+ const path = join13(dir, `${SERVICE_LABEL}.plist`);
38351
+ writeFileSync6(path, plist);
37657
38352
  execSync2(`launchctl unload ${path} 2>/dev/null; launchctl load ${path}`, { shell: "/bin/sh" });
37658
38353
  console.log(`\u2713 host installed as a login service (${path}) \u2014 logs at ~/.paigy/host.log`);
37659
38354
  console.log(" file limit raised to 65536 for the host and every session it spawns");
@@ -37675,7 +38370,7 @@ async function main() {
37675
38370
  process.exit(1);
37676
38371
  }
37677
38372
  const name = slotName(slot) ?? slot;
37678
- console.log(`\u2713 ${name} is handed off \u2014 wakes in ${cwd.replace(homedir9(), "~")}`);
38373
+ console.log(`\u2713 ${name} is handed off \u2014 wakes in ${cwd.replace(homedir11(), "~")}`);
37679
38374
  if (!allowed(cwd, { file: workspacesFile() })) {
37680
38375
  console.log(` \u26A0 that folder isn't on the allow-list, so wakes will land in the first granted`);
37681
38376
  console.log(` workspace instead \u2014 add it in the desktop app, or: paigy-harness host --grant ${cwd}`);
@@ -37710,29 +38405,36 @@ async function main() {
37710
38405
  });
37711
38406
  return;
37712
38407
  }
38408
+ if (parsed.launch) {
38409
+ const device = readSlot("Desktop") || null;
38410
+ const own = readToken() || null;
38411
+ const code = await launchViaHost({ ...parsed, launch: parsed.launch }, {
38412
+ agentToken: own && own !== device ? own : null,
38413
+ parentName: slotName(agentName()),
38414
+ deviceToken: device,
38415
+ deviceTokenId: slotIdentity("Desktop").tokenId,
38416
+ isTTY: !!process.stdin.isTTY && !!process.stdout.isTTY,
38417
+ confirm: async (question) => {
38418
+ const readline = await import("readline/promises");
38419
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
38420
+ try {
38421
+ return /^\s*y(es)?\s*$/i.test(await rl.question(question));
38422
+ } finally {
38423
+ rl.close();
38424
+ }
38425
+ },
38426
+ launch: launchSession,
38427
+ log: (line) => console.log(line),
38428
+ error: (line) => console.error(line)
38429
+ });
38430
+ process.exit(code);
38431
+ }
37713
38432
  const state = detectAll().find((a) => a.name === parsed.harness);
37714
38433
  if (state && state.status !== "ready") {
37715
38434
  const hint = state.hint ?? "setup incomplete";
37716
38435
  console.error(`\u270B ${state.label}: ${hint}`);
37717
38436
  process.exit(1);
37718
38437
  }
37719
- let launched;
37720
- if (parsed.launch) {
37721
- const parent = slotName(agentName());
37722
- const name = lineageName(parent, parsed.launch);
37723
- overrideToken(readSlot("Desktop") || null);
37724
- const session = randomUUID5();
37725
- const minted = await hatch(name, parsed.voice ?? null, {
37726
- reach: reachAs(session),
37727
- brief: parsed.prompt,
37728
- ...parsed.under ? { parentGoalId: parsed.under } : {}
37729
- }).catch((e) => {
37730
- console.error(`\u270B the helper was not launched: ${e.message}`);
37731
- process.exit(1);
37732
- }).finally(() => overrideToken(null));
37733
- launched = { token: minted.token, session, ...minted.goalId ? { goalId: minted.goalId } : {} };
37734
- console.log(`\u2713 launched "${minted.name ?? name}"${minted.name ? "" : " (unnamed: you already have an agent with that name)"}, on its own session; its Goal is ${minted.goalId ?? "missing"}`);
37735
- }
37736
38438
  const askTerminal = async (promptText) => {
37737
38439
  if (parsed.graceSeconds <= 0 || !process.stdin.isTTY) return null;
37738
38440
  const readline = await import("readline/promises");
@@ -37753,10 +38455,9 @@ async function main() {
37753
38455
  harness: parsed.harness,
37754
38456
  cwd: parsed.cwd,
37755
38457
  mode: parsed.mode,
37756
- // hatch already admitted this brief; the pump must not admit it again after completion.
37757
- prompt: launched ? "" : parsed.prompt,
38458
+ ...parsed.model ? { model: parsed.model } : {},
38459
+ prompt: parsed.prompt,
37758
38460
  ...state?.bin ? { bin: state.bin } : {},
37759
- ...launched ? { token: launched.token, session: launched.session } : {},
37760
38461
  localAsk: {
37761
38462
  permission: async (summary) => {
37762
38463
  const said = await askTerminal(`\u23F8 blocked: ${summary} \u2014 allow? [y/n]`);
@@ -37768,7 +38469,7 @@ async function main() {
37768
38469
  });
37769
38470
  const beat2 = async () => {
37770
38471
  try {
37771
- await heartbeat(void 0, launched ? { token: launched.token } : {});
38472
+ await heartbeat();
37772
38473
  signedOut = false;
37773
38474
  } catch (e) {
37774
38475
  if (!isUnauthorized(e) || signedOut) return;