@howaboua/pi-shepherdr 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.13
4
+
5
+ - Added Remote notes and history to existing-agent attachment, including mixed Local, Tree and Remote storage.
6
+
7
+ ## 0.2.12
8
+
9
+ - Manage orchestration, board defaults and SSH connections in `/herdr`, and attach existing agents without replacing their context.
10
+
11
+ ### Control panel
12
+ - `/herdr` opens Settings, Status and Connections instead of toggling orchestration. Panel controls replace `/herdr board` and `/herdr connect`; outside the TUI, `/herdr` reports status without changes.
13
+ - Add SSH machines through Herdr's interactive setup, preserving its installation approvals and machine catalog. Inspect connection errors and reconnect from Status.
14
+ - Fixed board startup when the global agent directory overlaps the launch folder's `.pi` directory. The global config is no longer mistaken for folder config.
15
+
16
+ ### Agent attachment
17
+ - `agents` gains `attach` and `detach` with independent context and board choices that persist across resume. Agent management stays in the tool, not the human panel.
18
+ - Local and Tree notes/history retain their original identities and use aliases for shared access. Board attachment preserves previous archives.
19
+ - Detachment retains read-only counterpart checkpoints. After an owner exits, reads use its reachable saved session or a timestamped retained snapshot with an explicit staleness warning. Counterpart history still needs its live owner.
20
+ - Remote notes/history attachment is unsupported; board-only attachment remains available.
21
+
3
22
  ## 0.2.11
4
23
 
5
24
  - Shepherdr now tells agents to use an enabled shared board for plans, decisions and findings in substantial multi-agent work, while keeping task assignment and urgent messages in agents. Spawned agents receive the same guidance.
package/README.md CHANGED
@@ -24,17 +24,21 @@ Do not load Pi Codex's example `agents.toml` custom tool alongside Shepherdr; th
24
24
 
25
25
  Pi Codex is optional. Without it, Shepherdr remains a normal Pi extension.
26
26
 
27
- ## Enable orchestration
27
+ ## Control panel
28
28
 
29
- The agent tool is always available in Pi, Code Mode and Notebook Mode. Run Pi inside Herdr to connect the fleet and start monitoring automatically. To prioritize orchestration over direct work for the current session:
29
+ The agent tool is always available in Pi, Code Mode and Notebook Mode. Run Pi inside Herdr to connect the fleet and start monitoring automatically. Open the control panel with:
30
30
 
31
31
  ```text
32
32
  /herdr
33
33
  ```
34
34
 
35
- The command only records one visible guidance message without triggering a turn. Run `/herdr` again to return to normal guidance. Resumed sessions restore their last mode; new sessions start with normal guidance. Tool availability and monitoring do not depend on this mode.
35
+ **Settings** contains orchestration and board preferences. **Status** shows machine connections and reconnect actions. **Connections** adds SSH machines through Herdr's setup flow. Agents handle discovery, attachment and detachment through the `agents` tool, not this panel.
36
36
 
37
- Shepherdr reads Herdr's existing machine profiles and connects enabled profiles at session startup. Manage profiles in Herdr. `/herdr connect [profile-id]` refreshes the catalog and retries failed connections or incomplete monitoring without dropping working connections. A catalog refresh stops watches for disabled or removed profiles without stopping remote agents.
37
+ `/herdr` is the only entry point; board, connect and orchestration subcommands are replaced by panel controls. Outside the TUI, it reports status without changing it. An orchestration change records one visible guidance message without triggering a turn. Resumed sessions restore their last mode; new sessions start with normal guidance. Tool availability and monitoring do not depend on this mode.
38
+
39
+ To add a machine, enter an SSH target or alias, a label and an optional remote session under **Connections**. Herdr performs setup in the terminal and asks before installing or replacing its remote server. OpenSSH owns authentication; Shepherdr does not store credentials. Profiles remain in Herdr's existing catalog, where they can also be renamed, disabled or removed.
40
+
41
+ Shepherdr connects enabled profiles at session startup. **Status** refreshes the catalog and retries failed connections or incomplete monitoring without dropping working connections. A catalog refresh stops watches for disabled or removed profiles without stopping remote agents.
38
42
 
