@openparachute/agent 0.2.2 → 0.2.3-rc.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 (58) hide show
  1. package/.parachute/module.json +3 -3
  2. package/package.json +4 -1
  3. package/src/transports/vault.ts +40 -22
  4. package/web/ui/dist/assets/index-5KEwEhfi.js +60 -0
  5. package/web/ui/dist/index.html +1 -1
  6. package/src/_parked/interactive-spawn.test.ts +0 -324
  7. package/src/_parked/interactive-spawn.ts +0 -701
  8. package/src/agent-defs.test.ts +0 -1504
  9. package/src/agent-mcp-config.test.ts +0 -115
  10. package/src/agents.test.ts +0 -360
  11. package/src/auth.test.ts +0 -46
  12. package/src/backends/attached-queue.test.ts +0 -376
  13. package/src/backends/programmatic.test.ts +0 -1715
  14. package/src/backends/registry.test.ts +0 -1494
  15. package/src/backends/stream-json.test.ts +0 -570
  16. package/src/channel-backend-wiring.test.ts +0 -237
  17. package/src/credentials.test.ts +0 -274
  18. package/src/cron.test.ts +0 -342
  19. package/src/daemon-agent-def-api.test.ts +0 -166
  20. package/src/daemon-agent-defs-api.test.ts +0 -953
  21. package/src/daemon-agent-env-api.test.ts +0 -338
  22. package/src/daemon-attached-queue-store.test.ts +0 -65
  23. package/src/daemon-config-api.test.ts +0 -962
  24. package/src/daemon-jobs-api.test.ts +0 -271
  25. package/src/daemon-vault-chat.test.ts +0 -250
  26. package/src/daemon.test.ts +0 -746
  27. package/src/def-vaults.test.ts +0 -136
  28. package/src/delivery-state.test.ts +0 -110
  29. package/src/effective-env.test.ts +0 -114
  30. package/src/grants.test.ts +0 -638
  31. package/src/hub-jwt.test.ts +0 -161
  32. package/src/jobs.test.ts +0 -245
  33. package/src/mcp-http.test.ts +0 -265
  34. package/src/mint-token.test.ts +0 -152
  35. package/src/module-manifest.test.ts +0 -158
  36. package/src/programmatic-wiring.test.ts +0 -838
  37. package/src/registry.test.ts +0 -227
  38. package/src/resolve-port.test.ts +0 -64
  39. package/src/routing.test.ts +0 -184
  40. package/src/runner.test.ts +0 -506
  41. package/src/sandbox/config.test.ts +0 -150
  42. package/src/sandbox/egress.test.ts +0 -113
  43. package/src/sandbox/live-seatbelt.test.ts +0 -277
  44. package/src/sandbox/mounts.test.ts +0 -154
  45. package/src/sandbox/sandbox.test.ts +0 -168
  46. package/src/services-manifest.test.ts +0 -106
  47. package/src/spa-serve.test.ts +0 -116
  48. package/src/spawn-agent-cli.test.ts +0 -172
  49. package/src/spawn-agent.test.ts +0 -1218
  50. package/src/spawn-deps.test.ts +0 -54
  51. package/src/terminal-assets.test.ts +0 -50
  52. package/src/terminal.test.ts +0 -530
  53. package/src/transports/http-ui.test.ts +0 -455
  54. package/src/transports/telegram.test.ts +0 -174
  55. package/src/transports/vault.test.ts +0 -2011
  56. package/src/ui-kit.test.ts +0 -178
  57. package/web/ui/dist/assets/index-VFETBk0a.js +0 -60
  58. package/web/ui/tsconfig.json +0 -21
