@howaboua/pi-shepherdr 0.2.24 → 0.2.25

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 (73) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +17 -9
  3. package/index.ts +2 -0
  4. package/package.json +5 -5
  5. package/src/agents-contract.ts +9 -6
  6. package/src/agents-discovery.ts +41 -15
  7. package/src/agents-focus.ts +15 -9
  8. package/src/agents-spawn.ts +22 -6
  9. package/src/agents-tool.ts +24 -6
  10. package/src/agents-work.ts +2 -2
  11. package/src/attachment.ts +2 -0
  12. package/src/board/host.ts +3 -1
  13. package/src/close-idle.ts +89 -0
  14. package/src/control-panel/index.ts +3 -1
  15. package/src/control-panel/items.ts +14 -2
  16. package/src/control-panel/view.ts +6 -2
  17. package/src/controller.ts +11 -2
  18. package/src/core/AGENTS.md +5 -0
  19. package/src/core/backend.ts +266 -0
  20. package/src/core/client.ts +249 -0
  21. package/src/core/context-relay.mjs +111 -0
  22. package/src/core/focus-channel-helper.mjs +165 -0
  23. package/src/core/focus-channel-stream.ts +140 -0
  24. package/src/core/focus-channel-wire.mjs +160 -0
  25. package/src/core/focus-channel.ts +213 -0
  26. package/src/core/focus-window.ts +192 -0
  27. package/src/core/pi-executable.mjs +34 -0
  28. package/src/core/protocol.ts +116 -0
  29. package/src/core/registration.ts +51 -0
  30. package/src/core/remote-endpoint.ts +119 -0
  31. package/src/core/remote-exec.ts +122 -0
  32. package/src/core/remote-helper.mjs +244 -0
  33. package/src/core/remote-reader.ts +67 -0
  34. package/src/core/remote-relay.ts +191 -0
  35. package/src/core/request.ts +124 -0
  36. package/src/core/spawn.ts +177 -0
  37. package/src/core/status.ts +68 -0
  38. package/src/core/terminal.ts +103 -0
  39. package/src/fleet/catalog.ts +83 -0
  40. package/src/fleet/connection.ts +111 -0
  41. package/src/fleet/index.ts +151 -122
  42. package/src/fleet/inspection.ts +19 -1
  43. package/src/fleet/machine.ts +3 -0
  44. package/src/fleet/monitor.ts +18 -4
  45. package/src/fleet/persistence.ts +26 -3
  46. package/src/fleet/setup.ts +54 -13
  47. package/src/herdr.ts +25 -5
  48. package/src/launch-contract.ts +48 -0
  49. package/src/launch-location.ts +151 -0
  50. package/src/launch.ts +30 -183
  51. package/src/messages/attribution.ts +15 -6
  52. package/src/messages/events.ts +10 -4
  53. package/src/messages/focus.ts +11 -2
  54. package/src/monitor-record.ts +9 -6
  55. package/src/monitor.ts +31 -0
  56. package/src/peer-commands.ts +11 -0
  57. package/src/peer-inbox-delivery.ts +171 -0
  58. package/src/peer-inbox-focus.ts +113 -0
  59. package/src/peer-inbox.ts +126 -208
  60. package/src/remote/deployment.ts +1 -1
  61. package/src/remote/shepherdr-context.mjs +1 -1
  62. package/src/remote/shepherdr-peer.mjs +18 -5
  63. package/src/remote/shepherdr-session.mjs +9 -2
  64. package/src/remote/shepherdr.mjs +1 -1
  65. package/src/settlement/collector.ts +2 -2
  66. package/src/settlement/index.ts +12 -0
  67. package/src/shared-context-host.ts +7 -3
  68. package/src/shared-context.ts +34 -2
  69. package/src/spawn-context.ts +4 -0
  70. package/src/spawn-ownership.ts +91 -0
  71. package/src/types.ts +9 -5
  72. package/src/worker-ownership.ts +92 -0
  73. package/src/worker-service.ts +12 -81
@@ -2,16 +2,25 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { LOCAL_MACHINE } from "../machine-catalog.js";
3
3
  export const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
4
4
 
