@phren/cli 0.3.47 → 0.3.49

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.
@@ -1,6 +1,6 @@
1
1
  // Moving a live session to another agent: the agent in the pane writes a
2
2
  // hand-off, exits the way it normally does, and the target harness starts in
3
- // the same pane, in the same folder, with that hand-off as its first prompt.
3
+ // the same pane by default, or a new chat that keeps the old agent running.
4
4
  //
5
5
  // The hand-off is asked for through the same durable prompt path `hand_off`
6
6
  // uses, as a reply between two marker lines; the Hook reads it from the
@@ -35,12 +35,13 @@ export { moveToSchema };
35
35
  export const moveRequestSchema = z.object({
36
36
  target: targetSchema,
37
37
  to: moveToSchema,
38
+ mode: z.enum(["replace", "new-chat"]).default("replace"),
38
39
  /** Kept on a retry: the same id returns the move already under way. */
39
40
  id: z.string().uuid().optional(),
40
41
  /** How long the agent gets to write its hand-off before Phren builds one. */
41
42
  handoffTimeoutMs: z.number().int().min(5_000).max(900_000).optional(),
42
43
  }).strict();
43
- const MOVE_STATES = ["handing-off", "exiting", "launching", "moved", "failed"];
44
+ const MOVE_STATES = ["handing-off", "exiting", "launching", "linking", "moved", "failed"];
44
45
  const timestamp = z.string().datetime();