@@ -1,701 +0,0 @@
1
- /**
2
- * PARKED — the interactive (tmux) agent SPAWNER + tmux session admin.
3
- *
4
- * This is NOT a live agent backend. The `interactive` backend was retired
5
- * 2026-06-19 (design `design/2026-06-19-retire-interactive-backend.md`): the
6
- * `channel` backend supersedes the human-driven-Claude-Code need it hedged,
7
- * without the tmux/send-keys/idle-wake fragility. The daemon no longer imports
8
- * or routes to any of this code.
9
- *
10
- * Per Aaron's note in the channel-backend design ("Retiring interactive"), the
11
- * PTY/terminal-spawning machinery is PARKED, not deleted: it gets repurposed
12
- * later (lower priority) into proper TERMINAL / PROCESS MANAGEMENT in the
13
- * Parachute interface — a general capability (spin up a Claude Code session, or
14
- * anything), decoupled from the agent backend.
15
- *
16
- * What's here:
17
- * - the tmux SPAWNER: `spawnAgent` + its argv/launch-script/dev-channels-prompt
18
- * helpers + the `TmuxLauncher`/`realTmuxLauncher` seam + the deps/result types;
19
- * - the tmux SESSION ADMIN: `AgentOps`/`TmuxAdmin`/`createRealAgentOps` +
20
- * `parseTmuxSessions`/`agentInfoFromSessions`/`realTmuxAdmin` + `AgentInfo`.
21
- *
22
- * What it still SHARES from the live tree (imported, not copied) — the sandbox/
23
- * filesystem/env helpers that the PROGRAMMATIC backend also uses, which stayed in
24
- * `src/spawn-agent.ts`: `wrapArgvInSandbox`, `seedAgentHome`, `buildAgentChildEnv`,
25
- * `resolveAgentCwd`, `sessionWorkspace`, `persistSpec`, `readPersistedSpec`,
26
- * `shellJoin`. Parking the spawner did NOT fork those.
27
- *
28
- * If/when this is revived as terminal-mgmt, it should be lifted out of the agent
29
- * module entirely (a `process`/`terminal` capability), not re-wired as a backend.
30
- */
31
-
32
- import { existsSync, statSync, writeFileSync, chmodSync } from "node:fs";
33
- import { join } from "node:path";
34
- import type {
35
- AgentSpec,
36
- AgentChannel,
37
- AgentVaultSpec,
38
- AgentMount,
39
- } from "../sandbox/types.ts";
40
- import { normalizeChannel } from "../sandbox/types.ts";
41
- import type { SandboxEngine, WrappedCommand } from "../sandbox/index.ts";
42
- import {
43
- buildAgentChildEnv,
44
- mergeSandboxLaunchEnv,
45
- resolveAgentCwd,
46
- seedAgentHome,
47
- sessionWorkspace,
48
- persistSpec,
49
- readPersistedSpec,
50
- shellJoin,
51
- wrapArgvInSandbox,
52
- type SpawnAgentBaseDeps,
53
- } from "../spawn-agent.ts";
54
- import {
55
- buildAgentMcpConfigJson,
56
- channelEntryKey,
57
- type ChannelMcpEntry,
58
- type VaultMcpEntry,
59
- type OtherMcpEntry,
60
- } from "../agent-mcp-config.ts";
61
- import {
62
- mintScopedToken,
63
- agentScope,
64
- vaultScope,
65
- type MintTokenDeps,
66
- type MintResult,
67
- } from "../mint-token.ts";
68
- import {
69
- resolveClaudeCredential,
70
- resolveChannelEnv,
71
- } from "../credentials.ts";
72
-
73
- /** Same slug shape spawnAgent enforces. */
74
- const AGENT_NAME_SLUG = /^[a-z0-9_-]+$/i;
75
-
76
- /** The `-agent` suffix tmux sessions launched by `spawnAgent` carry. */
77
- const AGENT_SESSION_SUFFIX = "-agent";
78
-
79
- /** A malformed spawn request body — the caller maps `.message` to a 400. */
80
- export class SpawnRequestError extends Error {
81
- constructor(message: string) {
82
- super(message);
83
- this.name = "SpawnRequestError";
84
- }
85
- }
86
-
87
- // ===========================================================================
88
- // The tmux SPAWNER (was spawn-agent.ts).
89
- // ===========================================================================
90
-
91
- /** A tmux launcher seam — real impl spawns tmux; tests inject a recorder. */
92
- export interface TmuxLauncher {
93
- newSession(opts: {
94
- name: string;
95
- argv: string[];
96
- env: Record<string, string | undefined>;
97
- cwd: string;
98
- scriptDir?: string;
99
- }): Promise<void>;
100
- hasSession(name: string): Promise<boolean>;
101
- confirmDevChannelsPrompt(session: string): Promise<"confirmed" | "already-running" | "timeout">;
102
- }
103
-
104
- /** Deps for the interactive {@link spawnAgent} — the shared base + the tmux launcher. */
105
- export interface SpawnAgentDeps extends SpawnAgentBaseDeps {
106
- /** tmux launcher (tests inject a recorder). */
107
- tmux: TmuxLauncher;
108
- }
109
-
110
- export interface SpawnAgentResult {
111
- session: string;
112
- workspace: string;
113
- tokens: Record<string, MintResult>;
114
- mcpConfigJson: string;
115
- wrapped: WrappedCommand;
116
- alreadyRunning: boolean;
117
- devChannelsPrompt?: "confirmed" | "already-running" | "timeout";
118
- }
119
-
120
- /** tmux session name for a spec — matches launch-session.sh's `<name>-agent`. */
121
- export function sessionName(specName: string): string {
122
- return `${specName}-agent`;
123
- }
124
-
125
- /**
126
- * Build the `claude` invocation argv (pre-sandbox-wrap). Interactive `claude`
127
- * (NOT `claude -p`) with the strict, multi-entry MCP config + the dev-channels
128
- * flag for the first channel. `--strict-mcp-config` closes the MCP surface.
129
- */
130
- export function buildAgentClaudeArgs(opts: {
131
- mcpConfigPath: string;
132
- firstChannelEntryKey: string;
133
- claudeBin?: string;
134
- systemPromptFile?: string;
135
- systemPromptMode?: "append" | "replace";
136
- }): string[] {
137
- const bin = opts.claudeBin ?? "claude";
138
- const argv = [
139
- bin,
140
- "--dangerously-skip-permissions",
141
- "--strict-mcp-config",
142
- "--mcp-config",
143
- opts.mcpConfigPath,
144
- `--dangerously-load-development-channels=server:${opts.firstChannelEntryKey}`,
145
- ];
146
- if (opts.systemPromptFile) {
147
- const flag = opts.systemPromptMode === "replace" ? "--system-prompt-file" : "--append-system-prompt-file";
148
- argv.push(flag, opts.systemPromptFile);
149
- }
150
- return argv;
151
- }
152
-
153
- /**
154
- * Spawn a sandboxed interactive agent session from a spec. Idempotent: an
155
- * existing tmux session is a no-op (returns `alreadyRunning: true`).
156
- */
157
- export async function spawnAgent(
158
- spec: AgentSpec,
159
- deps: SpawnAgentDeps,
160
- ): Promise<SpawnAgentResult> {
161
- if (!AGENT_NAME_SLUG.test(spec.name)) {
162
- throw new Error(
163
- `spawnAgent: spec name "${spec.name}" must be a slug (alphanumeric, dash, underscore only)`,
164
- );
165
- }
166
-
167
- const session = sessionName(spec.name);
168
- const workspace = sessionWorkspace(deps.sessionsDir, spec.name);
169
-
170
- if (await deps.tmux.hasSession(session)) {
171
- return {
172
- session,
173
- workspace,
174
- tokens: {},
175
- mcpConfigJson: "",
176
- wrapped: { argv: [], env: {}, config: { network: { allowedDomains: [], deniedDomains: [] }, filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } } },
177
- alreadyRunning: true,
178
- };
179
- }
180
-
181
- if (spec.channels.length === 0) {
182
- throw new Error(`spawnAgent: spec "${spec.name}" declares no channels`);
183
- }
184
-
185
- const wakeChannel = normalizeChannel(spec.channels[0]!).name;
186
- const resolveToken = deps.resolveClaudeToken ?? ((ch: string) => resolveClaudeCredential(ch));
187
- const claudeOauthToken = resolveToken(wakeChannel);
188
-
189
- const resolveEnv = deps.resolveChannelEnv ?? ((ch: string) => resolveChannelEnv(ch));
190
- const channelEnv = resolveEnv(wakeChannel);
191
-
192
- const mintDeps: MintTokenDeps = {
193
- hubOrigin: deps.hubOrigin,
194
- managerBearer: deps.managerBearer,
195
- ...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),
196
- };
197
-
198
- const tokens: Record<string, MintResult> = {};
199
- const channelEntries: ChannelMcpEntry[] = [];
200
- for (const rawChannel of spec.channels) {
201
- const { name: channel, access } = normalizeChannel(rawChannel);
202
- const minted = await mintScopedToken(
203
- { scope: agentScope({ write: access === "write" }), audience: "agent" },
204
- mintDeps,
205
- );
206
- tokens[channel] = minted;
207
- channelEntries.push({ channel, token: minted.token });
208
- }
209
-
210
- let vaultArg: { url: string; entry: VaultMcpEntry } | undefined;
211
- if (spec.vault) {
212
- const v = spec.vault;
213
- const minted = await mintScopedToken(
214
- {
215
- scope: vaultScope(v.name, v.access),
216
- audience: `vault.${v.name}`,
217
- ...(v.tags && v.tags.length > 0 ? { permissions: { scoped_tags: v.tags } } : {}),
218
- },
219
- mintDeps,
220
- );
221
- tokens[`vault:${v.name}`] = minted;
222
- vaultArg = {
223
- url: deps.vaultUrl ?? deps.hubOrigin,
224
- entry: { name: v.name, token: minted.token },
225
- };
226
- }
227
-
228
- const otherEntries: OtherMcpEntry[] = [];
229
- for (const o of spec.otherMcps ?? []) {
230
- let token: string | undefined;
231
- if (o.scope) {
232
- const minted = await mintScopedToken(
233
- { scope: o.scope, ...(o.audience ? { audience: o.audience } : {}) },
234
- mintDeps,
235
- );
236
- tokens[o.name] = minted;
237
- token = minted.token;
238
- }
239
- otherEntries.push({ name: o.name, url: o.url, ...(token ? { token } : {}) });
240
- }
241
-
242
- const mcpConfigJson = buildAgentMcpConfigJson({
243
- channelUrl: deps.channelUrl,
244
- channels: channelEntries,
245
- ...(vaultArg ? { vault: vaultArg } : {}),
246
- ...(otherEntries.length > 0 ? { otherMcps: otherEntries } : {}),
247
- });
248
- persistSpec(workspace, spec);
249
- const mcpConfigPath = join(workspace, ".mcp.json");
250
- writeFileSync(mcpConfigPath, mcpConfigJson, { mode: 0o600 });
251
-
252
- let systemPromptFile: string | undefined;
253
- if (typeof spec.systemPrompt === "string" && spec.systemPrompt.length > 0) {
254
- systemPromptFile = join(workspace, "system-prompt.txt");
255
- writeFileSync(systemPromptFile, spec.systemPrompt, { mode: 0o600 });
256
- }
257
-
258
- const claudeArgs = buildAgentClaudeArgs({
259
- mcpConfigPath,
260
- firstChannelEntryKey: channelEntryKey(wakeChannel),
261
- ...(deps.claudeBin ? { claudeBin: deps.claudeBin } : {}),
262
- ...(systemPromptFile
263
- ? { systemPromptFile, systemPromptMode: spec.systemPromptMode ?? "append" }
264
- : {}),
265
- });
266
-
267
- const wrapped = await wrapArgvInSandbox({
268
- spec,
269
- workspace,
270
- runtimeReadOnly: deps.runtimeReadOnly,
271
- hubOrigin: deps.hubOrigin,
272
- ...(deps.vaultUrl ? { vaultUrl: deps.vaultUrl } : {}),
273
- argv: claudeArgs,
274
- ...(deps.sandboxEngine ? { sandboxEngine: deps.sandboxEngine } : {}),
275
- ...(deps.ripgrep ? { ripgrep: deps.ripgrep } : {}),
276
- });
277
-
278
- const cwd = resolveAgentCwd(spec, workspace);
279
-
280
- const mcpServerNames = Object.keys(
281
- (JSON.parse(mcpConfigJson) as { mcpServers?: Record<string, unknown> }).mcpServers ?? {},
282
- );
283
- const homeEnv = seedAgentHome(workspace, { mcpServers: mcpServerNames, projectRoot: cwd });
284
-
285
- const childEnv = buildAgentChildEnv(deps.parentEnv ?? process.env, claudeOauthToken, channelEnv);
286
- // Scrub WINS: only allowlisted sandbox/proxy keys from `wrapped.env` (not the whole
287
- // daemon `process.env` the engine returns) layer on top. See mergeSandboxLaunchEnv.
288
- // (This file is the PARKED/retired interactive backend — kept in sync with the live
289
- // programmatic backend's shared seam, not a live spawn path.)
290
- const launchEnv = mergeSandboxLaunchEnv(childEnv, wrapped.env, homeEnv);
291
-
292
- await deps.tmux.newSession({
293
- name: session,
294
- argv: wrapped.argv,
295
- env: launchEnv,
296
- cwd,
297
- scriptDir: workspace,
298
- });
299
-
300
- const devChannelsPrompt = await deps.tmux.confirmDevChannelsPrompt(session);
301
-
302
- return {
303
- session,
304
- workspace,
305
- tokens,
306
- mcpConfigJson,
307
- wrapped,
308
- alreadyRunning: false,
309
- devChannelsPrompt,
310
- };
311
- }
312
-
313
- /** Per-session launch-script path under the session workspace (`cwd`). */
314
- function launchScriptPath(cwd: string): string {
315
- return join(cwd, ".launch.sh");
316
- }
317
-
318
- /**
319
- * Build the per-session **launch script** body for an already-sandbox-wrapped argv.
320
- * On macOS `wrapWithSandboxArgv` returns `["/bin/bash","-c","<~84KB profile inline>"]`
321
- * — too large for a tmux argument, so we write it to a file tmux runs via a short argv.
322
- */
323
- export function buildLaunchScript(argv: string[]): string {
324
- const header = "#!/bin/bash\nset -euo pipefail\n";
325
- if (argv.length === 3 && argv[0] === "/bin/bash" && argv[1] === "-c") {
326
- return `${header}${argv[2]}\n`;
327
- }
328
- return `${header}exec ${shellJoin(argv)}\n`;
329
- }
330
-
331
- /** The prompt marker for the dev-channels consent gate (agent#70). */
332
- export const DEV_CHANNELS_PROMPT_MARKER = "I am using this for local development";
333
- /** The ready marker shown once claude is running interactively. */
334
- export const DEV_CHANNELS_READY_MARKER = "bypass permissions on";
335
-
336
- /**
337
- * Auto-confirm claude's `--dangerously-load-development-channels` consent gate in a
338
- * detached tmux session (agent#70). NEVER throws.
339
- */
340
- export async function confirmDevChannelsPrompt(
341
- session: string,
342
- opts: {
343
- spawnFn?: typeof Bun.spawn;
344
- timeoutMs?: number;
345
- intervalMs?: number;
346
- sleepFn?: (ms: number) => Promise<void>;
347
- } = {},
348
- ): Promise<"confirmed" | "already-running" | "timeout"> {
349
- const spawnFn = opts.spawnFn ?? Bun.spawn;
350
- const timeoutMs = opts.timeoutMs ?? 15_000;
351
- const intervalMs = opts.intervalMs ?? 400;
352
- const sleep = opts.sleepFn ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
353
-
354
- async function capture(): Promise<string> {
355
- try {
356
- const proc = spawnFn(["tmux", "capture-pane", "-t", session, "-p"], {
357
- stdout: "pipe",
358
- stderr: "ignore",
359
- });
360
- const text = await new Response(proc.stdout as ReadableStream<Uint8Array>).text();
361
- await proc.exited;
362
- return text;
363
- } catch {
364
- return "";
365
- }
366
- }
367
-
368
- const deadline = Date.now() + timeoutMs;
369
- do {
370
- const pane = await capture();
371
- if (pane.includes(DEV_CHANNELS_PROMPT_MARKER)) {
372
- try {
373
- const proc = spawnFn(["tmux", "send-keys", "-t", session, "Enter"], {
374
- stdout: "ignore",
375
- stderr: "ignore",
376
- });
377
- await proc.exited;
378
- return "confirmed";
379
- } catch {
380
- break;
381
- }
382
- }
383
- if (pane.includes(DEV_CHANNELS_READY_MARKER)) {
384
- return "already-running";
385
- }
386
- if (Date.now() >= deadline) break;
387
- await sleep(intervalMs);
388
- } while (Date.now() < deadline);
389
-
390
- console.warn(
391
- `parachute-agent: dev-channels consent prompt for tmux session "${session}" did not ` +
392
- `appear within ${timeoutMs}ms (agent#70). If \`mcp_sessions\` stays 0, attach to the ` +
393
- `session and press Enter in its terminal to clear the gate.`,
394
- );
395
- return "timeout";
396
- }
397
-
398
- /** The real tmux launcher — `tmux new-session -d` running the sandboxed argv via a launch script. */
399
- export function realTmuxLauncher(spawnFn: typeof Bun.spawn = Bun.spawn): TmuxLauncher {
400
- return {
401
- async hasSession(name: string): Promise<boolean> {
402
- const proc = spawnFn(["tmux", "has-session", "-t", name], {
403
- stdout: "ignore",
404
- stderr: "ignore",
405
- });
406
- const code = await proc.exited;
407
- return code === 0;
408
- },
409
- async newSession(opts): Promise<void> {
410
- const scriptPath = launchScriptPath(opts.scriptDir ?? opts.cwd);
411
- writeFileSync(scriptPath, buildLaunchScript(opts.argv), { mode: 0o600 });
412
- chmodSync(scriptPath, 0o600);
413
-
414
- const envArgs: string[] = [];
415
- for (const [k, v] of Object.entries(opts.env)) {
416
- if (typeof v === "string") envArgs.push("-e", `${k}=${v}`);
417
- }
418
- const argv = [
419
- "tmux",
420
- "new-session",
421
- "-d",
422
- "-s",
423
- opts.name,
424
- "-c",
425
- opts.cwd,
426
- "-x",
427
- "220",
428
- "-y",
429
- "50",
430
- ...envArgs,
431
- "--",
432
- "/bin/bash",
433
- scriptPath,
434
- ];
435
- const proc = spawnFn(argv, { stdout: "pipe", stderr: "pipe" });
436
- const code = await proc.exited;
437
- if (code !== 0) {
438
- const err = await new Response(proc.stderr as ReadableStream<Uint8Array>).text();
439
- throw new Error(`tmux new-session failed (exit ${code}): ${err.trim()}`);
440
- }
441
- },
442
- async confirmDevChannelsPrompt(session) {
443
- return confirmDevChannelsPrompt(session, { spawnFn });
444
- },
445
- };
446
- }
447
-
448
- // ===========================================================================
449
- // The tmux SESSION ADMIN (was agents.ts).
450
- // ===========================================================================
451
-
452
- /** One running (or recently-launched) interactive agent session, as the page listed them. */
453
- export interface AgentInfo {
454
- name: string;
455
- session: string;
456
- attached: boolean;
457
- workspace: string;
458
- hasWorkspace: boolean;
459
- backend: "interactive";
460
- status?: string;
461
- channel?: string;
462
- vault?: string;
463
- systemPromptMode?: "append" | "replace";
464
- workingDir?: string;
465
- }
466
-
467
- /** A redacted mint summary — scope + audience + expiry, NEVER the token value. */
468
- export interface RedactedToken {
469
- resource: string;
470
- scope: string;
471
- expiresAt: string;
472
- }
473
-
474
- /** The redacted spawn result the web endpoint returned (no token values). */
475
- export interface RedactedSpawnResult {
476
- session: string;
477
- workspace: string;
478
- alreadyRunning: boolean;
479
- tokens: RedactedToken[];
480
- mcpServers: string[];
481
- filesystem: "workspace" | "full";
482
- network: "open" | "restricted";
483
- egress: string[];
484
- }
485
-
486
- export interface RedactedRestartResult extends RedactedSpawnResult {
487
- killed: boolean;
488
- }
489
-
490
- /** The spawn/list/kill/restart operations the daemon routes called. Injectable for tests. */
491
- export interface AgentOps {
492
- spawn(spec: AgentSpec): Promise<SpawnAgentResult>;
493
- list(): Promise<AgentInfo[]>;
494
- kill(name: string): Promise<{ killed: boolean }>;
495
- restart(name: string): Promise<RedactedRestartResult>;
496
- }
497
-
498
- /** A tmux admin seam — real impl shells out to tmux; tests inject a recorder. */
499
- export interface TmuxAdmin {
500
- listSessions(): Promise<{ name: string; attached: boolean }[]>;
501
- killSession(name: string): Promise<boolean>;
502
- }
503
-
504
- /** Parse `tmux list-sessions -F '#{session_name} #{session_attached}'` stdout. */
505
- export function parseTmuxSessions(stdout: string): { name: string; attached: boolean }[] {
506
- const out: { name: string; attached: boolean }[] = [];
507
- for (const line of stdout.split("\n")) {
508
- const trimmed = line.trim();
509
- if (!trimmed) continue;
510
- const idx = trimmed.lastIndexOf(" ");
511
- if (idx < 0) {
512
- out.push({ name: trimmed, attached: false });
513
- continue;
514
- }
515
- const name = trimmed.slice(0, idx);
516
- const attachedRaw = trimmed.slice(idx + 1);
517
- out.push({ name, attached: parseInt(attachedRaw, 10) > 0 });
518
- }
519
- return out;
520
- }
521
-
522
- /** Map raw tmux sessions to {@link AgentInfo}, keeping only `*-agent` sessions. */
523
- export function agentInfoFromSessions(
524
- sessions: { name: string; attached: boolean }[],
525
- sessionsDirPath: string,
526
- ): AgentInfo[] {
527
- const agents: AgentInfo[] = [];
528
- for (const s of sessions) {
529
- if (!s.name.endsWith(AGENT_SESSION_SUFFIX)) continue;
530
- const name = s.name.slice(0, -AGENT_SESSION_SUFFIX.length);
531
- if (name.length === 0) continue;
532
- const workspace = sessionWorkspace(sessionsDirPath, name);
533
- const persisted = readPersistedSpec(workspace);
534
- const hasPrompt = typeof persisted?.systemPrompt === "string" && persisted.systemPrompt.length > 0;
535
- const hasWorkingDir =
536
- typeof persisted?.workspace === "string" &&
537
- persisted.workspace.length > 0 &&
538
- existsSync(persisted.workspace);
539
- agents.push({
540
- name,
541
- session: s.name,
542
- attached: s.attached,
543
- workspace,
544
- hasWorkspace: existsSync(join(workspace, ".mcp.json")),
545
- backend: "interactive",
546
- ...(hasPrompt ? { systemPromptMode: persisted!.systemPromptMode ?? "append" } : {}),
547
- ...(hasWorkingDir ? { workingDir: persisted!.workspace } : {}),
548
- });
549
- }
550
- agents.sort((a, b) => a.name.localeCompare(b.name));
551
- return agents;
552
- }
553
-
554
- /** The real tmux admin — shells out via Bun.spawn. */
555
- export function realTmuxAdmin(spawnFn: typeof Bun.spawn = Bun.spawn): TmuxAdmin {
556
- return {
557
- async listSessions() {
558
- const proc = spawnFn(
559
- ["tmux", "list-sessions", "-F", "#{session_name} #{session_attached}"],
560
- { stdout: "pipe", stderr: "pipe" },
561
- );
562
- const code = await proc.exited;
563
- if (code !== 0) return [];
564
- const stdout = await new Response(proc.stdout as ReadableStream<Uint8Array>).text();
565
- return parseTmuxSessions(stdout);
566
- },
567
- async killSession(name: string) {
568
- const proc = spawnFn(["tmux", "kill-session", "-t", name], {
569
- stdout: "ignore",
570
- stderr: "ignore",
571
- });
572
- const code = await proc.exited;
573
- return code === 0;
574
- },
575
- };
576
- }
577
-
578
- /** Redact a {@link SpawnAgentResult} for the wire — never the token values. */
579
- export function redactSpawnResult(result: SpawnAgentResult): RedactedSpawnResult {
580
- const tokens: RedactedToken[] = Object.entries(result.tokens).map(([resource, minted]) => ({
581
- resource,
582
- scope: minted.scope,
583
- expiresAt: minted.expiresAt,
584
- }));
585
- let mcpServers: string[] = [];
586
- try {
587
- const parsed = JSON.parse(result.mcpConfigJson || "{}") as { mcpServers?: Record<string, unknown> };
588
- mcpServers = Object.keys(parsed.mcpServers ?? {});
589
- } catch {
590
- mcpServers = [];
591
- }
592
- const allowed = result.wrapped.config.network.allowedDomains as string[] | undefined;
593
- const scopedReads = (result.wrapped.config.filesystem.denyRead ?? []).length > 0;
594
- return {
595
- session: result.session,
596
- workspace: result.workspace,
597
- alreadyRunning: result.alreadyRunning,
598
- tokens,
599
- mcpServers,
600
- filesystem: scopedReads ? "workspace" : "full",
601
- network: allowed === undefined ? "open" : "restricted",
602
- egress: allowed ?? [],
603
- };
604
- }
605
-
606
- /**
607
- * The PARKED interactive {@link AgentOps} — spawn/list/kill/restart over tmux
608
- * sessions. The live daemon no longer constructs or routes to this (the
609
- * interactive backend retired); kept buildable for the future revival + its tests.
610
- * `depsFactory` resolves the shared base deps; the caller supplies the tmux launcher.
611
- */
612
- export function createRealAgentOps(opts?: {
613
- depsFactory?: () => SpawnAgentDeps;
614
- tmux?: TmuxAdmin;
615
- sessionsDirPath?: string;
616
- }): AgentOps {
617
- const depsFactory =
618
- opts?.depsFactory ?? (() => {
619
- throw new SpawnRequestError(
620
- "createRealAgentOps: no depsFactory — the interactive backend is parked; wire " +
621
- "resolveSpawnDeps + realTmuxLauncher explicitly if reviving it.",
622
- );
623
- });
624
- const tmux = opts?.tmux ?? realTmuxAdmin();
625
- const dir = opts?.sessionsDirPath ?? "";
626
- return {
627
- async spawn(spec) {
628
- return spawnAgent(spec, depsFactory());
629
- },
630
- async list() {
631
- return agentInfoFromSessions(await tmux.listSessions(), dir);
632
- },
633
- async kill(name) {
634
- if (!AGENT_NAME_SLUG.test(name)) {
635
- throw new SpawnRequestError(
636
- `agent name "${name}" must be a slug (alphanumeric, dash, underscore only)`,
637
- );
638
- }
639
- const killed = await tmux.killSession(sessionName(name));
640
- return { killed };
641
- },
642
- async restart(name) {
643
- if (!AGENT_NAME_SLUG.test(name)) {
644
- throw new SpawnRequestError(
645
- `agent name "${name}" must be a slug (alphanumeric, dash, underscore only)`,
646
- );
647
- }
648
- const workspace = sessionWorkspace(dir, name);
649
- const spec = readPersistedSpec(workspace);
650
- if (!spec) {
651
- throw new SpawnRequestError(
652
- `cannot restart agent "${name}": no persisted spec at ${workspace}/spec.json ` +
653
- `(it predates spawn-spec persistence, or was never spawned through this daemon). ` +
654
- `Kill it and spawn a fresh session from the Agents page.`,
655
- );
656
- }
657
- const killed = await tmux.killSession(sessionName(name));
658
- const result = await spawnAgent(spec, depsFactory());
659
- return { ...redactSpawnResult(result), killed };
660
- },
661
- };
662
- }
663
-
664
- /** Parse a mount entry from an untrusted body (parked). */
665
- export function parseMountEntry(raw: unknown, i: number): AgentMount {
666
- if (!raw || typeof raw !== "object") {
667
- throw new SpawnRequestError(`body.mounts[${i}] must be { hostPath, mountPath, mode, shared? }`);
668
- }
669
- const m = raw as Record<string, unknown>;
670
- if (typeof m.hostPath !== "string" || m.hostPath.length === 0) {
671
- throw new SpawnRequestError(`body.mounts[${i}].hostPath (non-empty string) is required`);
672
- }
673
- if (typeof m.mountPath !== "string" || m.mountPath.length === 0) {
674
- throw new SpawnRequestError(`body.mounts[${i}].mountPath (non-empty string) is required`);
675
- }
676
- if (!m.hostPath.startsWith("/")) {
677
- throw new SpawnRequestError(`body.mounts[${i}].hostPath must be an absolute path (start with "/")`);
678
- }
679
- if (!m.mountPath.startsWith("/")) {
680
- throw new SpawnRequestError(`body.mounts[${i}].mountPath must be an absolute path (start with "/")`);
681
- }
682
- if (m.mode !== "ro" && m.mode !== "rw") {
683
- throw new SpawnRequestError(`body.mounts[${i}].mode must be "ro" or "rw"`);
684
- }
685
- const mount: AgentMount = {
686
- hostPath: m.hostPath,
687
- mountPath: m.mountPath,
688
- mode: m.mode as "ro" | "rw",
689
- };
690
- if (m.shared !== undefined && m.shared !== null) {
691
- if (typeof m.shared !== "string" || m.shared.length === 0) {
692
- throw new SpawnRequestError(`body.mounts[${i}].shared must be a non-empty string`);
693
- }
694
- mount.shared = m.shared;
695
- }
696
- return mount;
697
- }
698
-
699
- // Re-exported so the parked unit references resolve without reaching into the live tree.
700
- export type { AgentSpec, AgentChannel, AgentVaultSpec, AgentMount };
701
- export { statSync };