@abelxiaoxing/cadence 2.0.28 → 2.0.30

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
@@ -88,11 +88,12 @@ Ihre tatsächlichen Ergebnisse bleiben von der automatischen Agent-Prüfung getr
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # nach einem Upgrade oder einer .env / models.json-Änderung
91
+ cadence server upgrade # npm-Globalinstallation: laden, installieren, neu starten
91
92
  cadence server stop # bleibt registriert und startet beim nächsten Boot oder Login erneut
92
93
  cadence server uninstall # vor npm uninstall -g ausführen
93
94
  ```
94
95
 
95
- Upgrade mit `npm install -g @abelxiaoxing/cadence@latest`, dann `cadence server restart`.
96
+ Upgrade mit `cadence server upgrade` oder im Cadence-Dienstdialog der WebUI: Die Version wird geladen, während Cadence weiterläuft, und die vorherige Version kommt zurück, wenn die neue nicht startet.
96
97
  Restart, Stop und Uninstall stoppen laufende Arbeit geordnet, statt sie getrennt zurückzulassen.
97
98
  Uninstall entfernt nur die Dienstdefinition; Projekte, Historie und Pi-Einstellungen bleiben.
98
99
  Linux-Root- und benannte Dienste, entfernter HTTPS-Zugang und Wiederherstellung sind in [Dienstverwaltung](docs/service-management.md) und [Fernzugriff](docs/remote-access.md) beschrieben.
package/README.es.md CHANGED
@@ -88,11 +88,12 @@ Sus resultados reales se mantienen separados de la revisión automática del age
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # después de una actualización o un cambio de .env / models.json
91
+ cadence server upgrade # instalación global de npm: descargar, instalar y reiniciar
91
92
  cadence server stop # permanece registrado y vuelve a iniciar en el próximo arranque o inicio de sesión
92
93
  cadence server uninstall # ejecutar antes de npm uninstall -g
93
94
  ```
94
95
 
95
- Actualiza con `npm install -g @abelxiaoxing/cadence@latest`, luego `cadence server restart`.
96
+ Actualiza con `cadence server upgrade` o desde el diálogo del servicio Cadence de la WebUI: descarga la versión mientras Cadence sigue en marcha y restaura la anterior si la nueva no arranca.
96
97
  Restart, stop y uninstall detienen el trabajo en ejecución en orden en lugar de dejarlo desconectado.
97
98
  Uninstall solo elimina la definición del servicio; los proyectos, el historial y la configuración de Pi permanecen.
98
99
  Los servicios raíz de Linux y con nombre, el acceso HTTPS remoto y la recuperación se cubren en [gestión del servicio](docs/service-management.md) y [acceso remoto](docs/remote-access.md).
package/README.fr.md CHANGED
@@ -88,11 +88,12 @@ Leurs résultats restent distincts de la revue automatique par un Agent.
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # après une mise à niveau ou un changement de .env / models.json
91
+ cadence server upgrade # installation npm globale : télécharger, installer, redémarrer
91
92
  cadence server stop # reste enregistré et redémarre au prochain boot ou connexion
92
93
  cadence server uninstall # à exécuter avant npm uninstall -g
93
94
  ```
94
95
 
95
- Mettez à niveau avec `npm install -g @abelxiaoxing/cadence@latest`, puis `cadence server restart`.
96
+ Mettez à niveau avec `cadence server upgrade` ou depuis la boîte de dialogue du service Cadence de la WebUI : la version est téléchargée pendant que Cadence continue de tourner, et la précédente est réinstallée si la nouvelle ne démarre pas.
96
97
  Restart, stop et uninstall arrêtent le travail en cours dans l'ordre au lieu de le laisser déconnecté.
97
98
  Uninstall supprime uniquement la définition du service ; les projets, l'historique et les réglages de Pi restent.
98
99
  Les services racine Linux et nommés, l'accès HTTPS distant et la récupération sont couverts par [gestion du service](docs/service-management.md) et [accès distant](docs/remote-access.md).
package/README.ja.md CHANGED
@@ -102,11 +102,13 @@ WebUI のフォルダピッカーも同じ方法でプロジェクトを開く
102
102
  ```sh
