@abelxiaoxing/cadence 2.0.29 → 2.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.de.md CHANGED
@@ -15,6 +15,8 @@ Plane eine Code-Aufgabe, lass Subagents daran arbeiten, führe deine Checks aus
15
15
  Subagent-Ausgabe, echte Check-Läufe und deine eigene Prüfung bleiben getrennt: Modelltext oder ein „Done“ zählt nie als bestanden, und fehlgeschlagene, abgebrochene und unbekannte Ergebnisse bleiben unterscheidbar.
16
16
  - **Vollständige Historie.**
17
17
  Jeder Lauf behält seine Nachrichten, Tool-Aufrufe und Ausgaben, mit exakter Suche und vollständigem Markdown/NDJSON-Export; bekannte Geheimnisse werden maskiert.
18
+ - **Ein Verlauf mit dem Terminal.**
19
+ Browser-Unterhaltungen sind die Pi-Sitzungen des Projekts: Setzen Sie eine Terminal-Sitzung im Browser fort oder eine Browser-Sitzung mit `/resume`, und lesen Sie Pis Verzweigungen an beiden Orten.
18
20
  - **Ein Link für alles.**
19
21
  Das WebUI (Desktop und Telefon, Englisch und Vereinfachtes Chinesisch) beherbergt außerdem gewöhnliche Pi-Gespräche und wechselt zwischen Projekten, jedes mit eigenem Owner und eigener Historie.
20
22
 
package/README.es.md CHANGED
@@ -15,6 +15,8 @@ Planifica una tarea de código, deja que los subagentes trabajen en ella, ejecut
15
15
  La salida de los subagentes, las ejecuciones reales de comprobaciones y tu propia revisión permanecen separadas: la prosa del modelo o un "Done" nunca cuentan como comprobación superada, y los resultados fallidos, cancelados y desconocidos permanecen distinguidos.
16
16
  - **Historial completo.**
17
17
  Cada ejecución conserva sus mensajes, llamadas a herramientas y salidas, con búsqueda exacta y exportación completa en Markdown/NDJSON; los secretos conocidos se enmascaran.
18
+ - **Un historial compartido con la terminal.**
19
+ Las conversaciones del navegador son las sesiones de Pi del proyecto: continúa una sesión de la terminal en el navegador o una del navegador con `/resume`, y consulta las ramas de Pi en ambos lugares.
18
20
  - **Un enlace para todo.**
19
21
  La interfaz web (escritorio y teléfono, inglés y chino simplificado) también aloja conversaciones ordinarias de Pi y cambia entre proyectos, cada uno con su propio owner e historial.
20
22
 
package/README.fr.md CHANGED
@@ -15,6 +15,8 @@ Planifiez une tâche de code, laissez les sous-agents y travailler, exécutez vo
15
15
  La sortie des sous-agents, les exécutions réelles de vérifications et votre propre examen restent distincts : le texte du modèle ou un « Done » ne compte jamais comme une vérification passée, et les résultats échoués, annulés et inconnus restent distincts.
16
16
  - **Historique complet.**
17
17
  Chaque exécution conserve ses messages, appels d'outils et sorties, avec recherche exacte et export Markdown/NDJSON complets ; les secrets connus sont masqués.
18
+ - **Un historique partagé avec le terminal.**
19
+ Les conversations du navigateur sont les sessions Pi du projet : reprenez une session du terminal dans le navigateur, ou une session du navigateur avec `/resume`, et consultez les branches de Pi des deux côtés.
18
20
  - **Un lien pour tout.**
19
21
  L'interface Web (bureau et téléphone, anglais et chinois simplifié) accueille également les conversations Pi ordinaires et bascule entre les projets, chacun avec son propre owner et son historique.
20
22
 
package/README.ja.md CHANGED
@@ -20,6 +20,9 @@ Cadence は [Pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent)
20
20
  - **完全な履歴。**
