@agentproto/driver-agent-cli 2.0.1 → 2.1.0

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.
@@ -5,8 +5,9 @@ import { spawn } from 'child_process';
5
5
  import { existsSync, readFileSync, mkdirSync, writeFileSync, rmSync, rmdirSync, mkdtempSync } from 'fs';
6
6
  import { createInterface } from 'readline';
7
7
  import { join } from 'path';
8
- import { randomUUID } from 'crypto';
9
8
  import { tmpdir, homedir } from 'os';
9
+ import { loadAdapterSpawnSandboxConfig, resolveCommandSandbox } from '@agentproto/command-sandbox';
10
+ import { randomUUID } from 'crypto';
10
11
  import { createDoctype } from '@agentproto/define-doctype';
11
12
 
12
13
  /**
@@ -151,10 +152,27 @@ var authSchema = z.object({
151
152
  }).strict().optional()
152
153
  }).strict();
153
154
  var authSubscriptionSchema = z.object({
154
- setEnv: z.string().min(1),
155
+ setEnv: z.string().min(1).optional(),
156
+ external: z.boolean().optional(),
155
157
  conflictEnv: z.array(z.string()).optional(),
156
158
  unsetEnvAdd: z.array(z.string()).optional()
157
- }).strict();
159
+ }).strict().superRefine((v, ctx) => {
160
+ if (v.external) {
161
+ if (v.setEnv !== void 0) {
162
+ ctx.addIssue({
163
+ code: z.ZodIssueCode.custom,
164
+ message: "authSubscription.external: true must NOT declare setEnv \u2014 an external (file-based) subscription injects no bearer; the CLI reads its own login file.",
165
+ path: ["setEnv"]
166
+ });
167
+ }
168
+ } else if (v.setEnv === void 0) {
169
+ ctx.addIssue({
170
+ code: z.ZodIssueCode.custom,
171
+ message: "authSubscription requires setEnv unless external: true (the bearer must be injected into some env var).",
172
+ path: ["setEnv"]
173
+ });
174
+ }
175
+ });
158
176
  var sessionSchema = z.object({
159
177
  mode: z.enum(["ephemeral", "persistent", "resumable"]).default("ephemeral"),
160
178
  idle_timeout_ms: z.number().int().min(1e3).default(6e5),
@@ -185,8 +203,7 @@ var modelsSchema = z.object({
185
203
  // How a model is selected at session start: "config" (ACP
186
204
  // set_config_option, default) | "command" (a `/model <id>` control turn,
187
205
  // for agents like hermes that ignore the ACP session model config) |
188
- // "arg" (a CLI argument composed into bin_args at spawn, for agents
189
- // like codex-acp that take their model as `-c model="<id>"`).
206
+ // "arg" (a CLI argument composed into bin_args at spawn).
190
207
  apply: z.enum(["config", "command", "arg"]).optional(),
191
208
  // Argv template for apply:"arg" — {model} interpolates the requested
192
209
  // model id. See AgentCliModels.bin_args_template.
@@ -200,6 +217,13 @@ var capabilitiesSchema = z.object({
200
217
  multimodal: z.boolean().optional(),
201
218
  resumable: z.boolean().optional(),
202
219
  bidirectional: z.boolean().optional(),
220
+ /**
221
+ * Adapter has a verified native CLI resume into a real terminal/TUI
222
+ * session (e.g. `claude --resume <id>` or `hermes --resume <id> --tui`).
223
+ * When true, the host MAY restart this adapter via its native resume argv
224
+ * as a PTY session. Distinct from ACP-level `resumable`.
225
+ */
226
+ nativeTerminalResume: z.boolean().optional(),
203
227
  /**
204
228
  * Adapter can ingest a filesystem path that the host UI just placed
205
229
  * on disk (host-side drag-drop into a terminal pastes the path
@@ -321,6 +345,26 @@ var agentCliFrontmatterSchema = z.object({
321
345
  // keep this generic doctype decoupled from @agentproto/model-catalog).
322
346
  provider: z.string().min(1).optional(),
323
347
  authSubscription: authSubscriptionSchema.optional(),
348
+ // How this adapter receives a GATEWAY-routed bearer credential — see the
349
+ // doc on AgentCliDefinition.gatewayAuth. Distinct from a gateway preset's
350
+ // `keyEnv` (the providers-store lookup key) and from
351
+ // authSubscription.setEnv (this adapter's own native bearer).
352
+ gatewayAuth: z.object({
353
+ setEnv: z.string().min(1)
354
+ }).strict().optional(),
355
+ // Auth-derivation axis (DECISION 3): true when the adapter's api-key auth
356
+ // is derived from the requested model rather than a fixed `provider`
357
+ // (e.g. `pi`, `opencode`, `mastracode`). When set, the runtime resolver
358
+ // allows `"api-key"` mode on the model-derived direct endpoint and
359
+ // includes it in eligibility manifests for by-model routers. DISTINCT
360
+ // from `routeSelection` (the UI-facing route-choice axis).
361
+ modelDerivedApiKey: z.boolean().optional(),
362
+ // UI-facing route-choice axis (AIP-45 launch-menu drill-down, WP1).
363
+ // Absent ⇒ "free" (route is an independent choice); "derived-from-model"
364
+ // means the endpoint falls out of the model id's vendor prefix. DISTINCT
365
+ // from `modelDerivedApiKey` (the auth-derivation axis) — see the field
366
+ // doc on AgentCliDefinition.routeSelection.
367
+ routeSelection: z.enum(["free", "derived-from-model"]).optional(),
324
368
  authEnforce: z.enum(["always", "when-configured"]).optional(),
325
369
  sandbox: z.union([z.string(), z.record(z.string(), z.unknown())]),
326
370
  runner: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
@@ -539,6 +583,69 @@ function toFileBasedMcpServers(servers) {
539
583
  }
540
584
  return out;
541
585
  }
586
+ function defaultToolchainWritePaths() {
587
+ const home = homedir();
588
+ return [
589
+ join(home, "Library", "pnpm", ".tools"),
590
+ // macOS pnpm self-managed toolchain
591
+ join(home, ".local", "share", "pnpm"),
592
+ // Linux pnpm self-managed toolchain
593
+ join(home, ".npm"),
594
+ // npm cache — self-update / global installs
595
+ join(home, ".claude", "session-env")
596
+ // claude-code's own Bash-tool session bookkeeping
597
+ ];
598
+ }
599
+ function defaultToolchainReadPaths() {
600
+ const home = homedir();
601
+ return [
602
+ join(home, ".npmrc"),
603
+ join(home, "Library", "Preferences", "pnpm", "rc"),
604
+ join(home, ".gitconfig"),
605
+ // git's own global config (credential.helper, user.*, …)
606
+ join(home, ".config", "git"),
607
+ // XDG git config fallback
608
+ join(home, ".config", "gh"),
609
+ // gh's config.yml + hosts.yml
610
+ join(home, "Library", "Keychains")
611
+ // macOS Keychain DB — git/gh credential retrieval (read-only; see doc above)
612
+ ];
613
+ }
614
+ async function wrapAgentCliSpawn(bin, args, opts) {
615
+ const cfg = await loadAdapterSpawnSandboxConfig(opts.cwd);
616
+ const mode = opts.mode ?? cfg.mode;
617
+ if (mode === void 0) return [bin, args];
618
+ if (mode === "off") {
619
+ console.error(
620
+ `[agent-cli] \u26A0 spawning '${opts.label}' UNCONFINED \u2014 no OS-level sandbox is active (commandSandbox mode is "off").`
621
+ );
622
+ return [bin, args];
623
+ }
624
+ const backend = resolveCommandSandbox();
625
+ if (!backend) {
626
+ throw new Error(
627
+ `agent-cli '${opts.label}': commandSandbox mode="${mode}" is configured but no sandbox backend is available on ${process.platform} (macOS needs sandbox-exec, Linux needs bwrap installed). Refusing to spawn unconfined \u2014 pass commandSandbox: "off" to explicitly accept unconfined execution, or install the missing backend.`
628
+ );
629
+ }
630
+ const policy = {
631
+ workspace: opts.cwd,
632
+ extraReadPaths: [
633
+ ...defaultToolchainReadPaths(),
634
+ ...cfg.extraReadPaths,
635
+ ...opts.extraReadPaths ?? []
636
+ ],
637
+ extraWritePaths: [
638
+ ...defaultToolchainWritePaths(),
639
+ ...cfg.extraWritePaths,
640
+ ...opts.extraWritePaths ?? []
641
+ ],
642
+ network: mode === "strict" || cfg.network === "deny" ? "deny" : "allow"
643
+ };
644
+ const wrapped = backend.wrap([bin, ...args], policy);
645
+ return [wrapped[0] ?? bin, wrapped.slice(1)];
646
+ }
647
+
648
+ // src/protocol/print-arm.ts
542
649
  var DEFAULT_OUTPUT = ["--output-format", "stream-json"];
543
650
  var DEFAULT_PRE_PROMPT = ["--no-interactive"];
544
651
  var DEFAULT_RESUME = { flag: "--resume", kind: "value" };
@@ -572,7 +679,13 @@ function createPrintSession(opts) {
572
679
  } else {
573
680
  args.push(prompt);
574
681
  }
575
- const child = spawn(opts.bin, args, {
682
+ const [execBin, execArgs] = await wrapAgentCliSpawn(opts.bin, args, {
683
+ mode: opts.commandSandbox,
684
+ cwd: opts.cwd,
685
+ ...opts.extraWritePaths ? { extraWritePaths: opts.extraWritePaths } : {},
686
+ label: "print-arm"
687
+ });
688
+ const child = spawn(execBin, execArgs, {
576
689
  cwd: opts.cwd,
577
690
  env: opts.env,
578
691
  stdio: ["ignore", "pipe", "pipe"]
@@ -1262,6 +1375,102 @@ function interpolateEnv(env, value) {
1262
1375
  }
1263
1376
  return out;
1264
1377
  }
1378
+ function createArmSessionControls(arm, definition) {
1379
+ const modelApply = definition.models?.apply ?? "config";
1380
+ return {
1381
+ // Capability read-surface (SPEC §3.9/§3.4a) — snapshotted once
1382
+ // `arm.connect()` has resolved. Not live-updated by a later
1383
+ // `setModel`/`setSessionMode` call.
1384
+ availableConfigOptions: arm.availableConfigOptions ?? [],
1385
+ availableModes: arm.availableModes ?? [],
1386
+ currentModeId: arm.currentModeId,
1387
+ /**
1388
+ * Mid-session model switch — the runtime counterpart to the
1389
+ * spawn-time model apply. Dispatches on the same
1390
+ * `definition.models.apply` strategy so a live switch behaves
1391
+ * exactly like the spawn-time apply would have, just against an
1392
+ * already-running session.
1393
+ */
1394
+ async setModel(modelId) {
1395
+ if (modelApply === "arg") {
1396
+ return { applied: false, reason: "requires-restart" };
1397
+ }
1398
+ if (modelApply === "command") {
1399
+ return applyModelCommand(arm, modelId);
1400
+ }
1401
+ if (!arm.setConfigOption) {
1402
+ return { applied: false, reason: "not-supported" };
1403
+ }
1404
+ const result = await arm.setConfigOption("model", modelId);
1405
+ return result.applied ? { applied: true, model: modelId } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1406
+ },
1407
+ /**
1408
+ * Mid-session posture switch — the native-mode counterpart to
1409
+ * `setModel`, wired directly to the arm's `setSessionMode` (only the
1410
+ * ACP arm implements it).
1411
+ */
1412
+ async setSessionMode(modeId) {
1413
+ if (!arm.setSessionMode) {
1414
+ return { applied: false, reason: "not-supported" };
1415
+ }
1416
+ const result = await arm.setSessionMode(modeId);
1417
+ return result.applied ? { applied: true, modeId } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1418
+ },
1419
+ /**
1420
+ * Mid-session effort switch — the effort-axis counterpart to
1421
+ * `setModel`'s `"config"` strategy, wired to the same
1422
+ * `arm.setConfigOption` surface with `configId:"effort"`. Best-effort:
1423
+ * an effort label the current model rejects resolves
1424
+ * `{applied:false, reason}` (SPEC risk R7).
1425
+ */
1426
+ async setEffort(effort) {
1427
+ if (!arm.setConfigOption) {
1428
+ return { applied: false, reason: "not-supported" };
1429
+ }
1430
+ const result = await arm.setConfigOption("effort", effort);
1431
+ return result.applied ? { applied: true, effort } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1432
+ }
1433
+ };
1434
+ }
1435
+ async function applyModelCommand(arm, modelId) {
1436
+ const turnId = randomUUID();
1437
+ let acked = false;
1438
+ try {
1439
+ for await (const evt of promptTurn(arm, turnId, {
1440
+ type: "text",
1441
+ text: `/model ${modelId}`
1442
+ })) {
1443
+ if (/switch|model\s+set|now using/i.test(JSON.stringify(evt))) acked = true;
1444
+ }
1445
+ } catch (err) {
1446
+ const reason = err instanceof Error ? err.message : String(err);
1447
+ console.warn(
1448
+ `[agent-cli] /model ${modelId} control turn failed (continuing on default):`,
1449
+ err instanceof Error ? err.message : err
1450
+ );
1451
+ return { applied: false, reason };
1452
+ }
1453
+ if (!acked) {
1454
+ const reason = "no switch acknowledgement \u2014 agent may be on its default model";
1455
+ console.warn(`[agent-cli] /model ${modelId}: ${reason}`);
1456
+ return { applied: false, reason };
1457
+ }
1458
+ return { applied: true, model: modelId };
1459
+ }
1460
+ async function* promptTurn(arm, turnId, message) {
1461
+ await arm.send(turnId, message);
1462
+ const stderrTail = arm._stderrTail;
1463
+ for await (const evt of arm.events()) {
1464
+ if (evt.kind === "error" && typeof stderrTail === "function") {
1465
+ const tail = stderrTail();
1466
+ if (tail) {
1467
+ const existing = evt.error.data ?? {};
1468
+ evt.error.data = { ...existing, stderr: tail };
1469
+ }
1470
+ }
1471
+ yield evt;
1472
+ }
1473
+ }
1265
1474
  var defineAgentCli = createDoctype(
1266
1475
  {
1267
1476
  aip: 45,
@@ -1311,21 +1520,11 @@ function createAgentCliRuntime(definition) {
1311
1520
  definition,
1312
1521
  async start(opts) {
1313
1522
  const cwd = opts?.cwd ?? process.cwd();
1314
- const cliEnv = {
1315
- ...filterStringEnv(process.env),
1316
- ...opts?.env ?? {}
1317
- };
1318
- const codexAuthMode = definition.id === "codex" ? detectCodexAuthMode(cliEnv, opts?.auth) : void 0;
1319
- const skipModelArg = definition.id === "codex" && codexAuthMode !== "api-key";
1320
- const composed = composeSpawn(definition, opts?.config, {
1321
- skipModelArg
1322
- });
1323
- const requestedModel = opts?.config?.options?.model;
1324
- if (skipModelArg && typeof requestedModel === "string") {
1325
- console.warn(
1326
- `[agent-cli] codex: skipped model override "${requestedModel}" for ChatGPT-account auth; using Codex's default model.`
1327
- );
1328
- }
1523
+ const contextMode = opts?.contextProfile ? (definition.modes ?? []).find(
1524
+ (mode) => mode.id === opts.contextProfile && mode.kind === "context"
1525
+ ) : void 0;
1526
+ const config = opts?.config?.mode || !contextMode ? opts?.config : { ...opts?.config, mode: contextMode.id };
1527
+ const composed = composeSpawn(definition, config);
1329
1528
  const env = {
1330
1529
  ...filterStringEnv(process.env),
1331
1530
  ...composed.env
@@ -1334,36 +1533,41 @@ function createAgentCliRuntime(definition) {
1334
1533
  const authSpec = opts?.auth;
1335
1534
  const hasGatewayAuthToken = "ANTHROPIC_AUTH_TOKEN" in composed.env;
1336
1535
  const hasGatewayBaseUrl = "ANTHROPIC_BASE_URL" in composed.env;
1337
- const engageAuth = !!authSpec && !hasGatewayAuthToken && !hasGatewayBaseUrl && (authSpec.enforce === "always" || authSpec.explicit === true);
1536
+ const resolverCoupledGateway = authSpec?.baseUrl !== void 0;
1537
+ const engageAuth = !!authSpec && !hasGatewayAuthToken && (resolverCoupledGateway || !hasGatewayBaseUrl) && (authSpec.enforce === "always" || authSpec.explicit === true);
1338
1538
  if (authSpec && engageAuth) {
1339
1539
  for (const key of authSpec.unsetEnv) {
1340
1540
  if (!(key in composed.env)) delete env[key];
1341
1541
  }
1342
- if (!authSpec.credential) {
1343
- const slug = definition.id;
1344
- const providerLabel = definition.provider ?? "<provider>";
1345
- const configBlock = `{"defaults":{"adapters":{"${slug}":{"auth":{"mode":"api-key"}}}}} in ~/.agentproto/config.json`;
1346
- const storeHint = authSpec.ignoredApiKeyInStore ? ` (providers.json already has a stored key for ${providerLabel} \u2014 ignored until that block exists)` : "";
1347
- const supportsSub = !!definition.authSubscription;
1348
- const message = authSpec.neitherConfigured && supportsSub ? `agent-cli '${slug}': no billing auth. Subscription \u2192 \`claude setup-token\`. Api-key \u2192 \`agentproto auth provider set ${providerLabel} sk-\u2026\`${storeHint}. Add ${configBlock}. Never inherited from the shell.` : authSpec.mode === "subscription" ? `agent-cli '${slug}': run \`claude setup-token\` and configure the result \u2014 bills the Max/Pro subscription, not API credits. Never inherited from the shell.` : `agent-cli '${slug}': run \`agentproto auth provider set ${providerLabel} sk-\u2026\`${storeHint}, then add ${configBlock}. Never inherited from the shell.`;
1349
- throw new RuntimeConfigError("missing_auth_credential", "opts.auth.credential", message);
1542
+ if (!authSpec.externalCredential) {
1543
+ if (!authSpec.credential) {
1544
+ const slug = definition.id;
1545
+ const providerLabel = definition.provider ?? "<provider>";
1546
+ const configBlock = `{"defaults":{"adapters":{"${slug}":{"auth":{"mode":"api-key"}}}}} in ~/.agentproto/config.json`;
1547
+ const storeHint = authSpec.ignoredApiKeyInStore ? ` (providers.json already has a stored key for ${providerLabel} \u2014 ignored until that block exists)` : "";
1548
+ const supportsSub = !!definition.authSubscription;
1549
+ const message = authSpec.neitherConfigured && supportsSub ? `agent-cli '${slug}': no billing auth. Subscription \u2192 \`claude setup-token\`. Api-key \u2192 \`agentproto auth provider set ${providerLabel} sk-\u2026\`${storeHint}. Add ${configBlock}. Never inherited from the shell.` : authSpec.mode === "subscription" ? `agent-cli '${slug}': run \`claude setup-token\` and configure the result \u2014 bills the Max/Pro subscription, not API credits. Never inherited from the shell.` : `agent-cli '${slug}': run \`agentproto auth provider set ${providerLabel} sk-\u2026\`${storeHint}, then add ${configBlock}. Never inherited from the shell.`;
1550
+ throw new RuntimeConfigError("missing_auth_credential", "opts.auth.credential", message);
1551
+ }
1552
+ env[authSpec.setEnv] = authSpec.credential;
1350
1553
  }
1351
- env[authSpec.setEnv] = authSpec.credential;
1352
1554
  }
1353
1555
  Object.assign(env, opts?.env ?? {});
1354
1556
  const permissionMode = resolveClaudeCodePermissionMode(
1355
1557
  definition,
1356
- opts?.config?.mode
1558
+ opts?.posture,
1559
+ config?.mode
1357
1560
  );
1561
+ let claudeConfigDir;
1358
1562
  if (permissionMode) {
1359
- const configDir = mkdtempSync(
1563
+ claudeConfigDir = mkdtempSync(
1360
1564
  join(tmpdir(), "agentproto-claude-config-")
1361
1565
  );
1362
1566
  writeFileSync(
1363
- join(configDir, "settings.json"),
1567
+ join(claudeConfigDir, "settings.json"),
1364
1568
  JSON.stringify({ permissions: { defaultMode: permissionMode } })
1365
1569
  );
1366
- env.CLAUDE_CONFIG_DIR = configDir;
1570
+ env.CLAUDE_CONFIG_DIR = claudeConfigDir;
1367
1571
  }
1368
1572
  if (definition.protocol === "print") {
1369
1573
  return createPrintSession({
@@ -1373,13 +1577,25 @@ function createAgentCliRuntime(definition) {
1373
1577
  env,
1374
1578
  ...opts?.resumeSessionId ? { resumeSessionId: opts.resumeSessionId } : {},
1375
1579
  ...opts?.mcpServers ? { mcpServers: opts.mcpServers } : {},
1376
- printConfig: definition.print
1580
+ printConfig: definition.print,
1581
+ commandSandbox: opts?.commandSandbox,
1582
+ ...claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {}
1377
1583
  });
1378
1584
  }
1379
1585
  let child;
1380
1586
  const stderrBuf = [];
1381
1587
  if (definition.protocol !== "proprietary") {
1382
- child = spawn(definition.bin, composed.binArgs, {
1588
+ const [execBin, execArgs] = await wrapAgentCliSpawn(
1589
+ definition.bin,
1590
+ composed.binArgs,
1591
+ {
1592
+ mode: opts?.commandSandbox,
1593
+ cwd,
1594
+ ...claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {},
1595
+ label: definition.id
1596
+ }
1597
+ );
1598
+ child = spawn(execBin, execArgs, {
1383
1599
  cwd,
1384
1600
  env,
1385
1601
  stdio: ["pipe", "pipe", "pipe"],
@@ -1399,7 +1615,7 @@ function createAgentCliRuntime(definition) {
1399
1615
  definition,
1400
1616
  child,
1401
1617
  cwd,
1402
- opts?.config?.mode,
1618
+ config?.mode,
1403
1619
  opts?.permissionHold ?? false
1404
1620
  );
1405
1621
  arm._stderrTail = () => stderrBuf.join("\n");
@@ -1409,11 +1625,11 @@ function createAgentCliRuntime(definition) {
1409
1625
  once: true
1410
1626
  });
1411
1627
  }
1412
- const optModel = opts?.config?.options?.model;
1413
- const optEffort = opts?.config?.options?.effort;
1628
+ const optModel = config?.options?.model;
1629
+ const optEffort = config?.options?.effort;
1414
1630
  const modelApply = definition.models?.apply ?? "config";
1415
1631
  const configModel = optModel && modelApply === "config" ? String(optModel) : void 0;
1416
- const requestedModeId = opts?.config?.mode;
1632
+ const requestedModeId = config?.mode;
1417
1633
  const requestedModeDecl = requestedModeId ? (definition.modes ?? []).find((m) => m.id === requestedModeId) : void 0;
1418
1634
  const configMode = requestedModeDecl?.apply === "config" ? requestedModeId : void 0;
1419
1635
  const turnIdleTimeoutMs = opts?.turnIdleTimeoutMs ?? definition.session?.turn_idle_timeout_ms;
@@ -1438,15 +1654,11 @@ function createAgentCliRuntime(definition) {
1438
1654
  return {
1439
1655
  sessionId,
1440
1656
  pid: child?.pid,
1441
- // Capability read-surface (SPEC §3.9/§3.4a) — snapshotted once
1442
- // `arm.connect()` above has resolved, so an ACP arm's captured
1443
- // `newSession`/`loadSession` response is already populated. Arms
1444
- // that don't model this (print, proprietary) leave the getters
1445
- // undefined, defaulted here to the same empty/absent shape their
1446
- // `setModel`-style counterparts use for "not supported".
1447
- availableConfigOptions: arm.availableConfigOptions ?? [],
1448
- availableModes: arm.availableModes ?? [],
1449
- currentModeId: arm.currentModeId,
1657
+ // Live model/mode/effort switches + the capability read-surface,
1658
+ // all pure arm delegation — shared with every host that builds
1659
+ // its own session over another transport. See session-controls.ts.
1660
+ // Snapshotted after `arm.connect()` above resolved.
1661
+ ...createArmSessionControls(arm, definition),
1450
1662
  send(message) {
1451
1663
  const turnId = randomUUID();
1452
1664
  currentTurnId = turnId;
@@ -1485,58 +1697,6 @@ function createAgentCliRuntime(definition) {
1485
1697
  return arm.respondPermission(requestId, resolution);
1486
1698
  }
1487
1699
  } : {},
1488
- /**
1489
- * Mid-session model switch — the runtime counterpart to the
1490
- * spawn-time `modelApply` handling above. Dispatches on the same
1491
- * `definition.models.apply` strategy so a live switch behaves
1492
- * exactly like the spawn-time apply would have, just against an
1493
- * already-running session. See {@link SetModelResult} for the
1494
- * reason vocabulary; this never throws and never tears down the
1495
- * session on a rejected switch.
1496
- */
1497
- async setModel(modelId) {
1498
- if (modelApply === "arg") {
1499
- return { applied: false, reason: "requires-restart" };
1500
- }
1501
- if (modelApply === "command") {
1502
- return applyModelCommand(arm, modelId);
1503
- }
1504
- if (!arm.setConfigOption) {
1505
- return { applied: false, reason: "not-supported" };
1506
- }
1507
- const result = await arm.setConfigOption("model", modelId);
1508
- return result.applied ? { applied: true, model: modelId } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1509
- },
1510
- /**
1511
- * Mid-session posture switch — the native-mode counterpart to
1512
- * `setModel`, wired directly to the arm's `setSessionMode` (only
1513
- * the ACP arm implements it). See {@link SetSessionModeResult} for
1514
- * the reason vocabulary; this never throws and never tears down
1515
- * the session on a rejected switch.
1516
- */
1517
- async setSessionMode(modeId) {
1518
- if (!arm.setSessionMode) {
1519
- return { applied: false, reason: "not-supported" };
1520
- }
1521
- const result = await arm.setSessionMode(modeId);
1522
- return result.applied ? { applied: true, modeId } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1523
- },
1524
- /**
1525
- * Mid-session effort switch — the effort-axis counterpart to
1526
- * `setModel`'s `"config"` strategy, wired to the same
1527
- * `arm.setConfigOption` surface with `configId:"effort"` (only the
1528
- * ACP arm implements it). Best-effort and non-fatal: an effort label
1529
- * the current model rejects resolves `{applied:false, reason}` (SPEC
1530
- * risk R7), never thrown and never tearing down the session. See
1531
- * {@link SetEffortResult} for the reason vocabulary.
1532
- */
1533
- async setEffort(effort) {
1534
- if (!arm.setConfigOption) {
1535
- return { applied: false, reason: "not-supported" };
1536
- }
1537
- const result = await arm.setConfigOption("effort", effort);
1538
- return result.applied ? { applied: true, effort } : { applied: false, ...result.reason ? { reason: result.reason } : {} };
1539
- },
1540
1700
  async close() {
1541
1701
  await arm.close();
1542
1702
  if (child && !child.killed) child.kill("SIGTERM");
@@ -1545,45 +1705,6 @@ function createAgentCliRuntime(definition) {
1545
1705
  }
1546
1706
  };
1547
1707
  }
1548
- async function applyModelCommand(arm, modelId) {
1549
- const turnId = randomUUID();
1550
- let acked = false;
1551
- try {
1552
- for await (const evt of promptTurn(arm, turnId, {
1553
- type: "text",
1554
- text: `/model ${modelId}`
1555
- })) {
1556
- if (/switch|model\s+set|now using/i.test(JSON.stringify(evt))) acked = true;
1557
- }
1558
- } catch (err) {
1559
- const reason = err instanceof Error ? err.message : String(err);
1560
- console.warn(
1561
- `[agent-cli] /model ${modelId} control turn failed (continuing on default):`,
1562
- err instanceof Error ? err.message : err
1563
- );
1564
- return { applied: false, reason };
1565
- }
1566
- if (!acked) {
1567
- const reason = "no switch acknowledgement \u2014 agent may be on its default model";
1568
- console.warn(`[agent-cli] /model ${modelId}: ${reason}`);
1569
- return { applied: false, reason };
1570
- }
1571
- return { applied: true, model: modelId };
1572
- }
1573
- async function* promptTurn(arm, turnId, message) {
1574
- await arm.send(turnId, message);
1575
- const stderrTail = arm._stderrTail;
1576
- for await (const evt of arm.events()) {
1577
- if (evt.kind === "error" && typeof stderrTail === "function") {
1578
- const tail = stderrTail();
1579
- if (tail) {
1580
- const existing = evt.error.data ?? {};
1581
- evt.error.data = { ...existing, stderr: tail };
1582
- }
1583
- }
1584
- yield evt;
1585
- }
1586
- }
1587
1708
  async function buildProtocolArm(def, child, cwd, requestedMode, permissionHold) {
1588
1709
  switch (def.protocol) {
1589
1710
  case "acp":
@@ -1610,8 +1731,18 @@ async function buildProtocolArm(def, child, cwd, requestedMode, permissionHold)
1610
1731
  throw new Error("createAgentCliRuntime: print arm bypasses buildProtocolArm");
1611
1732
  }
1612
1733
  }
1613
- function resolveClaudeCodePermissionMode(definition, configMode) {
1614
- if (definition.id !== "claude-code" || !configMode) return void 0;
1734
+ function resolveClaudeCodePermissionMode(definition, posture, configMode) {
1735
+ if (definition.id !== "claude-code") return void 0;
1736
+ const canonicalPermissionMode = {
1737
+ plan: "plan",
1738
+ "read-only": "plan",
1739
+ "accept-edits": "acceptEdits",
1740
+ bypass: "bypassPermissions"
1741
+ };
1742
+ if (posture && canonicalPermissionMode[posture]) {
1743
+ return canonicalPermissionMode[posture];
1744
+ }
1745
+ if (!configMode) return void 0;
1615
1746
  const mode = (definition.modes ?? []).find((m) => m.id === configMode);
1616
1747
  const args = mode?.bin_args_append ?? [];
1617
1748
  const flagIndex = args.indexOf("--permission-mode");
@@ -1625,22 +1756,7 @@ function filterStringEnv(env) {
1625
1756
  }
1626
1757
  return out;
1627
1758
  }
1628
- function detectCodexAuthMode(env, authSpec) {
1629
- if (authSpec?.credential && (authSpec.explicit === true || authSpec.enforce === "always")) {
1630
- return authSpec.mode === "api-key" ? "api-key" : "chatgpt";
1631
- }
1632
- if (env.OPENAI_API_KEY || env.CODEX_API_KEY) return "api-key";
1633
- const authPath = join(homedir(), ".codex", "auth.json");
1634
- try {
1635
- const parsed = JSON.parse(readFileSync(authPath, "utf8"));
1636
- if (parsed.auth_mode === "api-key" || parsed.auth_mode === "chatgpt") {
1637
- return parsed.auth_mode;
1638
- }
1639
- } catch {
1640
- }
1641
- return "chatgpt";
1642
- }
1643
1759
 
1644
- export { LEGACY_GATEWAY_MODE_IDS, LEGACY_POSTURE_MODE_IDS, RuntimeConfigError, agentCliFrontmatterSchema, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, createMastraMapperState, createPrintSession, createProprietaryProtocolArm, defineAgentCli, inferLegacyModeKind, isLegacyExtractedModeId, mapMastraEvent, planModePermissionHandler, resolveContinuationStrategy, runtimeConfigSchema, toFileBasedMcpServers };
1645
- //# sourceMappingURL=chunk-H43KNN32.mjs.map
1646
- //# sourceMappingURL=chunk-H43KNN32.mjs.map
1760
+ export { LEGACY_GATEWAY_MODE_IDS, LEGACY_POSTURE_MODE_IDS, RuntimeConfigError, agentCliFrontmatterSchema, applyModelCommand, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, createArmSessionControls, createMastraMapperState, createPrintSession, createProprietaryProtocolArm, defineAgentCli, inferLegacyModeKind, isLegacyExtractedModeId, mapMastraEvent, planModePermissionHandler, promptTurn, resolveContinuationStrategy, runtimeConfigSchema, toFileBasedMcpServers };
1761
+ //# sourceMappingURL=chunk-QL3CS6E4.mjs.map
1762
+ //# sourceMappingURL=chunk-QL3CS6E4.mjs.map