5
- export function savedAgents(ctx: ExtensionContext): unknown[] {
5
+ export function savedAgents(
6
+ ctx: ExtensionContext,
7
+ localCoreId?: string,
8
+ ): unknown[] {
6
9
  let latest: unknown[] = [];
7
10
  let version: unknown;
11
+ let savedCoreId: unknown;
8
12
  for (const entry of ctx.sessionManager.getBranch()) {
9
13
  if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
10
14
  continue;
11
- const data = entry.data as { version?: unknown; agents?: unknown };
15
+ const data = entry.data as {
16
+ version?: unknown;
17
+ agents?: unknown;
18
+ localCoreId?: unknown;
19
+ };
12
20
  if (Array.isArray(data?.agents)) {
13
21
  latest = data.agents;
14
22
  version = data.version;
23
+ savedCoreId = data.localCoreId;
15
24
  }
16
25
  }
17
26
  if (latest.length > 0 && version !== 2) {
@@ -21,7 +30,21 @@ export function savedAgents(ctx: ExtensionContext): unknown[] {
21
30
  );
22
31
  return [];
23
32
  }
24
- return latest;
33
+ if (savedCoreId === localCoreId) return latest;
34
+ const retained = latest.filter(
35
+ (value) =>
36
+ typeof value === "object" &&
37
+ value !== null &&
38
+ "machine" in value &&
39
+ typeof value.machine === "string" &&
40
+ value.machine !== LOCAL_MACHINE,
41
+ );
42
+ if (retained.length !== latest.length)
43
+ ctx.ui.notify(
44
+ "Ignored saved local agent watches from another Herdr session; watch them again in this session.",
45
+ "warning",
46
+ );
47
+ return retained;
25
48
  }
26
49
 
27
50
  export function groupSaved(values: unknown[]): Map<string, unknown[]> {
@@ -1,9 +1,15 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
2
3
  import { RemoteHerdrClient } from "../remote/client.js";
3
4
  import { errorMessage, type MachineRuntime } from "./machine.js";
4
5
 
5
6
  /** Explicitly requested sharing/monitor readiness; fleet supplies current-selection leases. */
6
7
  export class FleetSetup {
8
+ // Concurrent publishers share one start; existing children retain its route.
9
+ private readonly relays = new WeakMap<
10
+ RemoteHerdrClient | CoreConnection,
11
+ Promise<void>
12
+ >();
7
13
  private readonly refresh: () => void;
8
14
  constructor(refresh: () => void) {
9
15
  this.refresh = refresh;
@@ -24,29 +30,63 @@ export class FleetSetup {
24
30
  ): void {
25
31
  this.contextRelay = handler;
26
32
  }
27
- async prepareContextRelay(
33
+ prepareContextRelay(
28
34
  name: string,
29
35
  runtime: MachineRuntime,
30
- client: RemoteHerdrClient,
36
+ client: RemoteHerdrClient | CoreConnection,
31
37
  ctx: ExtensionContext,
32
38
  isSelected: () => boolean,
33
39
  ): Promise<void> {
34
- if (!this.contextRelay) return;
35
- try {
36
- await client.startContextRelay(
37
- ctx.sessionManager.getSessionId(),
38
- name,
39
- (request, signal) => this.contextRelay!(ctx, request, signal),
40
+ if (!this.contextRelay)
41
+ return Promise.reject(
42
+ new Error("Context sharing is unavailable in this session"),
40
43
  );
41
- if (!isSelected()) return;
42
- delete runtime.contextRelayError;
43
- } catch (error) {
44
+ const ready = this.relays.get(client);
45
+ if (ready) return ready;
46
+ const starting = this.openContextRelay(
47
+ name,
48
+ runtime,
49
+ client,
50
+ ctx,
51
+ isSelected,
52
+ );
53
+ this.relays.set(client, starting);
54
+ return starting;
55
+ }
56
+ private async openContextRelay(
57
+ name: string,
58
+ runtime: MachineRuntime,
59
+ client: RemoteHerdrClient | CoreConnection,
60
+ ctx: ExtensionContext,
61
+ isSelected: () => boolean,
62
+ ): Promise<void> {
63
+ if (!this.contextRelay)
64
+ throw new Error("Context sharing is unavailable in this session");
65
+ const failed = (error: unknown) => {
66
+ this.relays.delete(client);
44
67
  if (!isSelected()) return;
45
68
  runtime.contextRelayError = errorMessage(error);
46
69
  ctx.ui.notify(
47
70
  `Context sharing unavailable on ${name}: ${runtime.contextRelayError}\nOpen /herdr → Status to retry sharing.`,
48
71
  "warning",
49
72
  );
73
+ this.refresh();
74
+ };
75
+ try {
76
+ const args = [
77
+ ctx.sessionManager.getSessionId(),
78
+ name,
79
+ (request: unknown, signal: AbortSignal) =>
80
+ this.contextRelay!(ctx, request, signal),
81
+ ] as const;
82
+ if (client instanceof CoreConnection)
83
+ await client.startContextRelay(...args, failed);
84
+ else await client.startContextRelay(...args);
85
+ if (!isSelected()) return;
86
+ delete runtime.contextRelayError;
87
+ } catch (error) {
88
+ failed(error);
89
+ throw error;
50
90
  }
51
91
  }
52
92
 
@@ -65,7 +105,8 @@ export class FleetSetup {
65
105
  try {
66
106
  if (
67
107
  runtime.contextRelayError &&
68
- runtime.client instanceof RemoteHerdrClient
108
+ (runtime.client instanceof RemoteHerdrClient ||
109
+ runtime.client instanceof CoreConnection)
69
110
  )
70
111
  await this.prepareContextRelay(
71
112
  name,
@@ -73,7 +114,7 @@ export class FleetSetup {
73
114
  runtime.client,
74
115
  ctx,
75
116
  isSelected,
76
- );
117
+ ).catch(() => {});
77
118
  if (isCurrent() && isRegistered() && runtime.monitoringIssue)
78
119
  await monitor.retryMonitoring();
79
120
  } catch (error) {
package/src/herdr.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { CoreConnection } from "./core/backend.js";
1
2
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
2
3
  import type {
3
4
  AgentStatus,
@@ -49,9 +50,14 @@ export async function getPane(
49
50
  export async function getCurrentPane(
50
51
  client: HerdrConnection,
51
52
  ): Promise<PaneInfo> {
52
- const callerPaneId = process.env["HERDR_PANE_ID"];
53
+ const callerPaneId =
54
+ client instanceof CoreConnection
55
+ ? process.env["HC_TERMINAL_ID"]
56
+ : process.env["HERDR_PANE_ID"];
53
57
  if (!callerPaneId)
54
- throw new Error("HERDR_PANE_ID is required to identify the sender");
58
+ throw new Error(
59
+ "Cannot identify this terminal; run Pi inside Herdr and retry",
60
+ );
55
61
  const result = record(
56
62
  await client.request<unknown>("pane.current", {
57
63
  caller_pane_id: callerPaneId,
@@ -64,7 +70,9 @@ export async function getCurrentPane(
64
70
  export async function resolvePiAgent(
65
71
  client: HerdrConnection,
66
72
  target: string,
67
- controllingPaneId = process.env["HERDR_PANE_ID"],
73
+ controllingPaneId = client instanceof CoreConnection
74
+ ? process.env["HC_TERMINAL_ID"]
75
+ : process.env["HERDR_PANE_ID"],
68
76
  ): Promise<PaneInfo> {
69
77
  const agent = await getAgent(client, target).catch((error: unknown) => {
70
78
  if (error instanceof Error && isHerdrErrorCode(error, "agent_not_found")) {
@@ -108,10 +116,22 @@ export function sessionPath(agent: PaneInfo): string | undefined {
108
116
  export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
109
117
  const pane = record(value, path);
110
118
  return {
119
+ ...(pane["backend"] === "core" ? { backend: "core" as const } : {}),
111
120
  pane_id: requiredString(pane, "pane_id", path),
112
121
  terminal_id: requiredString(pane, "terminal_id", path),
113
- workspace_id: requiredString(pane, "workspace_id", path),
114
- tab_id: requiredString(pane, "tab_id", path),
122
+ ...(pane["backend"] === "core"
123
+ ? {
124
+ ...(typeof pane["workspace_id"] === "string"
125
+ ? { workspace_id: pane["workspace_id"] }
126
+ : {}),
127
+ ...(typeof pane["tab_id"] === "string"
128
+ ? { tab_id: pane["tab_id"] }
129
+ : {}),
130
+ }
131
+ : {
132
+ workspace_id: requiredString(pane, "workspace_id", path),
133
+ tab_id: requiredString(pane, "tab_id", path),
134
+ }),
115
135
  agent_status: parseAgentStatus(
116
136
  pane["agent_status"],
117
137
  `${path}.agent_status`,
@@ -0,0 +1,48 @@
1
+ import type { PaneInfo } from "./types.js";
2
+
3
+ export const START_PLACEMENTS = [
4
+ "new_workspace",
5
+ "new_tab",
6
+ "pane",
7
+ "terminal",
8
+ ] as const;
9
+
10
+ export interface StartAgentParams {
11
+ cwd?: string;
12
+ label?: string;
13
+ name?: string;
14
+ pane?: string;
15
+ placement?: (typeof START_PLACEMENTS)[number];
16
+ workspace?: string;
17
+ }
18
+
19
+ export interface CreatedLocationCleanup {
20
+ id: string;
21
+ method: "tab.close" | "workspace.close" | "terminal.close";
22
+ }
23
+
24
+ export interface StartedAgent {
25
+ agent: PaneInfo;
26
+ cleanup?: CreatedLocationCleanup;
27
+ id: string;
28
+ }
29
+
30
+ export class RolledBackAgentLaunchError extends Error {
31
+ constructor(cause: unknown) {
32
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
33
+ }
34
+ }
35
+
36
+ export class UnstartedAgentLaunchError extends Error {
37
+ constructor(cause: unknown) {
38
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
39
+ }
40
+ }
41
+
42
+ export function requiredStartField(
43
+ value: string | undefined,
44
+ field: string,
45
+ ): string {
46
+ if (!value?.trim()) throw new Error(`${field} is required for start`);
47
+ return value.trim();
48
+ }
@@ -0,0 +1,151 @@
1
+ import { getSnapshot, parsePaneInfo, resolveWorkspace } from "./herdr.js";
2
+ import type { HerdrConnection } from "./herdr-client.js";
3
+ import {
4
+ type CreatedLocationCleanup,
5
+ RolledBackAgentLaunchError,
6
+ requiredStartField,
7
+ type StartAgentParams,
8
+ UnstartedAgentLaunchError,
9
+ } from "./launch-contract.js";
10
+ import type { PaneInfo } from "./types.js";
11
+
12
+ export async function createStartPane(
13
+ client: HerdrConnection,
14
+ params: StartAgentParams,
15
+ cwd: string,
16
+ label: string,
17
+ ): Promise<{
18
+ cleanup?: CreatedLocationCleanup;
19
+ paneId: string;
20
+ }> {
21
+ const placement = params.placement;
22
+ if (!placement) throw new Error("placement is required for start");
23
+ if (placement === "terminal")
24
+ throw new UnstartedAgentLaunchError(
25
+ "terminal placement requires Core; use new_tab or new_workspace in legacy Herdr",
26
+ );
27
+ if (placement === "pane") {
28
+ return { paneId: requiredStartField(params.pane, "pane") };
29
+ }
30
+ if (placement === "new_tab") {
31
+ const workspaceTarget = requiredStartField(params.workspace, "workspace");
32
+ let workspace;
33
+ try {
34
+ workspace = resolveWorkspace(await getSnapshot(client), workspaceTarget);
35
+ } catch (error) {
36
+ throw new UnstartedAgentLaunchError(error);
37
+ }
38
+ // A failed create response may still have created a location.
39
+ const created = createdLocation(
40
+ await client.request<unknown>("tab.create", {
41
+ workspace_id: workspace.workspace_id,
42
+ cwd,
43
+ label,
44
+ focus: false,
45
+ }),
46
+ "tab.create result",
47
+ );
48
+ return {
49
+ paneId: created.root_pane.pane_id,
50
+ cleanup: { method: "tab.close", id: created.tab.tab_id },
51
+ };
52
+ }
53
+ const created = createdLocation(
54
+ await client.request<unknown>("workspace.create", {
55
+ cwd,
56
+ focus: false,
57
+ }),
58
+ "workspace.create result",
59
+ true,
60
+ );
61
+ try {
62
+ await client.request("tab.rename", { tab_id: created.tab.tab_id, label });
63
+ } catch (error) {
64
+ return rollbackCreatedLocation(
65
+ client,
66
+ { method: "workspace.close", id: created.workspace.workspace_id },
67
+ error,
68
+ );
69
+ }
70
+ return {
71
+ paneId: created.root_pane.pane_id,
72
+ cleanup: { method: "workspace.close", id: created.workspace.workspace_id },
73
+ };
74
+ }
75
+
76
+ function createdLocation(
77
+ value: unknown,
78
+ path: string,
79
+ ): { root_pane: PaneInfo; tab: { tab_id: string } };
80
+ function createdLocation(
81
+ value: unknown,
82
+ path: string,
83
+ withWorkspace: true,
84
+ ): {
85
+ root_pane: PaneInfo;
86
+ tab: { tab_id: string };
87
+ workspace: { workspace_id: string };
88
+ };
89
+ function createdLocation(
90
+ value: unknown,
91
+ path: string,
92
+ withWorkspace = false,
93
+ ): {
94
+ root_pane: PaneInfo;
95
+ tab: { tab_id: string };
96
+ workspace?: { workspace_id: string };
97
+ } {
98
+ if (typeof value !== "object" || value === null) {
99
+ throw new Error(`Herdr ${path} must be an object`);
100
+ }
101
+ const result = value as Record<string, unknown>;
102
+ const tabId = nestedId(result["tab"], "tab_id", `${path}.tab`);
103
+ return {
104
+ root_pane: parsePaneInfo(result["root_pane"], `${path}.root_pane`),
105
+ tab: { tab_id: tabId },
106
+ ...(withWorkspace
107
+ ? {
108
+ workspace: {
109
+ workspace_id: nestedId(
110
+ result["workspace"],
111
+ "workspace_id",
112
+ `${path}.workspace`,
113
+ ),
114
+ },
115
+ }
116
+ : {}),
117
+ };
118
+ }
119
+
120
+ function nestedId(value: unknown, key: string, path: string): string {
121
+ if (typeof value !== "object" || value === null) {
122
+ throw new Error(`Herdr ${path} must be an object`);
123
+ }
124
+ const id = (value as Record<string, unknown>)[key];
125
+ if (typeof id !== "string")
126
+ throw new Error(`Herdr ${path}.${key} must be string`);
127
+ return id;
128
+ }
129
+
130
+ export async function rollbackCreatedLocation(
131
+ client: HerdrConnection,
132
+ cleanup: CreatedLocationCleanup | undefined,
133
+ cause: unknown,
134
+ ): Promise<never> {
135
+ if (!cleanup) throw cause;
136
+ try {
137
+ await client.request(cleanup.method, {
138
+ [cleanup.method === "tab.close"
139
+ ? "tab_id"
140
+ : cleanup.method === "terminal.close"
141
+ ? "id"
142
+ : "workspace_id"]: cleanup.id,
143
+ });
144
+ } catch (cleanupError) {
145
+ throw new Error(
146
+ `${cause instanceof Error ? cause.message : String(cause)}; rollback also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
147
+ { cause },
148
+ );
149
+ }
150
+ throw new RolledBackAgentLaunchError(cause);
151
+ }
package/src/launch.ts CHANGED
@@ -1,34 +1,27 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import { parseArgs } from "@earendil-works/pi-coding-agent";
4
- import {
5
- getAgent,
6
- getPane,
7
- getSnapshot,
8
- parsePaneInfo,
9
- resolveWorkspace,
10
- sessionPath,
11
- } from "./herdr.js";
4
+ import { CoreConnection } from "./core/backend.js";
5
+ import { startCoreAgent } from "./core/spawn.js";
6
+ import { getAgent, getPane, parsePaneInfo, sessionPath } from "./herdr.js";
12
7
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
8
+ import {
9
+ requiredStartField,
10
+ type StartAgentParams,
11
+ type StartedAgent,
12
+ UnstartedAgentLaunchError,
13
+ } from "./launch-contract.js";
14
+ import { createStartPane, rollbackCreatedLocation } from "./launch-location.js";
13
15
  import type { PaneInfo } from "./types.js";
14
16
  import { WORKER_FLAG } from "./worker-role.js";
15
17
 
16
- export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
17
- const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
18
+ export {
19
+ RolledBackAgentLaunchError,
20
+ START_PLACEMENTS,
21
+ UnstartedAgentLaunchError,
22
+ } from "./launch-contract.js";
18
23
 
19
- export interface StartAgentParams {
20
- cwd?: string;
21
- label?: string;
22
- name?: string;
23
- pane?: string;
24
- placement?: (typeof START_PLACEMENTS)[number];
25
- workspace?: string;
26
- }
27
-
28
- function required(value: string | undefined, field: string): string {
29
- if (!value?.trim()) throw new Error(`${field} is required for start`);
30
- return value.trim();
31
- }
24
+ const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
32
25
 
33
26
  async function directory(
34
27
  value: string | undefined,
@@ -66,10 +59,14 @@ export async function resolvePreparationDirectory(
66
59
  fallbackCwd: string,
67
60
  resolveDirectory: DirectoryResolver = directory,
68
61
  ): Promise<string> {
62
+ if (client instanceof CoreConnection && params.placement === "pane")
63
+ throw new UnstartedAgentLaunchError(
64
+ "Core cannot start Pi in an existing terminal without terminal input; use terminal, new_tab or new_workspace placement",
65
+ );
69
66
  if (params.placement !== "pane") {
70
67
  return resolveStartDirectory(params, fallbackCwd, resolveDirectory);
71
68
  }
72
- const pane = await getPane(client, required(params.pane, "pane"));
69
+ const pane = await getPane(client, requiredStartField(params.pane, "pane"));
73
70
  return pane.foreground_cwd?.trim() || pane.cwd?.trim() || fallbackCwd;
74
71
  }
75
72
 
@@ -77,143 +74,6 @@ interface StartAgentOptions {
77
74
  agentArgs?: string[];
78
75
  }
79
76
 
80
- interface CreatedLocationCleanup {
81
- id: string;
82
- method: "tab.close" | "workspace.close";
83
- }
84
-
85
- export interface StartedAgent {
86
- agent: PaneInfo;
87
- cleanup?: CreatedLocationCleanup;
88
- id: string;
89
- }
90
-
91
- export class RolledBackAgentLaunchError extends Error {
92
- constructor(cause: unknown) {
93
- super(cause instanceof Error ? cause.message : String(cause), { cause });
94
- }
95
- }
96
-
97
- export class UnstartedAgentLaunchError extends Error {
98
- constructor(cause: unknown) {
99
- super(cause instanceof Error ? cause.message : String(cause), { cause });
100
- }
101
- }
102
-
103
- async function createStartPane(
104
- client: HerdrConnection,
105
- params: StartAgentParams,
106
- cwd: string,
107
- label: string,
108
- ): Promise<{
109
- cleanup?: CreatedLocationCleanup;
110
- paneId: string;
111
- }> {
112
- const placement = params.placement;
113
- if (!placement) throw new Error("placement is required for start");
114
- if (placement === "pane") {
115
- return { paneId: required(params.pane, "pane") };
116
- }
117
- if (placement === "new_tab") {
118
- const workspaceTarget = required(params.workspace, "workspace");
119
- let workspace;
120
- try {
121
- workspace = resolveWorkspace(await getSnapshot(client), workspaceTarget);
122
- } catch (error) {
123
- throw new UnstartedAgentLaunchError(error);
124
- }
125
- // A failed create response may still have created a location.
126
- const created = createdLocation(
127
- await client.request<unknown>("tab.create", {
128
- workspace_id: workspace.workspace_id,
129
- cwd,
130
- label,
131
- focus: false,
132
- }),
133
- "tab.create result",
134
- );
135
- return {
136
- paneId: created.root_pane.pane_id,
137
- cleanup: { method: "tab.close", id: created.tab.tab_id },
138
- };
139
- }
140
- const created = createdLocation(
141
- await client.request<unknown>("workspace.create", {
142
- cwd,
143
- focus: false,
144
- }),
145
- "workspace.create result",
146
- true,
147
- );
148
- try {
149
- await client.request("tab.rename", { tab_id: created.tab.tab_id, label });
150
- } catch (error) {
151
- return rollbackCreatedLocation(
152
- client,
153
- { method: "workspace.close", id: created.workspace.workspace_id },
154
- error,
155
- );
156
- }
157
- return {
158
- paneId: created.root_pane.pane_id,
159
- cleanup: { method: "workspace.close", id: created.workspace.workspace_id },
160
- };
161
- }
162
-
163
- function createdLocation(
164
- value: unknown,
165
- path: string,
166
- ): { root_pane: PaneInfo; tab: { tab_id: string } };
167
- function createdLocation(
168
- value: unknown,
169
- path: string,
170
- withWorkspace: true,
171
- ): {
172
- root_pane: PaneInfo;
173
- tab: { tab_id: string };
174
- workspace: { workspace_id: string };
175
- };
176
- function createdLocation(
177
- value: unknown,
178
- path: string,
179
- withWorkspace = false,
180
- ): {
181
- root_pane: PaneInfo;
182
- tab: { tab_id: string };
183
- workspace?: { workspace_id: string };
184
- } {
185
- if (typeof value !== "object" || value === null) {
186
- throw new Error(`Herdr ${path} must be an object`);
187
- }
188
- const result = value as Record<string, unknown>;
189
- const tabId = nestedId(result["tab"], "tab_id", `${path}.tab`);
190
- return {
191
- root_pane: parsePaneInfo(result["root_pane"], `${path}.root_pane`),
192
- tab: { tab_id: tabId },
193
- ...(withWorkspace
194
- ? {
195
- workspace: {
196
- workspace_id: nestedId(
197
- result["workspace"],
198
- "workspace_id",
199
- `${path}.workspace`,
200
- ),
201
- },
202
- }
203
- : {}),
204
- };
205
- }
206
-
207
- function nestedId(value: unknown, key: string, path: string): string {
208
- if (typeof value !== "object" || value === null) {
209
- throw new Error(`Herdr ${path} must be an object`);
210
- }
211
- const id = (value as Record<string, unknown>)[key];
212
- if (typeof id !== "string")
213
- throw new Error(`Herdr ${path}.${key} must be string`);
214
- return id;
215
- }
216
-
217
77
  export async function startAgent(
218
78
  client: HerdrConnection,
219
79
  params: StartAgentParams,
@@ -221,7 +81,7 @@ export async function startAgent(
221
81
  resolveDirectory: DirectoryResolver = directory,
222
82
  options: StartAgentOptions = {},
223
83
  ): Promise<StartedAgent> {
224
- const name = required(params.name, "name");
84
+ const name = requiredStartField(params.name, "name");
225
85
  if (!AGENT_NAME.test(name)) {
226
86
  throw new Error(
227
87
  "name must be 1–32 characters, start with a lowercase letter, and contain only lowercase letters, digits, underscores or hyphens. Omit name to generate it from label; label can be longer.",
@@ -250,12 +110,18 @@ export async function startAgent(
250
110
  "cwd cannot change an existing pane; prepare the pane through Herdr",
251
111
  );
252
112
  }
113
+ if (client instanceof CoreConnection && params.placement === "pane")
114
+ throw new UnstartedAgentLaunchError(
115
+ "Core cannot start Pi in an existing terminal without terminal input; use terminal, new_tab or new_workspace placement",
116
+ );
253
117
  let cwd: string;
254
118
  try {
255
119
  cwd = await resolveStartDirectory(params, fallbackCwd, resolveDirectory);
256
120
  } catch (error) {
257
121
  throw new UnstartedAgentLaunchError(error);
258
122
  }
123
+ if (client instanceof CoreConnection)
124
+ return startCoreAgent(client, params, cwd, label, args);
259
125
  const created = await createStartPane(client, params, cwd, label);
260
126
  let agent: PaneInfo;
261
127
  try {
@@ -284,25 +150,6 @@ export async function rollbackStartedAgent(
284
150
  return rollbackCreatedLocation(client, started.cleanup, cause);
285
151
  }
286
152
 
287
- async function rollbackCreatedLocation(
288
- client: HerdrConnection,
289
- cleanup: CreatedLocationCleanup | undefined,
290
- cause: unknown,
291
- ): Promise<never> {
292
- if (!cleanup) throw cause;
293
- try {
294
- await client.request(cleanup.method, {
295
- [cleanup.method === "tab.close" ? "tab_id" : "workspace_id"]: cleanup.id,
296
- });
297
- } catch (cleanupError) {
298
- throw new Error(
299
- `${cause instanceof Error ? cause.message : String(cause)}; rollback also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
300
- { cause },
301
- );
302
- }
303
- throw new RolledBackAgentLaunchError(cause);
304
- }
305
-
306
153
  async function startWhenShellReady(
307
154
  client: HerdrConnection,
308
155
  params: Record<string, unknown>,
@@ -331,11 +178,11 @@ async function startWhenShellReady(
331
178
  }
332
179
  }
333
180
 
334
- const name = required(
181
+ const name = requiredStartField(
335
182
  typeof params["name"] === "string" ? params["name"] : undefined,
336
183
  "name",
337
184
  );
338
- const paneId = required(
185
+ const paneId = requiredStartField(
339
186
  typeof params["pane_id"] === "string" ? params["pane_id"] : undefined,
340
187
  "pane_id",
341
188
  );