39
43
  Profiles belong to the host running Pi, not the machine displaying its terminal. Omit `machine` for local agent calls. `list` and `find` search all machines unless filtered. Explicit `local` also means the host running Pi. For remote calls, use the opaque profile ID returned by `list`, not its label or hostname. Renaming a profile changes its label, not its routing identity.
40
44
 
@@ -56,6 +60,8 @@ Call the `agents` tool with `action: "help"` before first use, then send flat re
56
60
  | `spawn` | Spawn a profiled Pi agent and send its initial task |
57
61
  | `send` | Send a peer message without waiting or subscribing |
58
62
  | `assign` | Delegate a task to an existing agent |
63
+ | `attach` | Share context or join a board with an existing idle agent |
64
+ | `detach` | Leave selected membership and retain read-only counterpart checkpoints |
59
65
  | `read` | Read the latest assistant reply or bounded terminal output |
60
66
  | `answer` | Answer a worker blocked on Pi Ask |
61
67
  | `watch` | Push future settlement from an existing Pi agent |
@@ -83,9 +89,33 @@ Idle messages start a prepared user turn. Messages arriving during a run use ste
83
89
 
84
90
  For `answer` inside Code or Notebook Mode, update Pi Ask on workers together with Shepherdr on controllers.
85
91
 
92
+ ### Attach existing agents
93
+
94
+ Use `attach` before delegating when an independently started agent needs shared notes, history or board membership:
95
+
96
+ ```js
97
+ await tools.agents({ action: "attach", target: "<target from find>", context: true, board: true })
98
+ ```
99
+
100
+ Supply both booleans and enable at least one. `context` shares notes and history through aliases without changing either session's original context identity or moving its notes. `contextAgent` addresses the target from the controller; `controllerContextAgent` addresses the controller from the target. Use these paths as `history`'s `agent_name` or as `<agent>/notes/<path>` for notes. Each agent's relative note paths remain its own. The target receives its controller alias without starting a turn.
101
+
102
+ Context attachment requires updated Codex Conversion with Local, Tree or Remote storage. Each owner keeps its original context identity and storage, including when the two agents use different stores. Remote access uses the reader's active Codex transport and requires the original account and backend, regardless of provider name. The explicit `context: true` choice does not depend on the controller's spawn-sharing setting. Use Code or Notebook with ordinary query and text for mixed-storage search and writes. Direct sensitive calls cannot cross between encrypted Remote arguments and ordinary Local or Tree arguments. If attachment changes context access during an exec cell, start a new cell before using notes or history.
103
+
104
+ An account mismatch rejects context sharing. Each agent keeps its own notes and history. If the account changes after attachment, pinned Remote notes become unavailable, including native Remote notes. Notes do not move to a new account or another store. Use messages to exchange the context the other agent needs.
105
+
106
+ `board: true` joins the controller's enabled board and returns `boardAgent` for subscriptions and notifications. The target's previous board archive stays untouched. If the folders differ, that archive remains in its original folder rather than becoming part of the controller's archive. Board-only attachment works without Codex Conversion and with Remote context storage.
107
+
108
+ The target must be idle and both Pi sessions must be saved. Existing shared-context members and controllers with context children cannot be context targets. Existing board members and roots with board children cannot switch boards. A target supports one controller and one fixed set of attachment choices. Attachment starts no task or watch; `assign` and `send` never attach implicitly.
109
+
110
+ Attachments survive resume, not forks. Local and Tree live access needs the owning Pi processes and machine connections. Remote access uses authenticated backend references rather than the owner's running process. After an interrupted attachment, resume the original sessions and retry the same target and choices. The target may already have joined even when the controller reports failure; retries reuse the original aliases and membership rather than creating duplicates.
111
+
112
+ To detach, call `agents` with `action: "detach"`, the same target, and both booleans. Enable each membership you want to leave. Context detach retains counterpart notes under the existing aliases read-only. Local and Tree notes use captured checkpoints. Remote notes retain an authenticated reference to the original owner's saved backend notes, not a frozen plaintext snapshot. Counterpart history and writes stop at detach. Native notes and history keep their original identities. Board detach restores the target's previous board and stops its shared-board notifications without deleting either archive. Board members with children cannot detach. Reattachment is unsupported.
113
+
114
+ If an attached owner closes or dies, Local and Tree notes reads first use its latest saved checkpoints when the source machine and session file remain reachable. This needs no running owner process and never writes to its session file. If the source is unavailable, reads return the timestamped snapshot captured at attachment, explicitly marked stale with the access failure. No latest-checkpoint guarantee is possible for a disconnected source machine or unsaved notes. Local and Tree counterpart history still requires its live owner. Remote notes and history remain reachable through the backend with the original account and backend. Backend failures stay visible without a local fallback. An incomplete detach fails with a retry instruction rather than claiming success.
115
+
86
116
  ## Message board