103
103
  cadence server status
104
104
  cadence server restart # アップグレードや .env / models.json の変更後
105
+ cadence server upgrade # npm グローバルインストール: 取得、インストール、再起動
105
106
  cadence server stop # 登録は保持され、次の起動またはログイン時に再び起動する
106
107
  cadence server uninstall # npm uninstall -g の前に実行
107
108
  ```
108
109
 
109
- `npm install -g @abelxiaoxing/cadence@latest` でアップグレードし、次に `cadence server restart`。
110
+ `cadence server upgrade` または WebUI の Cadence サービスダイアログでアップグレードします。
111
+ Cadence の実行中に新しいバージョンを取得し、新しいバージョンが起動しない場合は以前のバージョンに戻します。
110
112
  restart、stop、uninstall はデタッチしたままにせずに、実行中の作業を順番に停止する。
111
113
  uninstall はサービス定義のみを削除する。
112
114
  プロジェクト、履歴、Pi の設定は残る。
package/README.ko.md CHANGED
@@ -99,11 +99,15 @@ WebUI 폴더 선택기도 같은 방법으로 프로젝트를 엽니다.
99
99
  ```sh
100
100
  cadence server status
101
101
  cadence server restart # 업그레이드나 .env / models.json 변경 후
102
+ cadence server upgrade # npm 전역 설치: 받기, 설치, 재시작
102
103
  cadence server stop # 등록은 유지되고 다음 부팅 또는 로그인 시 다시 시작
103
104
  cadence server uninstall # npm uninstall -g 전에 실행
104
105
  ```
105
106
 
106
- `npm install -g @abelxiaoxing/cadence@latest`로 업그레이드하고, 그 후 `cadence server restart`. restart, stop, uninstall는 작업이 연결 끊긴 채로 남지 않도록 실행 중인 작업을 순서대로 멈춥니다. uninstall은 서비스 정의만 제거합니다.
107
+ `cadence server upgrade` 또는 WebUI의 Cadence 서비스 대화 상자로 업그레이드합니다.
108
+ Cadence가 실행 중일 때 새 버전을 받아 두고, 새 버전이 시작되지 않으면 이전 버전으로 되돌립니다.
109
+ Restart, stop, uninstall는 작업이 연결 끊긴 채로 남지 않도록 실행 중인 작업을 순서대로 멈춥니다.
110
+ Uninstall은 서비스 정의만 제거합니다.
107
111
  프로젝트, 역사, Pi 설정은 유지됩니다.
108
112
  Linux 루트 및 이름 지정 서비스, 원격 HTTPS 액세스, 복구에는 [서비스 관리](docs/service-management.md)와 [원격 액세스](docs/remote-access.md)를 참조하세요.
109
113
 
package/README.md CHANGED
@@ -87,6 +87,7 @@ Their actual outcomes remain separate from automatic Agent review.
87
87
  ```sh
88
88
  cadence server status
89
89
  cadence server restart # after an upgrade or a .env / models.json change
90
+ cadence server upgrade # npm global install: fetch, install and restart
90
91
  cadence server stop # stays registered and starts again at the next boot or login
91
92
  cadence server uninstall # run before npm uninstall -g
92
93
  cadence doctor # what is left over or recently recovered; --fix for the rest
@@ -94,7 +95,7 @@ cadence doctor # what is left over or recently recovered; --fix for
94
95
 
95
96
  A power loss, shutdown or crash needs no cleanup: the next start recovers automatically, marks interrupted work as interrupted and says what it did.
96
97
 
97
- Upgrade with `npm install -g @abelxiaoxing/cadence@latest`, then `cadence server restart`.
98
+ Upgrade with `cadence server upgrade` or from the WebUI's Cadence service dialog: it fetches the release while Cadence keeps running and puts the previous version back if the new one does not start.
98
99
  Restart, stop and uninstall stop running work in order rather than leaving it detached.
