pi-fabric 0.131.1 → 0.131.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +1 -1
  2. package/dist/activity/store.d.ts.map +1 -1
  3. package/dist/actors/global-registry.d.ts.map +1 -1
  4. package/dist/actors/manager.d.ts.map +1 -1
  5. package/dist/agents/manager.d.ts.map +1 -1
  6. package/dist/agents/request.d.ts.map +1 -1
  7. package/dist/agents/transports/herdr-core-socket.d.ts +13 -0
  8. package/dist/agents/transports/herdr-core-socket.d.ts.map +1 -0
  9. package/dist/agents/transports/herdr-core-transport.d.ts +10 -0
  10. package/dist/agents/transports/herdr-core-transport.d.ts.map +1 -0
  11. package/dist/agents.js +1 -1
  12. package/dist/audit/details.d.ts +2 -0
  13. package/dist/audit/details.d.ts.map +1 -1
  14. package/dist/chunks/{chunk-3PKZSIRA.js → chunk-ASOJYFKU.js} +8 -4
  15. package/dist/chunks/chunk-ASOJYFKU.js.map +7 -0
  16. package/dist/chunks/{chunk-5BOTHX47.js → chunk-HKGHRPX7.js} +3 -3
  17. package/dist/chunks/chunk-HKGHRPX7.js.map +7 -0
  18. package/dist/chunks/{chunk-7CIES6X2.js → chunk-HRVYXRWZ.js} +2 -2
  19. package/dist/chunks/chunk-HRVYXRWZ.js.map +7 -0
  20. package/dist/chunks/{chunk-36XQFTEN.js → chunk-L6H46CPY.js} +2 -2
  21. package/dist/chunks/{chunk-4KX6BIPL.js → chunk-LRSZFYUC.js} +2 -2
  22. package/dist/chunks/chunk-LRSZFYUC.js.map +7 -0
  23. package/dist/chunks/{chunk-UFMYN5TA.js → chunk-MX53BRAC.js} +2 -2
  24. package/dist/chunks/{chunk-IOGDTIGN.js → chunk-QYBALDEM.js} +2 -2
  25. package/dist/chunks/{chunk-WWTGWGH7.js → chunk-RKJPBTBB.js} +22 -6
  26. package/dist/chunks/chunk-RKJPBTBB.js.map +7 -0
  27. package/dist/chunks/{chunk-W3N72XYK.js → chunk-SQRDHUD2.js} +70 -38
  28. package/dist/chunks/chunk-SQRDHUD2.js.map +7 -0
  29. package/dist/chunks/{chunk-YHFWMAQ5.js → chunk-TEMKDJJY.js} +151 -52
  30. package/dist/chunks/chunk-TEMKDJJY.js.map +7 -0
  31. package/dist/chunks/{chunk-ZFWICFNJ.js → chunk-UTPA2PBN.js} +6 -3
  32. package/dist/chunks/chunk-UTPA2PBN.js.map +7 -0
  33. package/dist/chunks/{chunk-VNWQIGQL.js → chunk-VGRUWTMG.js} +415 -252
  34. package/dist/chunks/chunk-VGRUWTMG.js.map +7 -0
  35. package/dist/chunks/{chunk-X7QETPBC.js → chunk-ZHROHNEE.js} +1 -1
  36. package/dist/commands/fabric-handler.js +1 -1
  37. package/dist/compaction/claim-events.js +1 -1
  38. package/dist/components/configuration.js +2 -2
  39. package/dist/config.d.ts +1 -1
  40. package/dist/config.d.ts.map +1 -1
  41. package/dist/core/call-presentation.d.ts +14 -0
  42. package/dist/core/call-presentation.d.ts.map +1 -0
  43. package/dist/core/shell-inbox.d.ts.map +1 -1
  44. package/dist/durable/agent.d.ts.map +1 -1
  45. package/dist/durable/worker-host.js +1 -1
  46. package/dist/durable-extension.d.ts +1 -1
  47. package/dist/durable-extension.js +1 -1
  48. package/dist/durable-extension.js.map +1 -1
  49. package/dist/durable-host.js +1 -1
  50. package/dist/durable.d.ts.map +1 -1
  51. package/dist/durable.js +5 -4
  52. package/dist/durable.js.map +2 -2
  53. package/dist/extension-bootstrap.js +5 -5
  54. package/dist/fabric-exec-tool.d.ts.map +1 -1
  55. package/dist/fabric-runtime-state.js +48 -31
  56. package/dist/fabric-runtime-state.js.map +2 -2
  57. package/dist/index.js +5 -5
  58. package/dist/jev.js +1 -1
  59. package/dist/providers/agents-provider.d.ts.map +1 -1
  60. package/dist/providers/jev-provider.js +1 -1
  61. package/dist/residency/host.js +3 -3
  62. package/dist/residency/pi-entry.js +3 -3
  63. package/dist/runtime/core-override-guest-types.js +2 -2
  64. package/dist/runtime/guest-types.d.ts +1 -1
  65. package/dist/runtime/guest-types.d.ts.map +1 -1
  66. package/dist/runtime/guest-types.js +1 -1
  67. package/dist/runtime/monty-runtime.js +1 -1
  68. package/dist/runtime/typescript-kernel.js +2 -2
  69. package/dist/topology/participant-directory.d.ts.map +1 -1
  70. package/dist/type-error-guidance.js +1 -1
  71. package/dist/ui/dashboard-model.d.ts.map +1 -1
  72. package/dist/ui/dashboard.js +6 -3
  73. package/dist/ui/dashboard.js.map +2 -2
  74. package/dist/ui/fabric-render.d.ts +1 -0
  75. package/dist/ui/fabric-render.d.ts.map +1 -1
  76. package/dist/ui/settings-values.d.ts +1 -1
  77. package/dist/ui/settings-values.d.ts.map +1 -1
  78. package/dist/ui/settings.js +2 -2
  79. package/dist/ui/settings.js.map +2 -2
  80. package/dist/ui/widget.d.ts +8 -4
  81. package/dist/ui/widget.d.ts.map +1 -1
  82. package/docs/agents.md +4 -1
  83. package/docs/background-tasks.md +24 -12
  84. package/docs/configuration.md +2 -0
  85. package/docs/interface.md +3 -1
  86. package/package.json +9 -9
  87. package/skillsets/typescript/fabric-exec/references/agents.md +1 -1
  88. package/dist/chunks/chunk-3PKZSIRA.js.map +0 -7
  89. package/dist/chunks/chunk-4KX6BIPL.js.map +0 -7
  90. package/dist/chunks/chunk-5BOTHX47.js.map +0 -7
  91. package/dist/chunks/chunk-7CIES6X2.js.map +0 -7
  92. package/dist/chunks/chunk-VNWQIGQL.js.map +0 -7
  93. package/dist/chunks/chunk-W3N72XYK.js.map +0 -7
  94. package/dist/chunks/chunk-WWTGWGH7.js.map +0 -7
  95. package/dist/chunks/chunk-YHFWMAQ5.js.map +0 -7
  96. package/dist/chunks/chunk-ZFWICFNJ.js.map +0 -7
  97. /package/dist/chunks/{chunk-36XQFTEN.js.map → chunk-L6H46CPY.js.map} +0 -0
  98. /package/dist/chunks/{chunk-UFMYN5TA.js.map → chunk-MX53BRAC.js.map} +0 -0
  99. /package/dist/chunks/{chunk-IOGDTIGN.js.map → chunk-QYBALDEM.js.map} +0 -0
  100. /package/dist/chunks/{chunk-X7QETPBC.js.map → chunk-ZHROHNEE.js.map} +0 -0