21
21
  各実行はメッセージ、ツール呼び出し、出力を保持し、正確な検索と完全な Markdown/NDJSON エクスポートをサポートします。
22
22
  既知のシークレットはマスクされます。
23
+ - **ターミナルと共有される履歴。**
24
+ ブラウザーの会話はプロジェクトの Pi セッションそのものです。
25
+ ターミナルのセッションをブラウザーで続けることも、ブラウザーのセッションを `/resume` で続けることもでき、Pi のブランチはどちらからでも読めます。
23
26
  - **すべてに一つのリンク。**
24
27
  WebUI(デスクトップとスマホ、英語と簡体字中国語)は通常の Pi 会話もホストし、プロジェクト間で切り替えられます。
25
28
  各プロジェクトには独自の owner と履歴があります。
package/README.ko.md CHANGED
@@ -20,6 +20,9 @@ Cadence는 [Pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent)
20
20
  - **완전한 역사.**
21
21
  모든 실행은 메시지, 도구 호출, 출력을 보관하며, 정확한 검색과 완전한 Markdown/NDJSON 내보내기를 지원합니다.
22
22
  알려진 비밀은 마스킹됩니다.
23
+ - **터미널과 공유하는 기록.**
24
+ 브라우저 대화는 프로젝트의 Pi 세션 그 자체입니다.
25
+ 터미널 세션을 브라우저에서 이어 가거나 브라우저 세션을 `/resume`으로 이어 갈 수 있고, Pi의 분기는 양쪽에서 모두 볼 수 있습니다.
23
26
  - **모든 것을 위한 하나의 링크.**
24
27
  WebUI(데스크톱과 전화, 영어와 간체 중국어)는 일반 Pi 대화도 호스트하며 프로젝트 간 전환이 가능하고, 각 프로젝트는 자체 owner와 역사를 가집니다.
25
28
 
package/README.md CHANGED
@@ -18,6 +18,8 @@ The optional WebUI supports the same persistent conversation workflow without a
18
18
  Conversation workflows retain sanitized transcripts and actual process results; legacy task history also provides exact search and Markdown/NDJSON export.
19
19
  - **One link for everything.**
20
20
  The WebUI (desktop and phone, English and 简体中文) also hosts ordinary Pi conversations and switches between projects, each with its own owner and history.
21
+ - **One history with the terminal.**
22
+ Browser conversations are the project's Pi sessions: continue a terminal session in the browser or a browser one with `/resume`, and read Pi's branches in either place.
21
23
 
22
24
  Cadence is a trusted assistant, **not a sandbox**: its agents edit your working copy directly with host tools, so use it on code you can review and recover.
23
25
 
package/README.pt-BR.md CHANGED
@@ -15,6 +15,8 @@ Planeje uma tarefa de código, deixe os subagentes trabalharem nela, execute sua
15
15
  A saída dos subagentes, as execuções reais de verificação e a sua própria revisão permanecem separadas: a prosa do modelo ou um "Done" nunca contam como verificação aprovada, e resultados com falha, cancelados e desconhecidos permanecem distintos.
16
16
  - **Histórico completo.**
17
17
  Cada execução mantém suas mensagens, chamadas de ferramentas e saídas, com busca exata e exportação completa em Markdown/NDJSON; segredos conhecidos são redigidos.
18
+ - **Um histórico compartilhado com o terminal.**
19
+ As conversas do navegador são as sessões do Pi do projeto: continue uma sessão do terminal no navegador ou uma do navegador com `/resume`, e leia os ramos do Pi em qualquer um dos dois.
18
20
  - **Um link para tudo.**
19
21
  A interface web (desktop e celular, inglês e chinês simplificado) também hospeda conversas comuns do Pi e alterna entre projetos, cada um com seu próprio owner e histórico.
20
22
 
