vibekit-agent 1.5.1 → 1.5.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.
package/dist/agent.js CHANGED
@@ -46,6 +46,18 @@ const fs = __importStar(require("fs"));
46
46
  const os = __importStar(require("os"));
47
47
  const path = __importStar(require("path"));
48
48
  const dns = __importStar(require("dns"));
49
+ const config_1 = require("./config");
50
+ /**
51
+ * The self-config tools, by the names claude allowlists them under.
52
+ *
53
+ * These are appended to EVERY `--allowedTools` list we build. That is the
54
+ * anti-lockout property: a user who says "only let yourself read files" would
55
+ * otherwise also revoke the single mechanism for undoing it from their phone,
56
+ * and would be stranded until they walked back to the machine. MCP tools are
57
+ * allowlisted by their own names, so restricting Write or Bash never touches
58
+ * these two.
59
+ */
60
+ const CONFIG_TOOL_NAMES = ['mcp__vkconfig__get_config', 'mcp__vkconfig__set_config'];
49
61
  /**
50
62
  * Read the package version from package.json dynamically. Until 1.1.0 this
51
63
  * was hardcoded to a string literal in the auth handshake, which meant
@@ -176,14 +188,18 @@ class AgentClient {
176
188
  // Whether the CURRENT message asked for supervision (rides on each
177
189
  // UserMessage; the toggle lives server-side on the remote_agents row).
178
190
  currentSupervised = false;
179
- // Localhost HTTP server the approval-mcp child calls back into. Started
180
- // lazily on the first supervised run, kept for the process lifetime.
181
- approvalServer = null;
182
- approvalPort = 0;
183
- // requestId -> the MCP child's blocked HTTP response + its deadline timer.
191
+ // Localhost HTTP server our MCP children call back into: /approve for
192
+ // supervised-mode permission prompts, /config for self-configuration.
193
+ // Started lazily on the first run that attaches an MCP server, kept for
194
+ // the process lifetime.
195
+ controlServer = null;
196
+ controlPort = 0;
197
+ // requestId -> the waiting caller's resolver + its deadline timer. Shared
198
+ // by both callers of askPhone (a tool permission prompt, and a config
199
+ // change that would reduce safety).
184
200
  pendingApprovals = new Map();
185
201
  // mcp-config written next to the OS tmpdir once per process.
186
- approvalMcpConfigPath = null;
202
+ mcpConfigPath = null;
187
203
  /** How long the phone gets before the agent denies locally. Well inside
188
204
  * the server's 5-minute per-run SSE ceiling, so a silent phone degrades
189
205
  * into a readable deny instead of a dead turn. */