87
117
 
88
- The board is off by default. In the root session, run `/herdr board` to open its settings menu. Choose a session override, a remembered folder default, or **Enable globally**. Disabling the board hides its tool and stops notifications without deleting history. Board storage requires Node.js 22.13 or newer. Pi Codex Conversion is not required.
118
+ The board is off by default. Open `/herdr` → **Settings** in the root session and choose a session override, a remembered folder default, or a global default. Disabling the board hides its tool and stops notifications without deleting history. Board storage requires Node.js 22.13 or newer. Pi Codex Conversion is not required.
89
119
 
90
120
  Session overrides survive resume but do not carry into new root sessions or forks. Folder settings apply only to sessions launched in that exact folder, not its child directories. Global enablement is a separate setting. Precedence is session, folder, then global. Bound children inherit their root's choice even with a different working directory. Orchestration mode and shared notes remain independent.
91
121
 
@@ -103,19 +133,19 @@ The extension creates `pi-shepherdr.json` in Pi's global agent directory with th
103
133
 
104
134
  The agent directory defaults to `~/.pi/agent` and respects `PI_CODING_AGENT_DIR`. Enabling a board in the home folder writes `~/.pi/pi-shepherdr.json`, not the global setting. It does not enable boards in other folders. Storage location never implies activation scope. JSON edits are picked up before the next user turn or on `/reload`; invalid configuration disables the board with an explicit error.
105
135
 
106
- Command equivalents are `/herdr board on` or `off` for this session, `/herdr board on folder` or `off folder` for a folder default, and `/herdr board on global` or `off global` for the global default. `/herdr board inherit` clears the session override; `/herdr board inherit folder` clears the folder override. A session override can mask changes to either default. Outside the TUI, `/herdr board` reports status and archive location.
136
+ If the global agent directory is the launch folder's `.pi` directory, that file is only global configuration. Use a session override instead of a folder default there.
107
137
 
108
138
  Agents call `board` with `action: "help"` to discover channels, posts, replies, search, subscriptions and bounded reads. Code and Notebook Mode use `tools.board`. Agents choose when discussions are useful. Enabling the board, starting sessions, reading history and spawning children do not create an empty board. The first successful channel creation or post to a new channel creates it.
109
139
 
110
140
  Results fit 8,000 serialized UTF-8 bytes, including JSON escaping and metadata. Reads may return smaller pages or text slices than requested. Continue with the returned cursor or `next_offset_chars`. A search with `after_message_id` requires a post in the selected board, even before an archive exists.
111
141
 
112
- One archive at `<owning-folder>/.pi/agent-message-board.sqlite` retains all boards for that folder. Each root Pi session has an isolated board; resume keeps it and new root sessions get separate boards. Children spawned while the board is enabled inherit its location and board ID even with another working directory. The spawn result's `boardAgent` is their address for subscriptions and explicit notifications, distinct from a pane or shared-notes identity. Independently started agents, existing `assign` targets and children spawned while it is off do not join automatically. Board identity is independent of shared notes and `share_context`.
142
+ One archive at `<owning-folder>/.pi/agent-message-board.sqlite` retains all boards for that folder. Each root Pi session has an isolated board; resume keeps it and new root sessions get separate boards. Children spawned while the board is enabled inherit its location and board ID even with another working directory. The spawn result's `boardAgent` is their address for subscriptions and explicit notifications, distinct from a pane or shared-notes identity. Independently started agents, existing `assign` targets and children spawned while it is off do not join automatically; use explicit `attach` to join an existing agent. Board identity is independent of shared notes and `share_context`.
113
143
 
114
144
  Calls default to the current board. `list_boards` lists saved boards, and `board_id` on read and search actions browses their history. Writes and subscriptions always target the current board. There is no task assignment, post editing or board deletion tool. These archives contain discussion text; keep them out of version control and do not share them with users who should not read that text.
