@agentproto/driver-agent-cli 2.2.2 → 2.4.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.
@@ -4,7 +4,7 @@ import { createAcpClient } from '@agentproto/acp/client';
4
4
  import { spawn } from 'child_process';
5
5
  import { existsSync, readFileSync, mkdirSync, writeFileSync, rmSync, rmdirSync, mkdtempSync } from 'fs';
6
6
  import { createInterface } from 'readline';
7
- import { join } from 'path';
7
+ import { join, dirname, delimiter } from 'path';
8
8
  import { tmpdir, homedir } from 'os';
9
9
  import { loadAdapterSpawnSandboxConfig, resolveCommandSandbox } from '@agentproto/command-sandbox';
10
10
  import { randomUUID } from 'crypto';
@@ -151,11 +151,14 @@ var authSchema = z.object({
151
151
  grace_s: z.number().int().nonnegative().optional()
152
152
  }).strict().optional()
153
153
  }).strict();
154
- var authSubscriptionSchema = z.object({
154
+ var authSubscriptionEntrySchema = z.object({
155
155
  setEnv: z.string().min(1).optional(),
156
156
  external: z.boolean().optional(),
157
157
  conflictEnv: z.array(z.string()).optional(),
158
- unsetEnvAdd: z.array(z.string()).optional()
158
+ unsetEnvAdd: z.array(z.string()).optional(),
159
+ // Provider scope for a multi-provider adapter's bearer surface (pi's
160
+ // ANTHROPIC_OAUTH_TOKEN is anthropic-only) — see AgentCliAuthSubscription.
161
+ provider: z.string().min(1).optional()
159
162
  }).strict().superRefine((v, ctx) => {
160
163
  if (v.external) {
161
164
  if (v.setEnv !== void 0) {
@@ -173,6 +176,20 @@ var authSubscriptionSchema = z.object({
173
176
  });
174
177
  }
175
178
  });
179
+ var authSubscriptionSchema = z.union([authSubscriptionEntrySchema, z.array(authSubscriptionEntrySchema).min(1)]).superRefine((v, ctx) => {
180
+ if (!Array.isArray(v)) return;
181
+ const seen = /* @__PURE__ */ new Set();
182
+ for (const entry of v) {
183
+ const key = entry.provider ?? "\0unscoped";
184
+ if (seen.has(key)) {
185
+ ctx.addIssue({
186
+ code: z.ZodIssueCode.custom,
187
+ message: entry.provider ? `authSubscription: duplicate provider scope "${entry.provider}" \u2014 two entries claim the same provider, which is ambiguous at spawn time.` : "authSubscription: more than one unscoped entry (no `provider`) \u2014 ambiguous which one applies at spawn time."
188
+ });
189
+ }
190
+ seen.add(key);
191
+ }
192
+ });
176
193
  var sessionSchema = z.object({
177
194
  mode: z.enum(["ephemeral", "persistent", "resumable"]).default("ephemeral"),
178
195
  idle_timeout_ms: z.number().int().min(1e3).default(6e5),
@@ -324,7 +341,7 @@ var printConfigSchema = z.object({
324
341
  flag: z.string(),
325
342
  kind: z.enum(["value", "boolean"])
326
343
  }).strict().optional(),
327
- event_schema: z.enum(["claude-stream-json", "mastra-jsonl", "antigravity-stream-json"]).optional()
344
+ event_schema: z.enum(["claude-stream-json", "mastra-jsonl", "antigravity-stream-json", "jcode-ndjson"]).optional()
328
345
  }).strict().optional();
329
346
  var agentCliFrontmatterSchema = z.object({
330
347
  name: z.string().min(1).max(80),
@@ -493,6 +510,9 @@ function createAcpProtocolArm(options) {
493
510
  get availableConfigOptions() {
494
511
  return session?.availableConfigOptions ?? [];
495
512
  },
513
+ get modelApplyRejection() {
514
+ return session?.modelApplyRejection;
515
+ },
496
516
  get availableModes() {
497
517
  return session?.availableModes ?? [];
498
518
  },
@@ -646,6 +666,14 @@ async function wrapAgentCliSpawn(bin, args, opts) {
646
666
  }
647
667
 
648
668
  // src/protocol/print-arm.ts
669
+ function printModelMismatch(requested, reported) {
670
+ const basename = (id) => {
671
+ const noSuffix = id.split("@")[0] ?? id;
672
+ const segs = noSuffix.split("/");
673
+ return (segs[segs.length - 1] ?? noSuffix).trim().toLowerCase();
674
+ };
675
+ return basename(requested) !== basename(reported);
676
+ }
649
677
  var DEFAULT_OUTPUT = ["--output-format", "stream-json"];
650
678
  var DEFAULT_PRE_PROMPT = ["--no-interactive"];
651
679
  var DEFAULT_RESUME = { flag: "--resume", kind: "value" };
@@ -722,20 +750,36 @@ function createPrintSession(opts) {
722
750
  throw new Error("print-arm: child has no stdout pipe");
723
751
  let capturedSessionId = "";
724
752
  const mastraState = eventSchema === "mastra-jsonl" ? createMastraMapperState() : void 0;
753
+ const jcodeState = eventSchema === "jcode-ndjson" ? createJcodeMapperState() : void 0;
725
754
  const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
726
755
  const queue = new EventQueue();
756
+ let modelMismatchAborted = false;
727
757
  rl.on("line", (line) => {
728
758
  if (!line.trim()) return;
759
+ if (modelMismatchAborted) return;
729
760
  let evt;
730
761
  try {
731
762
  evt = JSON.parse(line);
732
763
  } catch {
733
764
  return;
734
765
  }
766
+ if (opts.expectedModel && eventSchema === "jcode-ndjson" && evt.type === "start" && typeof evt.model === "string" && printModelMismatch(opts.expectedModel, evt.model)) {
767
+ modelMismatchAborted = true;
768
+ const provider = typeof evt.provider === "string" ? ` (provider ${evt.provider})` : "";
769
+ queue.push({
770
+ kind: "error",
771
+ error: {
772
+ message: `model mismatch: requested "${opts.expectedModel}" but the agent started on "${evt.model}"${provider} \u2014 its CLI silently fell back to a default it resolved itself. This adapter routes AND bills by the model id, so the turn was aborted instead of silently running (and billing) a model you didn't ask for. Check the id against the adapter's model menu.`
773
+ }
774
+ });
775
+ queue.end();
776
+ child.kill("SIGTERM");
777
+ return;
778
+ }
735
779
  const csid = captureSessionId(evt, eventSchema);
736
780
  if (csid) capturedSessionId = csid;
737
781
  const sid = capturedSessionId || sessionId || "";
738
- const mapped = mapEvent(evt, sid, stderrLines, eventSchema, mastraState);
782
+ const mapped = mapEvent(evt, sid, stderrLines, eventSchema, mastraState, jcodeState);
739
783
  if (Array.isArray(mapped)) {
740
784
  for (const m of mapped) queue.push(m);
741
785
  } else if (mapped) {
@@ -749,7 +793,7 @@ function createPrintSession(opts) {
749
793
  const exitCode = await waitForExit(child);
750
794
  if (capturedSessionId) sessionId = capturedSessionId;
751
795
  if (exitCode !== 0 && exitCode !== null) {
752
- const binLabel = eventSchema === "mastra-jsonl" ? "mastracode" : eventSchema === "antigravity-stream-json" ? "agy" : "claude";
796
+ const binLabel = eventSchema === "mastra-jsonl" ? "mastracode" : eventSchema === "antigravity-stream-json" ? "agy" : eventSchema === "jcode-ndjson" ? "jcode" : "claude";
753
797
  const errEvt = {
754
798
  kind: "error",
755
799
  error: {
@@ -898,9 +942,13 @@ function captureSessionId(evt, schema) {
898
942
  if (evt.type === "result" && typeof evt.threadId === "string" && evt.threadId)
899
943
  return evt.threadId;
900
944
  return null;
945
+ case "jcode-ndjson":
946
+ if ((evt.type === "start" || evt.type === "done") && typeof evt.session_id === "string" && evt.session_id)
947
+ return evt.session_id;
948
+ return null;
901
949
  }
902
950
  }
903
- function mapEvent(evt, sessionId, stderrLines, schema, mastraState) {
951
+ function mapEvent(evt, sessionId, stderrLines, schema, mastraState, jcodeState) {
904
952
  switch (schema) {
905
953
  case "claude-stream-json":
906
954
  return mapClaudeEvent(evt, sessionId, stderrLines);
@@ -912,6 +960,8 @@ function mapEvent(evt, sessionId, stderrLines, schema, mastraState) {
912
960
  }
913
961
  return mapMastraEvent(evt, sessionId, stderrLines, mastraState);
914
962
  }
963
+ case "jcode-ndjson":
964
+ return mapJcodeEvent(evt, sessionId, jcodeState ?? createJcodeMapperState());
915
965
  default:
916
966
  return mapClaudeEvent(evt, sessionId, stderrLines);
917
967
  }
@@ -1047,6 +1097,74 @@ function mapAntigravityUsage(usage, sessionId) {
1047
1097
  ...tokensOut !== void 0 ? { tokensOut } : {}
1048
1098
  };
1049
1099
  }
1100
+ function createJcodeMapperState() {
1101
+ return {};
1102
+ }
1103
+ function mapJcodeEvent(evt, sessionId, state) {
1104
+ switch (evt.type) {
1105
+ case "text_delta":
1106
+ return typeof evt.text === "string" ? { kind: "text-delta", sessionId, text: evt.text } : null;
1107
+ case "tool_start":
1108
+ state.pending = {
1109
+ id: typeof evt.id === "string" ? evt.id : "",
1110
+ name: typeof evt.name === "string" ? evt.name : "?",
1111
+ input: ""
1112
+ };
1113
+ return null;
1114
+ case "tool_input":
1115
+ if (state.pending && typeof evt.delta === "string")
1116
+ state.pending.input += evt.delta;
1117
+ return null;
1118
+ case "tool_exec":
1119
+ return flushPendingJcodeCall(state, sessionId);
1120
+ case "tool_done": {
1121
+ const call = flushPendingJcodeCall(state, sessionId);
1122
+ const result = {
1123
+ kind: "tool-result",
1124
+ sessionId,
1125
+ toolCallId: typeof evt.id === "string" ? evt.id : "",
1126
+ result: evt.output ?? null,
1127
+ isError: evt.error !== null && evt.error !== void 0
1128
+ };
1129
+ return call ? [call, result] : result;
1130
+ }
1131
+ case "tokens": {
1132
+ const tokensIn = typeof evt.input === "number" ? evt.input : void 0;
1133
+ const tokensOut = typeof evt.output === "number" ? evt.output : void 0;
1134
+ if (tokensIn === void 0 && tokensOut === void 0) return null;
1135
+ return {
1136
+ kind: "usage_update",
1137
+ sessionId,
1138
+ size: 0,
1139
+ used: 0,
1140
+ ...tokensIn !== void 0 ? { tokensIn } : {},
1141
+ ...tokensOut !== void 0 ? { tokensOut } : {}
1142
+ };
1143
+ }
1144
+ case "done":
1145
+ return { kind: "turn-end", sessionId, reason: "completed" };
1146
+ default:
1147
+ return null;
1148
+ }
1149
+ }
1150
+ function flushPendingJcodeCall(state, sessionId) {
1151
+ const pending = state.pending;
1152
+ state.pending = void 0;
1153
+ if (!pending) return null;
1154
+ let args;
1155
+ try {
1156
+ args = JSON.parse(pending.input);
1157
+ } catch {
1158
+ args = { raw: pending.input };
1159
+ }
1160
+ return {
1161
+ kind: "tool-call",
1162
+ sessionId,
1163
+ toolCallId: pending.id,
1164
+ toolName: pending.name,
1165
+ arguments: args
1166
+ };
1167
+ }
1050
1168
  function createMastraMapperState() {
1051
1169
  return { lastTextLength: 0 };
1052
1170
  }
@@ -1551,6 +1669,13 @@ function createArmSessionControls(arm, definition) {
1551
1669
  }
1552
1670
  };
1553
1671
  }
1672
+ var MODEL_SWITCH_ACK_RE = /switch|model\s+set|now using/i;
1673
+ function isModelSwitchAcknowledgement(evt) {
1674
+ return MODEL_SWITCH_ACK_RE.test(JSON.stringify(evt));
1675
+ }
1676
+ function parseModelSwitchCommand(text) {
1677
+ return /^\s*\/model\s+(\S+)/i.exec(text)?.[1];
1678
+ }
1554
1679
  async function applyModelCommand(arm, modelId) {
1555
1680
  const turnId = randomUUID();
1556
1681
  let acked = false;
@@ -1559,7 +1684,7 @@ async function applyModelCommand(arm, modelId) {
1559
1684
  type: "text",
1560
1685
  text: `/model ${modelId}`
1561
1686
  })) {
1562
- if (/switch|model\s+set|now using/i.test(JSON.stringify(evt))) acked = true;
1687
+ if (isModelSwitchAcknowledgement(evt)) acked = true;
1563
1688
  }
1564
1689
  } catch (err) {
1565
1690
  const reason = err instanceof Error ? err.message : String(err);
@@ -1634,8 +1759,24 @@ var defineAgentCli = createDoctype(
1634
1759
  }
1635
1760
  }
1636
1761
  );
1637
- function resolveSpawnBin(bin) {
1638
- return bin === "node" ? process.execPath : bin;
1762
+ function resolveSpawnBin(bin, deps) {
1763
+ const execPath = process.execPath;
1764
+ if (bin === "node") return execPath;
1765
+ if (bin === "npx" || bin === "npm") {
1766
+ const exists = existsSync;
1767
+ const sibling = join(
1768
+ dirname(execPath),
1769
+ process.platform === "win32" ? `${bin}.cmd` : bin
1770
+ );
1771
+ if (exists(sibling)) return sibling;
1772
+ }
1773
+ return bin;
1774
+ }
1775
+ function ensureExecDirOnPath(env, execPath = process.execPath) {
1776
+ const execDir = dirname(execPath);
1777
+ const parts = (env.PATH ?? "").split(delimiter).filter(Boolean);
1778
+ if (parts.includes(execDir)) return;
1779
+ env.PATH = [...parts, execDir].join(delimiter);
1639
1780
  }
1640
1781
  function createAgentCliRuntime(definition) {
1641
1782
  return {
@@ -1676,6 +1817,7 @@ function createAgentCliRuntime(definition) {
1676
1817
  }
1677
1818
  }
1678
1819
  Object.assign(env, opts?.env ?? {});
1820
+ ensureExecDirOnPath(env);
1679
1821
  const permissionMode = resolveClaudeCodePermissionMode(
1680
1822
  definition,
1681
1823
  opts?.posture,
@@ -1684,12 +1826,26 @@ function createAgentCliRuntime(definition) {
1684
1826
  const isolateClaudeCodeConfig = definition.id === "claude-code";
1685
1827
  let claudeConfigDir;
1686
1828
  if (isolateClaudeCodeConfig) {
1687
- claudeConfigDir = mkdtempSync(
1688
- join(tmpdir(), "agentproto-claude-config-")
1689
- );
1829
+ if (opts?.configDir) {
1830
+ claudeConfigDir = opts.configDir;
1831
+ mkdirSync(claudeConfigDir, { recursive: true });
1832
+ } else {
1833
+ claudeConfigDir = mkdtempSync(
1834
+ join(tmpdir(), "agentproto-claude-config-")
1835
+ );
1836
+ }
1837
+ const globalConfigPath = join(claudeConfigDir, ".claude.json");
1838
+ let priorGlobalConfig = {};
1839
+ try {
1840
+ const parsed = JSON.parse(readFileSync(globalConfigPath, "utf8"));
1841
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1842
+ priorGlobalConfig = parsed;
1843
+ }
1844
+ } catch {
1845
+ }
1690
1846
  writeFileSync(
1691
- join(claudeConfigDir, ".claude.json"),
1692
- JSON.stringify({ mcpServers: {} })
1847
+ globalConfigPath,
1848
+ JSON.stringify({ ...priorGlobalConfig, mcpServers: {} })
1693
1849
  );
1694
1850
  const isolatedSettings = {
1695
1851
  attribution: { commit: "", pr: "", sessionUrl: false }
@@ -1704,6 +1860,7 @@ function createAgentCliRuntime(definition) {
1704
1860
  env.CLAUDE_CONFIG_DIR = claudeConfigDir;
1705
1861
  }
1706
1862
  if (definition.protocol === "print") {
1863
+ const printModel = config?.options?.model;
1707
1864
  return createPrintSession({
1708
1865
  bin: resolvedBin,
1709
1866
  baseArgs: composed.binArgs,
@@ -1713,7 +1870,8 @@ function createAgentCliRuntime(definition) {
1713
1870
  ...opts?.mcpServers ? { mcpServers: opts.mcpServers } : {},
1714
1871
  printConfig: definition.print,
1715
1872
  commandSandbox: opts?.commandSandbox,
1716
- ...claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {}
1873
+ ...claudeConfigDir ? { extraWritePaths: [claudeConfigDir] } : {},
1874
+ ...definition.routeSelection === "derived-from-model" && printModel ? { expectedModel: String(printModel) } : {}
1717
1875
  });
1718
1876
  }
1719
1877
  let child;
@@ -1745,8 +1903,13 @@ function createAgentCliRuntime(definition) {
1745
1903
  });
1746
1904
  });
1747
1905
  if (spawnFailure) {
1906
+ const isEnoent = spawnFailure.code === "ENOENT";
1907
+ const cwdMissing = isEnoent && !existsSync(cwd);
1908
+ const enoentHint = !isEnoent ? "" : cwdMissing ? `
1909
+ cwd '${cwd}' does not exist \u2014 Node reports a missing working directory with this same ENOENT. Recreate the directory, or pass a valid cwd/workspace (is the workspace path stale, or its worktree removed?).` : `
1910
+ '${execBin}' was not found on the daemon's PATH. If it works in your own terminal, the daemon's environment may be stale \u2014 restart the daemon from a shell where \`which ${definition.bin}\` resolves (\`agentproto daemon restart\`).`;
1748
1911
  throw new Error(
1749
- `agent-cli '${definition.id}': failed to spawn '${execBin} ${execArgs.join(" ")}': ${spawnFailure.message}`
1912
+ `agent-cli '${definition.id}': failed to spawn '${execBin} ${execArgs.join(" ")}': ${spawnFailure.message}${enoentHint}`
1750
1913
  );
1751
1914
  }
1752
1915
  spawned.on("error", (err) => {
@@ -1797,8 +1960,25 @@ function createAgentCliRuntime(definition) {
1797
1960
  ...turnIdleTimeoutMs !== void 0 ? { turnIdleTimeoutMs } : {},
1798
1961
  ...opts?.permissionHold ? { permissionHold: true } : {}
1799
1962
  });
1963
+ if (configModel && definition.routeSelection === "derived-from-model" && arm.modelApplyRejection) {
1964
+ const { requested, reason } = arm.modelApplyRejection;
1965
+ await arm.close().catch(() => {
1966
+ });
1967
+ if (child && !child.killed) child.kill("SIGTERM");
1968
+ throw derivedModelRefusalError(definition, requested, reason);
1969
+ }
1800
1970
  if (optModel && modelApply === "command") {
1801
- await applyModelCommand(arm, String(optModel));
1971
+ const commandResult = await applyModelCommand(arm, String(optModel));
1972
+ if (!commandResult.applied && definition.routeSelection === "derived-from-model") {
1973
+ await arm.close().catch(() => {
1974
+ });
1975
+ if (child && !child.killed) child.kill("SIGTERM");
1976
+ throw derivedModelRefusalError(
1977
+ definition,
1978
+ String(optModel),
1979
+ commandResult.reason ?? "model switch not acknowledged"
1980
+ );
1981
+ }
1802
1982
  }
1803
1983
  const sessionId = arm.sessionId ?? randomUUID();
1804
1984
  let currentTurnId;
@@ -1907,7 +2087,14 @@ function filterStringEnv(env) {
1907
2087
  }
1908
2088
  return out;
1909
2089
  }
2090
+ function derivedModelRefusalError(definition, requested, reason) {
2091
+ const first = definition.models?.allowed?.[0];
2092
+ const example = (typeof first === "string" ? first : first?.id) ?? "openrouter/anthropic/claude-sonnet-4-6";
2093
+ return new Error(
2094
+ `${definition.bin}: refusing to start on the default model \u2014 the requested model "${requested}" was not applied (${reason}). This adapter routes AND bills by the model id's own provider prefix, so continuing would silently run (and bill) a model you didn't ask for. Use the adapter's "<provider>/<model>" form (e.g. "${example}"), or pick an id from its model menu.`
2095
+ );
2096
+ }
1910
2097
 
1911
- 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 };
1912
- //# sourceMappingURL=chunk-ZXVIBZ4S.mjs.map
1913
- //# sourceMappingURL=chunk-ZXVIBZ4S.mjs.map
2098
+ export { LEGACY_GATEWAY_MODE_IDS, LEGACY_POSTURE_MODE_IDS, RuntimeConfigError, agentCliFrontmatterSchema, applyModelCommand, autoAllowPermissionHandler, composeSpawn, createAcpProtocolArm, createAgentCliRuntime, createArmSessionControls, createJcodeMapperState, createMastraMapperState, createPrintSession, createProprietaryProtocolArm, defineAgentCli, inferLegacyModeKind, isLegacyExtractedModeId, isModelSwitchAcknowledgement, mapJcodeEvent, mapMastraEvent, parseModelSwitchCommand, planModePermissionHandler, promptTurn, resolveContinuationStrategy, runtimeConfigSchema, toFileBasedMcpServers };
2099
+ //# sourceMappingURL=chunk-DBU5VORQ.mjs.map
2100
+ //# sourceMappingURL=chunk-DBU5VORQ.mjs.map