@@ -472,39 +488,76 @@ class AgentClient {
472
488
  // far more than any normal chat needs; the rare task that legitimately
473
489
  // exceeds it can be split across messages.
474
490
  args.push('--max-turns', '50');
491
+ // MCP plumbing. The SELF-CONFIG server is attached on every run, not just
492
+ // supervised ones: "change your own settings" has to work in the default
493
+ // posture, which is where nearly every user actually lives. Supervised
494
+ // mode additionally attaches the permission-prompt server.
495
+ let mcpConfigPath = null;
496
+ let supervisedArmed = false;
475
497
  if (this.currentSupervised) {
476
- // Supervised mode: no skip-permissions. Every prompt claude would have
477
- // shown in a terminal routes through our MCP permission tool → parent
478
- // HTTP callback → WebSocket → the user's phone, which answers with
479
- // allow/deny (auto-deny after APPROVAL_TIMEOUT_MS). An explicit
480
- // allowedTools list still pre-approves those tools; everything else
481
- // gets prompted instead of refused.
482
498
  try {
483
- const cfgPath = this.ensureApprovalPlumbing();
484
- args.push('--permission-prompt-tool', 'mcp__vkapprove__approve');
485
- args.push('--mcp-config', cfgPath);
486
- if (allowedTools.length > 0)
487
- args.push('--allowedTools', allowedTools.join(','));
488
- console.log('[Supervised] Permission prompts will be sent to your phone.');
499
+ mcpConfigPath = this.ensureMcpPlumbing(true);
500
+ supervisedArmed = true;
489
501
  }
490
502
  catch (e) {
491
503
  // Fail CLOSED into the old restricted behavior rather than silently
492
504
  // granting everything the user asked us to gate.
493
505
  console.error(`[Supervised] Could not start approval plumbing (${e?.message || e}) — running with tool restrictions instead.`);
494
- if (allowedTools.length > 0)
495
- args.push('--allowedTools', allowedTools.join(','));
496
- else
497
- args.push('--allowedTools', 'Read,Grep,Glob,LS');
498
506
  }
499
507
  }
508
+ else {
509
+ // A missing or broken config-mcp.js must never take down an ordinary
510
+ // run, so this degrades to "no self-config this turn" rather than throw.
511
+ try {
512
+ mcpConfigPath = this.ensureMcpPlumbing(false);
513
+ }
514
+ catch {
515
+ mcpConfigPath = null;
516
+ }
517
+ }
518
+ if (mcpConfigPath)
519
+ args.push('--mcp-config', mcpConfigPath);
520
+ /** An --allowedTools value that always keeps the self-config tools on it.
521
+ * See CONFIG_TOOL_NAMES for why this is not optional. */
522
+ const allowList = (tools) => [...tools, ...(mcpConfigPath ? CONFIG_TOOL_NAMES : [])].join(',');
523
+ if (supervisedArmed) {
524
+ // Supervised mode: no skip-permissions. Every prompt claude would have
525
+ // shown in a terminal routes through our MCP permission tool → parent
526
+ // HTTP callback → WebSocket → the user's phone, which answers with
527
+ // allow/deny (auto-deny after APPROVAL_TIMEOUT_MS). An explicit
528
+ // allowedTools list still pre-approves those tools; everything else
529
+ // gets prompted instead of refused.
530
+ //
531
+ // The flag is passed ONLY when the user already had a list, exactly as
532
+ // before. Adding one where there was none would put this live safety
533
+ // path into a state it has never run in, on an assumption about
534
+ // claude-cli's precedence that is not worth testing in production. The
535
+ // cost of not doing it is one extra tap to change a setting while
536
+ // supervised, which is what "ask before actions" means anyway, and the
537
+ // anti-lockout property still holds: an unlisted config tool prompts,
538
+ // and the user can approve it.
539
+ args.push('--permission-prompt-tool', 'mcp__vkapprove__approve');
540
+ if (allowedTools.length > 0)
541
+ args.push('--allowedTools', allowList(allowedTools));
542
+ console.log('[Supervised] Permission prompts will be sent to your phone.');
543
+ }
544
+ else if (this.currentSupervised) {
545
+ // Arming failed above — restricted fallback.
546
+ args.push('--allowedTools', allowList(allowedTools.length > 0 ? allowedTools : ['Read', 'Grep', 'Glob', 'LS']));
547
+ }
500
548
  else if (allowedTools.length === 0) {
501
549
  // No restrictions - allow everything
502
550
  args.push('--dangerously-skip-permissions');
503
551
  }
504
552
  else {
505
553
  // Use specific allowed tools
506
- args.push('--allowedTools', allowedTools.join(','));
554
+ args.push('--allowedTools', allowList(allowedTools));
507
555
  }
556
+ // Model override. Unset (the default, and the only behaviour before this
557
+ // key existed) leaves the choice to the user's claude install.
558
+ const model = this.config.getModel();
559
+ if (model)
560
+ args.push('--model', model);
508
561
  // Decide how to launch claude:
509
562
  // - local binary (installed) → spawn it directly (fast)
510
563
  // - not installed → fall back to `npx --yes @anthropic-ai/claude-code`
@@ -1202,9 +1255,21 @@ class AgentClient {
1202
1255
  // can leave the socket stuck in CONNECTING state for whatever the OS
1203
1256
  // timeout is (often minutes), blocking the reconnect loop. Cleared on
1204
1257
  // every terminal event below.
1258
+ //
1259
+ // `terminate()` on a socket still in CONNECTING is reported by ws as an
1260
+ // 'error' carrying a fixed message ("WebSocket was closed before the
1261
+ // connection was established"), emitted just before 'close'. That error
1262
+ // IS this watchdog firing, not a fault we hit, so it is flagged here and
1263
+ // read by the error handler below. Untagged, it reached prod's error log
1264
+ // at error level and was scraped into the admin Server Errors panel as an
1265
+ // unexplained failure, while the reconnect it triggered worked perfectly
1266
+ // (2026-08-16). Only this call site can produce it: the heartbeat and wake
1267
+ // watchdogs start inside 'open', so their terminate() always sees OPEN.
1268
+ let handshakeAborted = false;
1205
1269
  let handshakeTimer = setTimeout(() => {
1206
1270
  handshakeTimer = null;
1207
1271
  if (this.ws && this.ws.readyState === ws_1.default.CONNECTING) {
1272
+ handshakeAborted = true;
1208
1273
  console.log('[Connect] Handshake timed out after 10s — terminating');
1209
1274
  try {
1210
1275
  this.ws.terminate();
@@ -1245,6 +1310,12 @@ class AgentClient {
1245
1310
  platform: os.platform(),
1246
1311
  workingDirectory: this.workingDirectory,
1247
1312
  branch: this.currentGitBranch(),
1313
+ // Additive: lets the phone show what this machine is set to without
1314
+ // waiting for a config change to happen. Deliberately NOT carrying
1315
+ // `supervised` — that one is the server's, and reporting our copy
1316
+ // on every reconnect would fight the iOS toggle.
1317
+ model: this.config.getModel() || null,
1318
+ allowedTools: this.config.getAllowedTools(),
1248
1319
  },
1249
1320
  timestamp: Date.now(),
1250
1321
  messageId: this.generateId(),
@@ -1269,8 +1340,16 @@ class AgentClient {
1269
1340
  });
1270
1341
  this.ws.on('error', (error) => {
1271
1342
  clearHandshakeTimer();
1272
- console.error('WebSocket error:', error.message);
1273
1343
  this.isConnected = false;
1344
+ if (handshakeAborted) {
1345
+ // Our own 10s watchdog aborted this handshake and already logged why.
1346
+ // ws emits 'close' straight after, which schedules the reconnect, so
1347
+ // there is nothing to report and nothing more to do. Reset the flag so
1348
+ // a genuine error later on this socket is still logged.
1349
+ handshakeAborted = false;
1350
+ return;
1351
+ }
1352
+ console.error('WebSocket error:', error.message);
1274
1353
  const msg = error?.message || '';
1275
1354
  if (msg.includes('ENOTFOUND') || msg.includes('EAI_AGAIN')) {
1276
1355
  this.lastErrorWasDns = true;
@@ -1490,13 +1569,42 @@ class AgentClient {
1490
1569
  * stay on the current version — the iOS tile's "Update" badge still nudges
1491
1570
  * the manual path, so nothing regresses.
1492
1571
  */
1572
+ /**
1573
+ * True when `candidate` is a strictly higher release than `current`.
1574
+ * Deliberately fail-closed: anything unparseable (prerelease tags, empty
1575
+ * strings, 'unknown' from a failed package.json read) returns false, so a
1576
+ * malformed version can never trigger an update-and-restart cycle.
1577
+ */
1578
+ static isNewerVersion(candidate, current) {
1579
+ const parse = (v) => {
1580
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(String(v).trim());
1581
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
1582
+ };
1583
+ const a = parse(candidate);
1584
+ const b = parse(current);
1585
+ if (!a || !b)
1586
+ return false;
1587
+ for (let i = 0; i < 3; i++) {
1588
+ if (a[i] !== b[i])
1589
+ return a[i] > b[i];
1590
+ }
1591
+ return false;
1592
+ }
1493
1593
  async maybeSelfUpdate(latest) {
1494
1594
  if (process.env.VIBEKIT_AGENT_NO_AUTOUPDATE)
1495
1595
  return;
1496
1596
  if (this.autoMode)
1497
1597
  return;
1498
- if (!latest || latest === AGENT_VERSION)
1499
- return; // unknown or already current
1598
+ // Only ever move FORWARD. This used to be `latest !== AGENT_VERSION`,
1599
+ // which treats "the server's cached latest is OLDER than what I run" as
1600
+ // an update: the agent then reinstalls @latest (a no-op), restarts, and
1601
+ // the fresh process repeats the whole dance, because updateAttempted is
1602
+ // per-process. That is an unbounded restart loop, and it fired for real
1603
+ // when a deploy restarted the server minutes before a publish, leaving
1604
+ // its hourly npm cache one version behind the agent (2026-08-02, 17
1605
+ // restarts in 20s). A stale or rolled-back cache must be a no-op.
1606
+ if (!latest || !AgentClient.isNewerVersion(latest, AGENT_VERSION))
1607
+ return;
1500
1608
  if (this.updateAttempted)
1501
1609
  return;
1502
1610
  if (this.claudeProcess) {
@@ -1507,6 +1615,8 @@ class AgentClient {
1507
1615
  }
1508
1616
  this.updateAttempted = true;
1509
1617
  console.log(`\n[Auto-update] New version available: v${AGENT_VERSION} -> v${latest}. Installing...`);
1618
+ // NOTE: installs the `latest` dist-tag, not a pinned `@${latest}` — the
1619
+ // registry is the authority on what "latest" resolves to.
1510
1620
  (0, child_process_1.execFile)('npm', ['install', '-g', 'vibekit-agent@latest'], { timeout: 180_000, env: process.env }, (err, _stdout, stderr) => {
1511
1621
  if (err) {
1512
1622
  // npm's stderr is dozens of "npm error" lines; dumping a tail of it
@@ -1666,84 +1776,125 @@ class AgentClient {
1666
1776
  */
1667
1777
  // ── Supervised-mode approval plumbing ──────────────────────────────
1668
1778
  /**
1669
- * Start (once) the localhost HTTP server the approval-mcp child calls,
1670
- * and write the --mcp-config file pointing claude at that child. Returns
1671
- * the config path. Throws when the compiled approval-mcp.js is missing —
1672
- * runClaude treats that as fail-closed.
1779
+ * Start (once) the localhost HTTP server our MCP children call, and write
1780
+ * the --mcp-config file pointing claude at them. Returns the config path,
1781
+ * or null when there is no MCP server worth attaching.
1782
+ *
1783
+ * `withApproval` adds the supervised-mode permission-prompt server and is
1784
+ * the only thing that can throw: a missing approval-mcp.js must fail
1785
+ * CLOSED (runClaude falls back to tool restrictions), while a missing
1786
+ * config-mcp.js just means no self-config this run.
1673
1787
  */
1674
- ensureApprovalPlumbing() {
1675
- const mcpScript = path.join(__dirname, 'approval-mcp.js');
1676
- if (!fs.existsSync(mcpScript))
1677
- throw new Error(`missing ${mcpScript}`);
1678
- if (!this.approvalServer) {
1679
- const server = http.createServer((req, res) => this.handleApprovalHttpRequest(req, res));
1788
+ ensureMcpPlumbing(withApproval) {
1789
+ const approveScript = path.join(__dirname, 'approval-mcp.js');
1790
+ const configScript = path.join(__dirname, 'config-mcp.js');
1791
+ if (withApproval && !fs.existsSync(approveScript))
1792
+ throw new Error(`missing ${approveScript}`);
1793
+ const withConfig = fs.existsSync(configScript);
1794
+ if (!withApproval && !withConfig)
1795
+ return null;
1796
+ if (!this.controlServer) {
1797
+ const server = http.createServer((req, res) => this.handleControlHttpRequest(req, res));
1680
1798
  server.listen(0, '127.0.0.1');
1681
1799
  const addr = server.address();
1682
1800
  if (!addr || typeof addr === 'string')
1683
- throw new Error('approval server failed to bind');
1684
- this.approvalPort = addr.port;
1801
+ throw new Error('control server failed to bind');
1802
+ this.controlPort = addr.port;
1685
1803
  server.unref(); // never keep the process alive on its own
1686
- this.approvalServer = server;
1804
+ this.controlServer = server;
1687
1805
  }
1688
1806
  // Port is baked into the config env, so rewrite whenever it changes
1689
- // (fresh process = fresh ephemeral port).
1690
- if (!this.approvalMcpConfigPath) {
1691
- this.approvalMcpConfigPath = path.join(os.tmpdir(), `vibekit-approval-mcp-${process.pid}.json`);
1692
- }
1693
- fs.writeFileSync(this.approvalMcpConfigPath, JSON.stringify({
1694
- mcpServers: {
1695
- vkapprove: {
1696
- command: process.execPath,
1697
- args: [mcpScript],
1698
- env: { VK_APPROVAL_PORT: String(this.approvalPort) },
1699
- },
1700
- },
1701
- }), { mode: 0o600 });
1702
- return this.approvalMcpConfigPath;
1807
+ // (fresh process = fresh ephemeral port). Rewritten per run rather than
1808
+ // once, because which servers belong in it depends on supervised mode:
1809
+ // declaring vkapprove outside supervised mode would offer claude a tool
1810
+ // that is never the right thing to call.
1811
+ if (!this.mcpConfigPath) {
1812
+ this.mcpConfigPath = path.join(os.tmpdir(), `vibekit-mcp-${process.pid}.json`);
1813
+ }
1814
+ const mcpServers = {};
1815
+ if (withApproval) {
1816
+ mcpServers.vkapprove = {
1817
+ command: process.execPath,
1818
+ args: [approveScript],
1819
+ env: { VK_APPROVAL_PORT: String(this.controlPort) },
1820
+ };
1821
+ }
1822
+ if (withConfig) {
1823
+ mcpServers.vkconfig = {
1824
+ command: process.execPath,
1825
+ args: [configScript],
1826
+ env: { VK_CONFIG_PORT: String(this.controlPort) },
1827
+ };
1828
+ }
1829
+ fs.writeFileSync(this.mcpConfigPath, JSON.stringify({ mcpServers }), { mode: 0o600 });
1830
+ return this.mcpConfigPath;
1703
1831
  }
1704
- /** POST /approve from the MCP child: hold the response open until the
1705
- * phone answers or the deadline passes. */
1706
- handleApprovalHttpRequest(req, res) {
1707
- if (req.method !== 'POST' || req.url !== '/approve') {
1832
+ /** Router for the two things our MCP children POST back to us. */
1833
+ handleControlHttpRequest(req, res) {
1834
+ if (req.method !== 'POST' || (req.url !== '/approve' && req.url !== '/config')) {
1708
1835
  res.writeHead(404).end();
1709
1836
  return;
1710
1837
  }
1838
+ const isConfig = req.url === '/config';
1711
1839
  let body = '';
1712
1840
  req.on('data', (c) => { body += c; if (body.length > 64_000)
1713
1841
  req.destroy(); });
1714
1842
  req.on('end', () => {
1715
- let toolName = 'unknown tool';
1716
- let input = {};
1843
+ let parsed = {};
1717
1844
  try {
1718
- const parsed = JSON.parse(body);
1719
- if (typeof parsed?.toolName === 'string')
1720
- toolName = parsed.toolName;
1721
- if (parsed?.input && typeof parsed.input === 'object')
1722
- input = parsed.input;
1845
+ parsed = JSON.parse(body);
1723
1846
  }
1724
1847
  catch { /* keep defaults */ }
1725
- const chatId = this.currentChatId;
1726
- if (!chatId || !this.isConnected) {
1727
- // No phone to ask — deny with a reason claude can surface.
1728
- res.writeHead(200, { 'Content-Type': 'application/json' });
1729
- res.end(JSON.stringify({ behavior: 'deny', message: 'VibeKit is not connected, so no one could approve this.' }));
1848
+ const reply = (payload) => {
1849
+ try {
1850
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1851
+ res.end(JSON.stringify(payload));
1852
+ }
1853
+ catch { /* MCP child already gone — claude was killed */ }
1854
+ };
1855
+ if (isConfig) {
1856
+ // The rejection arm matters: an unhandled throw would never call
1857
+ // reply(), and the MCP child would sit on its 200s socket timeout
1858
+ // with claude blocked behind it. An error is a far better failure
1859
+ // than a three-minute hang.
1860
+ void this.handleConfigToolCall(parsed).then(reply, (e) => {
1861
+ console.error(`[Config] handler threw: ${e?.message || e}`);
1862
+ reply({ ok: false, text: 'The agent hit an error applying that, so nothing changed.' });
1863
+ });
1730
1864
  return;
1731
1865
  }
1732
- const requestId = (0, crypto_1.randomUUID)();
1733
- const expiresAt = Date.now() + AgentClient.APPROVAL_TIMEOUT_MS;
1734
- const timer = setTimeout(() => {
1735
- this.resolveApproval(requestId, 'deny', 'No answer from your phone in 3 minutes — denied. Send the message again when you are ready.');
1736
- }, AgentClient.APPROVAL_TIMEOUT_MS);
1737
- this.pendingApprovals.set(requestId, { res, timer });
1866
+ const toolName = typeof parsed?.toolName === 'string' ? parsed.toolName : 'unknown tool';
1867
+ const input = (parsed?.input && typeof parsed.input === 'object') ? parsed.input : {};
1738
1868
  // Trim the input we ship to the phone: a Write's full content can be
1739
1869
  // hundreds of KB; the card only needs enough to decide.
1740
1870
  const slim = {};
1741
1871
  for (const [k, v] of Object.entries(input)) {
1742
1872
  slim[k] = typeof v === 'string' && v.length > 2_000 ? v.slice(0, 2_000) + '…' : v;
1743
1873
  }
1874
+ void this.askPhone(toolName, slim).then(reply);
1875
+ });
1876
+ }
1877
+ /**
1878
+ * Put a question on the user's phone and wait for the answer. Used by the
1879
+ * supervised-mode tool prompt and by a config change that would reduce
1880
+ * safety, so both share one deadline, one cancel path, and one card.
1881
+ * Resolves to a deny (never rejects) when there is no phone to ask.
1882
+ */
1883
+ askPhone(toolName, input) {
1884
+ const chatId = this.currentChatId;
1885
+ if (!chatId || !this.isConnected) {
1886
+ return Promise.resolve({ behavior: 'deny', message: 'VibeKit is not connected, so no one could approve this.' });
1887
+ }
1888
+ return new Promise((resolve) => {
1889
+ const requestId = (0, crypto_1.randomUUID)();
1890
+ const expiresAt = Date.now() + AgentClient.APPROVAL_TIMEOUT_MS;
1891
+ const timer = setTimeout(() => {
1892
+ this.resolveApproval(requestId, 'deny', 'No answer from your phone in 3 minutes — denied. Send the message again when you are ready.');
1893
+ }, AgentClient.APPROVAL_TIMEOUT_MS);
1894
+ this.pendingApprovals.set(requestId, { resolve, timer });
1744
1895
  this.send({
1745
1896
  type: 'permission_request',
1746
- payload: { chatId, requestId, toolName, input: slim, expiresAt },
1897
+ payload: { chatId, requestId, toolName, input, expiresAt },
1747
1898
  timestamp: Date.now(),
1748
1899
  messageId: this.generateId(),
1749
1900
  });
@@ -1757,13 +1908,163 @@ class AgentClient {
1757
1908
  return; // already resolved / expired — idempotent
1758
1909
  this.pendingApprovals.delete(requestId);
1759
1910
  clearTimeout(pending.timer);
1760
- try {
1761
- pending.res.writeHead(200, { 'Content-Type': 'application/json' });
1762
- pending.res.end(JSON.stringify({ behavior, message }));
1763
- }
1764
- catch { /* MCP child already gone — claude was killed */ }
1911
+ pending.resolve({ behavior, message });
1765
1912
  console.log(`[Supervised] ${behavior}${message ? ` (${message})` : ''} for ${requestId.slice(0, 8)}`);
1766
1913
  }
1914
+ // ── Self-configuration (the vkconfig MCP tools) ────────────────────
1915
+ /** Human-readable current settings, for get_config and for confirmations. */
1916
+ describeConfig() {
1917
+ const model = this.config.getModel();
1918
+ const tools = this.config.getAllowedTools();
1919
+ return [
1920
+ `Model: ${model || 'default (whatever your claude install picks)'}`,
1921
+ `Allowed tools: ${tools.length === 0 ? 'all (no restrictions)' : tools.join(', ')}`,
1922
+ `Working directory: ${this.workingDirectory}`,
1923
+ `Supervised mode: ${this.currentSupervised ? 'on' : 'off'}`,
1924
+ ].join('\n');
1925
+ }
1926
+ /**
1927
+ * POST /config from the vkconfig MCP child: the agent changing its own
1928
+ * settings because the conversation asked it to.
1929
+ *
1930
+ * Atomic. A call carrying both a safe change and a refused one applies
1931
+ * NEITHER, because partially-applied settings are the kind of thing a user
1932
+ * discovers three days later.
1933
+ */
1934
+ async handleConfigToolCall(body) {
1935
+ if (body?.action === 'get')
1936
+ return { ok: true, text: this.describeConfig() };
1937
+ if (body?.action !== 'set')
1938
+ return { ok: false, text: 'Unsupported settings action.' };
1939
+ const raw = (body?.changes && typeof body.changes === 'object') ? body.changes : {};
1940
+ // Refuse unknown keys BY NAME instead of dropping them. The MCP schema
1941
+ // does not offer `token` or `wsUrl`, but a schema is a hint to the model,
1942
+ // not a gate — this is the gate. Writing `wsUrl` would re-point the agent
1943
+ // at someone else's server and hand over the machine, so it has to be
1944
+ // visibly impossible rather than quietly ignored, which would read back
1945
+ // to the model (and then the user) as "done".
1946
+ const unknown = Object.keys(raw).filter((k) => !config_1.CONFIG_CHANGE_KEYS.includes(k));
1947
+ if (unknown.length > 0) {
1948
+ return {
1949
+ ok: false,
1950
+ text: `Refused: ${unknown.join(', ')} cannot be changed from a conversation. `
1951
+ + 'The pairing itself (auth token and server URL) is deliberately not settable this way. '
1952
+ + `Changeable settings are: ${config_1.CONFIG_CHANGE_KEYS.join(', ')}.`,
1953
+ };
1954
+ }
1955
+ const next = {};
1956
+ if ('model' in raw) {
1957
+ const m = raw.model;
1958
+ if (m !== null && typeof m !== 'string')
1959
+ return { ok: false, text: 'model must be a string, or null to clear it.' };
1960
+ if (typeof m === 'string' && !(0, config_1.isValidModel)(m)) {
1961
+ return { ok: false, text: `"${m}" is not a model name claude accepts. Use opus, sonnet, haiku, or a full claude model id.` };
1962
+ }
1963
+ next.model = m;
1964
+ }
1965
+ if ('allowedTools' in raw) {
1966
+ const t = raw.allowedTools;
1967
+ if (!Array.isArray(t) || t.some((x) => typeof x !== 'string' || !x.trim())) {
1968
+ return { ok: false, text: 'allowedTools must be an array of tool names.' };
1969
+ }
1970
+ next.allowedTools = t.map((x) => x.trim());
1971
+ }
1972
+ if ('cwd' in raw) {
1973
+ if (typeof raw.cwd !== 'string' || !raw.cwd.trim())
1974
+ return { ok: false, text: 'cwd must be a path.' };
1975
+ next.cwd = raw.cwd.trim();
1976
+ }
1977
+ if ('supervised' in raw) {
1978
+ if (typeof raw.supervised !== 'boolean')
1979
+ return { ok: false, text: 'supervised must be true or false.' };
1980
+ next.supervised = raw.supervised;
1981
+ }
1982
+ if (Object.keys(next).length === 0)
1983
+ return { ok: false, text: 'No settings were named, so nothing changed.' };
1984
+ // Anything that reduces safety costs a tap on the phone, even when
1985
+ // supervised mode is off. The agent reads repos, issue text and web
1986
+ // pages, so the realistic attack is a poisoned file telling it to disarm
1987
+ // the user's own gate. Failure to reach the phone is a REFUSAL.
1988
+ const loosenings = (0, config_1.describeLoosenings)({ allowedTools: this.config.getAllowedTools(), supervised: this.currentSupervised }, next);
1989
+ if (loosenings.length > 0) {
1990
+ const summary = loosenings.join(' and ');
1991
+ // PHRASING IS CONSTRAINED BY THE SHIPPED CLIENT, not by taste. The card
1992
+ // renders `"Agent wants to run \(toolName)"` (NativeRemoteView) and the
1993
+ // push falls through to `"Wants to run \(toolName)"` (permissionSummary
1994
+ // in remote-agent.ts) whenever the input carries no command/file_path/
1995
+ // path/url key, which ours never will. Both of those templates are in
1996
+ // App Store builds that are already on phones and cannot be changed, so
1997
+ // the toolName has to complete those sentences by itself. A bare label
1998
+ // here renders as "Agent wants to run VibeKit settings", which is the
1999
+ // last thing the one card that guards against prompt injection should
2000
+ // look like. Keep this a phrase that reads after "wants to run".
2001
+ const decision = await this.askPhone(`a settings change: ${summary}`, {
2002
+ note: 'This reduces what the agent has to ask you about before it acts. Approve only if you just asked for this.',
2003
+ });
2004
+ if (decision.behavior !== 'allow') {
2005
+ return { ok: false, text: `Refused: ${summary} was not approved on the phone${decision.message ? ` (${decision.message})` : ''}. Nothing changed.` };
2006
+ }
2007
+ }
2008
+ // ORDER IS LOAD-BEARING for the atomicity promised above. Every field was
2009
+ // validated and the approval gate cleared before we got here, so the only
2010
+ // thing left that can fail is a directory that does not exist — which is
2011
+ // why cwd goes FIRST and can honestly report "nothing else changed".
2012
+ // setModel cannot throw after isValidModel, and setAllowedTools swallows
2013
+ // its own write errors. Reorder this and the guarantee quietly weakens.
2014
+ const applied = [];
2015
+ if (next.cwd !== undefined) {
2016
+ // Reuse the cd path so the directory is validated once and the server
2017
+ // gets its cd_result exactly as it does for a server-initiated cd.
2018
+ const result = this.changeDirectory(next.cwd);
2019
+ if (!result.success)
2020
+ return { ok: false, text: `Could not switch directory: ${result.error}. Nothing else changed.` };
2021
+ applied.push(`working directory is now ${result.path}`);
2022
+ }
2023
+ if (next.model !== undefined) {
2024
+ try {
2025
+ this.config.setModel(next.model);
2026
+ }
2027
+ catch (e) {
2028
+ return { ok: false, text: e?.message || 'Could not set the model.' };
2029
+ }
2030
+ applied.push(next.model === null ? 'model override cleared' : `model is now ${next.model}`);
2031
+ }
2032
+ if (next.allowedTools !== undefined) {
2033
+ this.config.setAllowedTools(next.allowedTools);
2034
+ applied.push(next.allowedTools.length === 0
2035
+ ? 'tool restrictions removed'
2036
+ : `tools restricted to ${next.allowedTools.join(', ')}`);
2037
+ }
2038
+ if (next.supervised !== undefined) {
2039
+ applied.push(`supervised mode ${next.supervised ? 'on' : 'off'}`);
2040
+ }
2041
+ // Tell the server, so the phone shows the same thing and `supervised`
2042
+ // (which is server-owned, on the remote_agents row) actually persists.
2043
+ this.sendConfigState(next.supervised);
2044
+ return {
2045
+ ok: true,
2046
+ text: `Done: ${applied.join('; ')}. This takes effect on your NEXT message, not this one.`,
2047
+ };
2048
+ }
2049
+ /**
2050
+ * Report settings upward. `supervised` is included ONLY when the user just
2051
+ * asked to change it: the flag is owned by the server (it rides down on
2052
+ * each UserMessage), and echoing our stale copy back on every change would
2053
+ * let a config edit clobber a toggle made from the iOS sheet in between.
2054
+ */
2055
+ sendConfigState(supervised) {
2056
+ this.send({
2057
+ type: 'config_state',
2058
+ payload: {
2059
+ model: this.config.getModel() || null,
2060
+ allowedTools: this.config.getAllowedTools(),
2061
+ workingDirectory: this.workingDirectory,
2062
+ ...(supervised === undefined ? {} : { supervised }),
2063
+ },
2064
+ timestamp: Date.now(),
2065
+ messageId: this.generateId(),
2066
+ });
2067
+ }
1767
2068
  /** Deny everything in flight — cancel, new message, or shutdown. */
1768
2069
  denyAllPendingApprovals(reason) {
1769
2070
  for (const id of [...this.pendingApprovals.keys()]) {
@@ -1818,9 +2119,17 @@ class AgentClient {
1818
2119
  }
1819
2120
  }
1820
2121
  /**
1821
- * Handle change directory command
2122
+ * Handle change directory command.
2123
+ *
2124
+ * Thin wrapper: `changeDirectory` does the work and owns the cd_result
2125
+ * frame, so the self-config tool gets the same validation and the same
2126
+ * server-side bookkeeping without a second implementation.
1822
2127
  */
1823
2128
  handleCdCommand(newPath) {
2129
+ this.changeDirectory(newPath);
2130
+ }
2131
+ /** Resolve, validate, apply and announce a working-directory change. */
2132
+ changeDirectory(newPath) {
1824
2133
  const resolved = path.resolve(this.workingDirectory, newPath);
1825
2134
  try {
1826
2135
  const fs = require('fs');
@@ -1831,7 +2140,7 @@ class AgentClient {
1831
2140
  timestamp: Date.now(),
1832
2141
  messageId: this.generateId(),
1833
2142
  });
1834
- return;
2143
+ return { success: false, error: 'Directory not found' };
1835
2144
  }
1836
2145
  this.workingDirectory = resolved;
1837
2146
  this.config.setLastDirectory(resolved);
@@ -1842,6 +2151,7 @@ class AgentClient {
1842
2151
  messageId: this.generateId(),
1843
2152
  });
1844
2153
  console.log(`Changed directory to: ${resolved}`);
2154
+ return { success: true, path: resolved };
1845
2155
  }
1846
2156
  catch (error) {
1847
2157
  this.send({
@@ -1850,6 +2160,7 @@ class AgentClient {
1850
2160
  timestamp: Date.now(),
1851
2161
  messageId: this.generateId(),
1852
2162
  });
2163
+ return { success: false, error: 'Failed to change directory' };
1853
2164
  }
1854
2165
  }
1855
2166
  /**