115
145
 
116
146
  Posting subscribes its author to discussion replies unless the author explicitly unsubscribed. Channel subscriptions concern only new first posts. Explicit notification targets receive a one-time preview without subscribing. Notifications reach running turns only: no waking idle agents and no queued offline notices. Full text remains available through reads.
117
147
 
118
- Child board calls use the owning Pi sessions and existing SSH connections, not a separately provisioned service. The root and intermediate controllers must be running as processes, but need not be in an active model turn. Resume the owner and use `/herdr connect` after a lost connection. Future root sessions can browse the archive even when the old owner is offline. A fork starts a new independent identity. Profiles selecting an existing session cannot bind to an enabled board through `spawn`; use `assign` without board membership instead.
148
+ Child board calls use the owning Pi sessions and existing SSH connections, not a separately provisioned service. The root and intermediate controllers must be running as processes, but need not be in an active model turn. Resume the owner and reconnect under `/herdr` → **Status** after a lost connection. Future root sessions can browse the archive even when the old owner is offline. A fork starts a new independent identity. Profiles selecting an existing session cannot bind to an enabled board through `spawn`; use `attach` followed by `assign` instead.
119
149
 
120
150
  ## Shared notes and history
121
151
 
@@ -125,9 +155,9 @@ Set `"share_context": false` in a profile to keep its new workers' notes and his
125
155
 
126
156
  Pi creates each worker session normally. The worker records its shared identity before Shepherdr delivers the first task; no pre-created session file or launch override is needed.
127
157
 
128
- Remote sharing requires Remote storage and the same Codex account on both ends. Local and Tree route through the owning Pi sessions and existing SSH connections. Those owners and intermediate controllers must be running; unavailable routes fail explicitly. Resume the owner and use `/herdr connect` after a connection loss. No note store is copied or silently substituted.
158
+ Remote sharing requires Remote storage and the same Codex account on both ends. Local and Tree route through the owning Pi sessions and existing SSH connections. Those owners and intermediate controllers must be running; unavailable routes fail explicitly. Resume the owner and reconnect under `/herdr` → **Status** after a connection loss. No note store is copied or silently substituted.
129
159
 
130
- Both extensions work independently. A target without active context support still starts, with a warning that its context is not shared. A conflicting storage mode or account rejects the shared spawn before task delivery. Profiles that select or resume an existing session cannot participate in shared `spawn`; use `assign` instead.
160
+ Both extensions work independently. A target without active context support still starts, with a warning that its context is not shared. A conflicting storage mode or account rejects the shared spawn before task delivery. Profiles that select or resume an existing session cannot participate in shared `spawn`; use `attach` for context access, then `assign`.
131
161
 
132
162
  ## Profiles
133
163
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=3.0.43",
46
+ "@howaboua/pi-codex-conversion": ">=3.0.45",
47
47
  "@earendil-works/pi-ai": ">=1.0.0",
48
48
  "@earendil-works/pi-coding-agent": ">=1.0.0",
49
49
  "@earendil-works/pi-tui": ">=1.0.0",
@@ -58,11 +58,11 @@
58
58
  "unicode-case-folding": "1.1.2"
59
59
  },
60
60
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.43",
61
+ "@howaboua/pi-codex-conversion": "3.0.45",
62
62
  "@biomejs/biome": "^2.5.10",
63
- "@earendil-works/pi-ai": "1.0.0",
64
- "@earendil-works/pi-coding-agent": "1.0.0",
65
- "@earendil-works/pi-tui": "1.0.0",
63
+ "@earendil-works/pi-ai": "1.0.1",
64
+ "@earendil-works/pi-coding-agent": "1.0.1",
65
+ "@earendil-works/pi-tui": "1.0.1",
66
66
  "@types/node": "^26.2.0",
67
67
  "typebox": "1.3.18",
68
68
  "typescript": "^7.0.2"
@@ -13,6 +13,8 @@ const ACTIONS = [
13
13
  "unwatch",
14
14
  "send",
15
15
  "assign",
16
+ "attach",
17
+ "detach",
16
18
  "read",
17
19
  "answer",
18
20
  ] as const;
