vibekit-agent 1.5.2 → 1.5.4

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. */
@@ -411,6 +427,10 @@ class AgentClient {
411
427
  // "agent offline" until the laptop wakes. Lid-close sleep is still
412
428
  // unstoppable from userspace — this only blocks idle sleep.
413
429
  this.startCaffeinate();
430
+ // Our MCP children call back on this port, and runClaude() bakes it into
431
+ // the argv synchronously — so it has to be bound before the first message
432
+ // can arrive, not on demand.
433
+ await this.ensureControlServer();
414
434
  // Connect to VibeKit WebSocket
415
435
  this.connect();
416
436
  // Handle process signals
@@ -472,39 +492,79 @@ class AgentClient {
472
492
  // far more than any normal chat needs; the rare task that legitimately
473
493
  // exceeds it can be split across messages.
474
494
  args.push('--max-turns', '50');
495
+ // MCP plumbing. The SELF-CONFIG server is attached on every run, not just
496
+ // supervised ones: "change your own settings" has to work in the default
497
+ // posture, which is where nearly every user actually lives. Supervised
498
+ // mode additionally attaches the permission-prompt server.
499
+ let mcpConfigPath = null;
500
+ let supervisedArmed = false;
475
501
  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
502
  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.');
503
+ mcpConfigPath = this.ensureMcpPlumbing(true);
504
+ supervisedArmed = true;
489
505
  }
490
506
  catch (e) {
491
507
  // Fail CLOSED into the old restricted behavior rather than silently
492
508
  // granting everything the user asked us to gate.
493
509
  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
510
  }
499
511
  }
512
+ else {
513
+ // A missing or broken config-mcp.js must never take down an ordinary
514
+ // run, so this degrades to "no self-config this turn" rather than throw.
515
+ // It SAYS so, though: swallowing the reason is what let a bind that
516
+ // failed on every run look like a feature nobody had asked for.
517
+ try {
518
+ mcpConfigPath = this.ensureMcpPlumbing(false);
519
+ }
520
+ catch (e) {
521
+ console.error(`[Self-config] Not attached this run (${e?.message || e}).`);
522
+ mcpConfigPath = null;
523
+ }
524
+ }
525
+ if (mcpConfigPath)
526
+ args.push('--mcp-config', mcpConfigPath);
527
+ /** An --allowedTools value that always keeps the self-config tools on it.
528
+ * See CONFIG_TOOL_NAMES for why this is not optional. */
529
+ const allowList = (tools) => [...tools, ...(mcpConfigPath ? CONFIG_TOOL_NAMES : [])].join(',');
530
+ if (supervisedArmed) {
531
+ // Supervised mode: no skip-permissions. Every prompt claude would have
532
+ // shown in a terminal routes through our MCP permission tool → parent
533
+ // HTTP callback → WebSocket → the user's phone, which answers with
534
+ // allow/deny (auto-deny after APPROVAL_TIMEOUT_MS). An explicit
535
+ // allowedTools list still pre-approves those tools; everything else
536
+ // gets prompted instead of refused.
537
+ //
538
+ // The flag is passed ONLY when the user already had a list, exactly as
539
+ // before. Adding one where there was none would put this live safety
540
+ // path into a state it has never run in, on an assumption about
541
+ // claude-cli's precedence that is not worth testing in production. The
542
+ // cost of not doing it is one extra tap to change a setting while
543
+ // supervised, which is what "ask before actions" means anyway, and the
544
+ // anti-lockout property still holds: an unlisted config tool prompts,
545
+ // and the user can approve it.
546
+ args.push('--permission-prompt-tool', 'mcp__vkapprove__approve');
547
+ if (allowedTools.length > 0)
548
+ args.push('--allowedTools', allowList(allowedTools));
549
+ console.log('[Supervised] Permission prompts will be sent to your phone.');
550
+ }
551
+ else if (this.currentSupervised) {
552
+ // Arming failed above — restricted fallback.
553
+ args.push('--allowedTools', allowList(allowedTools.length > 0 ? allowedTools : ['Read', 'Grep', 'Glob', 'LS']));
554
+ }
500
555
  else if (allowedTools.length === 0) {
501
556
  // No restrictions - allow everything
502
557
  args.push('--dangerously-skip-permissions');
503
558
  }