99
100
  Uninstall removes only the service definition; projects, history and Pi settings stay.
100
101
  Linux root and named services, remote HTTPS access and automatic recovery are covered in [service management](docs/service-management.md) and [remote access](docs/remote-access.md).
package/README.pt-BR.md CHANGED
@@ -88,11 +88,12 @@ Os resultados reais permanecem separados da revisão automática do agente.
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # após um upgrade ou uma alteração de .env / models.json
91
+ cadence server upgrade # instalação global do npm: baixar, instalar e reiniciar
91
92
  cadence server stop # permanece registrado e inicia de novo no próximo boot ou login
92
93
  cadence server uninstall # executar antes de npm uninstall -g
93
94
  ```
94
95
 
95
- Faça upgrade com `npm install -g @abelxiaoxing/cadence@latest`, depois `cadence server restart`.
96
+ Faça upgrade com `cadence server upgrade` ou pela caixa de diálogo do serviço Cadence na WebUI: a versão é baixada enquanto o Cadence continua em execução, e a anterior volta se a nova não iniciar.
96
97
  Restart, stop e uninstall param o trabalho em execução em ordem, em vez de deixá-lo desconectado.
97
98
  Uninstall remove apenas a definição do serviço; projetos, histórico e configurações do Pi permanecem.
98
99
  Serviços root e nomeados do Linux, acesso HTTPS remoto e recuperação estão cobertos em [gerenciamento do serviço](docs/service-management.md) e [acesso remoto](docs/remote-access.md).
package/README.ru.md CHANGED
@@ -88,11 +88,12 @@ cadence project open /absolute/new-project --create
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # после обновления или изменения .env / models.json
91
+ cadence server upgrade # глобальная установка npm: загрузить, установить, перезапустить
91
92
  cadence server stop # остаётся зарегистрированной и снова запускается при следующей загрузке или входе
92
93
  cadence server uninstall # выполнить перед npm uninstall -g
93
94
  ```
94
95
 
95
- Обновляйте с помощью `npm install -g @abelxiaoxing/cadence@latest`, затем `cadence server restart`.
96
+ Обновляйте с помощью `cadence server upgrade` или в диалоге службы Cadence в WebUI: новая версия загружается, пока Cadence продолжает работать, а если она не запускается, возвращается предыдущая.
96
97
  Restart, stop и uninstall останавливают выполняемую работу по порядку, а не оставляют её отключённой.
97
98
  Uninstall удаляет только определение службы; проекты, история и настройки Pi остаются.
98
99
  Корневые и именованные службы Linux, удалённый HTTPS-доступ и восстановление описаны в [управлении службой](docs/service-management.md) и [удалённом доступе](docs/remote-access.md).
package/README.zh-CN.md CHANGED
@@ -88,11 +88,12 @@ cadence project open /absolute/new-project --create
88
88
  ```sh
89
89
  cadence server status
90
90
  cadence server restart # 升级或修改 .env / models.json 之后
91
+ cadence server upgrade # npm 全局安装:下载、安装并重启
91
92
  cadence server stop # 保持注册状态,并在下次启动或登录时再次启动
92
93
  cadence server uninstall # 在 npm uninstall -g 之前运行
93
94
  ```
94
95
 
95
- 用 `npm install -g @abelxiaoxing/cadence@latest` 升级,然后 `cadence server restart`。
96
+ 用 `cadence server upgrade` 或 WebUI 的 Cadence 服务对话框升级:它在 Cadence 继续运行时先下载新版本,新版本无法启动时会装回原版本。
96
97
  restart、stop 和 uninstall 按顺序停止运行中的工作,而不是留下断开连接的工作。
97
98
  uninstall 只删除服务定义;项目、历史和 Pi 设置保留。
98
99
  Linux root 与命名服务、远程 HTTPS 访问和恢复见[服务管理](docs/service-management.md)和[远程访问](docs/remote-access.md)。
@@ -74,11 +74,12 @@ Changing to root changes the effective account and its private namespace: stop a
74
74
  cadence server install [--workspace /absolute/project] [--system|--user] [--no-linger]
75
75
  cadence server status
76
76
  cadence server restart
77
+ cadence server upgrade [--to VERSION]
77
78
  cadence server stop
78
79
  cadence server uninstall
79
80
  ```
80
81
 
81
- Only these explicit commands register, change or remove the service; no package install, update hook, `/cadence` or browser visit does.
82
+ Only these explicit commands and the WebUI's confirmed [restart and upgrade](#restart-and-upgrade-from-the-webui) register, change or remove the service; no package install, update hook, `/cadence` or browser visit does.
82
83
  The package has no install script, so npm 12 and Bun skipping untrusted scripts by default changes nothing; the pinned Pi SDK's blocked `@google/genai` preinstall only echoes `no-op`, and its `protobufjs` postinstall only warns about version schemes.
83
84
  Linux server commands accept `--system` or `--user` after the action; root defaults to system scope and other accounts to user scope.
84
85
  `--system` requires root and never runs sudo itself; `--user` explicitly selects the legacy per-user manager, even when invoked by root.
@@ -97,6 +98,9 @@ A successful manager start request is not owner readiness: an unready owner repo
97
98
  Status also retains the manager's `active`/`activating`/`failed` observation separately.
98
99
  A definition whose project directory was removed gets a readable refusal (exit78, so the unit does not restart in a loop); `cadence server install` switches it to the workbench.
99
100
  `restart` rewrites an existing definition with the current Node and package paths, keeping its workspace and the user's disable choices, and starts it; run it after an npm upgrade, a Node change or a `models.json` edit.
101
+ The `upgrade` command (Linux) installs the latest version, or exactly `--to VERSION`, with npm and restarts; see [Restart and upgrade from the WebUI](#restart-and-upgrade-from-the-webui) for its steps.
102
+ Commands that change the service (`install`, `restart`, `stop`, `uninstall`, `upgrade`) refuse with `inside-service` when they run inside the service they would stop, for example from a tool of its own agent: stopping a systemd unit ends every process in it, so the command would die before it started the service again.
103
+ Use the WebUI or a terminal outside the service instead.
100
104
  `stop` joins the workbench's accepted openings and associated exact-epoch project owners, then closes the entry; unrelated project owners stay independent.
101
105
  An associated owner that is not running (or whose directory is gone) has nothing to stop; one whose Stop is unconfirmed keeps its own state, and the workbench still stops.
102
106
  Project-specific `stop --workspace <path>` remains scoped to that owner.
@@ -116,6 +120,24 @@ It is a warning rather than part of the info card because Pi's TUI replaces one
116
120
  The readonly `/cadence-history` client names the same management command when no owner exists; daily `/cadence` instead uses explicit on-demand project startup, without requiring a boot service.
117
121
  A machine without a supported user service manager and `CADENCE_AUTOSTART=0` keep both quiet; with `CADENCE_LINGER=0` they suggest `--no-linger`.
118
122
 
123
+ ### Restart and upgrade from the WebUI
124
+
125
+ On Linux the workbench has a **Cadence service** dialog: the server button on the entry page, or **More → Cadence service** in a project.
126
+ It shows the running version and its systemd unit, asks npm for the latest version only when you press **Check for updates**, and offers **Restart service** and **Upgrade to VERSION**.
127
+ The confirmation names the running workflows and conversations the restart stops; they stop through the orderly Stop, never by a signal.
128
+ If work starts or ends before you confirm, the request is refused as stale and the dialog reads the service again.
129
+
130
+ The request runs outside the service, in a transient unit `cadence.maintenance.service` (`cadence-NAME.maintenance.service` for a named service), so closing or reloading the page does not interrupt it and one job runs at a time.
131
+ It runs the same `cadence server restart` or `cadence server upgrade`, then records its outcome; the page waits for that record and offers to reload.
132
+ If it reports nothing, see `journalctl --user -u cadence.maintenance.service` (without `--user` for a system service) and `cadence server status`.
133
+
134
+ An upgrade fetches the exact release while the service still runs, so an unreachable registry changes nothing.
135
+ Then it stops the service, installs the release with `npm install --global` and starts the new copy's own `server restart`.
136
+ A new version that does not become ready is replaced by the previous version again from npm's cache.
137
+ The npm calls use npm's own configuration (`~/.npmrc` registry, proxy and prefix).
138
+ Only a copy that `npm root --global` names, and that the service account can write, upgrades itself; the dialog says when another installation (Pi's own copy, a checkout, Bun, a root-owned prefix) has to be upgraded the way it was installed, followed by `cadence server restart`.
139
+ A workbench that was not started by its systemd service, and services on macOS and Windows, show the version only; restart and upgrade them in a terminal.
140
+
119
141
  ### One copy for Pi and the service
120
142
 
121
143
  After `npm install -g`, `pi install "$(npm root -g)/@abelxiaoxing/cadence"` records that path and loads it in place, so an npm upgrade updates the service and native `/cadence` together.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.0.28",
3
+ "version": "2.0.30",
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",
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "45f3666b0fc0d853e95e618b50156819f6282ce648e9703b876d9658ae15b78f",
5
+ "d0edc9d93f682dd7c637bd28cdb756b823ad8eafeabebc63479bee1bac5b2b55",
6
6
  } as const;
@@ -72,16 +72,24 @@ export type WorkbenchRead =
72
72
  | { kind: "workflow-detail"; id: string; stepId: string }
73
73
  | { kind: "workflow-transcript"; id: string; stepId: string }
74
74
  | { kind: "workflow"; id: string }
75
+ | { kind: "conversation-active" }
76
+ | { kind: "conversations"; after?: ChatCursor | null; scan?: string }
77
+ | { kind: "task-origin"; taskId: string }
78
+ | { kind: "conversation"; id: string }
79
+ | {
80
+ kind: "conversation-turn";
81
+ id: string;
82
+ ordinal: number;
83
+ /** Exclusive end of the steps to list; null lists the latest ones. */
84
+ before: number | null;
85
+ }
75
86
  | {
76
- kind: "conversation-transcript";
87
+ kind: "conversation-step";
77
88
  id: string;
78
89
  turnId: string;
79
- page: number;
90
+ step: number;
91
+ part: number;
80
92
  }
81
- | { kind: "conversation-active" }
82
- | { kind: "conversations"; after?: ChatCursor | null; scan?: string }
83
- | { kind: "task-origin"; taskId: string }
84
- | { kind: "conversation"; id: string; before: string | null }
85
93
  | { kind: "files"; path: string }
86
94
  | { kind: "file"; path: string }
87
95
  | { kind: "directories"; path: string }
@@ -173,6 +181,93 @@ export interface ChatTurn {
173
181
  * `other` is a block of a type Cadence does not recognize. */
174
182
  omitted: { thinking: boolean; media: boolean; other: boolean };
175
183
  }
184
+ /** One recorded item of a turn as listed. A listing never carries a tool's
185
+ * arguments or output and keeps at most `STEP_TEXT_BYTES` of message text;
186
+ * the full item is read per step with `conversation-step`, one part at a time. */
187
+ export interface ChatStep {
188
+ id: string;
189
+ role: ChatItem["role"];
190
+ /** User or assistant text, a prefix of it when `clipped`; empty for tools. */
191
+ text: string;
192
+ clipped: boolean;
193
+ name: string;
194
+ /** What a tool acted on: a command's first line, else its pattern and path. */
195
+ target: string;
196
+ error: boolean;
197
+ /** Stored parts that hold the full item; 0 when nothing more is recorded. */
198
+ parts: number;
199
+ }
200
+ export interface ChatTurnHeader {
201
+ id: string;
202
+ epoch: string;
203
+ status: ChatStatus;
204
+ notice: string;
205
+ omitted: ChatTurn["omitted"];
206
+ steps: number;
207
+ /** Leading steps that can no longer change: all of them once settled. */
208
+ stable: number;
209
+ }
210
+ /** Encoded bytes of message text a listed step keeps. */
211
+ export const STEP_TEXT_BYTES = 16 * 1024;
212
+ const TARGET_BYTES = 1024;
213
+ /** Steps one `conversation-turn` read lists: as many as always fit its reply
214
+ * (512 KiB) at the encoded worst case of every field. */
215
+ export const STEP_READ = 24;
216
+ /** A string's prefix whose JSON encoding fits `bytes`, ending on a whole code point. */
217
+ export function clipText(value: string, bytes: number): string {
218
+ const size = (s: string) =>
219
+ new TextEncoder().encode(JSON.stringify(s)).length;
220
+ if (size(value) <= bytes) return value;
221
+ let low = 0,
222
+ high = Math.min(value.length, bytes);
223
+ while (low < high) {
224
+ const mid = Math.ceil((low + high) / 2);
225
+ if (size(value.slice(0, mid)) <= bytes) low = mid;
226
+ else high = mid - 1;
227
+ }
228
+ return /[\uD800-\uDBFF]/u.test(value.slice(low - 1, low))
229
+ ? value.slice(0, low - 1)
230
+ : value.slice(0, low);
231
+ }
232
+ /** What a tool acted on, from its recorded arguments: a command's first line,
233
+ * else a pattern and path. Partial or unparsable arguments name nothing. */
234
+ export function toolTarget(args: string): string {
235
+ let value: unknown;
236
+ try {
237
+ value = JSON.parse(args);
238
+ } catch {
239
+ return "";
240
+ }
241
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "";
242
+ const field = (name: string) => {
243
+ const v = Object.hasOwn(value, name)
244
+ ? (value as Record<string, unknown>)[name]
245
+ : undefined;
246
+ return typeof v === "string" ? v.trim() : "";
247
+ };
248
+ const command = field("command");
249
+ if (command) return command.split("\n", 1)[0];
250
+ return [field("pattern"), field("path")].filter(Boolean).join(" ");
251
+ }
252
+ /** The listed form of an item; `more` says its text continues beyond `item.text`. */
253
+ export function chatStep(
254
+ item: ChatItem,
255
+ parts: number,
256
+ more = false,
257
+ ): ChatStep {
258
+ const tool = item.role === "tool";
259
+ const text = tool ? "" : clipText(item.text, STEP_TEXT_BYTES);
260
+ return {
261
+ id: item.id,
262
+ role: item.role,
263
+ text,
264
+ clipped: !tool && (more || text !== item.text),
265
+ name: item.name,
266
+ target: tool ? clipText(toolTarget(item.args), TARGET_BYTES) : "",
267
+ error: item.error,
268
+ parts,
269
+ };
270
+ }
176
271
  export interface ChatCursor {
177
272
  id: string;
178
273
  updatedAt: number;
@@ -195,12 +290,6 @@ export interface FileEntry {
195
290
  directory: boolean;
196
291
  }
197
292
  export type WorkbenchResult =
198
- | {
199
- kind: "conversation-transcript";
200
- conversationId: string;
201
- page: number;
202
- turn: ChatTurn;
203
- }
204
293
  | { kind: "workflow-history-progress"; after: string | null; scan: string }
205
294
  | {
206
295
  kind: "workflow-history";
@@ -233,11 +322,23 @@ export type WorkbenchResult =
233
322
  | { kind: "conversation-active"; entries: ChatSummary[] }
234
323
  | { kind: "conversations-progress"; after: ChatCursor | null; scan: string }
235
324
  | { kind: "conversations"; entries: ChatSummary[]; next?: ChatCursor | null }
325
+ | { kind: "conversation"; summary: ChatSummary | null; turns: number }
236
326
  | {
237
- kind: "conversation";
238
- summary: ChatSummary | null;
239
- turns: ChatTurn[];
240
- before: string | null;
327
+ kind: "conversation-turn";
328
+ conversationId: string;
329
+ ordinal: number;
330
+ turn: ChatTurnHeader;
331
+ /** Index of the first listed step. */
332
+ start: number;
333
+ steps: ChatStep[];
334
+ }
335
+ | {
336
+ kind: "conversation-step";
337
+ conversationId: string;
338
+ turnId: string;
339
+ step: number;
340
+ part: number;
341
+ item: ChatItem;
241
342
  }
242
343
  | {
243
344
  kind: "files" | "directories";
@@ -273,13 +374,23 @@ const statuses = [
273
374
  export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
274
375
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
275
376
  switch (kind) {
276
- case "conversation-transcript": {
277
- const o = closed(v, ["kind", "id", "turnId", "page"]);
377
+ case "conversation-turn": {
378
+ const o = closed(v, ["kind", "id", "ordinal", "before"]);
379
+ return {
380
+ kind,
381
+ id: decodeId(o.id),
382
+ ordinal: integer(o.ordinal, 0),
383
+ before: nullable(o.before, (b) => integer(b, 0)),
384
+ };
385
+ }
386
+ case "conversation-step": {
387
+ const o = closed(v, ["kind", "id", "turnId", "step", "part"]);
278
388
  return {
279
389
  kind,
280
390
  id: decodeId(o.id),
281
391
  turnId: decodeId(o.turnId),
282
- page: integer(o.page, 0),
392
+ step: integer(o.step, 0),
393
+ part: integer(o.part, 0),
283
394
  };
284
395
  }
285
396
  case "cadence-conversation": {
@@ -330,8 +441,8 @@ export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
330
441
  return { kind, taskId: decodeId(o.taskId) };
331
442
  }
332
443
  case "conversation": {
333
- const o = closed(v, ["kind", "id", "before"]);
334
- return { kind, id: decodeId(o.id), before: nullable(o.before, decodeId) };
444
+ const o = closed(v, ["kind", "id"]);
445
+ return { kind, id: decodeId(o.id) };
335
446
  }
336
447
  default: {
337
448
  const o = closed(v, ["kind", "path"]);
@@ -496,17 +607,69 @@ export function decodeChatTurn(v: unknown): ChatTurn {
496
607
  media: omitted ? bool(omitted.media) : false,
497
608
  other: omitted ? bool(omitted.other) : false,
498
609
  },
499
- items: list(o.items, 256, (v) => {
500
- const i = closed(v, ["id", "role", "text", "name", "args", "error"]);
501
- return {
502
- id: text(i.id, 160, true),
503
- role: oneOf(i.role, ["user", "assistant", "tool"]),
504
- text: text(i.text, 256 * 1024),
505
- name: text(i.name, 128),
506
- args: text(i.args, 64 * 1024),
507
- error: bool(i.error),
508
- };
509
- }),
610
+ items: list(o.items, 256, decodeChatItem),
611
+ };
612
+ }
613
+ export function decodeChatItem(v: unknown): ChatItem {
614
+ const i = closed(v, ["id", "role", "text", "name", "args", "error"]);
615
+ return {
616
+ id: text(i.id, 160, true),
617
+ role: oneOf(i.role, ["user", "assistant", "tool"]),
618
+ text: text(i.text, 256 * 1024),
619
+ name: text(i.name, 128),
620
+ args: text(i.args, 64 * 1024),
621
+ error: bool(i.error),
622
+ };
623
+ }
624
+ function decodeChatStep(v: unknown): ChatStep {
625
+ const o = closed(v, [
626
+ "id",
627
+ "role",
628
+ "text",
629
+ "clipped",
630
+ "name",
631
+ "target",
632
+ "error",
633
+ "parts",
634
+ ]);
635
+ const step = {
636
+ id: text(o.id, 160, true),
637
+ role: oneOf(o.role, ["user", "assistant", "tool"]),
638
+ text: text(o.text, STEP_TEXT_BYTES),
639
+ clipped: bool(o.clipped),
640
+ name: text(o.name, 128),
641
+ target: text(o.target, TARGET_BYTES),
642
+ error: bool(o.error),
643
+ parts: integer(o.parts, 0),
644
+ };
645
+ if (step.role === "tool" && (step.text || step.clipped))
646
+ throw new ContractError("invalid");
647
+ return step;
648
+ }
649
+ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
650
+ const o = closed(v, [
651
+ "id",
652
+ "epoch",
653
+ "status",
654
+ "notice",
655
+ "omitted",
656
+ "steps",
657
+ "stable",
658
+ ]);
659
+ const omitted = closed(o.omitted, ["thinking", "media", "other"]);
660
+ const steps = integer(o.steps, 0);
661
+ return {
662
+ id: decodeId(o.id),
663
+ epoch: decodeId(o.epoch),
664
+ status: oneOf(o.status, statuses),
665
+ notice: text(o.notice, 1024),
666
+ omitted: {
667
+ thinking: bool(omitted.thinking),
668
+ media: bool(omitted.media),
669
+ other: bool(omitted.other),
670
+ },
671
+ steps,
672
+ stable: integer(o.stable, 0, steps),
510
673
  };
511
674
  }
512
675
  export function decodeChatSummary(v: unknown): ChatSummary {
@@ -532,14 +695,6 @@ export function decodeChatSummary(v: unknown): ChatSummary {
532
695
  export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
533
696
  canonicalJson(v, 512 * 1024);
534
697
  const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
535
- if (k === "conversation-transcript") {
536
- const o = closed(v, ["kind", "conversationId", "page", "turn"]);
537
- const turn = decodeChatTurn(o.turn),
538
- page = integer(o.page, 0);
539
- if (!turn.transcript || page >= turn.transcript.pages)
540
- throw new ContractError("invalid");
541
- return { kind: k, conversationId: decodeId(o.conversationId), page, turn };
542
- }
543
698
  if (k === "workflow-transcript") {
544
699
  const o = closed(v, ["kind", "runId", "stepId", "turn"]);
545
700
  return {
@@ -657,12 +812,50 @@ export function decodeWorkbenchResult(v: unknown): WorkbenchResult {
657
812
  };
658
813
  }
659
814
  if (kind === "conversation") {
660
- const o = closed(v, ["kind", "summary", "turns", "before"]);
815
+ const o = closed(v, ["kind", "summary", "turns"]);
816
+ const summary = nullable(o.summary, decodeChatSummary),
817
+ turns = integer(o.turns, 0);
818
+ if (!summary && turns) throw new ContractError("invalid");
819
+ return { kind, summary, turns };
820
+ }
821
+ if (kind === "conversation-turn") {
822
+ const o = closed(v, [
823
+ "kind",
824
+ "conversationId",
825
+ "ordinal",
826
+ "turn",
827
+ "start",
828
+ "steps",
829
+ ]);
830
+ const turn = decodeChatTurnHeader(o.turn),
831
+ start = integer(o.start, 0),
832
+ steps = list(o.steps, STEP_READ, decodeChatStep);
833
+ if (start + steps.length > turn.steps) throw new ContractError("invalid");
661
834
  return {
662
835
  kind,
663
- summary: nullable(o.summary, decodeChatSummary),
664
- turns: list(o.turns, 20, decodeChatTurn),
665
- before: nullable(o.before, decodeId),
836
+ conversationId: decodeId(o.conversationId),
837
+ ordinal: integer(o.ordinal, 0),
838
+ turn,
839
+ start,
840
+ steps,
841
+ };
842
+ }
843
+ if (kind === "conversation-step") {
844
+ const o = closed(v, [
845
+ "kind",
846
+ "conversationId",
847
+ "turnId",
848
+ "step",
849
+ "part",
850
+ "item",
851
+ ]);
852
+ return {
853
+ kind,
854
+ conversationId: decodeId(o.conversationId),
855
+ turnId: decodeId(o.turnId),
856
+ step: integer(o.step, 0),
857
+ part: integer(o.part, 0),
858
+ item: decodeChatItem(o.item),
666
859
  };
667
860
  }
668
861
  if (kind === "files" || kind === "directories") {