@@ -42,6 +44,8 @@ const ACTION_FIELDS: Record<(typeof ACTIONS)[number], ReadonlySet<string>> = {
42
44
  unwatch: new Set(["action", "machine", "target"]),
43
45
  send: new Set(["action", "machine", "target", "message"]),
44
46
  assign: new Set(["action", "machine", "target", "message", "blocking"]),
47
+ attach: new Set(["action", "machine", "target", "context", "board"]),
48
+ detach: new Set(["action", "machine", "target", "context", "board"]),
45
49
  read: new Set(["action", "machine", "target", "source", "lines"]),
46
50
  answer: new Set(["action", "machine", "target", "ask_id", "answers"]),
47
51
  };
@@ -83,6 +87,8 @@ const AgentsRequest = Type.Object(
83
87
  "Delegation only; profile policy overrides spawn; otherwise defaults true",
84
88
  }),
85
89
  ),
90
+ context: Type.Optional(Type.Boolean()),
91
+ board: Type.Optional(Type.Boolean()),
86
92
  query: Type.Optional(Type.String()),
87
93
  status: Type.Optional(StringEnum(STATUSES)),
88
94
  source: Type.Optional(StringEnum(READ_SOURCES)),
@@ -134,6 +140,15 @@ export function parseAgentsRequest(input: unknown): AgentsParams {
134
140
  );
135
141
  }
136
142
  const request = value as Record<string, unknown>;
143
+ if (
144
+ (action === "attach" || action === "detach") &&
145
+ (typeof request["context"] !== "boolean" ||
146
+ typeof request["board"] !== "boolean" ||
147
+ (!request["context"] && !request["board"]))
148
+ )
149
+ throw new Error(
150
+ `${action} requires context and board booleans; enable at least one`,
151
+ );
137
152
  const askId = request["ask_id"];
138
153
  if (action === "answer" && (typeof askId !== "string" || !askId.trim())) {
139
154
  throw new Error("ask_id is required for answer");
@@ -36,6 +36,8 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
36
36
  unwatch: "target machine?",
37
37
  send: "target message machine?",
38
38
  assign: "target message machine? blocking?",
39
+ attach: "target context board machine?",
40
+ detach: "target context board machine?",
39
41
  read: "target machine? source? lines?",
40
42
  answer: "target ask_id answers machine?",
41
43
  },
@@ -48,6 +50,10 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
48
50
  ask_id: "Exact pending Ask ID",
49
51
  send: "Only for a needed answer or to change the recipient's current work. No courtesy updates, acknowledgements or completion echoes. Can wake idle agents; no wait/watch",
50
52
  assign: "Delegate a task to an existing agent",
53
+ attach:
54
+ "Idle target; context/board booleans choose shared access and board membership independently; no task/watch",
55
+ detach:
56
+ "Stop selected membership; retain counterpart checkpoints read-only; idle target",
51
57
  blocking:
52
58
  "spawn/assign default true; profile blocking overrides spawn. Fan out independent implementation workers with false; end your turn when only waiting. Completion/blockage arrives after you reply; no polling or sleep waits",
53
59
  share_context:
@@ -90,6 +90,17 @@ export function createAgentsTool(
90
90
  target,
91
91
  runtime.local ? process.env["HERDR_PANE_ID"] : "",
92
92
  );