504
559
  else {
505
560
  // Use specific allowed tools
506
- args.push('--allowedTools', allowedTools.join(','));
561
+ args.push('--allowedTools', allowList(allowedTools));
507
562
  }
563
+ // Model override. Unset (the default, and the only behaviour before this
564
+ // key existed) leaves the choice to the user's claude install.
565
+ const model = this.config.getModel();
566
+ if (model)
567
+ args.push('--model', model);
508
568
  // Decide how to launch claude:
509
569
  // - local binary (installed) → spawn it directly (fast)
510
570
  // - not installed → fall back to `npx --yes @anthropic-ai/claude-code`
@@ -1202,9 +1262,21 @@ class AgentClient {
1202
1262
  // can leave the socket stuck in CONNECTING state for whatever the OS
1203
1263
  // timeout is (often minutes), blocking the reconnect loop. Cleared on
1204
1264
  // every terminal event below.
1265
+ //
1266
+ // `terminate()` on a socket still in CONNECTING is reported by ws as an
1267
+ // 'error' carrying a fixed message ("WebSocket was closed before the
1268
+ // connection was established"), emitted just before 'close'. That error
1269
+ // IS this watchdog firing, not a fault we hit, so it is flagged here and
1270
+ // read by the error handler below. Untagged, it reached prod's error log
1271
+ // at error level and was scraped into the admin Server Errors panel as an
1272
+ // unexplained failure, while the reconnect it triggered worked perfectly
1273
+ // (2026-08-16). Only this call site can produce it: the heartbeat and wake
1274
+ // watchdogs start inside 'open', so their terminate() always sees OPEN.
1275
+ let handshakeAborted = false;
1205
1276
  let handshakeTimer = setTimeout(() => {
1206
1277
  handshakeTimer = null;
1207
1278
  if (this.ws && this.ws.readyState === ws_1.default.CONNECTING) {
1279
+ handshakeAborted = true;
1208
1280
  console.log('[Connect] Handshake timed out after 10s — terminating');
1209
1281
  try {
1210
1282
  this.ws.terminate();
@@ -1245,6 +1317,12 @@ class AgentClient {
1245
1317
  platform: os.platform(),
1246
1318
  workingDirectory: this.workingDirectory,
1247
1319
  branch: this.currentGitBranch(),
1320
+ // Additive: lets the phone show what this machine is set to without
1321
+ // waiting for a config change to happen. Deliberately NOT carrying
1322
+ // `supervised` — that one is the server's, and reporting our copy
1323
+ // on every reconnect would fight the iOS toggle.
1324
+ model: this.config.getModel() || null,
1325
+ allowedTools: this.config.getAllowedTools(),
1248
1326
  },
1249
1327
  timestamp: Date.now(),
1250
1328
  messageId: this.generateId(),
@@ -1269,8 +1347,16 @@ class AgentClient {
1269
1347
  });
1270
1348
  this.ws.on('error', (error) => {
1271
1349
  clearHandshakeTimer();
1272
- console.error('WebSocket error:', error.message);
1273
1350
  this.isConnected = false;
1351
+ if (handshakeAborted) {
1352
+ // Our own 10s watchdog aborted this handshake and already logged why.
1353
+ // ws emits 'close' straight after, which schedules the reconnect, so
1354
+ // there is nothing to report and nothing more to do. Reset the flag so
1355
+ // a genuine error later on this socket is still logged.
1356
+ handshakeAborted = false;
1357
+ return;
1358
+ }
1359
+ console.error('WebSocket error:', error.message);
1274
1360
  const msg = error?.message || '';
1275
1361
  if (msg.includes('ENOTFOUND') || msg.includes('EAI_AGAIN')) {
1276
1362
  this.lastErrorWasDns = true;
@@ -1697,84 +1783,151 @@ class AgentClient {
1697
1783
  */
1698
1784
  // ── Supervised-mode approval plumbing ──────────────────────────────
1699
1785
  /**
1700
- * Start (once) the localhost HTTP server the approval-mcp child calls,
1701
- * and write the --mcp-config file pointing claude at that child. Returns
1702
- * the config path. Throws when the compiled approval-mcp.js is missing —
1703
- * runClaude treats that as fail-closed.
1786
+ * Bind (once) the localhost HTTP server our MCP children call back on.
1787
+ *
1788
+ * Awaited at startup rather than done inline where it is needed, because
1789
+ * binding is ASYNCHRONOUS: `listen(0, '127.0.0.1')` resolves the host
1790
+ * through dns.lookup first, so `server.address()` on the next line is null.
1791
+ * The inline version read it there and threw "control server failed to
1792
+ * bind" on every single run — which the caller swallowed, so self-config
1793
+ * (and supervised mode's approval prompts) silently never attached from the
1794
+ * day they shipped. runClaude() is synchronous and cannot await, so the
1795
+ * port has to already exist by the time it builds the argv.
1796
+ *
1797
+ * Resolves either way: a box that cannot bind loopback still gets a working
1798
+ * agent, minus self-config, and is told so rather than failing to start.
1704
1799
  */
1705
- ensureApprovalPlumbing() {
1706
- const mcpScript = path.join(__dirname, 'approval-mcp.js');
1707
- if (!fs.existsSync(mcpScript))
1708
- throw new Error(`missing ${mcpScript}`);
1709
- if (!this.approvalServer) {
1710
- const server = http.createServer((req, res) => this.handleApprovalHttpRequest(req, res));
1711
- server.listen(0, '127.0.0.1');
1712
- const addr = server.address();
1713
- if (!addr || typeof addr === 'string')
1714
- throw new Error('approval server failed to bind');
1715
- this.approvalPort = addr.port;
1716
- server.unref(); // never keep the process alive on its own
1717
- this.approvalServer = server;
1718
- }
1800
+ ensureControlServer() {
1801
+ if (this.controlServer)
1802
+ return Promise.resolve();
1803
+ return new Promise((resolve) => {
1804
+ const server = http.createServer((req, res) => this.handleControlHttpRequest(req, res));
1805
+ server.once('error', (e) => {
1806
+ console.error(`Self-config and supervised mode are unavailable: control server could not bind (${e?.message || e}).`);
1807
+ resolve();
1808
+ });
1809
+ server.listen(0, '127.0.0.1', () => {
1810
+ const addr = server.address();
1811
+ if (addr && typeof addr !== 'string') {
1812
+ this.controlPort = addr.port;
1813
+ this.controlServer = server;
1814
+ }
1815
+ server.unref(); // never keep the process alive on its own
1816
+ resolve();
1817
+ });
1818
+ });
1819
+ }
1820
+ /**
1821
+ * Write the --mcp-config file pointing claude at our MCP children. Returns
1822
+ * the config path, or null when there is no MCP server worth attaching.
1823
+ *
1824
+ * `withApproval` adds the supervised-mode permission-prompt server. Throws
1825
+ * when the plumbing it needs is missing: a missing approval-mcp.js must
1826
+ * fail CLOSED (runClaude falls back to tool restrictions), while a missing
1827
+ * config-mcp.js just means no self-config this run.
1828
+ */
1829
+ ensureMcpPlumbing(withApproval) {
1830
+ const approveScript = path.join(__dirname, 'approval-mcp.js');
1831
+ const configScript = path.join(__dirname, 'config-mcp.js');
1832
+ if (withApproval && !fs.existsSync(approveScript))
1833
+ throw new Error(`missing ${approveScript}`);
1834
+ const withConfig = fs.existsSync(configScript);
1835
+ if (!withApproval && !withConfig)
1836
+ return null;
1837
+ if (!this.controlPort)
1838
+ throw new Error('control server is not listening');
1719
1839
  // Port is baked into the config env, so rewrite whenever it changes
1720
- // (fresh process = fresh ephemeral port).
1721
- if (!this.approvalMcpConfigPath) {
1722
- this.approvalMcpConfigPath = path.join(os.tmpdir(), `vibekit-approval-mcp-${process.pid}.json`);
1723
- }
1724
- fs.writeFileSync(this.approvalMcpConfigPath, JSON.stringify({
1725
- mcpServers: {
1726
- vkapprove: {
1727
- command: process.execPath,
1728
- args: [mcpScript],
1729
- env: { VK_APPROVAL_PORT: String(this.approvalPort) },
1730
- },
1731
- },
1732
- }), { mode: 0o600 });
1733
- return this.approvalMcpConfigPath;
1840
+ // (fresh process = fresh ephemeral port). Rewritten per run rather than
1841
+ // once, because which servers belong in it depends on supervised mode:
1842
+ // declaring vkapprove outside supervised mode would offer claude a tool
1843
+ // that is never the right thing to call.
1844
+ if (!this.mcpConfigPath) {
1845
+ this.mcpConfigPath = path.join(os.tmpdir(), `vibekit-mcp-${process.pid}.json`);
1846
+ }
1847
+ const mcpServers = {};
1848
+ if (withApproval) {
1849
+ mcpServers.vkapprove = {
1850
+ command: process.execPath,
1851
+ args: [approveScript],
1852
+ env: { VK_APPROVAL_PORT: String(this.controlPort) },
1853
+ };
1854
+ }
1855
+ if (withConfig) {
1856
+ mcpServers.vkconfig = {
1857
+ command: process.execPath,
1858
+ args: [configScript],
1859
+ env: { VK_CONFIG_PORT: String(this.controlPort) },
1860
+ };
1861
+ }
1862
+ fs.writeFileSync(this.mcpConfigPath, JSON.stringify({ mcpServers }), { mode: 0o600 });
1863
+ return this.mcpConfigPath;
1734
1864
  }
1735
- /** POST /approve from the MCP child: hold the response open until the
1736
- * phone answers or the deadline passes. */
1737
- handleApprovalHttpRequest(req, res) {
1738
- if (req.method !== 'POST' || req.url !== '/approve') {
1865
+ /** Router for the two things our MCP children POST back to us. */
1866
+ handleControlHttpRequest(req, res) {
1867
+ if (req.method !== 'POST' || (req.url !== '/approve' && req.url !== '/config')) {
1739
1868
  res.writeHead(404).end();
1740
1869
  return;
1741
1870
  }
1871
+ const isConfig = req.url === '/config';
1742
1872
  let body = '';
1743
1873
  req.on('data', (c) => { body += c; if (body.length > 64_000)
1744
1874
  req.destroy(); });
1745
1875
  req.on('end', () => {
1746
- let toolName = 'unknown tool';
1747
- let input = {};
1876
+ let parsed = {};
1748
1877
  try {
1749
- const parsed = JSON.parse(body);
1750
- if (typeof parsed?.toolName === 'string')
1751
- toolName = parsed.toolName;
1752
- if (parsed?.input && typeof parsed.input === 'object')
1753
- input = parsed.input;
1878
+ parsed = JSON.parse(body);
1754
1879
  }
1755
1880
  catch { /* keep defaults */ }
1756
- const chatId = this.currentChatId;
1757
- if (!chatId || !this.isConnected) {
1758
- // No phone to ask — deny with a reason claude can surface.
1759
- res.writeHead(200, { 'Content-Type': 'application/json' });
1760
- res.end(JSON.stringify({ behavior: 'deny', message: 'VibeKit is not connected, so no one could approve this.' }));
1881
+ const reply = (payload) => {
1882
+ try {
1883
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1884
+ res.end(JSON.stringify(payload));
1885
+ }
1886
+ catch { /* MCP child already gone — claude was killed */ }
1887
+ };
1888
+ if (isConfig) {
1889
+ // The rejection arm matters: an unhandled throw would never call
1890
+ // reply(), and the MCP child would sit on its 200s socket timeout
1891
+ // with claude blocked behind it. An error is a far better failure
1892
+ // than a three-minute hang.
1893
+ void this.handleConfigToolCall(parsed).then(reply, (e) => {
1894
+ console.error(`[Config] handler threw: ${e?.message || e}`);
1895
+ reply({ ok: false, text: 'The agent hit an error applying that, so nothing changed.' });
1896
+ });
1761
1897
  return;
1762
1898
  }
1763
- const requestId = (0, crypto_1.randomUUID)();
1764
- const expiresAt = Date.now() + AgentClient.APPROVAL_TIMEOUT_MS;
1765
- const timer = setTimeout(() => {
1766
- this.resolveApproval(requestId, 'deny', 'No answer from your phone in 3 minutes — denied. Send the message again when you are ready.');
1767
- }, AgentClient.APPROVAL_TIMEOUT_MS);
1768
- this.pendingApprovals.set(requestId, { res, timer });
1899
+ const toolName = typeof parsed?.toolName === 'string' ? parsed.toolName : 'unknown tool';
1900
+ const input = (parsed?.input && typeof parsed.input === 'object') ? parsed.input : {};
1769
1901
  // Trim the input we ship to the phone: a Write's full content can be
1770
1902
  // hundreds of KB; the card only needs enough to decide.
1771
1903
  const slim = {};
1772
1904
  for (const [k, v] of Object.entries(input)) {
1773
1905
  slim[k] = typeof v === 'string' && v.length > 2_000 ? v.slice(0, 2_000) + '…' : v;
1774
1906
  }
1907
+ void this.askPhone(toolName, slim).then(reply);
1908
+ });
1909
+ }
1910
+ /**
1911
+ * Put a question on the user's phone and wait for the answer. Used by the
1912
+ * supervised-mode tool prompt and by a config change that would reduce
1913
+ * safety, so both share one deadline, one cancel path, and one card.
1914
+ * Resolves to a deny (never rejects) when there is no phone to ask.
1915
+ */
1916
+ askPhone(toolName, input) {
1917
+ const chatId = this.currentChatId;
1918
+ if (!chatId || !this.isConnected) {
1919
+ return Promise.resolve({ behavior: 'deny', message: 'VibeKit is not connected, so no one could approve this.' });
1920
+ }
1921
+ return new Promise((resolve) => {
1922
+ const requestId = (0, crypto_1.randomUUID)();
1923
+ const expiresAt = Date.now() + AgentClient.APPROVAL_TIMEOUT_MS;
1924
+ const timer = setTimeout(() => {
1925
+ this.resolveApproval(requestId, 'deny', 'No answer from your phone in 3 minutes — denied. Send the message again when you are ready.');
1926
+ }, AgentClient.APPROVAL_TIMEOUT_MS);
1927
+ this.pendingApprovals.set(requestId, { resolve, timer });
1775
1928
  this.send({
1776
1929
  type: 'permission_request',
1777
- payload: { chatId, requestId, toolName, input: slim, expiresAt },
1930
+ payload: { chatId, requestId, toolName, input, expiresAt },
1778
1931
  timestamp: Date.now(),
1779
1932
  messageId: this.generateId(),
1780
1933
  });
@@ -1788,13 +1941,163 @@ class AgentClient {
1788
1941
  return; // already resolved / expired — idempotent
1789
1942
  this.pendingApprovals.delete(requestId);
1790
1943
  clearTimeout(pending.timer);
1791
- try {
1792
- pending.res.writeHead(200, { 'Content-Type': 'application/json' });
1793
- pending.res.end(JSON.stringify({ behavior, message }));
1794
- }
1795
- catch { /* MCP child already gone — claude was killed */ }
1944
+ pending.resolve({ behavior, message });
1796
1945
  console.log(`[Supervised] ${behavior}${message ? ` (${message})` : ''} for ${requestId.slice(0, 8)}`);
1797
1946
  }
1947
+ // ── Self-configuration (the vkconfig MCP tools) ────────────────────
1948
+ /** Human-readable current settings, for get_config and for confirmations. */
1949
+ describeConfig() {
1950
+ const model = this.config.getModel();
1951
+ const tools = this.config.getAllowedTools();
1952
+ return [
1953
+ `Model: ${model || 'default (whatever your claude install picks)'}`,
1954
+ `Allowed tools: ${tools.length === 0 ? 'all (no restrictions)' : tools.join(', ')}`,
1955
+ `Working directory: ${this.workingDirectory}`,
1956
+ `Supervised mode: ${this.currentSupervised ? 'on' : 'off'}`,
1957
+ ].join('\n');
1958
+ }
1959
+ /**
1960
+ * POST /config from the vkconfig MCP child: the agent changing its own
1961
+ * settings because the conversation asked it to.
1962
+ *
1963
+ * Atomic. A call carrying both a safe change and a refused one applies
1964
+ * NEITHER, because partially-applied settings are the kind of thing a user
1965
+ * discovers three days later.
1966
+ */
1967
+ async handleConfigToolCall(body) {
1968
+ if (body?.action === 'get')
1969
+ return { ok: true, text: this.describeConfig() };
1970
+ if (body?.action !== 'set')
1971
+ return { ok: false, text: 'Unsupported settings action.' };
1972
+ const raw = (body?.changes && typeof body.changes === 'object') ? body.changes : {};
1973
+ // Refuse unknown keys BY NAME instead of dropping them. The MCP schema
1974
+ // does not offer `token` or `wsUrl`, but a schema is a hint to the model,
1975
+ // not a gate — this is the gate. Writing `wsUrl` would re-point the agent
1976
+ // at someone else's server and hand over the machine, so it has to be
1977
+ // visibly impossible rather than quietly ignored, which would read back
1978
+ // to the model (and then the user) as "done".
1979
+ const unknown = Object.keys(raw).filter((k) => !config_1.CONFIG_CHANGE_KEYS.includes(k));
1980
+ if (unknown.length > 0) {
1981
+ return {
1982
+ ok: false,
1983
+ text: `Refused: ${unknown.join(', ')} cannot be changed from a conversation. `
1984
+ + 'The pairing itself (auth token and server URL) is deliberately not settable this way. '
1985
+ + `Changeable settings are: ${config_1.CONFIG_CHANGE_KEYS.join(', ')}.`,
1986
+ };
1987
+ }
1988
+ const next = {};
1989
+ if ('model' in raw) {
1990
+ const m = raw.model;
1991
+ if (m !== null && typeof m !== 'string')
1992
+ return { ok: false, text: 'model must be a string, or null to clear it.' };
1993
+ if (typeof m === 'string' && !(0, config_1.isValidModel)(m)) {
1994
+ return { ok: false, text: `"${m}" is not a model name claude accepts. Use opus, sonnet, haiku, or a full claude model id.` };
1995
+ }
1996
+ next.model = m;
1997
+ }
1998
+ if ('allowedTools' in raw) {
1999
+ const t = raw.allowedTools;
2000
+ if (!Array.isArray(t) || t.some((x) => typeof x !== 'string' || !x.trim())) {
2001
+ return { ok: false, text: 'allowedTools must be an array of tool names.' };
2002
+ }
2003
+ next.allowedTools = t.map((x) => x.trim());
2004
+ }
2005
+ if ('cwd' in raw) {
2006
+ if (typeof raw.cwd !== 'string' || !raw.cwd.trim())
2007
+ return { ok: false, text: 'cwd must be a path.' };
2008
+ next.cwd = raw.cwd.trim();
2009
+ }
2010
+ if ('supervised' in raw) {
2011
+ if (typeof raw.supervised !== 'boolean')
2012
+ return { ok: false, text: 'supervised must be true or false.' };
2013
+ next.supervised = raw.supervised;
2014
+ }
2015
+ if (Object.keys(next).length === 0)
2016
+ return { ok: false, text: 'No settings were named, so nothing changed.' };
2017
+ // Anything that reduces safety costs a tap on the phone, even when
2018
+ // supervised mode is off. The agent reads repos, issue text and web
2019
+ // pages, so the realistic attack is a poisoned file telling it to disarm
2020
+ // the user's own gate. Failure to reach the phone is a REFUSAL.
2021
+ const loosenings = (0, config_1.describeLoosenings)({ allowedTools: this.config.getAllowedTools(), supervised: this.currentSupervised }, next);
2022
+ if (loosenings.length > 0) {
2023
+ const summary = loosenings.join(' and ');
2024
+ // PHRASING IS CONSTRAINED BY THE SHIPPED CLIENT, not by taste. The card
2025
+ // renders `"Agent wants to run \(toolName)"` (NativeRemoteView) and the
2026
+ // push falls through to `"Wants to run \(toolName)"` (permissionSummary
2027
+ // in remote-agent.ts) whenever the input carries no command/file_path/
2028
+ // path/url key, which ours never will. Both of those templates are in
2029
+ // App Store builds that are already on phones and cannot be changed, so
2030
+ // the toolName has to complete those sentences by itself. A bare label
2031
+ // here renders as "Agent wants to run VibeKit settings", which is the
2032
+ // last thing the one card that guards against prompt injection should
2033
+ // look like. Keep this a phrase that reads after "wants to run".
2034
+ const decision = await this.askPhone(`a settings change: ${summary}`, {
2035
+ note: 'This reduces what the agent has to ask you about before it acts. Approve only if you just asked for this.',
2036
+ });
2037
+ if (decision.behavior !== 'allow') {
2038
+ return { ok: false, text: `Refused: ${summary} was not approved on the phone${decision.message ? ` (${decision.message})` : ''}. Nothing changed.` };
2039
+ }
2040
+ }
2041
+ // ORDER IS LOAD-BEARING for the atomicity promised above. Every field was
2042
+ // validated and the approval gate cleared before we got here, so the only
2043
+ // thing left that can fail is a directory that does not exist — which is
2044
+ // why cwd goes FIRST and can honestly report "nothing else changed".
2045
+ // setModel cannot throw after isValidModel, and setAllowedTools swallows
2046
+ // its own write errors. Reorder this and the guarantee quietly weakens.
2047
+ const applied = [];
2048
+ if (next.cwd !== undefined) {
2049
+ // Reuse the cd path so the directory is validated once and the server
2050
+ // gets its cd_result exactly as it does for a server-initiated cd.
2051
+ const result = this.changeDirectory(next.cwd);
2052
+ if (!result.success)
2053
+ return { ok: false, text: `Could not switch directory: ${result.error}. Nothing else changed.` };
2054
+ applied.push(`working directory is now ${result.path}`);
2055
+ }
2056
+ if (next.model !== undefined) {
2057
+ try {
2058
+ this.config.setModel(next.model);
2059
+ }
2060
+ catch (e) {
2061
+ return { ok: false, text: e?.message || 'Could not set the model.' };
2062
+ }
2063
+ applied.push(next.model === null ? 'model override cleared' : `model is now ${next.model}`);
2064
+ }
2065
+ if (next.allowedTools !== undefined) {
2066
+ this.config.setAllowedTools(next.allowedTools);
2067
+ applied.push(next.allowedTools.length === 0
2068
+ ? 'tool restrictions removed'
2069
+ : `tools restricted to ${next.allowedTools.join(', ')}`);
2070
+ }
2071
+ if (next.supervised !== undefined) {
2072
+ applied.push(`supervised mode ${next.supervised ? 'on' : 'off'}`);
2073
+ }
2074
+ // Tell the server, so the phone shows the same thing and `supervised`
2075
+ // (which is server-owned, on the remote_agents row) actually persists.
2076
+ this.sendConfigState(next.supervised);
2077
+ return {
2078
+ ok: true,
2079
+ text: `Done: ${applied.join('; ')}. This takes effect on your NEXT message, not this one.`,
2080
+ };
2081
+ }
2082
+ /**
2083
+ * Report settings upward. `supervised` is included ONLY when the user just
2084
+ * asked to change it: the flag is owned by the server (it rides down on
2085
+ * each UserMessage), and echoing our stale copy back on every change would
2086
+ * let a config edit clobber a toggle made from the iOS sheet in between.
2087
+ */
2088
+ sendConfigState(supervised) {
2089
+ this.send({
2090
+ type: 'config_state',
2091
+ payload: {
2092
+ model: this.config.getModel() || null,
2093
+ allowedTools: this.config.getAllowedTools(),
2094
+ workingDirectory: this.workingDirectory,
2095
+ ...(supervised === undefined ? {} : { supervised }),
2096
+ },
2097
+ timestamp: Date.now(),
2098
+ messageId: this.generateId(),
2099
+ });
2100
+ }
1798
2101
  /** Deny everything in flight — cancel, new message, or shutdown. */
1799
2102
  denyAllPendingApprovals(reason) {
1800
2103
  for (const id of [...this.pendingApprovals.keys()]) {
@@ -1849,9 +2152,17 @@ class AgentClient {
1849
2152
  }
1850
2153
  }
1851
2154
  /**
1852
- * Handle change directory command
2155
+ * Handle change directory command.
2156
+ *
2157
+ * Thin wrapper: `changeDirectory` does the work and owns the cd_result
2158
+ * frame, so the self-config tool gets the same validation and the same
2159
+ * server-side bookkeeping without a second implementation.
1853
2160
  */
1854
2161
  handleCdCommand(newPath) {
2162
+ this.changeDirectory(newPath);
2163
+ }
2164
+ /** Resolve, validate, apply and announce a working-directory change. */
2165
+ changeDirectory(newPath) {
1855
2166
  const resolved = path.resolve(this.workingDirectory, newPath);
1856
2167
  try {
1857
2168
  const fs = require('fs');
@@ -1862,7 +2173,7 @@ class AgentClient {
1862
2173
  timestamp: Date.now(),
1863
2174
  messageId: this.generateId(),
1864
2175
  });
1865
- return;
2176
+ return { success: false, error: 'Directory not found' };
1866
2177
  }
1867
2178
  this.workingDirectory = resolved;
1868
2179
  this.config.setLastDirectory(resolved);
@@ -1873,6 +2184,7 @@ class AgentClient {
1873
2184
  messageId: this.generateId(),
1874
2185
  });
1875
2186
  console.log(`Changed directory to: ${resolved}`);
2187
+ return { success: true, path: resolved };
1876
2188
  }
1877
2189
  catch (error) {
1878
2190
  this.send({
@@ -1881,6 +2193,7 @@ class AgentClient {
1881
2193
  timestamp: Date.now(),
1882
2194
  messageId: this.generateId(),
1883
2195
  });
2196
+ return { success: false, error: 'Failed to change directory' };
1884
2197
  }
1885
2198
  }
1886
2199
  /**