package/README.ru.md CHANGED
@@ -15,6 +15,8 @@ Cadence превращает [Pi](https://www.npmjs.com/package/@earendil-works/
15
15
  Вывод субагентов, фактические запуски проверок и ваш собственный обзор остаются разделёнными: текст модели или «Done» никогда не считаются пройденной проверкой, а неудачные, отменённые и неизвестные исходы остаются различимыми.
16
16
  - **Полная история.**
17
17
  Каждый запуск сохраняет свои сообщения, вызовы инструментов и выводы, с точным поиском и полным экспортом в Markdown/NDJSON; известные секреты скрываются.
18
+ - **Общая история с терминалом.**
19
+ Разговоры в браузере — это сеансы Pi проекта: продолжайте сеанс терминала в браузере или сеанс браузера через `/resume` и просматривайте ветви Pi в обоих местах.
18
20
  - **Одна ссылка на всё.**
19
21
  Веб-интерфейс (десктоп и телефон, английский и упрощённый китайский) также принимает обычные разговоры Pi и переключается между проектами, у каждого из которых свой owner и своя история.
20
22
 
package/README.zh-CN.md CHANGED
@@ -15,6 +15,8 @@ Cadence 把 [Pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent)
15
15
  子代理输出、真实的检查运行和你自己的审阅彼此独立:模型的文字或一句“Done”都不算检查通过,失败、取消和未知结果保持相互区分。
16
16
  - **完整历史。**
17
17
  新工作流保留脱敏后的子代理记录与实际进程结果;旧任务历史另支持精确搜索及 Markdown/NDJSON 导出。
18
+ - **与终端共用一份历史。**
19
+ 浏览器对话就是项目的 Pi 会话:可以在浏览器里继续终端会话,也可以用 `/resume` 在终端继续浏览器会话,两边都能查看 Pi 的分支。
18
20
  - **一个链接涵盖一切。**
19
21
  WebUI(桌面和手机,英文与简体中文)还承载普通的 Pi 对话,并可在项目间切换,每个项目都有自己的 owner 和历史。
20
22
 
@@ -23,6 +23,8 @@ Browser conversation mode is retained by the project owner, not by a browser-onl
23
23
  Ask for status, more detail, cancellation, or the next goal normally.
24
24
 
25
25
  Native mode is branch-aware; browser mode follows its server-owned conversation identity.
26
+ The browser and the terminal share the conversation itself (it is the same Pi session), but each keeps its own Cadence mode and plan approval: entering Cadence in one does not enter it in the other.
27
+ A workflow started in either place appears as a card in that conversation in the browser.
26
28
  A saved native mode is active only in a trusted interactive terminal; print/RPC sessions keep ordinary tools and can still exit with `/cadence exit`.
27
29
  In Pi, the agent panel lists workflow subagents and opens their transcripts; `cadence_status` can read one step's transcript.
28
30
  Resume and compaction retain the mode/context, not execution grants.
@@ -108,7 +110,7 @@ Research, implementation and review subagents are listed in the lower-left **Sub
108
110
  Active workflows are listed under **Running conversations** with **Cancel workflow — request stop**; this includes native-started workflows, and an unavailable observation is not proof of no work.
109
111
  The old task creation/Save/Start/check/human-Review controls are retired on both clients and refused by the service.
110
112
  Existing task records remain readonly; they are not converted into workflows.
111
- Existing browser conversations enter the new mode only on explicit Send/activation; old tasks and Pi transcripts are not converted or imported.
113
+ Existing browser conversations enter the new mode only on explicit Send/activation; old tasks are not converted into workflows.
112
114
  Approval grants are neither stored in the browser nor restored after restart.
113
115
  Losing a response only observes its original command/run identity; it never retries execution.
114
116
  Exit does not stop accepted work, and **Cancel workflow — request stop** remains independent of conversation mode.
package/docs/history.md CHANGED
@@ -7,13 +7,11 @@ History is evidence, not a second task manager or renewed execution consent.
7
7
 
8
8
  - In the conversation, open a workflow's steps to see actual checks, Agent review, delivery and failures.
9
9
  **Open subagent context** shows the retained transcript; **Read retained step result** reads the retained result rather than its clipped status preview.
10
- - In the browser sidebar, expand **Workflow history** to find retained runs, including completed native-started work.
11
- The listing is paged in ID order, not chronological order.
12
- Larger histories show scan progress before a complete page; use **Continue reading history** in the browser or **Continue scanning** in Pi.
13
- An expired scan requires a fresh observation; it never deletes history or resumes execution.
14
- A new run may appear before a page you already read; return to the first page and refresh to observe it.
15
- An unreadable record stays visibly unavailable rather than disappearing or being repaired.
10
+ - A workflow belongs to the conversation that started it, in the browser or in the terminal, and its card stays there.
11
+ An active workflow is also listed under **Running conversations** in the browser sidebar.
16
12
  - In a trusted Pi terminal, `/cadence-history` lists workflows without asking a model.
13
+ The listing is paged in ID order, not chronological order; larger histories show scan progress first, and **Continue scanning** resumes it.
14
+ An expired scan requires a fresh observation, and an unreadable record stays visibly unavailable; nothing is deleted, repaired or resumed.
17
15
  `/cadence-history <run-id>` opens one exact run directly.
18
16
  Use **Full result** or **Subagent transcript** for step evidence, and the arrow/page/Home/End keys to read long text.
19
17
 
@@ -23,6 +21,27 @@ If no owner is available, use the explicit service commands in [Service manageme
23
21
  Known omitted or truncated source content is still omitted or truncated; viewing a full retained result cannot recreate unrecorded data.
24
22
  Automatic Agent review is never human review, and a check's actual exit is independent of model prose.
25
23
 
24
+ ## Shared conversation history
25
+
26
+ Browser conversations are the project's Pi sessions, the same files `pi -r` and `/resume` list in the terminal.
27
+ The browser sidebar lists sessions started in either place, newest first, and labels where each one started.
28
+ A conversation can be continued from either side: open it in the browser, or run `/resume` (or `pi --session <id>`) in the terminal.
29
+ Only sessions started in the project's root folder are listed, and only those of the account the service runs as.
30
+
31
+ Pi keeps a session as a tree.
32
+ When a message continues an earlier point, the session gains a branch instead of losing anything:
33
+
34
+ - In the browser, **Continue from here** under an earlier reply shows the conversation up to that point; the next message starts a new branch there.
35
+ - **Branches** in the conversation header opens the tree of messages; choose a line to read that branch, and **Show the latest** to follow the newest again.
36
+ - In the terminal, `/tree` shows the same tree.
37
+
38
+ A terminal holds its own copy of an open session.
39
+ If the browser continues it meanwhile, the terminal says so; run `/resume` and choose the session again to see those messages.
40
+ A message sent in the terminal first starts a new branch from where the terminal is.
41
+
42
+ Sessions are stored as Pi writes them, including tool output; the browser redacts the service's credentials from what it shows.
43
+ Browser conversations from before 2.0.31 are added to the shared history only when you choose **Add them to the shared history** in the sidebar; the old records are kept.
44
+
26
45
  ## Existing task archives
27
46
 
28
47
  The old `/cadence-inspect` interface and browser **Legacy task** creation route are removed.
@@ -152,7 +152,7 @@ The background service reads two lines of the research configuration `~/.pi/agen
152
152
 
153
153
  ```sh
154
154
  CADENCE_PORT=17423
155
- CADENCE_TOKEN=<at least 32 characters, no control or format characters>
155
+ CADENCE_TOKEN=<any non-empty token up to 1024 bytes, no control or format characters>
156
156
  ```
157
157
 
158
158
  The file keeps the research skills' syntax (`KEY=value` lines, `#` comments, one optional pair of quotes), and each of these keys may appear only once.
@@ -160,7 +160,7 @@ The file keeps the research skills' syntax (`KEY=value` lines, `#` comments, one
160
160
  They append a missing `CADENCE_PORT` (17423) or `CADENCE_TOKEN` (random, 43 characters) under a comment, in the file's own line endings, and never change an existing line.
161
161
  It is your own file, made by hand, by older docs (`mkdir -p ~/.pi/agent/cadence`) or by a dotfiles manager, so it is read like Pi's sources: its mode bits are not checked (0644, or 0664 under umask 002, work), links in its path and the file itself are followed, and a rewrite goes to the real file, written 0600, leaving the links in place.
162
162
  When other users can read it, `install` and `restart` add a note naming `chmod 600`, without refusing.
163
- Only a file that cannot be the user's own configuration makes them change nothing: missing or a link to nothing, not a regular file, not owned by you or in a directory you do not own, hard-linked, over 64 KiB or not UTF-8, a line the research skills would also refuse, a duplicate key, a port outside 1-65535 or a short token.
163
+ Only a file that cannot be the user's own configuration makes them change nothing: missing or a link to nothing, not a regular file, not owned by you or in a directory you do not own, hard-linked, over 64 KiB or not UTF-8, a line the research skills would also refuse, a duplicate key, a port outside 1-65535 or an empty token.
164
164
  Each refusal names its reason and line number, never a byte of the file.
165
165
  A project's `.pi/cadence/.env`, which the research skills prefer, is never read for the service.
166
166
  `start --server-config <.env>` makes these lines authoritative.
@@ -168,6 +168,7 @@ The host reads them once before binding, like an environment token, so editing t
168
168
  A workspace whose token comes from the file follows it at every `start`, also without `--server-config`; a contradicting `--port`, `--token-file` or `CADENCE_WEB_TOKEN` refuses.
169
169
  `CADENCE_WEB_TOKEN` stays the separate process-environment source; sourcing the `.env` in a shell sets `CADENCE_PORT` and `CADENCE_TOKEN`, which Cadence never reads from its environment.
170
170
  The token never enters Cadence's state home, and status and diagnosis never print it.
171
+ It has no minimum length, but the owner redacts its exact text from conversations, plans and checks, so a short or common word also hides every matching word there; a generated token is 43 random characters.
171
172
  `token-rotate` replaces only the `CADENCE_TOKEN` line's value with a new random token, keeping every other byte, and invalidates old links and cookies without stopping work.
172
173
  It refuses without any effect when that token was edited since the start, so a pending edit is never overwritten.
173
174
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.0.29",
3
+ "version": "2.0.31",
4
4
  "description": "Conversation-driven Pi workspace: persistent native and WebUI workflows, explicit plan approval, checks and local delivery.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -68,7 +68,8 @@
68
68
  "LICENSE",
69
69
  "THIRD_PARTY_NOTICES.md",
70
70
  "licenses",
71
- "src/conversation-context.mjs",
71
+ "src/session-entries.mjs",
72
+ "src/session-sharing.ts",
72
73
  "src/conversation-resources.mjs",
73
74
  "src/service/contracts/workbench.ts",
74
75
  "src/cadence-mode.ts",
@@ -43,10 +43,12 @@ import {
43
43
  type PublicError,
44
44
  type Reply,
45
45
  } from "./service-contract.ts";
46
+ import { CADENCE_MODE_ENTRY } from "./session-entries.mjs";
46
47
  import { diagnosticText } from "./verification-diagnostics.ts";
47
48
  import { effectiveWorkspace } from "./workspace.ts";
48
49
 
49
- export const CADENCE_MODE_ENTRY = "cadence-conversation-mode/1";
50
+ export { CADENCE_MODE_ENTRY };
51
+
50
52
  const CONTEXT = "cadence-mode-context";
51
53
  const READY = "cadence-mode-ready";
52
54
  const TOOLS = [
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ import { registerCadenceAgentFeed } from "./agent-panel-cadence.ts";
5
5
  import { registerCadenceMode } from "./cadence-mode.ts";
6
6
  import { registerHistoryShell } from "./history-shell.ts";
7
7
  import { autostartNotice } from "./native-client.ts";
8
+ import { registerSessionSharing } from "./session-sharing.ts";
8
9
  import { CONFIG_MISSING, startupCardLines } from "./startup-card.ts";
9
10
 
10
11
  /** Sole production composition. Discovery registers inert capabilities only;
@@ -13,6 +14,8 @@ export default function register(pi: ExtensionAPI): void {
13
14
  if (process.env.CADENCE_SUBAGENT_CHILD === "1") return;
14
15
  registerHistoryShell(pi);
15
16
  registerCadenceMode(pi);
17
+ // Readonly: notices the browser continuing the session this terminal holds.
18
+ registerSessionSharing(pi);
16
19
  // Observes `subagent:*` bus events only; renders nothing until one arrives.
17
20
  registerAgentPanel(pi);
18
21
  // Publishes a running owner's child runs there; readonly, never starts one.
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65",
5
+ "3305384b10bb0c658565426ec2291d0237533cb9ae7aeb1d63f42ac8824b0c82",
6
6
  } as const;
@@ -1,7 +1,15 @@
1
1
  // Isolated SDK child, not Pi CLI startup. Task discovery stays disabled;
2
2
  // ordinary conversations explicitly load only context/skills, never extensions.
3
3
  import { createHash } from "node:crypto";
4
- import { readFileSync, writeFileSync } from "node:fs";
4
+ import {
5
+ closeSync,
6
+ constants,
7
+ fstatSync,
8
+ openSync,
9
+ readFileSync,
10
+ readSync,
11
+ writeSync,
12
+ } from "node:fs";
5
13
  import {
6
14
  createProvider,
7
15
  InMemoryCredentialStore,
@@ -16,13 +24,10 @@ import {
16
24
  SettingsManager,
17
25
  VERSION,
18
26
  } from "@earendil-works/pi-coding-agent";
19
- import {
20
- conversationContextRecords,
21
- iterateConversationContext,
22
- } from "./conversation-context.mjs";
23
27
  import { conversationResources } from "./conversation-resources.mjs";
24
28
  import { coordinatorTools } from "./coordinator-tools.mjs";
25
29
  import { researchClock, researchTools } from "./research-tools.mjs";
30
+ import { WEBUI_SESSION_ENTRY } from "./session-entries.mjs";
26
31
  import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
27
32
  import {
28
33
  closed,
@@ -125,6 +130,54 @@ const abortForFailure = () => {
125
130
  }
126
131
  })();
127
132
  };
133
+ /** A torn final line (a writer killed mid-line) would swallow the next entry. */
134
+ const terminateLastLine = (file) => {
135
+ const fd = openSync(
136
+ file,
137
+ constants.O_RDWR | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0),
138
+ );
139
+ try {
140
+ const size = fstatSync(fd).size;
141
+ const last = Buffer.alloc(1);
142
+ if (size > 0 && readSync(fd, last, 0, 1, size - 1) === 1 && last[0] !== 10)
143
+ writeSync(fd, "\n");
144
+ } finally {
145
+ closeSync(fd);
146
+ }
147
+ };
148
+ /** The project's Pi session a browser turn writes, as the terminal shares it:
149
+ * continued from the entry the browser showed, so a session that moved on
150
+ * meanwhile gains a branch. Pi records the model and thinking level only when
151
+ * a session starts; a continued one records a change so a resume keeps it. */
152
+ const openConversation = (target, cwd, model, thinkingLevel) => {
153
+ let manager;
154
+ if (target.file === null) {
155
+ manager = SessionManager.create(cwd, target.dir, { id: target.id });
156
+ manager.appendCustomEntry(WEBUI_SESSION_ENTRY, {});
157
+ } else {
158
+ terminateLastLine(target.file);
159
+ manager = SessionManager.open(target.file, target.dir, cwd);
160
+ if (manager.getSessionId() !== target.id)
161
+ refuse("session", "session-mismatch");
162
+ if (target.head === null) manager.resetLeaf();
163
+ else if (!manager.getEntry(target.head)) refuse("session", "stale-head");
164
+ else manager.branch(target.head);
165
+ }
166
+ const context = manager.buildSessionContext();
167
+ if (context.messages.length) {
168
+ if (
169
+ context.model?.provider !== model.provider ||
170
+ context.model?.modelId !== model.id
171
+ )
172
+ manager.appendModelChange(model.provider, model.id);
173
+ if (
174
+ context.thinkingLevel !== thinkingLevel &&
175
+ manager.getBranch().some((e) => e.type === "thinking_level_change")
176
+ )
177
+ manager.appendThinkingLevelChange(thinkingLevel);
178
+ }
179
+ return manager;
180
+ };
128
181
  const emitFailure = () => {
129
182
  // Construct from fixed labels/primitives only; never inspect exception text,
130
183
  // provider diagnostics, response headers, payloads, usage or tool contents.
@@ -213,17 +266,31 @@ try {
213
266
  envelope.conversation === undefined
214
267
  ? null
215
268
  : closed(envelope.conversation, [
216
- "previous",
269
+ "session",
217
270
  "agentDir",
218
271
  ...(Object.hasOwn(envelope.conversation, "coordinator")
219
272
  ? ["coordinator"]
220
273
  : []),
221
274
  ]);
275
+ const target = conversation
276
+ ? closed(conversation.session, ["id", "dir", "file", "head"])
277
+ : null;
278
+ // Stop and timeout signal the process group. A browser turn aborts its Pi
279
+ // session first, so the session records the interrupted reply as Pi does.
280
+ if (conversation)
281
+ process.once("SIGTERM", () => {
282
+ if (!session) process.exit(143);
283
+ abortForFailure();
284
+ });
222
285
  if (
223
286
  conversation &&
224
- ((conversation.previous !== null &&
225
- typeof conversation.previous !== "string") ||
226
- typeof conversation.agentDir !== "string")
287
+ (typeof conversation.agentDir !== "string" ||
288
+ typeof target.id !== "string" ||
289
+ !target.id ||
290
+ typeof target.dir !== "string" ||
291
+ !target.dir ||
292
+ !(target.file === null || typeof target.file === "string") ||
293
+ !(target.head === null || typeof target.head === "string"))
227
294
  )
228
295
  refuse("parse", "invalid-conversation");
229
296
  const investigation =
@@ -388,10 +455,9 @@ try {
388
455
  process.stdout.on("error", stdoutFailureListener);
389
456
  stage = "session";
390
457
  const requestedThinkingLevel = thinkingLevel ?? "off";
391
- const manager = SessionManager.inMemory(cwd);
392
- if (conversation)
393
- for (const message of iterateConversationContext(conversation.previous))
394
- manager.appendMessage(message);
458
+ const manager = conversation
459
+ ? openConversation(target, cwd, model, requestedThinkingLevel)
460
+ : SessionManager.inMemory(cwd);
395
461
  const coordinationTools = coordinator ? coordinatorTools() : undefined;
396
462
  ownsCoordinatorChannel = coordinator;
397
463
  const created = await createAgentSession({
@@ -579,13 +645,6 @@ try {
579
645
  stage = "assistant-final";
580
646
  if (failure || terminalStopReason !== "stop" || ingress.frames !== 0)
581
647
  refuse("assistant-final", "terminal-incomplete");
582
- // Anonymous pipe only. The owner applies its access-secret sanitizer before
583
- // any checkpoint reaches disk; worker output cannot contain owner credentials.
584
- if (conversation) {
585
- stage = "conversation-context";
586
- for (const record of conversationContextRecords(session.messages, secrets))
587
- writeFileSync(3, record);
588
- }
589
648
  await capture.final();
590
649
  await emitter.drain();
591
650
  } catch {