93
+ if (params.action === "attach" || params.action === "detach") {
94
+ return toolResult(
95
+ await sharedContext.attachment[params.action](
96
+ ctx,
97
+ runtime,
98
+ panel,
99
+ params,
100
+ executionSignal,
101
+ ),
102
+ );
103
+ }
93
104
  if (params.action === "watch") {
94
105
  await runtime.monitor.watch(panel);
95
106
  return toolResult({
@@ -0,0 +1,181 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type {
3
+ ContextAgentIdentity,
4
+ ContextSharingService,
5
+ SharedContextRequest,
6
+ SharedContextResult,
7
+ } from "@howaboua/pi-codex-conversion/context-sharing";
8
+
9
+ /** Read-only continuity when a live owner disappears. Parsing remains Conversion-owned. */
10
+ export class AttachmentNotes {
11
+ private readonly getService: () => ContextSharingService | undefined;
12
+ constructor(getService: () => ContextSharingService | undefined) {
13
+ this.getService = getService;
14
+ }
15
+ private service() {
16
+ const service = this.getService();
17
+ if (
18
+ !service?.exportAttachmentNotes ||
19
+ !service.parseAttachmentNotes ||
20
+ !service.readAttachmentNotes
21
+ )
22
+ throw new Error("Update Codex Conversion to retain attached checkpoints");
23
+ return {
24
+ export: service.exportAttachmentNotes,
25
+ parse: service.parseAttachmentNotes,
26
+ read: service.readAttachmentNotes,
27
+ validate: service.validateAttachmentNotes,
28
+ verify: service.verifyAttachmentAccess,
29
+ remote: service.executeRemoteAttachment,
30
+ };
31
+ }
32
+ export(ctx: ExtensionContext) {
33
+ return this.service().export(ctx);
34
+ }
35
+ validate(snapshot: unknown, identity: ContextAgentIdentity) {
36
+ const service = this.service();
37
+ if (service.validate) return service.validate(snapshot, identity);
38
+ if (identity.storage === "remote")
39
+ throw new Error("Update Codex Conversion to retain Remote checkpoints");
40
+ this.service().read(snapshot, {
41
+ action: "list_files_by_prefix",
42
+ prefix: `${identity.agentName}/notes`,
43
+ });
44
+ }
45
+ async verify(
46
+ ctx: ExtensionContext,
47
+ snapshot: unknown,
48
+ identity: ContextAgentIdentity,
49
+ alreadyShared = false,
50
+ ) {
51
+ this.validate(snapshot, identity);
52
+ if (identity.storage === "remote") {
53
+ const verify = this.service().verify;
54
+ if (!verify)
55
+ throw new Error(
56
+ "Update Codex Conversion to authenticate Remote attachments",
57
+ );
58
+ try {
59
+ await verify(ctx, snapshot);
60
+ } catch (error) {
61
+ if (
62
+ !alreadyShared &&
63
+ error instanceof Error &&
64
+ error.message.startsWith("Account mismatch.")
65
+ )
66
+ throw new Error(
67
+ "Account mismatch. Context was not shared. Each agent keeps its own notes and history. Use messages to exchange the context you need.",
68
+ { cause: error },
69
+ );
70
+ throw error;
71
+ }
72
+ }
73
+ }
74
+ async remote(
75
+ ctx: ExtensionContext,
76
+ reference: unknown,
77
+ request: SharedContextRequest,
78
+ signal?: AbortSignal,
79
+ ) {
80
+ const execute = this.service().remote;
81
+ if (!execute)
82
+ throw new Error(
83
+ "Update Codex Conversion to read attached Remote context",
84
+ );
85
+ return execute(ctx, reference, request, signal);
86
+ }
87
+ checkTransport(value: unknown) {
88
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > 7 * 1024 * 1024)
89
+ throw new Error(
90
+ "Attached checkpoints exceed the transport limit; attachment or detach was not committed",
91
+ );
92
+ }
93
+ canRead(request: SharedContextRequest) {
94
+ return (
95
+ request.namespace === "notes" &&
96
+ ["read_file", "list_files_by_prefix", "search_contents"].includes(
97
+ String(request.params["action"]),
98
+ )
99
+ );
100
+ }
101
+ unavailable(error: unknown) {
102
+ return (
103
+ error instanceof Error &&
104
+ /^(Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
105
+ error.message,
106
+ )
107
+ );
108
+ }
109
+ async read(
110
+ request: SharedContextRequest,
111
+ identity: ContextAgentIdentity,
112
+ retained: unknown,
113
+ detached: boolean,
114
+ persisted: () => Promise<unknown>,
115
+ liveError?: unknown,
116
+ ): Promise<SharedContextResult> {
117
+ if (request.namespace !== "notes")
118
+ throw new Error(
119
+ "Counterpart history requires its live attached owner; native history is unchanged",
120
+ );
121
+ if (
122
+ !["read_file", "list_files_by_prefix", "search_contents"].includes(
123
+ String(request.params["action"]),
124
+ )
125
+ )
126
+ throw new Error(
127
+ "Retained checkpoints are read-only; resume the attached owner to write notes",
128
+ );
129
+ let snapshot = retained;
130
+ let source = "retained-checkpoints";
131
+ let unavailable: string | undefined;
132
+ let savedAt: number | undefined;
133
+ if (!detached) {
134
+ try {
135
+ const result = await persisted();
136
+ if (
137
+ !result ||
138
+ typeof result !== "object" ||
139
+ !("entries" in result) ||
140
+ !("savedAt" in result) ||
141
+ typeof result.savedAt !== "number"
142
+ )
143
+ throw new Error("Invalid persisted checkpoint response");
144
+ snapshot = this.service().parse(result.entries, identity);
145
+ savedAt = result.savedAt;
146
+ source = "persisted-owner-checkpoints";
147
+ } catch (error) {
148
+ unavailable = String(error);
149
+ }
150
+ }
151
+ const result = this.service().read(snapshot, request.params);
152
+ if (
153
+ !snapshot ||
154
+ typeof snapshot !== "object" ||
155
+ !("timestamp" in snapshot) ||
156
+ typeof snapshot.timestamp !== "number"
157
+ )
158
+ throw new Error("Invalid retained checkpoint timestamp");
159
+ const details = {
160
+ ...result.details.codexHistoryNotes,
161
+ source,
162
+ read_only: true,
163
+ captured_at: new Date(snapshot.timestamp).toISOString(),
164
+ ...(savedAt === undefined
165
+ ? {}
166
+ : { saved_at: new Date(savedAt).toISOString() }),
167
+ ...(detached
168
+ ? { detached: true }
169
+ : {
170
+ live_unavailable: String(liveError),
171
+ ...(unavailable
172
+ ? { persisted_unavailable: unavailable, stale: true }
173
+ : {}),
174
+ }),
175
+ };
176
+ return {
177
+ content: [{ type: "text", text: JSON.stringify(details) }],
178
+ details: { codexHistoryNotes: details },
179
+ };
180
+ }
181
+ }
@@ -0,0 +1,155 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { SharedContextResult } from "@howaboua/pi-codex-conversion/context-sharing";
5
+ import type { Static, TSchema } from "typebox";
6
+ import { Check } from "typebox/value";
7
+ import { BindingSchema } from "./board/identity.js";
8
+
9
+ const AgentPath = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
10
+ export const Identity = Type.Object({
11
+ protocol: Type.Literal(1),
12
+ sessionId: Type.String({ minLength: 1 }),
13
+ threadId: Type.String({ minLength: 1 }),
14
+ agentName: AgentPath,
15
+ storage: Type.Union([Type.Literal("session"), Type.Literal("remote")]),
16
+ accountScope: Type.Optional(Type.String({ pattern: "^[a-f0-9]{64}$" })),
17
+ backendUrl: Type.Optional(Type.String({ minLength: 1 })),
18
+ routing: Type.Optional(Type.Unknown()),
19
+ });
20
+ const ContextLink = Type.Object({
21
+ controller: Identity,
22
+ target: Identity,
23
+ alias: AgentPath,
24
+ controllerAlias: AgentPath,
25
+ controllerFile: Type.Optional(Type.String()),
26
+ controllerNotes: Type.Unknown(),
27
+ targetNotes: Type.Unknown(),
28
+ });
29
+ export const Plan = Type.Object(
30
+ {
31
+ controllerSessionId: Type.String({ minLength: 1 }),
32
+ targetSessionId: Type.String({ minLength: 1 }),
33
+ upstream: Type.String({ minLength: 1 }),
34
+ context: Type.Optional(ContextLink),
35
+ board: Type.Optional(
36
+ Type.Object({
37
+ previous: BindingSchema,
38
+ desired: BindingSchema,
39
+ controller: BindingSchema,
40
+ }),
41
+ ),
42
+ },
43
+ { additionalProperties: false },
44
+ );
45
+ const Route = Type.Object({
46
+ plan: Plan,
47
+ machine: Type.String(),
48
+ sessionFile: Type.String({ minLength: 1 }),
49
+ phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
50
+ detached: Type.Optional(
51
+ Type.Object({
52
+ context: Type.Optional(Type.Unknown()),
53
+ board: Type.Optional(Type.Literal(true)),
54
+ }),
55
+ ),
56
+ });
57
+ export const Snapshot = Type.Object({
58
+ sessionId: Type.String({ minLength: 1 }),
59
+ board: BindingSchema,
60
+ context: Type.Optional(Identity),
61
+ notes: Type.Optional(Type.Unknown()),
62
+ contextError: Type.Optional(Type.String()),
63
+ boardError: Type.Optional(Type.String()),
64
+ });
65
+ export type AttachmentPlan = Static<typeof Plan>;
66
+ export type AttachmentRoute = Static<typeof Route>;
67
+ export const OWNER = "shepherdr-attachment-owner";
68
+ export const ROUTE = "shepherdr-attachment-route";
69
+ export const DETACHED = "shepherdr-attachment-detached";
70
+ export const Detachment = Type.Object({
71
+ plan: Plan,
72
+ context: Type.Optional(Type.Unknown()),
73
+ board: Type.Optional(Type.Literal(true)),
74
+ });
75
+
76
+ function saved<T extends TSchema>(
77
+ ctx: ExtensionContext,
78
+ key: string,
79
+ schema: T,
80
+ ): Static<T>[] {
81
+ return ctx.sessionManager.getEntries().flatMap((entry) => {
82
+ if (entry.type !== "custom" || entry.customType !== key) return [];
83
+ if (!Check(schema, entry.data))
84
+ throw new Error("Invalid saved agent attachment");
85
+ return [entry.data as Static<T>];
86
+ });
87
+ }
88
+ export function inside(path: string, root: string) {
89
+ return path === root || path.startsWith(`${root}/`);
90
+ }
91
+ export function remap(value: string, from: string, to: string) {
92
+ return inside(value, from) ? `${to}${value.slice(from.length)}` : value;
93
+ }
94
+ export function remapParams(
95
+ params: Record<string, unknown>,
96
+ from: string,
97
+ to: string,
98
+ ) {
99
+ return Object.fromEntries(
100
+ Object.entries(params).map(([key, value]) => [
101
+ key,
102
+ ["agent_name", "path", "prefix", "path_prefix"].includes(key) &&
103
+ typeof value === "string"
104
+ ? remap(value, from, to)
105
+ : value,
106
+ ]),
107
+ );
108
+ }
109
+ export function remapResult(
110
+ result: SharedContextResult,
111
+ from: string,
112
+ to: string,
113
+ ): SharedContextResult {
114
+ if (
115
+ typeof result.details.codexHistoryNotes["encrypted_output"] === "string"
116
+ ) {
117
+ const hint = `Source ${from}, access through ${to}. Use ${to}/notes for note paths and ${to} for history agent_name`;
118
+ // Ciphertext paths cannot be remapped. Preserve host-only provenance on the original details.
119
+ result.details.codexHistoryNotes["attachment_hint"] = hint;
120
+ return {
121
+ ...result,
122
+ content: [{ type: "text", text: hint }, ...result.content],
123
+ };
124
+ }
125
+ const details = JSON.parse(
126
+ JSON.stringify(result.details.codexHistoryNotes),
127
+ (key, value: unknown) =>
128
+ (key === "path" || key === "agent_name") && typeof value === "string"
129
+ ? remap(value, from, to)
130
+ : value,
131
+ ) as Record<string, unknown>;
132
+ return {
133
+ ...result,
134
+ content: [{ type: "text", text: JSON.stringify(details) }],
135
+ details: { codexHistoryNotes: details },
136
+ };
137
+ }
138
+
139
+ export function detachment(ctx: ExtensionContext, plan: AttachmentPlan) {
140
+ return saved(ctx, DETACHED, Detachment).findLast((entry) =>
141
+ isDeepStrictEqual(entry.plan, plan),
142
+ );
143
+ }
144
+ export function attachmentOwner(ctx: ExtensionContext) {
145
+ return saved(ctx, OWNER, Plan).findLast(
146
+ (plan) => plan.targetSessionId === ctx.sessionManager.getSessionId(),
147
+ );
148
+ }
149
+ export function attachmentRoutes(ctx: ExtensionContext) {
150
+ const found = new Map<string, AttachmentRoute>();
151
+ for (const route of saved(ctx, ROUTE, Route))
152
+ if (route.plan.controllerSessionId === ctx.sessionManager.getSessionId())
153
+ found.set(route.sessionFile + "\0" + route.machine, route);
154
+ return [...found.values()];
155
+ }