@@ -53,11 +53,15 @@ export declare const shouldShowFabricWidget: (snapshot: FabricDashboardSnapshot,
53
53
  export declare const WIDGET_TERMINAL_ROW_SHARE = 0.5;
54
54
  /** Effective row budget: the configured maximum, bounded by the live pane. */
55
55
  export declare const widgetRowLimit: (maxRows: number, terminalRows?: number) => number;
56
- /**
57
- * Row budget while the widget has focus. Focus is a request to see the list,
58
- * so it may use its whole terminal share instead of `maxRows`, but never more.
59
- */
56
+ /** Keyboard focus must not resize the footer or move the transcript. */
60
57
  export declare const widgetFocusedRowLimit: (maxRows: number, terminalRows?: number) => number;
58
+ /** Reserve an overflow row for the whole scroll range, not just while rows remain below. */
59
+ export declare const widgetViewport: (contentRows: number, budget: number, offset: number) => {
60
+ windowRows: number;
61
+ hasCue: boolean;
62
+ maxOffset: number;
63
+ offset: number;
64
+ };
61
65
  export declare class FabricWidget implements Component, Focusable {
62
66
  #private;
63
67
  readonly theme: Theme;
@@ -1 +1 @@
1
- {"version":3,"file":"widget.d.ts","sourceRoot":"","sources":["../../src/ui/widget.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAEvG,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAA4B,MAAM,gBAAgB,CAAC;AAQjF,OAAO,EAGL,KAAK,uBAAuB,EAE7B,MAAM,YAAY,CAAC;AAgDpB,oDAAoD;AACpD,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;IA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,SAAS;;IAErD,QAAQ,CAAC,KAAK,EAAE,KAAK;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,uBAAuB;IAChD,QAAQ,CAAC,OAAO,EAAE,MAAM;IAGxB,QAAQ,CAAC,YAAY,CAAC,GAAE,MAAM,MAAM,GAAG,SAAS;IAChD,QAAQ,CAAC,SAAS;IAClB,QAAQ,CAAC,WAAW,CAAC,EAAE,uBAAuB;gBAPrC,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,MAAM,uBAAuB,EACvC,OAAO,EAAE,MAAM,EAGf,YAAY,CAAC,GAAE,MAAM,MAAM,GAAG,SAAS,aAAA,EACvC,SAAS,wBAA8B,EACvC,WAAW,CAAC,EAAE,uBAAuB,YAAA;IAGhD,oEAAoE;IACpE,OAAO,UAAS;IAahB,6FAA6F;IAC7F,aAAa,IAAI,IAAI;IAQrB,yEAAyE;IACzE,WAAW,IAAI,IAAI;IAKnB,kDAAkD;IAClD,OAAO,IAAI,OAAO;IAQlB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IA6B/B,WAAW,CAAC,KAAK,EAAE,aAAa,GAAG,mBAAmB,GAAG,SAAS;IAoElE,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IA+B/B,UAAU,IAAI,OAAO;IAYrB,UAAU,IAAI,IAAI;CAkOnB"}
package/docs/agents.md CHANGED
@@ -549,7 +549,10 @@ This is the host-level equivalent of the `pi-model-switch` extension's `switch_m
549
549
  | `screen` | Creates one detached GNU Screen session for each child | `screen -r …` |
550
550
  | `localterm` | Creates one pinned LocalTerm PTY for each child | `localterm session attach …` |
551
551
  | `herdr` | Creates one background Herdr tab for each child | `herdr terminal attach …` |
552
- | `auto` | Tries Herdr, LocalTerm, tmux, screen, and then process | Depends on the transport |
552
+ | `herdr-core` | Creates one background Herdr Core terminal per child | `hc attach tN` |
553
+ | `auto` | Tries Herdr Core, Herdr, LocalTerm, tmux, screen, and then process | Depends on the transport |
554
+
555
+ Herdr Core (`herdr-core`) is a separate terminal service, not the Herdr workspace/tab API. Both explicit selection (`transport: "herdr-core"`) and auto-selection require the parent’s injected `HC_TERMINAL_ID` and `HC_TERMINAL_SOCKET`, and a reachable generation-1 service advertising terminal run/get/kill. Fabric uses only that socket (including native Windows pipe names); it does not search other sessions, start/restart the service, or require a CLI on PATH. Auto falls through safely when this context is missing, unreachable or incompatible; explicit selection reports unavailable. Each child receives direct argv and cwd, a unique sanitized name, and Core’s own child identity, not a copy of the parent’s environment. Launches disable typed parent notifications, waiting, keep/recovery, and outliving the parent. Handles report Core terminal addresses and `hc attach tN`; use `herdr-core attach tN` if the `hc` alias is absent, in the same Core session. Finished or removed terminals are not alive. Stop kills only that child; it does not remove retained output or mutate the service lifecycle. RPC failures other than a missing child remain visible. Existing Herdr status and session-label UI features still apply only to legacy Herdr.
553
556
 
554
557
  Herdr uses its local socket API to create an argv-backed background tab as one atomic operation. It does not change focus or require shell quoting. Automatic selection works only when the parent Pi process already runs in Herdr. This requires `HERDR_ENV=1` with an injected workspace and socket. Select `transport: "herdr"` under the same conditions. Use the attach command in the handle to open a child directly.
555
558
 
@@ -88,14 +88,24 @@ before sealing their log, regardless of extension shutdown order.
88
88
 
89
89
  ## Agent awareness and yielding
90
90
 
91
- Before each model request, Fabric projects one bounded live-task reminder into
92
- context, independently of the returned `fabric_exec` value. Even if a program
93
- discards the nested shell result, the owning agent can see that work is running.
94
- The reminder is reconstructed from live session state after context compaction;
95
- it is not a persisted transcript entry and **never triggers a turn** itself.
96
- Unchanged task state keeps the same message; elapsed time and process output do
97
- not churn it. It includes at most eight task IDs and short, quoted labels, with
98
- an omitted count for additional jobs.
91
+ When a task moves to the background, Fabric appends one note to the result of
92
+ the tool call that spilled it, independently of the returned `fabric_exec`
93
+ value. Even if a program discards the nested shell result, the owning agent can
94
+ see that work is running. Tasks spilled by one call share one note, which
95
+ includes at most eight task IDs and short, quoted labels, with an omitted count
96
+ for additional jobs, and never elapsed time or process output. The note
97
+ **never triggers a turn** itself.
98
+
99
+ The note records a moment and is never edited or retracted; later task events
100
+ report each outcome in transcript order. Fabric does not rewrite requests for
101
+ awareness, so each request extends the previous one and the provider's prompt
102
+ cache keeps hitting while tasks run. A reminder projected at the end of every
103
+ request would be missing from the next request in that position, which caps
104
+ the cached prefix at the last request without it. The note lives in an ordinary
105
+ tool result, not a custom message, because Pi rebuilds custom-message objects
106
+ on every refresh and its idle cache warmer, which compares objects by identity,
107
+ then treats the conversation as changed. After compaction, which replaces the
108
+ prefix anyway, Fabric restates still-running tasks on the next tool result.
99
109
 
100
110
  For ordinary detached commands and wake-enabled monitors, it tells the agent to
101
111
  continue independent work or **end the turn if it needs their results**. Completion
@@ -104,10 +114,12 @@ are unnecessary. UI-only monitors are explicitly marked **no automatic wakeup**,
104
114
  including on completion, so the agent must not yield expecting them to resume it.
105
115
  Pending required results are not evidence that the assignment is complete.
106
116
 
107
- Foreground, completed, stopping, and abandoned-branch jobs are excluded. Abort/error
108
- suspension suppresses the reminder until new input, just like automatic delivery.
109
- Reload/session shutdown removes the context hook along with the inbox. Awareness
110
- works without a terminal and does not restore processes across Pi restarts.
117
+ Foreground jobs, jobs that end before the next tool result, abandoned-branch
118
+ jobs, and durable tasks reattached after a restart are not announced; the
119
+ process that spilled a reattached task already wrote its note. A note stays on
120
+ its own branch of the session tree. Reload/session shutdown closes the inbox.
121
+ Awareness works without a terminal and does not restore processes across Pi
122
+ restarts.
111
123
 
112
124
  ### Prompt-cache warming while yielded
113
125
 
@@ -685,6 +685,8 @@ Fabric attributes each file through a `session_info` marker (`fabricagent-<name>
685
685
 
686
686
  ccusage's double-count guard rejects a named store that overlaps the default pi store, so the isolated-row form requires the separate directory.
687
687
 
688
+ `agents.transport` accepts `process` (default), `auto`, `tmux`, `screen`, `localterm`, `herdr`, and `herdr-core`; per-call `transport` uses the same values. Herdr Core requires the existing parent terminal’s `HC_TERMINAL_ID` and `HC_TERMINAL_SOCKET` plus a reachable generation-1 service. It never starts a server. `auto` tries Core before legacy Herdr and falls back when unavailable.
689
+
688
690
  See [agents, actors & mesh](agents.md) for the runner and transport details.
689
691
 
690
692
  ## MCP
package/docs/interface.md CHANGED
@@ -10,6 +10,8 @@ Nested `pi.read`, `pi.bash`, `pi.powershell`, `pi.grep`, `pi.find`, `pi.ls`, `pi
10
10
 
11
11
  Fabric keeps its orchestration-specific behavior around those previews. Multi-call rows stay compact, and live write composition with phase/call progress stays visible during the run. Agent and actor audits can expose their current child tools directly in the parent card, with owner, runner, and run metadata. One execution-wide throttle coalesces parallel nested-call updates before they reach Pi, and continuous streams are not starved. Long ANSI rows are bounded without clearing the enclosing tool background. The widget lease plus result-to-source row transfer keep completion height stable. The highlighter initializes lazily and falls back to plain text until it is ready. When Pi switches between its light and dark variants, the highlighter swaps themes live. Collapsed previews use the configured expand keybinding, for example `Ctrl-O`.
12
12
 
13
+ Successful internal `native.load` calls are hidden from ordinary tool rows and call totals, including partial updates, resumed cards, and dashboard summaries. Errors remain visible, and the raw audits and execution trace still record the calls. This is a presentation filter only: branch-local `load`/`store` behavior and commit ordering are unchanged. Built-in provider actions use scoped labels and bounded, allowlisted target metadata (for example `tasks.wait task-id`); stdin, credentials, arbitrary program input, and model state are not used as fallback labels.
14
+
13
15
  ## Terminal title
14
16
 
15
17
  In an interactive session, the terminal window/tab title carries the declared `fabric_exec` display name: `record release evidence`, `Apply migration`, and so on. Nested call detail such as `read src/config.ts · typescript` never reaches the window; it stays in the transcript and the activity surface, where there is room for it.
@@ -24,7 +26,7 @@ See [Background tasks and monitors](background-tasks.md) for completion delivery
24
26
 
25
27
  ## Agent list
26
28
 
27
- The Fabric widget sits at the bottom of the screen, below Pi's footer and a blank row, as in Claude Code. Its header is the main session's row: `● FAB-3` shows the session's [peer label](agents.md#peer-labels-and-queue-gates), followed by the current run's declared name and totals. A new session takes its label at its first Fabric use, so a session that has done nothing yet shows none. Without a label it reads `● Fabric`. A session with a label also shows it on the right of the editor's top border, in a badge like the one a conversation window shows for its target, whether or not the list is showing. While the list has no row to select, with no agent, actor worker, or shell task (idle actors have none), it takes no rows. The badge yields to Pi's own border text, such as a scroll indicator, and needs the list to be placed after the footer; otherwise the header row stays. Below it, running agents and actors are listed as a tree, above any background shell tasks, each child under its parent and indented by depth. Each row shows a circle, the participant's name, what it is doing, its model, tool calls, tokens, and elapsed time. What it is doing is the latest display name the agent declared for a `fabric_exec` call, which holds until it declares another; before that, the row shows the current tool or `thinking`. A finished row shows its result or error. The circle's colour is the status: accent while running, green when done, red on failure. Shell tasks list one per row after agents and actors, within the same row budget. Shell rows are selectable like agents: **Enter** or a click on a shell opens that task's detail with its output, status, and stop action. There is no secondary task-list overlay. **Esc** closes a task opened this way in one step, and focus returns to the list. Lines disclose progressively: when a line is too wide, its statistics drop first, then its title or activity is shortened, and its key hints go last. Pi gives extensions no slot below its footer, so Fabric registers an empty below-editor widget and places the list after the footer itself, in both the fullscreen and the regular renderer. Pi's footer and footers from other extensions stay as they are. In fullscreen mode, the list uses only the rows left after Pi's editor, other widgets (including Better OpenAI's status line), and footer, keeping at least one transcript row. It shrinks or temporarily disappears when those need the space, and returns when space is available. If Pi's layout is not the one Fabric expects, the list falls back to below the editor and stays last among the widgets other extensions place there. Press **↓** in an empty editor to move into the list; **ctrl+shift+e**, **`/fabric focus`**, or a click on a row also focuses it. The filled circle `●` marks the selected row, and **↑↓** or **j/k** moves it. **↑** on the top row returns to the editor. **Enter** or a click opens the participant's full conversation, where you can read its whole transcript, see its model and thinking level, and steer it or send a follow-up. Closing that view returns focus to the list. As in Claude Code, there is no inline preview: the conversation is where a participant's activity is shown. In Pi's fullscreen renderer, hovering the pointer over a row fills its circle too. Pi turns on hover tracking only outside tmux, zellij, and screen, and there is no event for leaving the widget, so the hover clears when the pointer crosses the header or the next key is pressed. **Esc** returns focus to the editor; while the list has focus, Esc does not halt background workers. Any other key returns focus to the editor and reaches it, so typing, Ctrl+C, and shortcuts keep working; only a click on a participant row takes focus. While it has focus, the list may grow past `ui.maxRows` to half of the terminal height, still bounded by the space left for it in the fullscreen dock. Arrow keys scroll within that bounded viewport, keeping every participant and task reachable. Unfocused overflow folds into a `+N` marker.
29
+ The Fabric widget sits at the bottom of the screen, below Pi's footer and a blank row, as in Claude Code. Its header is the main session's row: `● FAB-3` shows the session's [peer label](agents.md#peer-labels-and-queue-gates), followed by the current run's declared name and totals. A new session takes its label at its first Fabric use, so a session that has done nothing yet shows none. Without a label it reads `● Fabric`. A session with a label also shows it on the right of the editor's top border, in a badge like the one a conversation window shows for its target, whether or not the list is showing. While the list has no row to select, with no agent, actor worker, or shell task (idle actors have none), it takes no rows. The badge yields to Pi's own border text, such as a scroll indicator, and needs the list to be placed after the footer; otherwise the header row stays. Below it, running agents and actors are listed as a tree, above any background shell tasks, each child under its parent and indented by depth. Each row shows a circle, the participant's name, what it is doing, its model, tool calls, tokens, and elapsed time. What it is doing is the latest display name the agent declared for a `fabric_exec` call, which holds until it declares another; before that, the row shows the current tool or `thinking`. A finished row shows its result or error. The circle's colour is the status: accent while running, green when done, red on failure. Shell tasks list one per row after agents and actors, within the same row budget. Shell rows are selectable like agents: **Enter** or a click on a shell opens that task's detail with its output, status, and stop action. There is no secondary task-list overlay. **Esc** closes a task opened this way in one step, and focus returns to the list. Lines disclose progressively: when a line is too wide, its statistics drop first, then its title or activity is shortened, and its key hints go last. Pi gives extensions no slot below its footer, so Fabric registers an empty below-editor widget and places the list after the footer itself, in both the fullscreen and the regular renderer. Pi's footer and footers from other extensions stay as they are. In fullscreen mode, the list uses only the rows left after Pi's editor, other widgets (including Better OpenAI's status line), and footer, keeping at least one transcript row. It shrinks or temporarily disappears when those need the space, and returns when space is available. If Pi's layout is not the one Fabric expects, the list falls back to below the editor and stays last among the widgets other extensions place there. Press **↓** in an empty editor to move into the list; **ctrl+shift+e**, **`/fabric focus`**, or a click on a row also focuses it. The filled circle `●` marks the selected row, and **↑↓** or **j/k** moves it. **↑** on the top row returns to the editor. **Enter** or a click opens the participant's full conversation, where you can read its whole transcript, see its model and thinking level, and steer it or send a follow-up. Closing that view returns focus to the list. As in Claude Code, there is no inline preview: the conversation is where a participant's activity is shown. In Pi's fullscreen renderer, hovering the pointer over a row fills its circle too. Pi turns on hover tracking only outside tmux, zellij, and screen, and there is no event for leaving the widget, so the hover clears when the pointer crosses the header or the next key is pressed. **Esc** returns focus to the editor; while the list has focus, Esc does not halt background workers. Any other key returns focus to the editor and reaches it, so typing, Ctrl+C, and shortcuts keep working; only a click on a participant row takes focus. The list never grows past `ui.maxRows` on focus and remains bounded by half the terminal height and the space left in the fullscreen dock. Arrow keys and the mouse wheel over the list scroll within that viewport, keeping every participant and task reachable without moving the footer. When content overflows, a bottom cue row stays reserved across the whole scroll range: `↓ N more` appears there while children remain below, and the row is blank at the end. `↑ N more` appears in the main header when children are above the viewport. Very short viewports prioritize the header and a reachable child over the cue. Short or idle lists do not reserve a large empty area.
28
30
 
29
31
  ## Focused conversations
30
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-fabric",
3
- "version": "0.131.1",
3
+ "version": "0.131.3",
4
4
  "description": "A programmable tool and agent runtime for Pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -143,9 +143,9 @@
143
143
  "image": "https://raw.githubusercontent.com/fabric-runtime/pi-fabric/main/media/banner.svg"
144
144
  },
145
145
  "dependencies": {
146
- "@earendil-works/chord": "1.4.0",
147
- "@earendil-works/pi-codemode": "1.4.0",
148
- "@earendil-works/pi-durable": "1.4.0",
146
+ "@earendil-works/chord": "1.5.0",
147
+ "@earendil-works/pi-codemode": "1.5.0",
148
+ "@earendil-works/pi-durable": "1.5.0",
149
149
  "@jitl/quickjs-singlefile-mjs-release-sync": "^0.32.0",
150
150
  "@lezer/common": "^1.5.2",
151
151
  "@lezer/python": "^1.1.19",
@@ -155,7 +155,7 @@
155
155
  "cross-spawn": "^7.0.6",
156
156
  "diff": "^9.0.0",
157
157
  "mcporter": "^0.12.3",
158
- "pi-fabric-worker-sdk": "npm:@earendil-works/pi-coding-agent@1.4.0",
158
+ "pi-fabric-worker-sdk": "npm:@earendil-works/pi-coding-agent@1.5.0",
159
159
  "quickjs-emscripten-core": "^0.32.0",
160
160
  "shiki": "4.4.3",
161
161
  "typescript": "^6.0.3",
@@ -172,10 +172,10 @@
172
172
  "@earendil-works/pi-durable": ">=1.4.0"
173
173
  },
174
174
  "devDependencies": {
175
- "@earendil-works/pi-agent-core": "1.4.0",
176
- "@earendil-works/pi-ai": "1.4.0",
177
- "@earendil-works/pi-coding-agent": "1.4.0",
178
- "@earendil-works/pi-tui": "1.4.0",
175
+ "@earendil-works/pi-agent-core": "1.5.0",
176
+ "@earendil-works/pi-ai": "1.5.0",
177
+ "@earendil-works/pi-coding-agent": "1.5.0",
178
+ "@earendil-works/pi-tui": "1.5.0",
179
179
  "@types/cross-spawn": "^6.0.6",
180
180
  "@types/node": "^26.1.2",
181
181
  "esbuild": "^0.25.12",
@@ -21,7 +21,7 @@ For Pi leaf or recursive agents, selecting `cwd` neither grants nor requires pro
21
21
  - `runner` is `pi`, `claude`, or `veda` and defaults to `agents.runner` (`pi`). The `veda` runner drives the Veda CLI as a one-shot headless child; `agents.veda.backend` selects Veda’s underlying CLI (`agy`, `codex`, `claude-code`, `droid`, `pi`, or another backend registered by the installed Veda build), while `persona` selects its behavior. An explicit `agents.run({ model })` overrides `agents.veda.model`; if both are omitted, Veda selects its backend default (see `docs/agents.md`). Extensions may register more runner ids through `pi-fabric/runners`; requests needing a capability the runner does not declare fail before launch. A result with `outcome: "indeterminate"` means Fabric cannot confirm whether the work ran; it is never retried automatically, so inspect before re-running.
22
22
  - `kernel` is `"typescript"`, `"python"`, or `"inherit"`. Omitted/`inherit` takes the caller's `executor.kernel`; a concrete value lets the model or skill choose its strongest language for the **child**. It never switches the current `fabric_exec` program. Concrete values require Pi with Fabric extensions; Claude/Veda/`extensions: false` reject them, while omitted/`inherit` leaves those runners native with no `kernel` in status. Supported handles/results/status expose the resolved language. Workflow, RLM, and council requests forward `kernel` too. Python uses the caller's configured `executor.pythonRuntime` backend (`monty` by default); there is no public per-request backend selector. Monty is sandboxed and fails closed if its optional dependency is missing. CPython requires explicit configuration and outside schema enforce is trusted native code, not QuickJS isolation.
23
23
  - The caller's resolved language and configured Python backend are frozen before worker launch or durable/trajectory transfer. Recursive and alternate-cwd children inherit them through validated worker environment overrides after config merge, not the destination cwd's language defaults. Explicit kernels and inherited Python ensure Fabric is loaded even outside full-code mode. See [execution kernels](../../../../docs/kernels.md).
24
- - `transport` is one of `auto`, `process`, `tmux`, `screen`, `localterm`, `herdr` (default `process`). `auto` tries Herdr when the parent runs inside a Herdr workspace, then LocalTerm, tmux, screen, and process.
24
+ - `transport` is one of `auto`, `process`, `tmux`, `screen`, `localterm`, `herdr`, `herdr-core` (default `process`). `auto` first tries Herdr Core with injected `HC_TERMINAL_ID`/`HC_TERMINAL_SOCKET` and a reachable generation-1 service, then Herdr inside a Herdr workspace, LocalTerm, tmux, screen, and process. Explicit `herdr-core` requires the same Core context; it never starts a server. Core handles use terminal addresses and `hc attach tN`, not workspace/tab/pane IDs.
25
25
  - Pi `model` values resolve only within the execution owner's visible `tools.models()` / `agents.models({ runner: "pi" })` set; omitted uses `agents.model` or inherits the host model. Explicit values go through the `agents.switchModel` selector resolution: `models.aliases` names, exact matches, then the closest fuzzy match (pi-model-sort recency ties break toward the recently used model). Unresolved values and exhausted aliases fail before launch, and actor defaults or per-activation overrides are revalidated at their actual owner. Catalog-fresh or custom ids must first be visible in that registry. Claude values are `claude/<value>` keys from `agents.models({ runner: "claude" })`; omitted uses `agents.claude.model` or Claude Code's runtime default. Veda model strings continue to pass through to its backend unchanged. `agents.models()` defaults to the configured runner; `agents.models({ runner, model })` returns only the entries whose `key` equals `model` exactly (no alias or fuzzy resolution, `[]` when absent); Claude discovery is a local CLI control handshake and makes no model inference request.
26
26
  - `modelMatch: "exact"` (Pi runners only) selects a listed `provider/id` without aliases, closest or fuzzy matching, or alias thinking. Missing, malformed or unlisted models and non-Pi runners are refused before launch; `handoff`, `create`, and actor activations do not accept it. Admission is strict, and a child guard detects session model switches and some rewrites of known API payloads. **This is not a security guarantee or final-dispatch enforcement:** later hooks, unknown API payloads, providers and extension-made calls can route data elsewhere. Attribution may detect drift only after a call; do not rely on this mode to prevent data disclosure. See `docs/agents.md`. Omit `modelMatch` for default resolution.
27
27
  - `systemPrompt` is appended to the child's system prompt (Veda gets it as a `<system_instructions>` block); blank is ignored and durable `spawn` refuses it.
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/durable/worker-host.ts", "../../src/durable/extension-load-error.ts", "../../src/durable/session.ts", "../../src/durable/agent.ts", "../../src/durable/storage.ts"],
4
- "sourcesContent": ["import { createHash, randomUUID } from \"node:crypto\";\nimport { lstat, readdir, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport {\n AgentSessionRuntime, createAgentSessionServices, createCodemodeExtension,\n createMcpExtension, createToolSearchExtension, ExtensionRunner, getAgentDir,\n hasTrustRequiringProjectResources, ProjectTrustStore, resolveCliModel,\n runRpcMode, SessionManager, SettingsManager,\n type CreateAgentSessionRuntimeFactory, type LoadExtensionsResult,\n type ProjectTrustContext, type ProjectTrustHandler,\n} from \"@earendil-works/pi-coding-agent\";\nimport { nativeFabricExecExclusions } from \"../core/child-tool-allowlist.js\";\nimport { durableExtensionLoadError } from \"./extension-load-error.js\";\nimport { createDurableAgentSession } from \"./session.js\";\nimport { openDurableWorkerStorage } from \"./storage.js\";\nimport type { DurableWorkerOptions } from \"./worker-options.js\";\n\n// A fabric_exec crash journal holds tool results, so it is deleted a day after\n// its last write. A call still waiting after that cannot resume and fails closed.\nconst FABRIC_JOURNAL_RETENTION_MS = 24 * 60 * 60 * 1000;\n\n/** Delete fabric_exec journals older than the retention window. Exported for tests. */\nexport async function sweepFabricJournals(directory: string, now = Date.now()): Promise<void> {\n let names: string[];\n try {\n names = await readdir(directory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n for (const name of names) {\n if (!/^[0-9a-f]{32}\\.jsonl$/.test(name)) continue;\n const file = path.join(directory, name);\n const info = await lstat(file).catch(() => undefined);\n if (info?.isFile() && now - info.mtimeMs > FABRIC_JOURNAL_RETENTION_MS) await unlink(file).catch(() => undefined);\n }\n}\n\n/** Match native headless trust: only global/explicit extensions can decide trust. */\nexport async function resolveDurableProjectTrust(options: {\n cwd: string; agentDir: string; extensionsResult: LoadExtensionsResult;\n defaultProjectTrust: \"ask\" | \"always\" | \"never\";\n}): Promise<boolean> {\n if (!hasTrustRequiringProjectResources(options.cwd)) return true;\n const store = new ProjectTrustStore(options.agentDir);\n const context: ProjectTrustContext = {\n cwd: options.cwd, mode: \"rpc\", hasUI: false,\n ui: { select: async () => undefined, confirm: async () => false,\n input: async () => undefined, notify: message => process.stderr.write(`${message}\\n`) },\n };\n for (const extension of options.extensionsResult.extensions) {\n for (const handler of extension.handlers.get(\"project_trust\")?.slice() ?? []) {\n try {\n const result = await (handler as ProjectTrustHandler)({ type: \"project_trust\", cwd: options.cwd }, context);\n if (result?.trusted !== \"yes\" && result?.trusted !== \"no\") continue;\n const trusted = result.trusted === \"yes\";\n if (result.remember === true) store.set(options.cwd, trusted);\n return trusted;\n } catch (error) {\n process.stderr.write(`Extension ${extension.path} project_trust error: ${String(error)}\\n`);\n }\n }\n }\n return store.get(options.cwd) ?? options.defaultProjectTrust === \"always\";\n}\n\n// Sessions here run on the pinned worker SDK, a class identity Fabric's tool\n// capture cannot locate by itself (see HOST_RUNNERS_SYMBOL in\n// src/capture/interceptor.ts). Advertise it before extensions load. A global\n// stays process-local, unlike an environment variable; it is inline so the\n// extension's startup graph gains no chunk shared with this worker module.\nconst advertiseHostExtensionRunner = (): void => {\n const key = Symbol.for(\"pi-fabric.host-extension-runners.v1\");\n const holder = globalThis as typeof globalThis & { [key: symbol]: Set<unknown> | undefined };\n (holder[key] ??= new Set()).add(ExtensionRunner);\n};\n\ninterface PiHttpDispatcher {\n applyHttpProxySettings(httpProxy: string | undefined): void;\n configureHttpDispatcher(timeoutMs?: number): void;\n}\nlet piHttpDispatcher: Promise<PiHttpDispatcher> | undefined;\n\n/**\n * Apply the HTTP policy Pi's CLI applies at startup: the global `httpProxy`\n * setting, then a proxy-aware dispatcher honoring HTTP(S)_PROXY, NO_PROXY and\n * the idle timeout. The SDK does not export this bootstrap, so load the pinned\n * SDK's own module beside its entry instead of copying the proxy logic (#270).\n */\nexport async function configureDurableHttp(settings: SettingsManager): Promise<void> {\n piHttpDispatcher ??= import(\n new URL(\"./core/http-dispatcher.js\", import.meta.resolve(\"@earendil-works/pi-coding-agent\")).href\n ) as Promise<PiHttpDispatcher>;\n const { applyHttpProxySettings, configureHttpDispatcher } = await piHttpDispatcher;\n applyHttpProxySettings(settings.getGlobalSettings().httpProxy);\n configureHttpDispatcher(settings.getHttpIdleTimeoutMs());\n}\n\n/** A full native Pi runtime host whose Agent scheduling is owned by pi-durable. */\nexport async function createDurableWorkerRuntime(options: DurableWorkerOptions): Promise<AgentSessionRuntime> {\n advertiseHostExtensionRunner();\n const cwd = process.cwd();\n const agentDir = getAgentDir();\n const manager = options.sessionFile ? SessionManager.open(options.sessionFile, undefined, cwd) : SessionManager.inMemory(cwd);\n let current: { close(): Promise<void> } | undefined;\n const initialSessionId = manager.getSessionId();\n let first = true;\n const closeCurrent = async () => {\n const previous = current;\n current = undefined;\n await previous?.close();\n };\n const factory: CreateAgentSessionRuntimeFactory = async target => {\n // The native runtime already aborts, emits shutdown, and disposes the old session.\n await closeCurrent();\n const settings = SettingsManager.create(target.cwd, target.agentDir, { projectTrusted: false });\n await configureDurableHttp(settings);\n const services = await createAgentSessionServices({\n cwd: target.cwd, agentDir: target.agentDir, settingsManager: settings,\n modelRuntimeSignal: AbortSignal.timeout(15_000),\n resourceLoaderReloadOptions: {\n resolveProjectTrust: ({ extensionsResult }) => resolveDurableProjectTrust({\n cwd: target.cwd, agentDir: target.agentDir, extensionsResult,\n defaultProjectTrust: settings.getDefaultProjectTrust(),\n }),\n },\n resourceLoaderOptions: {\n additionalExtensionPaths: options.extensions,\n noExtensions: options.noExtensions,\n noSkills: options.noSkills,\n additionalSkillPaths: options.skills,\n appendSystemPrompt: options.appendSystemPrompt ? [options.appendSystemPrompt] : [],\n extensionFactories: [\n { name: \"codemode\", factory: createCodemodeExtension(), builtin: true, replaceable: true },\n { name: \"tool-search\", factory: createToolSearchExtension(), builtin: true, replaceable: true },\n { name: \"mcp\", factory: createMcpExtension(), builtin: true, replaceable: true },\n ],\n },\n });\n const extensionErrors = services.resourceLoader.getExtensions().errors;\n if (extensionErrors.length) throw durableExtensionLoadError(extensionErrors);\n for (const diagnostic of services.diagnostics) {\n process.stderr.write(`${diagnostic.type}: ${diagnostic.message}\\n`);\n }\n const selection = resolveCliModel({\n ...(options.model ? { cliModel: options.model } : {}),\n ...(options.provider ? { cliProvider: options.provider } : {}),\n ...(options.thinking ? { cliThinking: options.thinking } : {}),\n modelRuntime: services.modelRuntime,\n });\n if (selection.error) throw new Error(selection.error);\n if (selection.warning) process.stderr.write(`${selection.warning}\\n`);\n // The initial run path is stable even for non-exported sessions on restart.\n // Native /new, /fork, and /resume receive separate durable conversation stores.\n const recoverInitialRequest = first;\n const sessionId = target.sessionManager.getSessionId();\n const key = sessionId === initialSessionId ? \"initial\" : createHash(\"sha256\").update(sessionId).digest(\"hex\");\n first = false;\n const lease = await openDurableWorkerStorage(path.join(options.directory, key));\n try {\n // Beside store/, which must hold only pi-durable's own files.\n const fabricJournalDirectory = path.join(options.directory, key, \"fabric-journal\");\n await sweepFabricJournals(fabricJournalDirectory);\n const host = await createDurableAgentSession({\n fabricJournalDirectory,\n ...services, sessionManager: target.sessionManager,\n ...(target.sessionStartEvent ? { sessionStartEvent: target.sessionStartEvent } : {}),\n storage: lease.storage, runId: `${options.runId}:${key}`,\n ...(selection.model ? { model: selection.model } : {}),\n ...((options.thinking ?? selection.thinkingLevel) ? { thinkingLevel: (options.thinking ?? selection.thinkingLevel)! } : {}),\n ...(options.tools ? { tools: options.tools } : {}),\n // Apply after wildcard expansion, including /new, /fork and /resume.\n excludeTools: [...(options.excludeTools ?? []), ...nativeFabricExecExclusions(options.tools)],\n ...(options.noTools ? { noTools: options.noTools } : {}),\n });\n // A normal /new, /fork, or /resume is a new request, not crash recovery\n // of this store's original submission. Keep its journal but admit new work.\n if (!recoverInitialRequest) host.agent.setRequestId(randomUUID());\n current = { close: async () => {\n try { await host.agent.close(); }\n finally {\n try { await lease.storage.close(BACKGROUND_CONTEXT); }\n finally { await lease.release(); }\n }\n } };\n return { session: host.session, extensionsResult: services.resourceLoader.getExtensions(), services, diagnostics: services.diagnostics };\n } catch (error) {\n try { await lease.storage.close(BACKGROUND_CONTEXT); } finally { await lease.release(); }\n throw error;\n }\n };\n const initial = await factory({ cwd, agentDir, sessionManager: manager });\n class DurableRuntime extends AgentSessionRuntime {\n override async dispose(): Promise<void> {\n try { await super.dispose(); } finally { await closeCurrent(); }\n }\n }\n return new DurableRuntime(initial.session, initial.services, factory, initial.diagnostics);\n}\n\nexport async function runDurableWorker(options: DurableWorkerOptions): Promise<void> {\n const runtime = await createDurableWorkerRuntime(options);\n try { await runRpcMode(runtime); }\n finally { await runtime.dispose(); }\n}\n", "/** One extension load failure as reported by the SDK resource loader. */\nexport interface DurableExtensionLoadFailure { path: string; error: string }\n\n// The pinned worker SDK aliases \"typebox\" to its single entry file, and jiti treats an\n// alias as a path prefix, so a subpath import fails as \"<.../typebox/...>.mjs/<subpath>\".\nconst TYPEBOX_ALIAS_FAILURE = /Cannot find module '[^']*[\\\\/]typebox[\\\\/][^']*\\.[cm]?js[\\\\/][^']+'/;\n\n/** Build the fatal durable worker error, naming the typebox alias cause when it applies. */\nexport function durableExtensionLoadError(errors: readonly DurableExtensionLoadFailure[]): Error {\n const message = `Durable worker extension loading failed: ${JSON.stringify(errors)}`;\n if (!errors.some(failure => TYPEBOX_ALIAS_FAILURE.test(failure.error))) return new Error(message);\n return new Error(`${message}\\nAn extension imported a typebox subpath that the durable worker cannot resolve, because the worker SDK aliases \"typebox\" to a single file; import from the \"typebox\" root instead, or use runner \"pi\".`);\n}\n", "// Worker-only: keep the SDK and durable engine out of Fabric's registration graph.\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { AgentOptions, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel } from \"@earendil-works/pi-ai/compat\";\nimport type { Storage } from \"@earendil-works/pi-durable\";\nimport {\n AgentSession, convertToLlm, DefaultResourceLoader, getAgentDir, ModelRuntime,\n SessionManager, SettingsManager,\n type CreateAgentSessionOptions, type ExtensionRunner,\n} from \"@earendil-works/pi-coding-agent\";\nimport { DurableAgent } from \"./agent.js\";\nimport { resolveNativeToolSelection } from \"../core/child-tool-allowlist.js\";\n\nconst absolute = (path: string) => resolve(path === \"~\" ? homedir() : path.startsWith(\"~/\") ? join(homedir(), path.slice(2)) : path);\n\n/**\n * Public-SDK host for a durable agent. AgentSession remains responsible for native\n * tool provenance/loadouts, extension tool hooks, request routing, and history.\n * Like createAgentSession, this does not bind extensions: the host calls\n * session.bindExtensions() with its mode/UI/error bindings before prompting.\n * Storage is borrowed; close settles this host but does not close its storage.\n */\nexport async function createDurableAgentSession(\n options: CreateAgentSessionOptions & { storage: Storage; runId: string; fabricJournalDirectory?: string },\n): Promise<{ session: AgentSession; agent: DurableAgent; close(): Promise<void> }> {\n if (!options.runId.trim()) throw new Error(\"A durable session requires a non-empty runId\");\n const cwd = absolute(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n const agentDir = absolute(options.agentDir ?? getAgentDir());\n const modelRuntime = options.modelRuntime ?? await ModelRuntime.create({\n authPath: join(agentDir, \"auth.json\"), modelsPath: join(agentDir, \"models.json\"),\n });\n const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n const sessionManager = options.sessionManager ?? SessionManager.create(\n cwd, join(agentDir, \"sessions\", `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`),\n );\n let resourceLoader = options.resourceLoader;\n if (!resourceLoader) {\n resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n await resourceLoader.reload();\n }\n\n const existing = sessionManager.buildSessionContext();\n const branch = sessionManager.getBranch();\n const hasHistory = existing.messages.length > 0;\n const hasThinking = branch.some(entry => entry.type === \"thinking_level_change\");\n // A virtual selection is recorded in model_change, not the physical response.\n const lastSelection = branch.slice().reverse().find(entry => entry.type === \"model_change\");\n const selected = lastSelection?.type === \"model_change\"\n ? modelRuntime.getModel(lastSelection.provider, lastSelection.modelId) : undefined;\n const saved = selected?.api === \"pi-virtual\" ? selected : existing.model\n ? modelRuntime.getModel(existing.model.provider, existing.model.modelId) : undefined;\n let model = options.model;\n if (!model && hasHistory && (lastSelection || existing.model)) {\n if (!saved || (saved.api !== \"pi-virtual\" && !modelRuntime.hasConfiguredAuth(saved.provider))) {\n throw new Error(\"Cannot restore durable session model; explicitly select an available model\");\n }\n model = saved;\n }\n if (!model) {\n const available = await modelRuntime.getAvailable();\n const provider = settingsManager.getDefaultProvider();\n const modelId = settingsManager.getDefaultModel();\n model = provider || modelId\n ? available.find(candidate => (!provider || candidate.provider === provider) && (!modelId || candidate.id === modelId))\n : available[0];\n if (!model && (provider || modelId)) throw new Error(`Configured durable model is unavailable: ${provider ?? \"*\"}/${modelId ?? \"*\"}`);\n }\n if (!model) throw new Error(\"No available model for durable session; supply model and modelRuntime\");\n const savedThinking = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"].includes(existing.thinkingLevel)\n ? existing.thinkingLevel as ThinkingLevel : \"medium\";\n const thinkingLevel = clampThinkingLevel(model, options.thinkingLevel ??\n (hasHistory ? (hasThinking ? savedThinking : settingsManager.getDefaultThinkingLevel() ?? \"medium\") : undefined) ??\n settingsManager.getModelThinkingLevel(model.provider, model.id) ?? settingsManager.getDefaultThinkingLevel() ?? \"medium\");\n\n const extensionRunnerRef: { current?: ExtensionRunner } = {};\n const agentOptions: AgentOptions = {\n initialState: { systemPrompt: \"\", model, thinkingLevel, tools: [], messages: existing.messages },\n convertToLlm: messages => {\n const converted = convertToLlm(messages);\n if (!settingsManager.getBlockImages()) return converted;\n return converted.map(message => {\n if ((message.role !== \"user\" && message.role !== \"toolResult\") || !Array.isArray(message.content)) return message;\n return { ...message, content: message.content.map(part => part.type === \"image\"\n ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : part) };\n });\n },\n transformContext: async messages => extensionRunnerRef.current?.emitContext(messages) ?? messages,\n streamFn: (requestModel, context, requestOptions = {}) => {\n const retry = settingsManager.getProviderRetrySettings();\n const idleTimeout = settingsManager.getHttpIdleTimeoutMs();\n const websocketConnectTimeoutMs = requestOptions.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n const maxRetries = requestOptions.maxRetries ?? retry.maxRetries;\n return modelRuntime.streamSimple(requestModel, context, {\n ...requestOptions,\n timeoutMs: requestOptions.timeoutMs ?? retry.timeoutMs ?? (idleTimeout === 0 ? 2147483647 : idleTimeout),\n ...(websocketConnectTimeoutMs !== undefined ? { websocketConnectTimeoutMs } : {}),\n ...(maxRetries !== undefined ? { maxRetries } : {}),\n maxRetryDelayMs: requestOptions.maxRetryDelayMs ?? retry.maxRetryDelayMs,\n transformHeaders: async headers => {\n const transformed = headers;\n const runner = extensionRunnerRef.current;\n return runner?.hasHandlers(\"before_provider_headers\")\n ? runner.emitBeforeProviderHeaders(transformed ?? {}) : transformed ?? {};\n },\n });\n },\n onPayload: async payload => {\n const runner = extensionRunnerRef.current;\n return runner?.hasHandlers(\"before_provider_request\") ? runner.emitBeforeProviderRequest(payload) : payload;\n },\n onResponse: async response => {\n const runner = extensionRunnerRef.current;\n if (runner?.hasHandlers(\"after_provider_response\")) {\n await runner.emit({ type: \"after_provider_response\", status: response.status, headers: response.headers });\n }\n },\n onProviderStreamEvent: async (data, requestModel) => {\n const runner = extensionRunnerRef.current;\n if (runner?.hasHandlers(\"provider_stream_event\")) {\n await runner.emit({ type: \"provider_stream_event\", data, provider: requestModel.provider, api: requestModel.api, model: requestModel.id });\n }\n },\n sessionId: sessionManager.getSessionId(),\n steeringMode: settingsManager.getSteeringMode(), followUpMode: settingsManager.getFollowUpMode(),\n transport: settingsManager.getTransport(),\n ...(settingsManager.getThinkingBudgets() ? { thinkingBudgets: settingsManager.getThinkingBudgets()! } : {}),\n ...(settingsManager.getProviderRetrySettings().maxRetryDelayMs !== undefined\n ? { maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs! } : {}),\n };\n // Harness owns its adapter lifecycle, not the worker's lease/storage lifetime.\n // Bind methods to the original instance (storage adapters may use private fields).\n const borrowedStorage = new Proxy(options.storage, {\n get(target, property) {\n if (property === \"close\") return async () => {};\n const value = Reflect.get(target, property, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n const agent = new DurableAgent({\n ...agentOptions, models: modelRuntime, storage: borrowedStorage, runId: options.runId,\n ...(options.fabricJournalDirectory ? { fabricJournalDirectory: options.fabricJournalDirectory } : {}),\n });\n try {\n if (!hasHistory) sessionManager.appendModelChange(model.provider, model.id);\n if (!hasHistory || !hasThinking) sessionManager.appendThinkingLevelChange(thinkingLevel);\n const excluded = new Set(options.excludeTools);\n const selection = resolveNativeToolSelection(options.tools,\n settingsManager.getDefaultTools() ?? [\"read\", \"bash\", \"edit\", \"write\"], options.noTools);\n const session = new AgentSession({\n agent, cwd, sessionManager, settingsManager, resourceLoader, modelRuntime,\n extensionRunnerRef,\n ...(options.customTools ? { customTools: options.customTools } : {}),\n ...(options.scopedModels ? { scopedModels: options.scopedModels } : {}),\n ...(options.sessionStartEvent ? { sessionStartEvent: options.sessionStartEvent } : {}),\n initialActiveToolNames: selection.active.filter(name => !excluded.has(name)),\n usesDefaultTools: options.tools === undefined && !options.noTools,\n ...(selection.allowed ? { allowedToolNames: selection.allowed } : {}),\n ...(options.excludeTools ? { excludedToolNames: options.excludeTools } : {}),\n });\n agent.recoverHistory = messages => {\n // Do not redeliver message_end: it runs extension hooks and accounts usage.\n // Match against source entries as well as the projection: compaction and\n // context edits can hide a committed message without making it missing.\n const key = (message: unknown) => JSON.stringify(message);\n const projected = sessionManager.buildSessionContext().messages;\n const branch = sessionManager.getBranch();\n const counts = (values: string[]) => {\n const result = new Map<string, number>();\n for (const value of values) result.set(value, (result.get(value) ?? 0) + 1);\n return result;\n };\n const present = counts(projected.map(key));\n for (const [value, count] of counts(branch.flatMap(entry => entry.type === \"message\" ? [key(entry.message)] : []))) {\n present.set(value, Math.max(present.get(value) ?? 0, count));\n }\n // Count occurrences, not just values: repeated identical messages are valid.\n const seen = new Map<string, number>();\n let end = 0;\n messages.forEach((message, index) => {\n const value = key(message); const count = (seen.get(value) ?? 0) + 1;\n seen.set(value, count);\n if ((present.get(value) ?? 0) >= count) end = index + 1;\n });\n const missing = messages.slice(end);\n // A deliberate branch switch must not resurrect the abandoned branch.\n const branchIds = new Set(branch.map(entry => entry.id));\n const elsewhere = new Set(sessionManager.getEntries().flatMap(entry =>\n entry.type === \"message\" && !branchIds.has(entry.id) ? [key(entry.message)] : []));\n if (!missing.some(message => elsewhere.has(key(message)))) {\n for (const message of missing) {\n if (message.role === \"compactionSummary\") {\n sessionManager.appendCompaction(message.summary, null, message.tokensBefore);\n } else if (message.role === \"branchSummary\") {\n sessionManager.branchWithSummary(sessionManager.getLeafId(), message.summary);\n } else {\n sessionManager.appendMessage(message);\n }\n }\n }\n // Keep the native projection (including context edits/compaction) canonical.\n agent.state.messages = sessionManager.buildSessionContext().messages;\n };\n const steer = session.steer.bind(session);\n session.steer = async (...args) => { const result = await steer(...args); await agent.awaitControls(); return result; };\n const followUp = session.followUp.bind(session);\n session.followUp = async (...args) => { const result = await followUp(...args); await agent.awaitControls(); return result; };\n let closing: Promise<void> | undefined;\n return { session, agent, close: () => closing ??= (async () => {\n try {\n await session.abort();\n await session.extensionRunner.emit({ type: \"session_shutdown\", reason: \"quit\" });\n } finally {\n try { session.dispose(); } finally { await agent.close(); }\n }\n })() };\n } catch (error) {\n await agent.close();\n throw error;\n }\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport { unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport type { JsonValue } from \"@earendil-works/chord\";\nimport { Agent, runToolCall, type AgentOptions, type AgentEvent, type AgentMessage, type AgentState, type AgentTurnContext, type AgentContext, type AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { getCurrentSystemMessage, getCurrentTools, getToolStateChanges, toToolDeclaration, normalizeContext } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, ImageContent, Message, Models, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport { Harness, createRegistry, defineDoc, defineTask, type Storage, type TaskId, type Tx, type Conversation } from \"@earendil-works/pi-durable\";\n\n// This is deliberately a worker-only module. The Harness scheduler owns both\n// requests and tool invocations; no native Agent loop runs behind this adapter.\nconst EVENT = \"fabric.agent.event.v1\";\nconst HISTORY = \"fabric.agent.history.v1\";\nconst copy = <T>(value: T): T => JSON.parse(JSON.stringify(value));\nconst wire = (value: unknown): JsonValue => copy(value) as JsonValue;\n// Streaming updates are presentation only: recovery never replays them (open()\n// reads HISTORY plus agent_start/message_end), and each provider partial or tool\n// partialResult repeats everything streamed before it. Persisting those payloads\n// grows a run's journal quadratically. Commit a slim, ordered marker instead and\n// rehydrate the payload in memory when that commit is delivered.\ntype TransientEvent = Extract<AgentEvent, { type: \"message_update\" | \"tool_execution_update\" }>;\nconst TRANSIENT = \"fabricTransient\";\nconst Ledger = defineDoc<{\n runId: string; requests: Record<string, number>; active: number;\n controls?: Record<string, boolean>;\n context?: { messages: JsonValue[]; tools: string[] };\n config?: { model: JsonValue; thinking: AgentState[\"thinkingLevel\"] };\n steering: JsonValue[]; followup: JsonValue[];\n}>({ kind: \"fabric.agent.ledger\", version: 1, scope: \"conversation\", history: \"latest\", fork: \"initial\",\n initial: () => ({ runId: \"\", requests: {}, active: 0, steering: [], followup: [] }),\n checkpointWhen: () => true });\n\ntype RunInput = { request: string };\ntype Checkpoint =\n | { phase: \"prepare\"; next?: Omit<AgentTurnContext, \"context\">; pending?: AgentMessage[]; skipSteering?: boolean }\n | { phase: \"model\"; messages: Message[]; model: AgentState[\"model\"]; thinking: AgentState[\"thinkingLevel\"] }\n | { phase: \"tools\"; message: AssistantMessage; children: TaskId<ToolResultMessage>[] }\n | { phase: \"boundary\"; message: AssistantMessage; results: ToolResultMessage[]; terminate?: boolean }\n | { phase: \"decide\"; message: AssistantMessage; results: ToolResultMessage[]; action?: \"end\" | \"continue\"; terminate?: boolean };\ntype ToolInput = { replaySafe?: boolean; message: AssistantMessage; call: Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }> };\ntype ToolCheckpoint = { phase: \"execute\" };\n// The Fabric extension can be another module instance in this process, so it\n// reads the fence through this global. It is inline so neither startup graph\n// gains a chunk shared with this worker module.\ntype ToolFence = {\n toolCallId: string; accept(): Promise<void>; arm(): Promise<void>;\n journal?: { path: string; digest?: string; accept(digest: string): Promise<void> };\n};\n// Each resume replays the journal and runs live from where it stopped. A program\n// that keeps crashing its process before recording progress must not loop.\nconst MAX_JOURNAL_RESUMES = 3;\n\nconst fabricJournalPath = (directory: string, taskId: string, callId: string): string =>\n path.join(directory, `${createHash(\"sha256\").update(`${taskId}\\0${callId}`).digest(\"hex\").slice(0, 32)}.jsonl`);\n\n// A fabric_exec journal holds tool results. Delete it once the call's terminal\n// result is committed; a crash before this leaves it to the worker's sweep.\nasync function removeFabricJournal(file: string): Promise<void> {\n await unlink(file).catch(() => undefined);\n}\nconst toolFences = (): AsyncLocalStorage<ToolFence | undefined> => {\n const holder = globalThis as typeof globalThis & { [key: symbol]: AsyncLocalStorage<ToolFence | undefined> | undefined };\n return holder[Symbol.for(\"pi-fabric.durable-tool-fence.v1\")] ??= new AsyncLocalStorage();\n};\ntype Listener = (event: AgentEvent, signal: AbortSignal) => void | Promise<void>;\n\n/** A public-API Agent facade over restartable pi-durable tasks. */\nexport class DurableAgent extends Agent {\n private readonly durableOptions: AgentOptions & { models: Models; storage: Storage; runId: string; fabricJournalDirectory?: string };\n private readonly observers = new Set<Listener>();\n private readonly registry = createRegistry();\n private engine?: Harness;\n private root?: Conversation;\n private opening?: Promise<void>;\n private releaseStartup!: (ready: boolean) => void;\n private readonly startup = new Promise<boolean>(resolve => { this.releaseStartup = resolve; });\n /** Reconcile committed history without replaying events, before any recovered task runs. */\n recoverHistory?: (messages: AgentMessage[]) => void | Promise<void>;\n private delivery: Promise<void> = Promise.resolve();\n private admission: Promise<void> = Promise.resolve();\n private running: Promise<void> | undefined;\n private controller: AbortController | undefined;\n private requestId: string | undefined;\n private firstRequest = true;\n private closing = false;\n private closeRequested = false;\n private closed?: Promise<void>;\n private active = false;\n private partial: AgentMessage | undefined;\n private failure: string | undefined;\n private readonly pending = new Set<string>();\n private emitted: AgentMessage[] = [];\n private restored = false;\n private resetPending = false;\n private queuePreview: { mode: \"steering\" | \"followup\"; message: AgentMessage }[] = [];\n private readonly transient = new Map<number, TransientEvent>();\n private transientSequence = 0;\n // Harness keeps its scheduler alive between requests. Never inherit the\n // scheduler's first-request permission/extension scope for later work.\n private requestScope = AsyncLocalStorage.snapshot();\n private readonly toolTask;\n private readonly runTask;\n\n /** `fabricJournalDirectory` lets an interrupted fabric_exec resume from a crash journal. */\n constructor(options: AgentOptions & { models: Models; storage: Storage; runId: string; fabricJournalDirectory?: string }) {\n super(options);\n if (!options.runId) throw new Error(\"DurableAgent requires a non-empty runId\");\n this.durableOptions = options;\n // Shadow only public state properties, never Agent's private implementation.\n Object.defineProperties(super.state, {\n isStreaming: { get: () => this.active },\n streamingMessage: { get: () => this.partial },\n pendingToolCalls: { get: () => this.pending },\n errorMessage: { get: () => this.failure },\n });\n this.toolTask = this.scopedTask<ToolInput, ToolCheckpoint, ToolResultMessage>({\n name: \"fabric.agent.tool\", version: 1, initial: () => ({ phase: \"execute\" }),\n phases: { execute: async (task, runtime, ctx) => {\n await this.delivery;\n const { call, message } = task.input;\n const context = await this.executionContext();\n const tool = context.tools?.find(t => t.name === call.name);\n const prior = await runtime.memo<boolean>(\"intent\", ctx);\n if (!prior) {\n await runtime.memo(\"intent\", true, ctx);\n await runtime.commit(async tx => { await this.event(tx, { type: \"tool_execution_start\", toolCallId: call.id, toolName: call.name, args: call.arguments }); }, ctx);\n await this.delivery;\n }\n // Fabric accepts the fence before its program starts and arms it before\n // any effect, so an accepted, unarmed attempt changed nothing. Wrapper\n // layers drop tool replay metadata, so the fence is offered by name.\n const fabricExec = call.name === \"fabric_exec\";\n const journalDirectory = fabricExec ? this.durableOptions.fabricJournalDirectory : undefined;\n const journalPath = journalDirectory === undefined ? undefined : fabricJournalPath(journalDirectory, String(task.id), call.id);\n // Header digest of the journal Fabric recorded for this call, if any.\n const recorded = prior && journalPath ? await runtime.memo<string>(\"fabric.journal\", ctx) : undefined;\n let execute = !prior || (task.input.replaySafe === true && tool?.replay === \"safe\");\n if (!execute && recorded !== undefined) {\n // Resume from the journal: recorded results are served, never rerun.\n for (let attempt = 1; attempt <= MAX_JOURNAL_RESUMES && !execute; attempt++) {\n if (await runtime.memo<boolean>(`fabric.resume.${attempt}`, ctx) === undefined) {\n execute = await runtime.memo(`fabric.resume.${attempt}`, true, ctx);\n }\n }\n } else if (!execute && fabricExec\n && await runtime.memo<boolean>(\"fabric.fence\", ctx) === true\n && await runtime.memo<boolean>(\"fabric.armed\", ctx) === undefined\n && await runtime.memo<boolean>(\"fabric.rerun\", ctx) === undefined) {\n // One rerun only: a program that keeps crashing its process must not loop.\n execute = await runtime.memo(\"fabric.rerun\", true, ctx);\n }\n const fence: ToolFence | undefined = fabricExec ? {\n toolCallId: call.id,\n accept: async () => {\n // A journal-aware Fabric skips accept when it resumes. Any other caller\n // would rerun recorded effects from the start.\n if (recorded !== undefined) throw new Error(\"This Fabric version cannot resume an interrupted fabric_exec from its journal. Nothing was rerun.\");\n await runtime.memo(\"fabric.fence\", true, ctx);\n },\n arm: async () => { await runtime.memo(\"fabric.armed\", true, ctx); },\n ...(journalPath ? { journal: {\n path: journalPath,\n ...(recorded !== undefined ? { digest: recorded } : {}),\n accept: async (digest: string) => {\n if (await runtime.memo(\"fabric.journal\", digest, ctx) !== digest) throw new Error(\"fabric_exec already recorded a different journal\");\n },\n } } : {}),\n } : undefined;\n const outcome: { isError: boolean; result: AgentToolResult<any> } = !execute\n ? { isError: true, result: { content: [{ type: \"text\" as const, text: \"Tool execution interrupted; unsafe effect was not replayed.\" }], details: { interrupted: true } } }\n // Every other tool runs outside any inherited fence.\n : await toolFences().run(fence, () => runToolCall(call, {\n tools: context.tools ?? [], assistantMessage: message, context, signal: runtime.signal,\n ...(this.beforeToolCall ? { beforeToolCall: this.beforeToolCall } : {}), ...(this.afterToolCall ? { afterToolCall: this.afterToolCall } : {}),\n onUpdate: async result => {\n await this.transientEvent(change => runtime.commit(change, ctx), { type: \"tool_execution_update\", toolCallId: call.id, toolName: call.name, args: call.arguments, partialResult: result });\n },\n }));\n const result: ToolResultMessage = { role: \"toolResult\", toolCallId: call.id, toolName: call.name,\n content: outcome.result.content ?? [], details: outcome.result.details, isError: outcome.isError,\n ...(outcome.result.usage ? { usage: outcome.result.usage } : {}), timestamp: Date.now() };\n await runtime.commit(async tx => {\n await this.event(tx, { type: \"tool_execution_end\", toolCallId: call.id, toolName: call.name, result: outcome.result, isError: outcome.isError });\n // Keep termination metadata in the child's durable outcome without changing the Pi message.\n return { status: \"terminal\", outcome: { status: \"completed\", result: copy({ ...result, terminate: \"terminate\" in outcome.result && outcome.result.terminate === true }) as ToolResultMessage } };\n }, ctx);\n // The result is durable now, so the journal can never be read again.\n if (journalPath) await removeFabricJournal(journalPath);\n } },\n abort: async (task, runtime, ctx) => {\n const { call } = task.input;\n const result: ToolResultMessage = { role: \"toolResult\", toolCallId: call.id, toolName: call.name, content: [{ type: \"text\", text: \"Tool execution aborted\" }], isError: true, timestamp: Date.now() };\n await runtime.commit(async tx => {\n await this.event(tx, { type: \"tool_execution_end\", toolCallId: call.id, toolName: call.name, result, isError: true });\n return { status: \"terminal\", outcome: { status: \"completed\", result } };\n }, ctx);\n const journalDirectory = call.name === \"fabric_exec\" ? this.durableOptions.fabricJournalDirectory : undefined;\n if (journalDirectory !== undefined) await removeFabricJournal(fabricJournalPath(journalDirectory, String(task.id), call.id));\n },\n });\n this.runTask = this.scopedTask<RunInput, Checkpoint, null>({\n name: \"fabric.agent.run\", version: 1, initial: () => ({ phase: \"prepare\" }),\n phases: {\n prepare: async (task, runtime, ctx) => {\n await this.delivery;\n let context = await this.executionContext();\n const saved = await this.engine!.snapshot(Ledger, runtime.conversationId, ctx);\n let model = (saved?.config?.model as unknown as AgentState[\"model\"] | undefined) ?? this.state.model;\n let thinking = saved?.config?.thinking ?? this.state.thinkingLevel;\n if (task.state.checkpoint.next) {\n const turn = { ...task.state.checkpoint.next, context };\n const update = this.prepareNextTurnWithContext\n ? await this.prepareNextTurnWithContext(turn, runtime.signal)\n : await this.prepareNextTurn?.(runtime.signal);\n if (update?.context) context = update.context;\n model = update?.model ?? model;\n thinking = update?.thinkingLevel ?? thinking;\n await runtime.commit(async tx => { await this.event(tx, { type: \"turn_start\" }); }, ctx);\n await this.delivery;\n if (update?.messages?.length) {\n const additions = update.messages;\n await runtime.commit(async tx => { for (const m of additions) await this.message(tx, m); }, ctx);\n await this.delivery;\n context = { ...context, messages: [...context.messages, ...additions] };\n }\n }\n await this.admit(runtime.signal);\n await runtime.commit(async tx => {\n const ledger = await tx.doc(Ledger, runtime.conversationId);\n const queued = task.state.checkpoint.pending?.map(wire) ?? (task.state.checkpoint.skipSteering ? [] : ledger.steering.splice(0, this.steeringMode === \"all\" ? ledger.steering.length : 1));\n for (const value of queued) {\n const message = value as unknown as AgentMessage;\n await this.message(tx, message); context.messages.push(message);\n }\n const changes = getToolStateChanges(getCurrentTools(context.messages), (context.tools ?? []).map(toToolDeclaration));\n if (changes.toolsAdded.length || changes.toolsRemoved.length) {\n const message = { role: \"system\" as const, content: \"\", timestamp: Date.now(), ...changes };\n await this.message(tx, message); context.messages.push(message);\n }\n }, ctx);\n await this.delivery;\n const update = await this.prepareRequest?.({ context, model, thinkingLevel: thinking }, runtime.signal);\n context = update?.context ?? context;\n model = update?.model ?? model;\n thinking = update?.thinkingLevel ?? thinking;\n const transformed = this.transformContext ? await this.transformContext(context.messages, runtime.signal) : context.messages;\n const messages = await this.convertToLlm(transformed);\n await runtime.commit(async tx => {\n const ledger = await tx.doc(Ledger, runtime.conversationId);\n ledger.config = { model: wire(model), thinking };\n // Tools run from the public loadout, rebound by name, so a loadout\n // refresh that rebuilds same-name tool objects keeps the request valid.\n // A hook-only tool whose name is not registered cannot be recovered.\n const registered = new Set(this.state.tools.map(tool => tool.name));\n if ((context.tools ?? []).some(tool => !registered.has(tool.name))) throw new Error(\"Durable request tools must be registered in agent.state.tools\");\n ledger.context = { messages: context.messages.map(wire), tools: (context.tools ?? []).map(tool => tool.name) };\n return { status: \"running\", checkpoint: { phase: \"model\", messages: copy(messages), model: copy(model), thinking } };\n }, ctx);\n },\n model: async (task, runtime, ctx) => {\n await this.delivery;\n const cp = task.state.checkpoint;\n const stream = await this.streamFunction(cp.model, normalizeContext({ messages: cp.messages }), {\n signal: runtime.signal, ...(cp.thinking === \"off\" ? {} : { reasoning: cp.thinking }),\n ...(this.sessionId ? { sessionId: this.sessionId } : {}),\n ...(this.thinkingBudgets ? { thinkingBudgets: this.thinkingBudgets } : {}), transport: this.transport,\n ...(this.maxRetryDelayMs !== undefined ? { maxRetryDelayMs: this.maxRetryDelayMs } : {}),\n ...(this.getApiKey ? { apiKey: (await this.getApiKey(cp.model.provider)) ?? \"\" } : {}),\n ...(this.onPayload ? { onPayload: this.onPayload } : {}),\n ...(this.onResponse ? { onResponse: this.onResponse } : {}),\n ...(this.onProviderStreamEvent ? { onProviderStreamEvent: this.onProviderStreamEvent } : {}),\n });\n let started = false;\n for await (const event of stream) {\n if (event.type === \"done\" || event.type === \"error\") continue;\n if (!started) {\n await runtime.commit(async tx => { await this.event(tx, { type: \"message_start\", message: event.partial }); }, ctx);\n await this.delivery;\n }\n started = true;\n if (event.type !== \"start\") await this.transientEvent(change => runtime.commit(change, ctx), { type: \"message_update\", message: event.partial, assistantMessageEvent: event });\n }\n const message = copy({ ...await stream.result(), thinkingLevel: cp.thinking });\n await runtime.commit(async tx => {\n if (!started) await this.event(tx, { type: \"message_start\", message });\n await this.event(tx, { type: \"message_end\", message });\n const calls = message.stopReason !== \"error\" && message.stopReason !== \"aborted\" ? message.content.filter(c => c.type === \"toolCall\") : [];\n if (message.stopReason === \"length\" && calls.length) {\n const results: ToolResultMessage[] = [];\n for (const call of calls) {\n const result = { content: [{ type: \"text\" as const, text: \"Tool call was truncated by the output token limit; execution refused.\" }], details: {} };\n await this.event(tx, { type: \"tool_execution_start\", toolCallId: call.id, toolName: call.name, args: call.arguments });\n await this.event(tx, { type: \"tool_execution_end\", toolCallId: call.id, toolName: call.name, result, isError: true });\n const toolResult: ToolResultMessage = { role: \"toolResult\", toolCallId: call.id, toolName: call.name, ...result, isError: true, timestamp: Date.now() };\n results.push(toolResult); await this.message(tx, toolResult);\n }\n return { status: \"running\", checkpoint: { phase: \"boundary\", message, results } };\n }\n const sequential = this.toolExecution === \"sequential\" || calls.some(c => this.state.tools.find(t => t.name === c.name)?.executionMode === \"sequential\");\n const children: TaskId<ToolResultMessage>[] = [];\n for (const call of sequential ? calls.slice(0, 1) : calls) children.push(await tx.createTask(this.toolTask, { message, call, replaySafe: this.state.tools.find(t => t.name === call.name)?.replay === \"safe\" }, { ownership: { kind: \"task\", taskId: task.id } }));\n return children.length\n ? { status: \"waiting\", checkpoint: { phase: \"tools\", message, children }, on: children, policy: \"allSettled\" }\n : { status: \"running\", checkpoint: { phase: \"boundary\", message, results: [] } };\n }, ctx);\n },\n tools: async (task, runtime, ctx) => {\n await this.delivery;\n const { message, children } = task.state.checkpoint;\n const calls = message.content.filter(c => c.type === \"toolCall\");\n if (children.length < calls.length) {\n await runtime.commit(async tx => {\n const child = await tx.createTask(this.toolTask, { message, call: calls[children.length]!, replaySafe: this.state.tools.find(t => t.name === calls[children.length]!.name)?.replay === \"safe\" }, { ownership: { kind: \"task\", taskId: task.id } });\n return { status: \"waiting\", checkpoint: { phase: \"tools\", message, children: [...children, child] }, on: [child], policy: \"allSettled\" };\n }, ctx);\n return;\n }\n const outcomes = await runtime.outcomes(children, ctx);\n const results = outcomes.map((o, index): ToolResultMessage => o.status === \"completed\" ? o.result : ({\n role: \"toolResult\", toolCallId: calls[index]!.id, toolName: calls[index]!.name,\n content: [{ type: \"text\", text: `Tool task ${o.status}` }], isError: true, timestamp: Date.now(),\n }));\n const terminate = results.length > 0 && results.every(r => (r as ToolResultMessage & { terminate?: boolean }).terminate);\n for (const result of results) delete (result as ToolResultMessage & { terminate?: boolean }).terminate;\n await runtime.commit(async tx => {\n for (const result of results) await this.message(tx, result);\n return { status: \"running\", checkpoint: copy({ phase: \"boundary\" as const, message, results, terminate }) };\n }, ctx);\n },\n boundary: async (task, runtime, ctx) => {\n await this.delivery;\n const { message, results, terminate } = task.state.checkpoint;\n const decision = await this.finishTurn?.({ message: this.lastAssistant(message), toolResults: this.canonicalToolResults(results), context: await this.executionContext(), newMessages: this.emitted.slice() }, runtime.signal);\n await runtime.commit(async tx => {\n await this.event(tx, { type: \"turn_end\", message, toolResults: results });\n return { status: \"running\", checkpoint: { phase: \"decide\", message, results, ...(decision ? { action: decision.action } : {}), ...(terminate ? { terminate: true } : {}) } };\n }, ctx);\n },\n decide: async (task, runtime, ctx) => {\n await this.delivery;\n await this.admit(runtime.signal);\n const cp = task.state.checkpoint;\n await runtime.commit(async tx => {\n const ledger = await tx.doc(Ledger, runtime.conversationId);\n const hardEnd = cp.message.stopReason === \"error\" || cp.message.stopReason === \"aborted\" || cp.action === \"end\";\n let queued: JsonValue[] = [];\n if (!hardEnd) {\n queued = ledger.steering.splice(0, this.steeringMode === \"all\" ? ledger.steering.length : 1);\n if (!queued.length && (!cp.results.length || cp.terminate) && cp.action !== \"continue\") queued = ledger.followup.splice(0, this.followUpMode === \"all\" ? ledger.followup.length : 1);\n }\n if (!hardEnd && (queued.length || (cp.results.length && !cp.terminate) || cp.action === \"continue\")) {\n const next = copy({ message: cp.message, toolResults: cp.results, newMessages: this.emitted.slice() });\n return { status: \"running\", checkpoint: { phase: \"prepare\", next, ...(queued.length ? { pending: copy(queued) as unknown as AgentMessage[] } : {}), skipSteering: queued.length > 0 } };\n }\n ledger.active = 0;\n await this.event(tx, { type: \"agent_end\", messages: this.emitted.slice() });\n return { status: \"terminal\", outcome: { status: \"completed\", result: null } };\n }, ctx);\n },\n },\n abort: async (task, runtime, ctx) => {\n await this.delivery;\n const results: ToolResultMessage[] = [];\n if (task.state.checkpoint.phase === \"tools\") {\n const { message, children } = task.state.checkpoint;\n const calls = message.content.filter(c => c.type === \"toolCall\");\n for (const [index, call] of calls.entries()) {\n const child = children[index] ? await runtime.getTask(children[index]!, ctx) : undefined;\n const outcome = child?.state.status === \"terminal\" ? child.state.outcome : undefined;\n const result = outcome?.status === \"completed\" ? copy(outcome.result) : {\n role: \"toolResult\" as const, toolCallId: call.id, toolName: call.name,\n content: [{ type: \"text\" as const, text: \"Tool execution aborted\" }], isError: true, timestamp: Date.now(),\n };\n delete (result as ToolResultMessage & { terminate?: boolean }).terminate;\n results.push(result);\n }\n }\n await runtime.commit(async tx => {\n const ledger = await tx.doc(Ledger, runtime.conversationId);\n ledger.active = 0;\n for (const result of results) await this.message(tx, result);\n const message = this.failureMessage(\"Operation aborted\", true);\n await this.message(tx, message);\n await this.event(tx, { type: \"turn_end\", message, toolResults: results });\n await this.event(tx, { type: \"agent_end\", messages: [...this.emitted, ...results, message] });\n return { status: \"terminal\", outcome: { status: \"aborted\" } };\n }, ctx);\n },\n });\n this.registry.install({ name: \"fabric-agent\", tasks: [this.runTask, this.toolTask] });\n }\n\n private scopedTask<I, S extends { phase: string }, R>(definition: Parameters<typeof defineTask<I, S, R>>[0]) {\n const phases = Object.fromEntries(Object.entries(definition.phases).map(([name, handler]) => [name,\n async (...args: unknown[]) => {\n if (!await this.startup) throw new Error(\"DurableAgent recovery failed\");\n return this.requestScope(handler as (...args: unknown[]) => unknown, ...args);\n },\n ])) as typeof definition.phases;\n const abort = definition.abort;\n return defineTask<I, S, R>({ ...definition, phases, ...(abort ? { abort: async (...args) => {\n if (!await this.startup) throw new Error(\"DurableAgent recovery failed\");\n return this.requestScope(abort, ...args);\n } } : {}) });\n }\n private failureMessage(errorMessage: string, aborted: boolean): AssistantMessage {\n return { role: \"assistant\", content: [], api: this.state.model.api, provider: this.state.model.provider, model: this.state.model.id,\n usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },\n stopReason: aborted ? \"aborted\" : \"error\", errorMessage, timestamp: Date.now() };\n }\n private context(): AgentContext { return { messages: this.state.messages.slice(), tools: this.state.tools.slice() }; }\n private async executionContext(): Promise<AgentContext> {\n const saved = await this.engine!.snapshot(Ledger, this.root!.id, BACKGROUND_CONTEXT);\n if (!saved?.context) return this.context();\n return { messages: copy(saved.context.messages) as unknown as AgentMessage[], tools: this.state.tools.filter(tool => saved.context!.tools.includes(tool.name)) };\n }\n private canonicalToolResults(results: ToolResultMessage[]): ToolResultMessage[] {\n const messages = this.state.messages.slice().reverse();\n return results.map(result => messages.find((message): message is ToolResultMessage =>\n message.role === \"toolResult\" && message.toolCallId === result.toolCallId) ?? result);\n }\n private lastAssistant(fallback: AssistantMessage): AssistantMessage {\n return this.state.messages.slice().reverse().find((m): m is AssistantMessage => m.role === \"assistant\") ?? fallback;\n }\n private async event(tx: Tx, event: AgentEvent) {\n await tx.appendEntry(this.root!.id, { kind: EVENT, data: wire(event) });\n if (event.type === \"message_end\") {\n const ledger = await tx.doc(Ledger, this.root!.id);\n ledger.context?.messages.push(wire(event.message));\n }\n }\n /** Commit an ordered, slim marker for a streaming update; its payload stays in memory until delivery. */\n private async transientEvent(commit: (change: (tx: Tx) => Promise<undefined>) => Promise<unknown>, event: TransientEvent) {\n const sequence = ++this.transientSequence;\n // Copy synchronously: providers and tools keep mutating their partials.\n this.transient.set(sequence, copy(event));\n let marker: Record<string, unknown>;\n if (event.type === \"message_update\") {\n const { partial: _partial, ...delta } = event.assistantMessageEvent as typeof event.assistantMessageEvent & { partial?: unknown };\n marker = { type: event.type, assistantMessageEvent: delta };\n } else marker = { type: event.type, toolCallId: event.toolCallId, toolName: event.toolName };\n try {\n await commit(async tx => { await tx.appendEntry(this.root!.id, { kind: EVENT, data: wire({ ...marker, [TRANSIENT]: sequence }) }); return undefined; });\n } catch (error) {\n this.transient.delete(sequence);\n throw error;\n }\n await this.delivery;\n }\n /** Restore a committed streaming marker to the full event; undefined when its payload is not in this process. */\n private rehydrate(data: Record<string, unknown>): AgentEvent | undefined {\n const sequence = data[TRANSIENT];\n if (typeof sequence !== \"number\") return data as unknown as AgentEvent;\n const event = this.transient.get(sequence);\n this.transient.delete(sequence);\n return event;\n }\n private async message(tx: Tx, message: AgentMessage) {\n await this.event(tx, { type: \"message_start\", message });\n await this.event(tx, { type: \"message_end\", message });\n }\n private async expose(event: AgentEvent) {\n // Durable entries are JSON values; native Pi boundaries identify the exact\n // objects delivered by message_end, not independent deserialized copies.\n if (event.type === \"turn_end\") event = {\n ...event, message: event.message.role === \"assistant\" ? this.lastAssistant(event.message) : event.message,\n toolResults: this.canonicalToolResults(event.toolResults),\n };\n if (event.type === \"message_start\" && event.message.role === \"assistant\") this.partial = event.message;\n if (event.type === \"message_update\") this.partial = event.message;\n if (event.type === \"message_end\") {\n this.state.messages = [...this.state.messages, event.message];\n this.emitted.push(event.message);\n this.partial = undefined;\n if (event.message.role === \"assistant\") this.failure = event.message.errorMessage;\n const index = this.queuePreview.findIndex(q => JSON.stringify(q.message) === JSON.stringify(event.message));\n if (index >= 0) this.queuePreview.splice(index, 1);\n }\n if (event.type === \"tool_execution_start\") this.pending.add(event.toolCallId);\n if (event.type === \"tool_execution_end\") this.pending.delete(event.toolCallId);\n for (const observer of this.observers) await observer(event, this.controller?.signal ?? new AbortController().signal);\n }\n private async open() {\n if (this.closing) throw new Error(\"DurableAgent is closed\");\n return this.opening ??= (async () => {\n // Session.close owns its Storage; this facade borrows the caller's handle.\n const borrowed = new Proxy(this.durableOptions.storage, { get(target, key) {\n if (key === \"close\") return async () => {};\n const value = Reflect.get(target, key, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n } });\n const harness = await Harness.open(borrowed, { models: this.durableOptions.models, registry: this.registry }, BACKGROUND_CONTEXT);\n this.engine = harness;\n this.root = await harness.root(BACKGROUND_CONTEXT);\n const ledger = await harness.snapshot(Ledger, this.root.id, BACKGROUND_CONTEXT);\n if (ledger?.runId && ledger.runId !== this.durableOptions.runId) throw new Error(\"DurableAgent storage belongs to a different runId\");\n const history = (await this.root.context(BACKGROUND_CONTEXT)).entries;\n const messages: AgentMessage[] = [];\n for (const entry of history) {\n if (entry.kind === HISTORY) { messages.splice(0, messages.length, ...(entry.data as unknown as AgentMessage[])); this.restored = true; }\n if (entry.kind === EVENT) {\n const event = entry.data as unknown as AgentEvent;\n if (event.type === \"agent_start\") this.emitted = [];\n if (event.type === \"message_end\") { messages.push(event.message); this.emitted.push(event.message); }\n }\n }\n if (this.restored && !this.resetPending) this.state.messages = messages;\n if (this.restored && !this.resetPending) await this.recoverHistory?.(copy(messages));\n this.queuePreview = [ ...this.queuePreview, ...(ledger?.steering ?? []).map(message => ({ mode: \"steering\" as const, message: message as unknown as AgentMessage })), ...(ledger?.followup ?? []).map(message => ({ mode: \"followup\" as const, message: message as unknown as AgentMessage })) ];\n harness.subscribeCommits(publication => {\n for (const change of publication.changes) {\n if (change.type !== \"entry\" || change.value.conversationId !== this.root!.id || change.value.kind !== EVENT) continue;\n // A marker whose payload is not in memory came from another process; it is never replayed.\n const event = this.rehydrate(copy(change.value.data) as Record<string, unknown>);\n if (!event) continue;\n this.delivery = this.delivery.then(() => this.requestScope(() => this.expose(event)));\n // Keep failures observable at every execution boundary, without an unhandled rejection.\n void this.delivery.catch(() => {});\n }\n });\n this.releaseStartup(true);\n })().catch(error => { this.releaseStartup(false); throw error; });\n }\n /** Resolves only after all controls accepted so far have committed. */\n awaitControls(): Promise<void> { return this.admission; }\n /**\n * A phase's wait for accepted controls. abort() chains the engine abort onto admission, and that abort joins the\n * running invocation, so a phase that kept waiting on admission after its abort signal would wait on itself. The\n * phase's next commit then rejects on the durable abort mark and the abort handler settles the task.\n */\n private admit(signal: AbortSignal): Promise<void> {\n if (signal.aborted) return Promise.resolve();\n let onAbort!: () => void;\n const aborted = new Promise<void>(resolve => { onAbort = resolve; signal.addEventListener(\"abort\", onAbort, { once: true }); });\n return Promise.race([this.admission, aborted]).finally(() => signal.removeEventListener(\"abort\", onAbort));\n }\n setRequestId(id: string): void { if (!id) throw new Error(\"requestId must not be empty\"); this.requestId = id; }\n override subscribe(listener: Listener) { this.observers.add(listener); return () => { this.observers.delete(listener); }; }\n override get signal() { return this.controller?.signal; }\n override waitForIdle() { return this.running ?? Promise.resolve(); }\n override abort() {\n this.controller?.abort();\n if (this.root && this.active) {\n const aborting = this.root.abort(BACKGROUND_CONTEXT);\n this.admission = this.admission.then(() => aborting);\n void this.admission.catch(() => {});\n }\n }\n override prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n override prompt(input: string, images?: ImageContent[]): Promise<void>;\n override prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n const messages: AgentMessage[] = typeof input === \"string\" ? [{ role: \"user\", content: images?.length ? [{ type: \"text\", text: input }, ...images] : input, timestamp: Date.now() }] : Array.isArray(input) ? input : [input];\n return this.start(messages);\n }\n override continue() { return this.start([]); }\n private start(messages: AgentMessage[]) {\n if (this.active) return Promise.reject(new Error(\"Agent is already processing a prompt\"));\n if (this.closeRequested) return Promise.reject(new Error(\"DurableAgent is closed\"));\n const request = this.requestId ?? (this.firstRequest && messages.length ? this.durableOptions.runId : randomUUID()); this.requestId = undefined; this.firstRequest = false;\n this.requestScope = AsyncLocalStorage.snapshot();\n this.active = true; this.failure = undefined; this.emitted = []; this.controller = new AbortController();\n const run = (async () => {\n await this.open();\n await this.admission;\n let id!: TaskId<null>;\n await this.root!.commit(async tx => {\n const ledger = await tx.doc(Ledger, this.root!.id);\n ledger.runId = this.durableOptions.runId;\n if (Object.hasOwn(ledger.requests, request)) { id = ledger.requests[request] as TaskId<null>; return; }\n if (ledger.active) {\n if (messages.length) throw new Error(\"Unfinished durable run: resume with continue() or its original requestId\");\n id = ledger.active as TaskId<null>; ledger.requests = { ...ledger.requests, [request]: id }; return;\n }\n if (!messages.length) {\n const last = this.state.messages.at(-1);\n if (!last || this.state.messages.every(m => m.role === \"system\")) throw new Error(\"No messages to continue from\");\n if (last.role === \"assistant\") {\n const queue = ledger.steering.length ? ledger.steering : ledger.followup;\n const mode = ledger.steering.length ? this.steeringMode : this.followUpMode;\n messages = queue.splice(0, mode === \"all\" ? queue.length : 1) as unknown as AgentMessage[];\n if (!messages.length) throw new Error(\"Cannot continue from message role: assistant\");\n }\n }\n delete ledger.context;\n ledger.config = { model: wire(this.state.model), thinking: this.state.thinkingLevel };\n if (!this.restored || this.resetPending || !ledger.active) {\n await tx.appendEntry(this.root!.id, { kind: HISTORY, data: wire(this.state.messages) });\n this.restored = true; this.resetPending = false;\n }\n this.emitted = [];\n await this.event(tx, { type: \"agent_start\" });\n await this.event(tx, { type: \"turn_start\" });\n for (const message of messages) await this.message(tx, message);\n id = await tx.createTask(this.runTask, { request }, { ownership: { kind: \"conversation\" } });\n ledger.requests = { ...ledger.requests, [request]: id }; ledger.active = id;\n }, BACKGROUND_CONTEXT);\n await this.delivery;\n if (this.controller!.signal.aborted) await this.engine!.abortTask(id, BACKGROUND_CONTEXT);\n const settled = await this.engine!.waitForTask(id, BACKGROUND_CONTEXT);\n await this.delivery;\n if (settled.state.outcome.status === \"failed\" || settled.state.outcome.status === \"faulted\") {\n const message = this.failureMessage(settled.state.outcome.error.message, false);\n await this.root!.commit(async tx => {\n const ledger = await tx.doc(Ledger, this.root!.id);\n // A retried failed identity must not append the same failure twice.\n if (ledger.active !== id) return;\n ledger.active = 0;\n await this.message(tx, message);\n await this.event(tx, { type: \"turn_end\", message, toolResults: [] });\n await this.event(tx, { type: \"agent_end\", messages: [...this.emitted, message] });\n }, BACKGROUND_CONTEXT);\n await this.delivery;\n }\n })().finally(() => { this.active = false; this.partial = undefined; this.pending.clear(); this.controller = undefined; this.running = undefined; });\n this.running = run;\n return run;\n }\n private enqueue(mode: \"steering\" | \"followup\", message: AgentMessage) {\n if (this.closeRequested) throw new Error(\"DurableAgent is closed\");\n const request = this.requestId; this.requestId = undefined;\n this.queuePreview.push({ mode, message: copy(message) });\n this.admission = this.admission.then(async () => {\n await this.open();\n await this.root!.commit(async tx => {\n const ledger = await tx.doc(Ledger, this.root!.id);\n ledger.runId ||= this.durableOptions.runId;\n ledger.controls ??= {};\n if (request && Object.hasOwn(ledger.controls, request)) {\n const index = this.queuePreview.findIndex(q => q.mode === mode && JSON.stringify(q.message) === JSON.stringify(message));\n if (index >= 0) this.queuePreview.splice(index, 1);\n return;\n }\n if (request) ledger.controls = { ...ledger.controls, [request]: true };\n ledger[mode].push(wire(message));\n }, BACKGROUND_CONTEXT);\n });\n void this.admission.catch(() => {});\n }\n override steer(message: AgentMessage) { this.enqueue(\"steering\", message); }\n override followUp(message: AgentMessage) { this.enqueue(\"followup\", message); }\n private clear(mode?: \"steering\" | \"followup\") {\n if (this.closeRequested) throw new Error(\"DurableAgent is closed\");\n this.queuePreview = this.queuePreview.filter(q => mode !== undefined && q.mode !== mode);\n this.admission = this.admission.then(async () => {\n await this.open();\n await this.root!.commit(async tx => { const d = await tx.doc(Ledger, this.root!.id); if (!mode || mode === \"steering\") d.steering = []; if (!mode || mode === \"followup\") d.followup = []; }, BACKGROUND_CONTEXT);\n });\n void this.admission.catch(() => {});\n }\n override clearSteeringQueue() { this.clear(\"steering\"); }\n override clearFollowUpQueue() { this.clear(\"followup\"); }\n override clearAllQueues() { this.clear(); }\n override hasQueuedMessages() { return this.queuePreview.length > 0; }\n override peekQueuedMessages() {\n const steering = this.queuePreview.filter(q => q.mode === \"steering\").map(q => q.message);\n const followup = this.queuePreview.filter(q => q.mode === \"followup\").map(q => q.message);\n return steering.length ? (this.steeringMode === \"all\" ? steering : steering.slice(0, 1)) : (this.followUpMode === \"all\" ? followup : followup.slice(0, 1));\n }\n override reset() {\n if (this.active) throw new Error(\"Cannot reset a running DurableAgent\");\n const baseline = getCurrentSystemMessage(this.state.messages);\n this.state.messages = baseline ? [baseline] : [];\n this.partial = undefined; this.failure = undefined; this.pending.clear();\n this.clearAllQueues(); this.resetPending = true;\n }\n /** Close cancels invocations, NOT durable tasks. A new Harness resumes their checkpoints. */\n close(): Promise<void> {\n this.closeRequested = true;\n return this.closed ??= (async () => {\n // Accepted queue writes may still need open(); seal only after they drain.\n // Even a rejected open (for example a foreign runId) must release Harness.\n const drained = await Promise.allSettled([this.opening, this.admission]);\n this.closing = true;\n if (this.engine) await this.engine.close(BACKGROUND_CONTEXT);\n await this.delivery;\n const rejected = drained.find(result => result.status === \"rejected\");\n if (rejected?.status === \"rejected\") throw rejected.reason;\n })();\n }\n}\n", "import type { Storage } from \"@earendil-works/pi-durable\";\nimport { constants } from \"node:fs\";\nimport { chmod, lstat, mkdir, open, readdir, realpath } from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n\n// Reserve before touching lease descriptors: POSIX locks can be dropped by\n// closing another descriptor for the same inode in the owning process.\nconst ownedDirectories = new Map<string, symbol>();\n\n/** Caller must close Harness/storage before releasing ownership. Never unlink the lease. */\nexport async function openDurableWorkerStorage(directory: string): Promise<{\n storage: Storage;\n release(): Promise<void>;\n}> {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const canonical = await realpath(directory);\n if (ownedDirectories.has(canonical)) throw new Error(`Durable worker storage is locked: ${canonical}`);\n const ownership = Symbol(canonical);\n ownedDirectories.set(canonical, ownership);\n const forget = () => {\n if (ownedDirectories.get(canonical) === ownership) ownedDirectories.delete(canonical);\n };\n try {\n return await acquire(canonical, forget);\n } catch (error) {\n forget();\n throw error;\n }\n}\n\nasync function acquire(canonical: string, forget: () => void): Promise<{ storage: Storage; release(): Promise<void> }> {\n await chmod(canonical, 0o700);\n const leasePath = join(canonical, \"lease.sqlite\");\n const regular = async (path: string, missing = false) => {\n try {\n const info = await lstat(path);\n if (!info.isFile() || info.nlink !== 1) throw new Error(`Durable file must be a regular, singly-linked file (no symlinks/hardlinks): ${path}`);\n } catch (error) {\n if (!missing || (error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n };\n // Precreate privately, before SQLite opens the database. Never replace the\n // inode: aliases must contend on the same OS-owned exclusive transaction.\n await regular(leasePath, true);\n try {\n const leaseFile = await open(leasePath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);\n await leaseFile.close();\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n }\n await regular(leasePath);\n await chmod(leasePath, 0o600);\n for (const suffix of [\"-journal\", \"-wal\", \"-shm\"]) await regular(leasePath + suffix, true);\n const { DatabaseSync } = await import(\"node:sqlite\");\n const lease = new DatabaseSync(leasePath, { timeout: 0 });\n let released = false;\n const release = async (): Promise<void> => {\n if (released) return;\n // close rolls back the exclusive transaction and releases the OS lock.\n lease.close();\n released = true;\n forget();\n };\n try {\n // DELETE mode makes EXCLUSIVE exclude other connections, not just writers\n // as in WAL mode. No PID files, expiry, retries, or lock stealing.\n lease.exec(\"PRAGMA busy_timeout = 0; PRAGMA journal_mode = DELETE; BEGIN EXCLUSIVE;\");\n const store = join(canonical, \"store\");\n await mkdir(store, { recursive: true, mode: 0o700 });\n if (!(await lstat(store)).isDirectory()) throw new Error(\"Durable store must be a directory, not a symlink\");\n await chmod(store, 0o700);\n // Existing stores are input, not trusted paths. Reject linked payloads before\n // recovery reads or truncates them, and repair legacy permissive file modes.\n for (const name of await readdir(store)) {\n const path = join(store, name);\n await regular(path);\n await chmod(path, 0o600);\n }\n const [{ JsonlStorage }, { NodeExecutionEnv }, { FileError }, { BACKGROUND_CONTEXT }] = await Promise.all([\n import(\"@earendil-works/pi-durable/storage/jsonl\"),\n import(\"@earendil-works/pi-durable/env/node\"),\n import(\"@earendil-works/pi-durable/env\"),\n import(\"@earendil-works/chord/context\"),\n ]);\n const fs = new NodeExecutionEnv({ cwd: canonical });\n const checked = async (path: string) => {\n if (dirname(resolve(path)) !== store || !/^(?:main|(?:doc|task)-(?:0|[1-9]\\d*))\\.jsonl(?:\\.reclaim)?$/.test(basename(path))) {\n throw new Error(`Durable path escapes storage: ${path}`);\n }\n if (!(await lstat(store)).isDirectory()) throw new Error(\"Durable store directory was replaced\");\n await regular(path, true);\n };\n const syncDirectory = async () => {\n // Windows does not expose directory fsync through Node. File fsync below\n // remains mandatory on every platform; no failed file flush is ignored.\n if (process.platform === \"win32\") return;\n const dir = await open(store, constants.O_RDONLY | constants.O_NOFOLLOW);\n try { await dir.sync(); } finally { await dir.close(); }\n };\n // The published JSONL adapter fsyncs sidecars, not every main commit marker.\n // Use one no-follow descriptor for mutation + fsync; do not reopen by name\n // between writing and flushing, or resolve a commit before its marker flush.\n for (const method of [\"appendFile\", \"writeFile\"] as const) {\n fs[method] = async (path, content, context) => {\n try {\n context.abortSignal?.throwIfAborted();\n await checked(path);\n const file = await open(path, constants.O_CREAT | constants.O_WRONLY | constants.O_NOFOLLOW |\n (method === \"appendFile\" ? constants.O_APPEND : 0), 0o600);\n try {\n const info = await file.stat();\n if (!info.isFile() || info.nlink !== 1) throw new Error(\"Durable file was replaced\");\n await file.chmod(0o600);\n if (method === \"writeFile\") await file.truncate(0);\n await file.writeFile(content);\n await file.sync();\n } finally { await file.close(); }\n await syncDirectory();\n return { ok: true, value: undefined };\n } catch (error) {\n return { ok: false, error: new FileError(\"unknown\", String(error), path, error instanceof Error ? error : undefined) };\n }\n };\n }\n // Recovery also reads and truncates incomplete tails; validate those paths.\n for (const method of [\"openTextLineReader\", \"flushFile\"] as const) {\n const original = fs[method].bind(fs);\n // These methods have different result types; retain their public signatures.\n const guarded = async (path: string, context: Parameters<typeof original>[1]) => {\n await checked(path);\n return original(path, context);\n };\n Object.defineProperty(fs, method, { value: guarded });\n }\n const truncate = fs.truncateFile.bind(fs);\n fs.truncateFile = async (path, size, context) => {\n await checked(path);\n const result = await truncate(path, size, context);\n return result.ok ? fs.flushFile(path, context) : result;\n };\n const storage = await JsonlStorage.open(store, fs, BACKGROUND_CONTEXT, { fsync: true });\n return { storage, release };\n } catch (error) {\n await release();\n throw new Error(`Cannot acquire durable worker storage at ${canonical}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n}\n"],
5
- "mappings": ";;;;;;AAAA,SAAS,cAAAA,aAAY,cAAAC,mBAAkB;AACvC,SAAS,SAAAC,QAAO,WAAAC,UAAS,UAAAC,eAAc;AACvC,OAAOC,WAAU;AACjB,SAAS,sBAAAC,2BAA0B;AACnC;AAAA,EACE;AAAA,EAAqB;AAAA,EAA4B;AAAA,EACjD;AAAA,EAAoB;AAAA,EAA2B;AAAA,EAAiB,eAAAC;AAAA,EAChE;AAAA,EAAmC;AAAA,EAAmB;AAAA,EACtD;AAAA,EAAY,kBAAAC;AAAA,EAAgB,mBAAAC;AAAA,OAGvB;;;ACNP,IAAM,wBAAwB;AAGvB,SAAS,0BAA0B,QAAuD;AAC/F,QAAM,UAAU,4CAA4C,KAAK,UAAU,MAAM,CAAC;AAClF,MAAI,CAAC,OAAO,KAAK,aAAW,sBAAsB,KAAK,QAAQ,KAAK,CAAC,EAAG,QAAO,IAAI,MAAM,OAAO;AAChG,SAAO,IAAI,MAAM,GAAG,OAAO;AAAA,uMAA0M;AACvO;;;ACXA,SAAS,eAAe;AACxB,SA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,IAAI,CAAC;AAAA,MACxD,CAAC;AAGD,UAAI,CAAC,sBAAuB,MAAK,MAAM,aAAaO,YAAW,CAAC;AAChE,gBAAU,EAAE,OAAO,YAAY;AAC7B,YAAI;AAAE,gBAAM,KAAK,MAAM,MAAM;AAAA,QAAG,UAChC;AACE,cAAI;AAAE,kBAAM,MAAM,QAAQ,MAAMC,mBAAkB;AAAA,UAAG,UACrD;AAAU,kBAAM,MAAM,QAAQ;AAAA,UAAG;AAAA,QACnC;AAAA,MACF,EAAE;AACF,aAAO,EAAE,SAAS,KAAK,SAAS,kBAAkB,SAAS,eAAe,cAAc,GAAG,UAAU,aAAa,SAAS,YAAY;AAAA,IACzI,SAAS,OAAO;AACd,UAAI;AAAE,cAAM,MAAM,QAAQ,MAAMA,mBAAkB;AAAA,MAAG,UAAE;AAAU,cAAM,MAAM,QAAQ;AAAA,MAAG;AACxF,YAAM;AAAA,IACR;AAAA,EACF;AACA,QAAM,UAAU,MAAM,QAAQ,EAAE,KAAK,UAAU,gBAAgB,QAAQ,CAAC;AAAA,EACxE,MAAM,uBAAuB,oBAAoB;AAAA,IAC/C,MAAe,UAAyB;AACtC,UAAI;AAAE,cAAM,MAAM,QAAQ;AAAA,MAAG,UAAE;AAAU,cAAM,aAAa;AAAA,MAAG;AAAA,IACjE;AAAA,EACF;AACA,SAAO,IAAI,eAAe,QAAQ,SAAS,QAAQ,UAAU,SAAS,QAAQ,WAAW;AAC3F;AAEA,eAAsB,iBAAiB,SAA8C;AACnF,QAAM,UAAU,MAAM,2BAA2B,OAAO;AACxD,MAAI;AAAE,UAAM,WAAW,OAAO;AAAA,EAAG,UACjC;AAAU,UAAM,QAAQ,QAAQ;AAAA,EAAG;AACrC;",
6
- "names": ["createHash", "randomUUID", "lstat", "readdir", "unlink", "path", "BACKGROUND_CONTEXT", "getAgentDir", "SessionManager", "SettingsManager", "resolve", "result", "update", "path", "branch", "join", "resolve", "path", "BACKGROUND_CONTEXT", "readdir", "path", "lstat", "unlink", "getAgentDir", "SessionManager", "SettingsManager", "createHash", "randomUUID", "BACKGROUND_CONTEXT"]
7
- }