45
46
  const moveRecordSchema = z.object({
46
47
  id: z.string().uuid(),
@@ -48,6 +49,9 @@ const moveRecordSchema = z.object({
48
49
  createdAt: timestamp, updatedAt: timestamp,
49
50
  from: z.object({ target: targetSchema, account: z.string().max(64).optional(), label: z.string().max(200).optional() }).strict(),
50
51
  to: moveToSchema,
52
+ mode: z.enum(["replace", "new-chat"]).optional(),
53
+ handedOffTo: z.object({ target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
54
+ handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
51
55
  cwd: z.string().max(4096),
52
56
  /** The dispatch the moved worker was launched for, as its turn record names it. */
53
57
  dispatch: briefId.optional(),
@@ -56,6 +60,9 @@ const moveRecordSchema = z.object({
56
60
  exit: z.enum(["clean", "interrupted", "killed"]).optional(),
57
61
  placement: z.enum(["same-pane", "adjacent-pane"]).optional(),
58
62
  target: z.union([targetSchema, startingTargetSchema]).optional(),
63
+ paneTarget: targetSchema.omit({ session: true }).optional(),
64
+ linkPending: z.boolean().optional(),
65
+ notice: z.string().max(500).optional(),
59
66
  movedAt: timestamp.optional(),
60
67
  error: z.string().max(500).optional(),
61
68
  }).strict();
@@ -111,6 +118,18 @@ export function moveFrom(records, target) {
111
118
  && (target.session === undefined || from.session === target.session);
112
119
  });
113
120
  }
121
+ /** Conversation-bound annotations shared by tab and pane overview rows. */
122
+ export function moveSessionFields(records, target, title) {
123
+ const matches = (other) => other.server === target.server && other.workspace === target.workspace
124
+ && other.tab === target.tab && other.pane === target.pane && other.source === target.source
125
+ && "session" in other && other.session === target.session;
126
+ const outgoing = records.find(record => record.state === "moved" && record.mode === "new-chat" && matches(record.from.target));
127
+ const incoming = records.find(record => record.state === "moved" && record.mode === "new-chat" && record.target && matches(record.target));
128
+ const suffix = outgoing ? ` (handed off to ${outgoing.to.harness})` : "";
129
+ return { ...(outgoing?.handedOffTo ? { handedOffTo: outgoing.handedOffTo,
130
+ title: `${(title ?? outgoing.from.label ?? outgoing.from.target.source).replace(/ \(handed off to [^)]+\)$/, "")}${suffix}` } : {}),
131
+ ...(incoming?.handedOffFrom ? { handedOffFrom: incoming.handedOffFrom } : {}) };
132
+ }
114
133
  /** The receipt fields for a finished move. */
115
134
  export function movedWorker(record) {
116
135
  if (record.state !== "moved" || !record.target)
@@ -128,7 +147,7 @@ const markers = (id) => {
128
147
  return { begin: `=== PHREN HANDOFF ${short} BEGIN ===`, end: `=== PHREN HANDOFF ${short} END ===` };
129
148
  };
130
149
  /** What the moving agent is asked to write. */
131
- export function handoffRequest(id, to) {
150
+ export function handoffRequest(id, to, mode = "replace") {
132
151
  const { begin, end } = markers(id);
133
152
  return [
134
153
  `Phren is moving this session to ${harnessName(to)}, which continues the work in this same folder. Write a hand-off for it now.`,
@@ -146,7 +165,8 @@ export function handoffRequest(id, to) {
146
165
  "## Decisions: what you chose and why, including approaches you ruled out",
147
166
  "## Next steps: in order",
148
167
  "## Open questions: for the owner, or still undecided",
149
- "## Key files: paths, a few words each",
168
+ "## Key files: paths, a few words each, including files you had open or changed",
169
+ ...(mode === "new-chat" ? ["The target starts in a new chat. Keep this agent running; do not exit after the hand-off."] : []),
150
170
  "",
151
171
  "Write it in full; do not shorten it. Use no tools once you start it. Phren saves it to a file and starts the next agent with it.",
152
172
  ].join("\n");
@@ -322,6 +342,9 @@ export function handoffDocument(record, body, observed, at) {
322
342
  "",
323
343
  `Moved by Phren at ${at} (move ${record.id}) in ${record.cwd}.${record.dispatch ? ` Dispatch ${record.dispatch}.` : ""}`,
324
344
  "",
345
+ ...(record.mode === "new-chat" ? ["## Previous chat", "",
346
+ `Title: ${record.from.label ?? record.from.target.source}`,
347
+ "Target (JSON, for opening the old chat):", "```json", JSON.stringify(record.from.target), "```", ""] : []),
325
348
  body.trim(),
326
349
  "",
327
350
  observed,
@@ -397,10 +420,10 @@ export class SessionMover {
397
420
  if (!path.isAbsolute(cwd))
398
421
  throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
399
422
  const dispatch = await this.deps.paneDispatch?.(target.server, pane).catch(() => undefined);
400
- const label = [pane.label, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
423
+ const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
401
424
  const at = new Date(this.now).toISOString();
402
425
  const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
403
- from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
426
+ mode: data.mode, from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
404
427
  ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}) };
405
428
  await saveMove(record);
406
429
  const key = `${target.server}\0${target.pane}`;
@@ -423,25 +446,34 @@ export class SessionMover {
423
446
  const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
424
447
  (this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
425
448
  const written = await this.askForHandoff(record, handoffMs);
426
- const body = "text" in written ? written.text : await this.fallback(record, written.reason);
449
+ const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
450
+ const body = "text" in written ? written.text : record.mode === "new-chat"
451
+ ? `## Goal and current state\n\n${fallback}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`
452
+ : fallback;
427
453
  const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString());
428
454
  const file = handoffPath(record.id);
429
455
  const prompt = briefText(continuePrompt(document, file));
430
456
  // The folder is the new agent's brief folder; the hand-off is written into it, whole.
431
457
  await writeLaunchBrief({ id: record.id, text: prompt }, this.now, record.from.label);
432
458
  await atomic(file, document);
433
- await this.update(record, { state: "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
459
+ await this.update(record, { state: record.mode === "new-chat" ? "launching" : "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
434
460
  ...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
435
- const exit = await this.exit(record);
436
- await this.update(record, { state: "launching", exit });
437
- await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
461
+ if (record.mode !== "new-chat") {
462
+ const exit = await this.exit(record);
463
+ await this.update(record, { state: "launching", exit });
464
+ await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
465
+ }
438
466
  const launched = await this.relaunch(record, prompt);
439
- await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
467
+ await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched,
468
+ ...(record.mode === "new-chat" ? {
469
+ ...(launched.target ? { handedOffTo: { target: launched.target } } : {}),
470
+ handedOffFrom: { target: from, title: record.from.label ?? from.source },
471
+ } : {}) });
440
472
  logger.info("move", `Moved ${from.source} in pane ${from.pane} to ${harnessName(record.to)} (${launched.placement}); hand-off ${record.handoff?.source}.`);
441
473
  }
442
474
  catch (error) {
443
475
  const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
444
- const stopped = record.state === "launching";
476
+ const stopped = record.exit !== undefined;
445
477
  const hint = stopped && record.handoff ? ` The old agent has exited; start ${HARNESS_NAMES[record.to.harness]} in the pane with the hand-off at ${record.handoff.path}.` : "";
446
478
  await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
447
479
  logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
@@ -452,7 +484,7 @@ export class SessionMover {
452
484
  const from = record.from.target;
453
485
  const deadline = this.now + handoffMs;
454
486
  try {
455
- const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to), `move-${record.id}`);
487
+ const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to, record.mode), `move-${record.id}`);
456
488
  if (sent.ok !== true && sent.queued !== true)
457
489
  return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
458
490
  }
@@ -547,33 +579,54 @@ export class SessionMover {
547
579
  // A Claude target with no account keeps the pane's own, so its shell's CLAUDE_CONFIG_DIR is right.
548
580
  const shellAccount = record.from.account ?? DEFAULT_ACCOUNT;
549
581
  const account = record.to.harness === "claude" ? record.to.account ?? shellAccount : undefined;
550
- const samePane = (this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount;
582
+ const samePane = record.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount);
551
583
  const data = { kind: record.to.harness, label: record.from.label ?? HARNESS_NAMES[record.to.harness], cwd: record.cwd,
552
584
  ...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
553
585
  brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
554
586
  const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
555
587
  const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch ? { dispatchId: record.dispatch } : {}) });
588
+ // Keep the launched location even if delivering its first prompt fails.
589
+ const paneTarget = targetSchema.omit({ session: true }).parse({ server: from.server,
590
+ workspace: launched.workspaceId, tab: launched.tabId, pane: launched.paneId, source: record.to.harness });
591
+ const launchedTarget = z.union([targetSchema, startingTargetSchema]).safeParse(launched.target);
592
+ await this.update(record, { paneTarget, placement: samePane ? "same-pane" : "adjacent-pane",
593
+ ...(launchedTarget.success ? { target: launchedTarget.data } : {}) });
556
594
  // The target that takes no brief at launch (Copilot) gets it typed, as dispatch does.
557
595
  if (launched.briefLaunched === false) {
558
- const typedTo = targetSchema.safeParse(launched.target);
559
- if (typedTo.success)
560
- await this.deps.deliver(typedTo.data, prompt, `move-${record.id}-brief`).catch(() => undefined);
561
- else
562
- await this.deps.terminal.prompt(from.server, String(launched.paneId), prompt).catch(() => undefined);
596
+ try {
597
+ const typedTo = targetSchema.safeParse(launched.target);
598
+ if (typedTo.success) {
599
+ const sent = await this.deps.deliver(typedTo.data, prompt, `move-${record.id}-brief`);
600
+ if (sent.state === "failed" || (sent.ok !== true && sent.queued !== true)
601
+ || (sent.delivered === false && sent.queued !== true)) {
602
+ throw new Error(String(sent.error ?? sent.state ?? "delivery was not confirmed"));
603
+ }
604
+ }
605
+ else
606
+ await this.deps.terminal.prompt(from.server, paneTarget.pane, prompt);
607
+ }
608
+ catch (error) {
609
+ const reason = error instanceof Error ? error.message : String(error);
610
+ throw new Error(`${record.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${reason}`);
611
+ }
563
612
  }
564
- if (!samePane)
613
+ if (!samePane && record.mode !== "new-chat")
565
614
  await this.deps.terminal.closePane(from.server, from.pane).catch(() => undefined);
566
615
  // The account the new agent runs under, also when the move named none.
567
616
  const to = account ? { ...record.to, account } : record.to;
568
- return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(from.server, launched, record.to.harness) };
617
+ return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(record, launched, record.to.harness) };
569
618
  }
570
- /** The new agent's full target, waiting a little for its conversation id when the launch did not have it yet. */
571
- async newTarget(server, launched, source) {
619
+ /** New chats remain open as linking while the harness establishes its conversation. */
620
+ async newTarget(record, launched, source) {
621
+ const server = record.from.target.server;
572
622
  const full = targetSchema.safeParse(launched.target);
573
623
  if (full.success)
574
624
  return { target: full.data };
575
625
  const place = { server, workspace: String(launched.workspaceId), tab: String(launched.tabId), pane: String(launched.paneId), source };
576
- for (const until = this.now + 30_000; this.now < until; await this.sleep(this.poll)) {
626
+ const newChat = record.mode === "new-chat";
627
+ if (newChat)
628
+ await this.update(record, { state: "linking" });
629
+ for (const until = this.now + (newChat ? 180_000 : 30_000); this.now < until; await this.sleep(this.poll)) {
577
630
  const pane = findPane(await this.deps.snapshot(server).catch(() => ({})), place);
578
631
  const session = pane && pane.agent === source ? await this.deps.identity(server, pane).catch(() => undefined) : undefined;
579
632
  const target = targetSchema.safeParse({ ...place, session });
@@ -581,7 +634,8 @@ export class SessionMover {
581
634
  return { target: target.data };
582
635
  }
583
636
  const starting = startingTargetSchema.safeParse(launched.target);
584
- return starting.success ? { target: starting.data } : {};
637
+ return { ...(starting.success ? { target: starting.data } : {}),
638
+ ...(newChat ? { linkPending: true, notice: "New chat started; the conversation link is pending after three minutes. Use the pane target to open it." } : {}) };
585
639
  }
586
640
  }
587
641
  /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */