@f5-sales-demo/xcsh 21.15.0 → 21.15.1

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/CHANGELOG.md CHANGED
@@ -40,6 +40,12 @@
40
40
 
41
41
  ### Fixed
42
42
 
43
+ - Prevented malformed task `submit_result` data, non-string write content, and invalid renderer path
44
+ values from crashing task, read, write, edit, inspect-image, or browser output. Semantically
45
+ ported from [can1357/oh-my-pi#1989](https://github.com/can1357/oh-my-pi/pull/1989),
46
+ [#4497](https://github.com/can1357/oh-my-pi/pull/4497), and
47
+ [#4529](https://github.com/can1357/oh-my-pi/pull/4529)
48
+ ([#3743](https://github.com/f5-sales-demo/xcsh/issues/3743)).
43
49
  - Preserved MCP `structuredContent` through the shared tool bridge, avoided duplicate verbatim
44
50
  payloads, and rendered every text block. Semantically ported from
45
51
  [can1357/oh-my-pi#10523](https://github.com/can1357/oh-my-pi/pull/10523)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@f5-sales-demo/xcsh",
4
- "version": "21.15.0",
4
+ "version": "21.15.1",
5
5
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://github.com/f5-sales-demo/xcsh",
7
7
  "author": "Can Boluk",
@@ -61,13 +61,13 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "@agentclientprotocol/sdk": "1.3.0",
64
- "@f5-sales-demo/pi-agent-core": "21.15.0",
65
- "@f5-sales-demo/pi-ai": "21.15.0",
66
- "@f5-sales-demo/pi-natives": "21.15.0",
67
- "@f5-sales-demo/pi-resource-management": "21.15.0",
68
- "@f5-sales-demo/pi-tui": "21.15.0",
69
- "@f5-sales-demo/pi-utils": "21.15.0",
70
- "@f5-sales-demo/xcsh-stats": "21.15.0",
64
+ "@f5-sales-demo/pi-agent-core": "21.15.1",
65
+ "@f5-sales-demo/pi-ai": "21.15.1",
66
+ "@f5-sales-demo/pi-natives": "21.15.1",
67
+ "@f5-sales-demo/pi-resource-management": "21.15.1",
68
+ "@f5-sales-demo/pi-tui": "21.15.1",
69
+ "@f5-sales-demo/pi-utils": "21.15.1",
70
+ "@f5-sales-demo/xcsh-stats": "21.15.1",
71
71
  "@mozilla/readability": "^0.6",
72
72
  "@sinclair/typebox": "^0.34",
73
73
  "@xterm/headless": "^6.0",
@@ -92,15 +92,15 @@ export interface EditToolDetails {
92
92
  // ═══════════════════════════════════════════════════════════════════════════
93
93
 
94
94
  interface EditRenderArgs {
95
- path?: string;
96
- file_path?: string;
95
+ path?: unknown;
96
+ file_path?: unknown;
97
97
  oldText?: string;
98
98
  newText?: string;
99
99
  patch?: string;
100
100
  all?: boolean;
101
101
  // Patch mode fields
102
102
  op?: Operation;
103
- rename?: string;
103
+ rename?: unknown;
104
104
  diff?: string;
105
105
  /**
106
106
  * Computed preview diff (used when tool args don't include a diff, e.g. hashline mode).
@@ -154,8 +154,8 @@ interface FormattedStreamingEdit {
154
154
  }
155
155
 
156
156
  /** Extract file path from an edit entry's path (handles chunk's file:selector format). */
157
- function filePathFromEditEntry(p: string | undefined): string | undefined {
158
- if (!p) return undefined;
157
+ function filePathFromEditEntry(p: unknown): string | undefined {
158
+ if (typeof p !== "string" || !p) return undefined;
159
159
  const ci = /^[a-zA-Z]:[/\\]/.test(p) ? p.indexOf(":", 2) : p.indexOf(":");
160
160
  return ci === -1 ? p : p.slice(0, ci);
161
161
  }
@@ -441,8 +441,15 @@ export const editToolRenderer = {
441
441
 
442
442
  // Extract path from first edit entry when top-level path is absent (new schema)
443
443
  const firstEdit = Array.isArray(args.edits) && args.edits.length > 0 ? args.edits[0] : undefined;
444
- const rawPath = args.file_path || args.path || (firstEdit as any)?.path || "";
445
- const rename = args.rename || (firstEdit as any)?.rename;
444
+ const rawPath =
445
+ typeof args.file_path === "string"
446
+ ? args.file_path
447
+ : typeof args.path === "string"
448
+ ? args.path
449
+ : (filePathFromEditEntry((firstEdit as { path?: unknown } | undefined)?.path) ?? "");
450
+ const rename =
451
+ (typeof args.rename === "string" ? args.rename : undefined) ??
452
+ filePathFromEditEntry((firstEdit as { rename?: unknown } | undefined)?.rename);
446
453
  const op = args.op || (firstEdit as any)?.op;
447
454
  const { description } = formatEditDescription(rawPath, uiTheme, { rename });
448
455
  const spinner =
@@ -498,9 +505,17 @@ function renderSingleFileResult(
498
505
  ): Component {
499
506
  const details = result.details;
500
507
  const isError = result.isError ?? (details && "isError" in details ? details.isError : false);
501
- const rawPath = args?.file_path || args?.path || (details && "path" in details ? details.path : "") || "";
508
+ const detailPath = details && "path" in details && typeof details.path === "string" ? details.path : undefined;
509
+ const rawPath =
510
+ typeof args?.file_path === "string"
511
+ ? args.file_path
512
+ : typeof args?.path === "string"
513
+ ? args.path
514
+ : (detailPath ?? "");
502
515
  const op = args?.op || details?.op;
503
- const rename = args?.rename || details?.move;
516
+ const rename =
517
+ (typeof args?.rename === "string" ? args.rename : undefined) ??
518
+ (details && "move" in details && typeof details.move === "string" ? details.move : undefined);
504
519
  const { language } = formatEditDescription(rawPath, uiTheme, { rename });
505
520
 
506
521
  const metadataLine =
@@ -17,17 +17,17 @@ export interface BuildInfo {
17
17
  }
18
18
 
19
19
  export const BUILD_INFO: BuildInfo = {
20
- "version": "21.15.0",
21
- "commit": "70ef59467d07010efc88051c877f5791673452fc",
22
- "shortCommit": "70ef594",
20
+ "version": "21.15.1",
21
+ "commit": "7b4768954fc15705b448863605d6c9d07099a309",
22
+ "shortCommit": "7b47689",
23
23
  "branch": "main",
24
- "tag": "v21.15.0",
25
- "commitDate": "2026-09-06T20:02:40+00:00",
26
- "buildDate": "2026-09-06T21:04:06.495Z",
24
+ "tag": "v21.15.1",
25
+ "commitDate": "2026-09-06T21:38:52+00:00",
26
+ "buildDate": "2026-09-06T22:29:45.915Z",
27
27
  "dirty": true,
28
28
  "prNumber": "",
29
29
  "repoUrl": "https://github.com/f5-sales-demo/xcsh",
30
30
  "repoSlug": "f5-sales-demo/xcsh",
31
- "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/70ef59467d07010efc88051c877f5791673452fc",
32
- "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.15.0"
31
+ "commitUrl": "https://github.com/f5-sales-demo/xcsh/commit/7b4768954fc15705b448863605d6c9d07099a309",
32
+ "releaseUrl": "https://github.com/f5-sales-demo/xcsh/releases/tag/v21.15.1"
33
33
  };
@@ -14,7 +14,7 @@ export const EMBEDDED_DOCS: Readonly<Record<string, string>> = {
14
14
  "en/architecture-contribution/storage-artifacts.mdx": "---\ntitle: \"Storage, blobs, and artifacts\"\ndescription: \"Trace configuration roots, session JSONL, binary blobs, text artifacts, scan caches, and move semantics.\"\nsidebar:\n order: 2\n label: \"Storage and artifacts\"\n---\n\nxcsh separates append-only conversation state from large or generated payloads. Session JSON Lines (JSONL) preserves the event graph; blob and artifact stores keep bulky data addressable without inflating every session entry.\n\n## How are stored values allocated and resolved?\n\nStorage helpers choose user or project roots, allocate collision-resistant identifiers, and record names separately from content addresses. Text artifacts remain inspectable; binary blobs are externalized and referenced by uniform resource locator (URL)-like identifiers. URL handlers validate the scheme and authority before opening the backing object.\n\n## How do resume, fork, and move treat state?\n\nResume rebuilds context from the selected session leaf. Forking creates a new branch without rewriting the source branch. Moves must update the session reference and its dependent stored values as one operation or leave the original valid; partial copies are not a successful move.\n\n## How is filesystem discovery cached?\n\nThe scan cache partitions keys by root and discovery options, evicts by freshness policy, and uses a short empty-result recheck so a newly created configuration file is noticed. Mutating code owns invalidation. A new consumer must define its cache key, freshness need, and invalidation points explicitly.\n\nRead `packages/coding-agent/src/session` for the append-only event graph and `packages/coding-agent/src/discovery` for the scan cache.\n",
15
15
  "en/architecture-contribution/tool-runtime.mdx": "---\ntitle: \"Tool runtime\"\ndescription: \"Trace Bash, notebook, deferred-action, custom-tool, context, and task-agent execution boundaries.\"\nsidebar:\n order: 3\n label: \"Tool runtime\"\n---\n\nThe agent loop sees a common tool contract, but each runtime owns its validation, cancellation, output, and side effects.\n\n## How do shell and notebook work execute?\n\nThe Bash tool validates the request, launches through the configured shell boundary, streams bounded output, and spills oversized results to an artifact. Notebook editing changes cell structure; kernel execution is a separate Python gateway operation with its own environment and Multipurpose Internet Mail Extensions (MIME) rendering.\n\n## How are deferred actions resolved?\n\nDeferred actions are pushed onto a last-in, first-out stack and resolved only at the runtime checkpoint that owns them. Custom tools use the host application programming interface (API) to register actions; they must pair cancellation and cleanup with any external resource they create.\n\n## How are commands and task agents discovered?\n\nSlash-command templates and agent definitions are discovered from normalized user, project, plugin, and bundled providers. Precedence resolves duplicate identifiers before execution. Argument expansion produces prompt input; it must not bypass tool policy or agent execution guardrails.\n\nRead `packages/coding-agent/src/tools/bash.ts` for the shell boundary, `packages/coding-agent/src/tools/notebook.ts` for cell editing, and `packages/coding-agent/src/slash-commands/builtin-registry.ts` for command discovery.\n",
16
16
  "en/architecture-contribution/tui-runtime.mdx": "---\ntitle: \"TUI runtime\"\ndescription: \"Trace component contracts, differential rendering, terminal input, modal UI, and custom tool renderers.\"\nsidebar:\n order: 8\n label: \"TUI runtime\"\n---\n\nThe terminal user interface (TUI) renders session and runtime state through components. Components return terminal cells and semantic styles; the renderer computes a differential update instead of repainting unrelated rows.\n\n## How are input and rendering routed?\n\nTerminal decoding turns bytes and escape sequences into key events. Focused overlays receive input before the prompt editor and global actions. State changes schedule a render, layout produces the next frame, and the diff layer emits only changed terminal regions.\n\n## How do I extend interactive surfaces?\n\nExtensions can open a modal through `ctx.ui.custom` only when an interactive UI host exists. Custom tools may provide renderers for calls and results while preserving a plain-text representation for headless clients. A renderer must not become the only copy of durable tool output.\n\nRead `packages/tui/src` for the component and rendering contracts, and `packages/coding-agent/src/tui` for the session-aware components built on them.\n",
17
- "en/architecture-contribution/upstream-pi.mdx": "---\ntitle: \"Relationship to pi\"\ndescription: \"Understand what xcsh inherits from pi and where the project deliberately specializes.\"\nsidebar:\n order: 9\n label: \"Relationship to pi\"\n---\n\nxcsh is derived from the open-source pi coding agent and adds F5 Distributed Cloud resource workflows, integrations, packaging, and project-specific governance.\n\n## Which upstream range was reviewed?\n\nThe last proven sync with `can1357/oh-my-pi` was `d350ea60e` on April 9, 2026. The security-first\naudit reviewed the divergent line through the frozen tip `b2f25dbfe1` on September 5, 2026.\nBecause the repositories no longer share a usable linear history, accepted changes are semantic\nports with adapted regressions rather than merges or ancestry-based cherry-picks.\n\n## Which changes were accepted?\n\nThe four implementation waves accepted these upstream pull requests:\n\n| Wave | Upstream pull requests | xcsh delivery |\n| --- | --- | --- |\n| Provider and prompt security | #2147, the opaque-thinking portion of #3239, #7067, and #8727 | #3710 |\n| Configuration and execution security | #7362 and #5636 | #3720 |\n| Core runtime | #7743, #10415, #10523, #10325, and #10550 | #3723 |\n| Terminal and platform | #10613, #10997, #10492, #9233, and #7634 | #3724 |\n\nThese ports protect provider-bound secrets and compaction boundaries, enforce exact-case\nenvironment references and complete protocol tails, repair Responses replay and shared MCP\nresults, improve rate-limit and retained-string behavior, chain directory completion, extend\npower assertions across supported platforms, and harden stats persistence and network exposure.\nThe source pull requests remain attributable to `can1357/oh-my-pi`; the xcsh deliveries link the\nexact commits and regression evidence.\n\n## Where does xcsh deliberately diverge?\n\nxcsh retains its own:\n\n- F5-scoped packages, prompts-as-files, tool factories, and capability discovery;\n- SQLite multi-credential storage, multi-account authentication, and provider routing;\n- MCP, SSH, F5 Distributed Cloud, Office, and browser integrations;\n- Bun-first runtime, session semantics, release pipeline, branding, and governance.\n\nPublic interfaces use prerelease clean breaks. In this wave,\n`MacOSPowerAssertion`/`MacOSPowerAssertionOptions` became\n`PowerAssertion`/`PowerAssertionOptions` without aliases, and `power.sleepPrevention` was added with\nan `idle` default.\n\n## What remains excluded or deferred?\n\nUpstream workflows, branding, release machinery, generated model catalogs, compatibility shims,\nnew packages, and large unrelated subsystems are excluded. The security-scan subsystem in #7048\nand the native minimizer in #2176 remain deferred. The range-dashboard optimization in #9327 and\nearendil-works/pi-only fullscreen transcript, mouse, clipboard, and renderer subsystems also remain\noutside this campaign. Commits after either frozen source tip require a later audit.\n\n## How do I decide where a fix belongs?\n\nTrace the affected module and compare it with the pinned upstream lineage. A generic agent-loop\ndefect may belong upstream; an xcsh resource command, integration, or packaging change belongs\nhere.\n\n## How do I preserve attribution?\n\nKeep upstream license notices and document imported changes. Avoid copying a patch blindly across\ndiverged modules; port the behavior with tests against the current xcsh architecture.\n",
17
+ "en/architecture-contribution/upstream-pi.mdx": "---\ntitle: \"Relationship to pi\"\ndescription: \"Understand what xcsh inherits from pi and where the project deliberately specializes.\"\nsidebar:\n order: 9\n label: \"Relationship to pi\"\n---\n\nxcsh is derived from the open-source pi coding agent and adds F5 Distributed Cloud resource workflows, integrations, packaging, and project-specific governance.\n\n## Which upstream range was reviewed?\n\nThe last proven sync with `can1357/oh-my-pi` was `d350ea60e` on April 9, 2026. The first-pass\nsecurity and shared-runtime audit reviewed the divergent line through `b2f25dbfe1` on September 5,\n2026. The second-pass TUI and renderer audit extends that lineage through the frozen tip\n`6d3bc569d16cd7351073eaa767caed51021befbb` on September 6, 2026.\nBecause the repositories no longer share a usable linear history, accepted changes are semantic\nports with adapted regressions rather than merges or ancestry-based cherry-picks.\n\n## Which changes were accepted?\n\nThe four implementation waves accepted these upstream pull requests:\n\n| Wave | Upstream pull requests | xcsh delivery |\n| --- | --- | --- |\n| Provider and prompt security | #2147, the opaque-thinking portion of #3239, #7067, and #8727 | #3710 |\n| Configuration and execution security | #7362 and #5636 | #3720 |\n| Core runtime | #7743, #10415, #10523, #10325, and #10550 | #3723 |\n| Terminal and platform | #10613, #10997, #10492, #9233, and #7634 | #3724 |\n| TUI and renderer crash containment | #1989, #4497, #4529, #2047, #5837, and #6788 | #3743 |\n\nThese ports protect provider-bound secrets and compaction boundaries, enforce exact-case\nenvironment references and complete protocol tails, repair Responses replay and shared MCP\nresults, improve rate-limit and retained-string behavior, chain directory completion, extend\npower assertions across supported platforms, and harden stats persistence and network exposure.\nThe source pull requests remain attributable to `can1357/oh-my-pi`; the xcsh deliveries link the\nexact commits and regression evidence.\n\nThe second-pass renderer work normalizes malformed task result data, accepts only strings at path\nboundaries, bounds ANSI-heavy rows before width measurement, and treats terminal disconnect\ncleanup as best effort before SIGHUP. Upstream #5438 is equivalent because `Container.render()`\nalready isolates child-render exceptions; its richer fallback display remains deferred.\n\n## Where does xcsh deliberately diverge?\n\nxcsh retains its own:\n\n- F5-scoped packages, prompts-as-files, tool factories, and capability discovery;\n- SQLite multi-credential storage, multi-account authentication, and provider routing;\n- MCP, SSH, F5 Distributed Cloud, Office, and browser integrations;\n- Bun-first runtime, session semantics, release pipeline, branding, and governance.\n\nPublic interfaces use prerelease clean breaks. In this wave,\n`MacOSPowerAssertion`/`MacOSPowerAssertionOptions` became\n`PowerAssertion`/`PowerAssertionOptions` without aliases, and `power.sleepPrevention` was added with\nan `idle` default.\n\n## What remains excluded or deferred?\n\nUpstream workflows, branding, release machinery, generated model catalogs, compatibility shims,\nnew packages, and large unrelated subsystems are excluded. The security-scan subsystem in #7048\nand the native minimizer in #2176 remain deferred. The range-dashboard optimization in #9327 and\nearendil-works/pi-only fullscreen transcript, mouse, clipboard, and renderer subsystems also remain\noutside this campaign. MCP, OpenCode, Herdr, #10625, and #10491 are explicitly excluded from the\nsecond-pass batch. Commits after the frozen source tip require a later audit.\n\n## How do I decide where a fix belongs?\n\nTrace the affected module and compare it with the pinned upstream lineage. A generic agent-loop\ndefect may belong upstream; an xcsh resource command, integration, or packaging change belongs\nhere.\n\n## How do I preserve attribution?\n\nKeep upstream license notices and document imported changes. Avoid copying a patch blindly across\ndiverged modules; port the behavior with tests against the current xcsh architecture.\n",
18
18
  "en/automate-extend/extensions-custom-tools.mdx": "---\ntitle: \"Build extensions and custom tools\"\ndescription: \"Add TypeScript behavior, slash commands, providers, or schema-validated tools.\"\nsidebar:\n order: 3\n label: \"Build extensions and custom tools\"\n---\n\nExtensions load TypeScript behavior with `--extension` or `--hook`; project discovery can also load extensions, tools, hooks, commands, and rules under `.xcsh/`.\n\n## How do I test an extension boundary?\n\nLoad one explicit file with `-e <PATH>` and disable discovery with `--no-extensions`. Confirm its registered command or tool, then test shutdown and error handling.\n\n## Where do hooks and rules belong?\n\nHooks observe or alter lifecycle events; rules add durable instructions. Keep each rule narrow and each hook deterministic. Use `--no-rules` to prove whether a rule changes the result.\n",
19
19
  "en/automate-extend/headless-protocols.mdx": "---\ntitle: \"Headless modes\"\ndescription: \"Integrate xcsh with scripts through print, JSON, JSON-RPC, agent client protocol, manager, and worker modes.\"\nsidebar:\n order: 1\n label: \"Headless modes\"\n---\n\nHeadless integrations select `json`, `rpc`, or `acp` with `--mode`: a JavaScript Object Notation (JSON) event stream, JSON remote procedure call (RPC), or the agent client protocol (ACP). Each mode has a different framing contract; consumers must parse that protocol rather than decorated terminal text.\n\n## How do I start with the smallest surface?\n\n```bash\nxcsh --mode json --no-session --no-tools -p \"Return one sentence\"\n```\n\nCapture stdout as protocol data and stderr as diagnostics. Pin the xcsh version in automation and test framing against the exact release.\n\n## When do I use the software development kit (SDK) instead?\n\nUse the SDK when the host process needs in-memory session control, tool registration, or provider events. See [SDK automation](./sdk/).\n",
20
20
  "en/automate-extend/hooks-rules.mdx": "---\ntitle: \"Apply hooks and rules\"\ndescription: \"Choose event-driven mutation or declarative prompt guidance and understand discovery precedence.\"\nsidebar:\n order: 4\n label: \"Hooks and rules\"\n---\n\nRules contribute normalized instructions to the prompt. Hooks execute code at named lifecycle events. Use rules for guidance that does not need side effects; use a hook only when an event must inspect, transform, or reject runtime data.\n\n## How are rules discovered and classified?\n\nRule providers scan project and user roots, parse frontmatter, normalize identifiers, then deduplicate by precedence. Classification separates ordinary rulebook entries, always-apply guidance, and time-to-self-reflect material. The `rule://` handler resolves the final normalized item rather than reading an arbitrary path.\n\n## What determines hook execution order?\n\nA hook module exports handlers for supported events. Discovery determines the module set, and registration order determines sequential mutation when more than one handler sees the same payload. A thrown error follows the event's propagation contract; it is not converted into a successful empty result.\n\n## How do I test the hook boundary?\n\nExercise each of these separately:\n\n1. Discovery, so the module set is the one you expect.\n2. The exact event, with a representative payload.\n3. Mutation ordering, with more than one handler registered.\n4. Cancellation.\n5. A handler that throws.\n\nInterface calls made by hooks require an interactive host, so a headless integration must not assume a modal interface exists.\n",
@@ -124,9 +124,12 @@ export class EventController {
124
124
  }
125
125
 
126
126
  subscribeToAgent(): void {
127
- this.ctx.unsubscribe = this.ctx.session.subscribe(async (event: AgentSessionEvent) => {
128
- await this.handleEvent(event);
129
- });
127
+ this.ctx.unsubscribe = this.ctx.session.subscribe(
128
+ async (event: AgentSessionEvent) => {
129
+ await this.handleEvent(event);
130
+ },
131
+ { waitForTurnSettlement: true },
132
+ );
130
133
  }
131
134
 
132
135
  async handleEvent(event: AgentSessionEvent): Promise<void> {
@@ -212,7 +212,15 @@ export type AgentSessionEvent =
212
212
  | { type: "todo_auto_clear" };
213
213
 
214
214
  /** Listener function for agent session events */
215
- export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
215
+ export type AgentSessionEventListener = (event: AgentSessionEvent) => unknown;
216
+ export interface AgentSessionEventSubscriptionOptions {
217
+ /** Delay normalized turn settlement until this listener finishes handling agent_end. */
218
+ waitForTurnSettlement?: boolean;
219
+ }
220
+ interface AgentSessionEventSubscription {
221
+ listener: AgentSessionEventListener;
222
+ waitForTurnSettlement: boolean;
223
+ }
216
224
  export type AsyncJobSnapshotItem = Pick<AsyncJob, "id" | "type" | "status" | "label" | "startTime">;
217
225
 
218
226
  export interface AsyncJobSnapshot {
@@ -475,7 +483,7 @@ export class AgentSession {
475
483
 
476
484
  // Event subscription state
477
485
  #unsubscribeAgent?: () => void;
478
- #eventListeners: AgentSessionEventListener[] = [];
486
+ #eventListeners: AgentSessionEventSubscription[] = [];
479
487
  #turnPhase = new TurnPhaseController(event => this.#publishTurnPhase(event));
480
488
 
481
489
  // Callers (e.g., SDK-level code that registers external listeners) register cleanups here so
@@ -767,12 +775,17 @@ export class AgentSession {
767
775
  // =========================================================================
768
776
 
769
777
  /** Emit an event to all listeners */
770
- #emit(event: AgentSessionEvent): void {
778
+ #emit(event: AgentSessionEvent): Promise<unknown>[] {
771
779
  // Copy array before iteration to avoid mutation during iteration
772
- const listeners = [...this.#eventListeners];
773
- for (const l of listeners) {
774
- l(event);
780
+ const subscriptions = [...this.#eventListeners];
781
+ const turnSettlementListeners: Promise<unknown>[] = [];
782
+ for (const subscription of subscriptions) {
783
+ const result = subscription.listener(event);
784
+ if (event.type === "agent_end" && subscription.waitForTurnSettlement) {
785
+ turnSettlementListeners.push(Promise.resolve(result));
786
+ }
775
787
  }
788
+ return turnSettlementListeners;
776
789
  }
777
790
 
778
791
  #queuedExtensionEvents: Promise<void> = Promise.resolve();
@@ -786,11 +799,11 @@ export class AgentSession {
786
799
  return queued;
787
800
  }
788
801
 
789
- async #emitSessionEvent(event: AgentSessionEvent): Promise<void> {
802
+ async #emitSessionEvent(event: AgentSessionEvent): Promise<Promise<unknown>[]> {
790
803
  if (event.type === "message_update" || event.type === "turn_phase") {
791
804
  this.#emit(event);
792
805
  void this.#queueExtensionEvent(event);
793
- return;
806
+ return [];
794
807
  }
795
808
 
796
809
  if (
@@ -804,7 +817,7 @@ export class AgentSession {
804
817
  }
805
818
 
806
819
  await this.#emitExtensionEvent(event);
807
- this.#emit(event);
820
+ return this.#emit(event);
808
821
  }
809
822
 
810
823
  // Track last assistant message for auto-compaction check
@@ -885,23 +898,33 @@ export class AgentSession {
885
898
  }
886
899
  }
887
900
 
888
- await this.#emitSessionEvent(displayEvent);
901
+ const turnSettlementListeners = await this.#emitSessionEvent(displayEvent);
889
902
 
890
903
  // `agent_end` is the provider-neutral completion boundary. Settle only
891
- // after subscribers have received it, so interactive consumers can begin
892
- // clearing provider/tool status before Herdr observes idle. This also
893
- // covers continuations that call Agent.continue() without #promptWithMessage.
904
+ // after the designated lifecycle consumer has finished clearing provider/tool
905
+ // status before Herdr observes idle. Other subscribers and post-turn maintenance
906
+ // continue concurrently. This also covers Agent.continue() continuations.
894
907
  if (event.type === "agent_end") {
895
908
  const lastAssistant = [...event.messages]
896
909
  .reverse()
897
910
  .find((message): message is AssistantMessage => message.role === "assistant");
898
- this.#turnPhase.settle(
899
- lastAssistant?.stopReason === "aborted"
900
- ? "aborted"
901
- : lastAssistant?.stopReason === "error"
902
- ? "error"
903
- : "stop",
904
- );
911
+ const settle = () => {
912
+ this.#turnPhase.settle(
913
+ lastAssistant?.stopReason === "aborted"
914
+ ? "aborted"
915
+ : lastAssistant?.stopReason === "error"
916
+ ? "error"
917
+ : "stop",
918
+ );
919
+ };
920
+ if (turnSettlementListeners.length === 0) {
921
+ settle();
922
+ } else {
923
+ void Promise.all(turnSettlementListeners).then(settle, error => {
924
+ logger.warn("Turn settlement listener failed", { error: String(error) });
925
+ settle();
926
+ });
927
+ }
905
928
  }
906
929
 
907
930
  if (event.type === "turn_start") {
@@ -2168,12 +2191,13 @@ export class AgentSession {
2168
2191
  * Session persistence is handled internally (saves messages on message_end).
2169
2192
  * Multiple listeners can be added. Returns unsubscribe function for this listener.
2170
2193
  */
2171
- subscribe(listener: AgentSessionEventListener): () => void {
2172
- this.#eventListeners.push(listener);
2194
+ subscribe(listener: AgentSessionEventListener, options: AgentSessionEventSubscriptionOptions = {}): () => void {
2195
+ const subscription = { listener, waitForTurnSettlement: options.waitForTurnSettlement ?? false };
2196
+ this.#eventListeners.push(subscription);
2173
2197
 
2174
2198
  // Return unsubscribe function for this specific listener
2175
2199
  return () => {
2176
- const index = this.#eventListeners.indexOf(listener);
2200
+ const index = this.#eventListeners.indexOf(subscription);
2177
2201
  if (index !== -1) {
2178
2202
  this.#eventListeners.splice(index, 1);
2179
2203
  }
@@ -79,6 +79,17 @@ function normalizeReportFindings(value: unknown): ReportFindingDetails[] {
79
79
  return findings;
80
80
  }
81
81
 
82
+ /** Normalize renderer-facing submit_result data without weakening tool schemas. */
83
+ function normalizeSubmitResultData(value: unknown): Array<{ data: unknown }> {
84
+ if (Array.isArray(value)) {
85
+ return value.filter((item): item is { data: unknown } => item !== null && typeof item === "object");
86
+ }
87
+ if (value !== null && typeof value === "object") {
88
+ return [value as { data: unknown }];
89
+ }
90
+ return [];
91
+ }
92
+
82
93
  function formatJsonScalar(value: unknown, _theme: Theme): string {
83
94
  if (value === null) return "null";
84
95
  if (typeof value === "string") {
@@ -588,12 +599,12 @@ function renderAgentProgress(
588
599
  if (progress.extractedToolData) {
589
600
  // For completed tasks, check for review verdict from submit_result tool
590
601
  if (progress.status === "completed") {
591
- const completeData = progress.extractedToolData.submit_result as Array<{ data: unknown }> | undefined;
602
+ const completeData = normalizeSubmitResultData(progress.extractedToolData.submit_result);
592
603
  const reportFindingData = normalizeReportFindings(progress.extractedToolData.report_finding);
593
604
  const reviewData = completeData
594
- ?.map(c => c.data as SubmitReviewDetails)
605
+ .map(c => c.data as SubmitReviewDetails)
595
606
  .filter(d => d && typeof d === "object" && "overall_correctness" in d);
596
- if (reviewData && reviewData.length > 0) {
607
+ if (reviewData.length > 0) {
597
608
  const summary = reviewData[reviewData.length - 1];
598
609
  const findings = reportFindingData;
599
610
  lines.push(...renderReviewResult(summary, findings, continuePrefix, expanded, theme));
@@ -798,16 +809,16 @@ function renderAgentResult(result: SingleResult, isLast: boolean, expanded: bool
798
809
  );
799
810
  }
800
811
  // Check for review result (submit_result with review schema + report_finding)
801
- const completeData = result.extractedToolData?.submit_result as Array<{ data: unknown }> | undefined;
812
+ const completeData = normalizeSubmitResultData(result.extractedToolData?.submit_result);
802
813
  const reportFindingData = normalizeReportFindings(result.extractedToolData?.report_finding);
803
814
 
804
815
  // Extract review verdict from submit_result tool's data field if it matches SubmitReviewDetails
805
816
  const reviewData = completeData
806
- ?.map(c => c.data as SubmitReviewDetails)
817
+ .map(c => c.data as SubmitReviewDetails)
807
818
  .filter(d => d && typeof d === "object" && "overall_correctness" in d);
808
- const submitReviewData = reviewData && reviewData.length > 0 ? reviewData : undefined;
819
+ const submitReviewData = reviewData.length > 0 ? reviewData : undefined;
809
820
 
810
- if (submitReviewData && submitReviewData.length > 0) {
821
+ if (submitReviewData) {
811
822
  // Use combined review renderer
812
823
  const summary = submitReviewData[submitReviewData.length - 1];
813
824
  const findings = reportFindingData;
@@ -815,7 +826,7 @@ function renderAgentResult(result: SingleResult, isLast: boolean, expanded: bool
815
826
  return lines;
816
827
  }
817
828
  if (reportFindingData.length > 0) {
818
- const hasCompleteData = completeData && completeData.length > 0;
829
+ const hasCompleteData = completeData.length > 0;
819
830
  const message = hasCompleteData
820
831
  ? "Review verdict missing expected fields"
821
832
  : "Review incomplete (submit_result not called)";
@@ -11,9 +11,9 @@ const TOOL_TITLE = "Browser";
11
11
  const MAX_CONTENT_LINES = 30;
12
12
 
13
13
  type BrowserRenderArgs = {
14
- action?: string;
15
- url?: string;
16
- selector?: string;
14
+ action?: unknown;
15
+ url?: unknown;
16
+ selector?: unknown;
17
17
  text?: string;
18
18
  };
19
19
 
@@ -42,12 +42,13 @@ const ACTION_COLORS: Partial<Record<string, ThemeColor>> = {
42
42
 
43
43
  export const browserRenderer = {
44
44
  renderCall(args: BrowserRenderArgs, _options: RenderResultOptions, uiTheme: Theme): Component {
45
- const action = args.action ?? "browse";
46
- const description = args.url
47
- ? uiTheme.fg("muted", args.url)
48
- : args.selector
49
- ? uiTheme.fg("dim", args.selector)
50
- : undefined;
45
+ const action = typeof args.action === "string" ? args.action : "browse";
46
+ const description =
47
+ typeof args.url === "string" && args.url
48
+ ? uiTheme.fg("muted", args.url)
49
+ : typeof args.selector === "string" && args.selector
50
+ ? uiTheme.fg("dim", args.selector)
51
+ : undefined;
51
52
  const badgeColor = ACTION_COLORS[action] ?? "muted";
52
53
  const text = renderStatusLine(
53
54
  { icon: "pending", title: TOOL_TITLE, badge: { label: action, color: badgeColor }, description },
@@ -70,7 +71,12 @@ export const browserRenderer = {
70
71
  return new Text(formatErrorMessage(errorText, uiTheme), 0, 0);
71
72
  }
72
73
 
73
- const action = details?.action ?? args?.action ?? "browse";
74
+ const action =
75
+ typeof details?.action === "string"
76
+ ? details.action
77
+ : typeof args?.action === "string"
78
+ ? args.action
79
+ : "browse";
74
80
  const badgeColor = ACTION_COLORS[action] ?? "muted";
75
81
  const sections: Array<{ label?: string; lines: string[] }> = [];
76
82
  const meta: string[] = [];
@@ -79,16 +85,12 @@ export const browserRenderer = {
79
85
  const errorText = result.content?.find(c => c.type === "text")?.text ?? "Unknown error";
80
86
  addSection(sections, "Error", [uiTheme.fg("error", errorText)], uiTheme);
81
87
  } else {
82
- if (details?.url)
88
+ if (typeof details?.url === "string" && details.url)
83
89
  meta.push(uiTheme.fg("dim", details.url.length > 50 ? `${details.url.slice(0, 47)}…` : details.url));
84
90
 
85
- if (details?.screenshotPath) {
86
- addSection(
87
- sections,
88
- "Screenshot",
89
- [uiTheme.fg("toolOutput", ` ${shortenPath(details.screenshotPath)}`)],
90
- uiTheme,
91
- );
91
+ const screenshotPath = typeof details?.screenshotPath === "string" ? details.screenshotPath : "";
92
+ if (screenshotPath) {
93
+ addSection(sections, "Screenshot", [uiTheme.fg("toolOutput", ` ${shortenPath(screenshotPath)}`)], uiTheme);
92
94
  }
93
95
 
94
96
  if (details?.viewport) {
@@ -10,13 +10,13 @@ const TOOL_TITLE = "Inspect Image";
10
10
  const MAX_OUTPUT_LINES = 30;
11
11
 
12
12
  interface InspectImageRenderArgs {
13
- path?: string;
14
- question?: string;
13
+ path?: unknown;
14
+ question?: unknown;
15
15
  }
16
16
 
17
17
  interface InspectImageRendererDetails {
18
18
  model: string;
19
- imagePath: string;
19
+ imagePath: unknown;
20
20
  mimeType: string;
21
21
  }
22
22
 
@@ -28,7 +28,7 @@ interface InspectImageRendererResult {
28
28
 
29
29
  export const inspectImageToolRenderer = {
30
30
  renderCall(args: InspectImageRenderArgs, _options: RenderResultOptions, uiTheme: Theme): Component {
31
- const rawPath = args.path ?? "";
31
+ const rawPath = typeof args.path === "string" ? args.path : "";
32
32
  const pathDisplay = rawPath ? shortenPath(rawPath) : "…";
33
33
  const description = uiTheme.fg("muted", pathDisplay);
34
34
  const text = renderStatusLine({ icon: "pending", title: TOOL_TITLE, description }, uiTheme);
@@ -49,7 +49,8 @@ export const inspectImageToolRenderer = {
49
49
  return new Text(formatErrorMessage(errorText, uiTheme), 0, 0);
50
50
  }
51
51
 
52
- const rawPath = details?.imagePath ?? args?.path ?? "";
52
+ const rawPath =
53
+ typeof details?.imagePath === "string" ? details.imagePath : typeof args?.path === "string" ? args.path : "";
53
54
  const pathDisplay = rawPath ? shortenPath(rawPath) : "image";
54
55
  const sections: Array<{ label?: string; lines: string[] }> = [];
55
56
  const meta: string[] = [];
@@ -61,7 +62,7 @@ export const inspectImageToolRenderer = {
61
62
  const errorText = result.content?.find(c => c.type === "text")?.text ?? "Unknown error";
62
63
  addSection(sections, "Error", [uiTheme.fg("error", errorText)], uiTheme);
63
64
  } else {
64
- if (args?.question) {
65
+ if (typeof args?.question === "string" && args.question) {
65
66
  addSection(sections, "Question", [uiTheme.fg("chromeAccent", ` ${args.question}`)], uiTheme);
66
67
  }
67
68
 
package/src/tools/read.ts CHANGED
@@ -1451,8 +1451,8 @@ export class ReadTool implements AgentTool<typeof readSchema, ReadToolDetails> {
1451
1451
  // =============================================================================
1452
1452
 
1453
1453
  interface ReadRenderArgs {
1454
- path?: string;
1455
- file_path?: string;
1454
+ path?: unknown;
1455
+ file_path?: unknown;
1456
1456
  sel?: string;
1457
1457
  timeout?: number;
1458
1458
  // Legacy fields from old schema — tolerated for in-flight tool calls during transition
@@ -1463,11 +1463,12 @@ interface ReadRenderArgs {
1463
1463
 
1464
1464
  export const readToolRenderer = {
1465
1465
  renderCall(args: ReadRenderArgs, _options: RenderResultOptions, uiTheme: Theme): Component {
1466
- if (isReadableUrlPath(args.file_path || args.path || "")) {
1467
- return renderReadUrlCall(args, _options, uiTheme);
1466
+ const rawPath =
1467
+ typeof args.file_path === "string" ? args.file_path : typeof args.path === "string" ? args.path : "";
1468
+ if (isReadableUrlPath(rawPath)) {
1469
+ return renderReadUrlCall({ path: rawPath, raw: args.raw }, _options, uiTheme);
1468
1470
  }
1469
1471
 
1470
- const rawPath = args.file_path || args.path || "";
1471
1472
  const filePath = shortenPath(rawPath);
1472
1473
  const offset = args.offset;
1473
1474
  const limit = args.limit;
@@ -1490,7 +1491,9 @@ export const readToolRenderer = {
1490
1491
  args?: ReadRenderArgs,
1491
1492
  ): Component {
1492
1493
  const urlDetails = result.details as ReadUrlToolDetails | undefined;
1493
- if (urlDetails?.kind === "url" || isReadableUrlPath(args?.file_path || args?.path || "")) {
1494
+ const rawPathForKind =
1495
+ typeof args?.file_path === "string" ? args.file_path : typeof args?.path === "string" ? args.path : "";
1496
+ if (urlDetails?.kind === "url" || isReadableUrlPath(rawPathForKind)) {
1494
1497
  return renderReadUrlResult(
1495
1498
  result as { content: Array<{ type: string; text?: string }>; details?: ReadUrlToolDetails },
1496
1499
  _options,
@@ -1501,9 +1504,9 @@ export const readToolRenderer = {
1501
1504
  const details = result.details;
1502
1505
  const contentText = result.content?.find(c => c.type === "text")?.text ?? "";
1503
1506
  const imageContent = result.content?.find(c => c.type === "image");
1504
- const rawPath = args?.file_path || args?.path || "";
1507
+ const rawPath = rawPathForKind;
1505
1508
  const filePath = shortenPath(rawPath);
1506
- const lang = getLanguageFromPath(rawPath);
1509
+ const lang = rawPath ? getLanguageFromPath(rawPath) : undefined;
1507
1510
 
1508
1511
  const warningLines: string[] = [];
1509
1512
  const truncation = details?.meta?.truncation;
@@ -549,7 +549,8 @@ export function truncateDiffByHunk(
549
549
  // Path Utilities
550
550
  // =============================================================================
551
551
 
552
- export function shortenPath(filePath: string, homeDir?: string): string {
552
+ export function shortenPath(filePath: unknown, homeDir?: string): string {
553
+ if (typeof filePath !== "string") return "";
553
554
  const home = homeDir ?? os.homedir();
554
555
  if (home && filePath.startsWith(home)) {
555
556
  return `~${filePath.slice(home.length)}`;
@@ -517,9 +517,9 @@ export class WriteTool implements AgentTool<typeof writeSchema, WriteToolDetails
517
517
  // =============================================================================
518
518
 
519
519
  interface WriteRenderArgs {
520
- path?: string;
521
- file_path?: string;
522
- content?: string;
520
+ path?: unknown;
521
+ file_path?: unknown;
522
+ content?: unknown;
523
523
  }
524
524
 
525
525
  const WRITE_PREVIEW_LINES = 6;
@@ -538,8 +538,9 @@ function formatMetadataLine(lineCount: number | null, language: string | undefin
538
538
  return uiTheme.fg("dim", `${icon}`);
539
539
  }
540
540
 
541
- function normalizeDisplayText(text: string): string {
542
- return text.replace(/\r/g, "");
541
+ function normalizeDisplayText(text: unknown): string {
542
+ if (text === undefined || text === null) return "";
543
+ return String(text).replace(/\r/g, "");
543
544
  }
544
545
 
545
546
  function formatStreamingContent(content: string, uiTheme: Theme, maxWidth: number): string {
@@ -580,9 +581,10 @@ function renderContentPreview(content: string, expanded: boolean, uiTheme: Theme
580
581
 
581
582
  export const writeToolRenderer = {
582
583
  renderCall(args: WriteRenderArgs, options: RenderResultOptions, uiTheme: Theme): Component {
583
- const rawPath = args.file_path || args.path || "";
584
+ const rawPath =
585
+ typeof args.file_path === "string" ? args.file_path : typeof args.path === "string" ? args.path : "";
584
586
  const filePath = shortenPath(rawPath);
585
- const lang = getLanguageFromPath(rawPath) ?? "text";
587
+ const lang = rawPath ? (getLanguageFromPath(rawPath) ?? "text") : "text";
586
588
  const langIcon = uiTheme.fg("muted", uiTheme.getLangIcon(lang));
587
589
  const pathDisplay = filePath ? uiTheme.fg("accent", filePath) : uiTheme.fg("toolOutput", "…");
588
590
  const spinner =
@@ -590,7 +592,8 @@ export const writeToolRenderer = {
590
592
 
591
593
  const header = `${formatTitle("Write", uiTheme)} ${spinner ? `${spinner} ` : ""}${langIcon} ${pathDisplay}`;
592
594
 
593
- if (!args.content) {
595
+ const content = normalizeDisplayText(args.content);
596
+ if (!content) {
594
597
  return {
595
598
  render(width: number) {
596
599
  return [truncateToWidth(header, width, Ellipsis.Omit)];
@@ -601,7 +604,7 @@ export const writeToolRenderer = {
601
604
 
602
605
  return {
603
606
  render(width: number) {
604
- const text = header + formatStreamingContent(args.content!, uiTheme, width);
607
+ const text = header + formatStreamingContent(content, uiTheme, width);
605
608
  return text.split("\n").map(l => truncateToWidth(l, width, Ellipsis.Omit));
606
609
  },
607
610
  invalidate() {},
@@ -614,10 +617,11 @@ export const writeToolRenderer = {
614
617
  uiTheme: Theme,
615
618
  args?: WriteRenderArgs,
616
619
  ): Component {
617
- const rawPath = args?.file_path || args?.path || "";
620
+ const rawPath =
621
+ typeof args?.file_path === "string" ? args.file_path : typeof args?.path === "string" ? args.path : "";
618
622
  const filePath = shortenPath(rawPath);
619
- const fileContent = args?.content || "";
620
- const lang = getLanguageFromPath(rawPath);
623
+ const fileContent = normalizeDisplayText(args?.content);
624
+ const lang = rawPath ? getLanguageFromPath(rawPath) : undefined;
621
625
  const langIcon = uiTheme.fg("muted", uiTheme.getLangIcon(lang));
622
626
  const pathDisplay = filePath ? uiTheme.fg("accent", filePath) : uiTheme.fg("toolOutput", "…");
623
627
  const lineCount = countLines(fileContent);