unbound-cli 1.26.2 → 1.27.1

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/README.md CHANGED
@@ -339,11 +339,11 @@ Needs Admin or Analytics Viewer over the whole organization (a token needs `anal
339
339
  | Command | Description |
340
340
  |---------|-------------|
341
341
  | `unbound delivery summary` | AI branches, PRs opened and merged, merge rate, AI spend, cost per PR and time to first PR |
342
- | `unbound delivery branches` | AI branches with their PR, ticket, work group, users and cost (`--outcome`, `--ticket-status`, `--work-group`, `--search`, `--sort first_seen\|cost`) |
342
+ | `unbound delivery branches` | AI branches with their PR, ticket, work group, users and cost (`--outcome`, `--ticket-status`, `--work-group`, `--search`, `--sort first-seen\|cost`) |
343
343
  | `unbound delivery branch <id>` | One branch with its PR and ticket links, timeline and sessions |
344
- | `unbound delivery users` | AI spend, PRs raised and merged per person (`--sort ai_spend`, `merge_rate_pct`, ...) |
344
+ | `unbound delivery users` | AI spend, PRs raised and merged per person (`--sort ai-spend`, `merge-rate-pct`, ...) |
345
345
  | `unbound delivery teams` | The same per department, with active AI users and share of branches with a ticket |
346
- | `unbound delivery spend --by outcome\|work-group` | AI spend by PR outcome, or by work group (`--pr-state all\|merged\|open\|no_pr`) |
346
+ | `unbound delivery spend --by outcome\|work-group` | AI spend by PR outcome, or by work group (`--pr-state all\|merged\|open\|no-pr`) |
347
347
  | `unbound delivery repos` | Repositories with AI work in the window, the values `--repo` takes |
348
348
 
349
349
  Every command except `branch` takes `--time-window ONE_DAY|THREE_DAYS|SEVEN_DAYS|FOURTEEN_DAYS|THIRTY_DAYS` (default `THIRTY_DAYS`) or `--start/--end YYYY-MM-DD` (max 31 days, within the last 31 days). `summary`, `branches`, `users`, `teams` and `spend` also filter by `--user` (user IDs, not emails), `--team`, `--manager`, `--tool` and `--repo`. `--json` prints the raw response.
@@ -352,7 +352,7 @@ Every command except `branch` takes `--time-window ONE_DAY|THREE_DAYS|SEVEN_DAYS
352
352
  unbound delivery summary --time-window SEVEN_DAYS
353
353
  unbound delivery branches --outcome merged --json | jq '.results[] | {name, pr: .pr.number, cost}'
354
354
  unbound delivery branch 4821
355
- unbound delivery users --sort merge_rate_pct --team Platform
355
+ unbound delivery users --sort merge-rate-pct --team Platform
356
356
  unbound delivery spend --by work-group --pr-state merged
357
357
  ```
358
358
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unbound-cli",
3
- "version": "1.26.2",
3
+ "version": "1.27.1",
4
4
  "description": "CLI tool for Unbound - AI Gateway management",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/src/api.js CHANGED
@@ -31,7 +31,7 @@ class ApiError extends Error {
31
31
 
32
32
  const DEFAULT_TIMEOUT_MS = 30000;
33
33
 
34
- function request(method, path, { body, query, apiKey, baseUrl, timeoutMs } = {}) {
34
+ function request(method, path, { body, query, apiKey, baseUrl, timeoutMs, signal } = {}) {
35
35
  // Explicit baseUrl wins over env-var-aware getBaseUrl(). Used by login /
36
36
  // setup / onboard so a user's just-passed --backend-url isn't shadowed by a
37
37
  // stale UNBOUND_API_URL env var from a prior shell session.
@@ -109,6 +109,16 @@ function request(method, path, { body, query, apiKey, baseUrl, timeoutMs } = {})
109
109
  reject(new Error(`Network error: ${err.message}`));
110
110
  }
111
111
  });
112
+ // Optional AbortSignal: aborting destroys the request, even one whose body is still arriving.
113
+ if (signal) {
114
+ const onAbort = () => {
115
+ req.destroy();
116
+ reject(new Error(`Request to ${url.host} was cancelled.`));
117
+ };
118
+ if (signal.aborted) onAbort();
119
+ else signal.addEventListener('abort', onAbort, { once: true });
120
+ req.on('close', () => signal.removeEventListener('abort', onAbort));
121
+ }
112
122
  if (payload) req.write(payload);
113
123
  req.end();
114
124
  });
@@ -88,11 +88,19 @@ function normalizeChoice(value) {
88
88
  return String(value).trim().toLowerCase().replace(/-/g, '_');
89
89
  }
90
90
 
91
+ function dashed(choice) {
92
+ return String(choice).replace(/_/g, '-');
93
+ }
94
+
95
+ function listChoices(choices, separator = ', ') {
96
+ return choices.map(dashed).join(separator);
97
+ }
98
+
91
99
  function parseChoice(flag, value, choices) {
92
100
  if (value === undefined) return undefined;
93
101
  const choice = normalizeChoice(value);
94
102
  if (!choices.includes(choice)) {
95
- throw new Error(`Invalid ${flag} "${value}". Must be one of: ${choices.join(', ')}.`);
103
+ throw new Error(`Invalid ${flag} "${value}". Must be one of: ${listChoices(choices)}.`);
96
104
  }
97
105
  return choice;
98
106
  }
@@ -380,7 +388,7 @@ function peopleColumn(key) {
380
388
  function warnSortFallback(data, requestedSort) {
381
389
  if (!requestedSort || !data.sort_by || data.sort_by === requestedSort) return;
382
390
  const reason = data.github ? 'is shown only when GitHub is not connected' : 'needs GitHub connected';
383
- output.warn(`Sorted by ${safe(data.sort_by)}: ${requestedSort} ${reason}.`);
391
+ output.warn(`Sorted by ${dashed(safe(data.sort_by))}: ${dashed(requestedSort)} ${reason}.`);
384
392
  }
385
393
 
386
394
  async function listPeople(noun, opts) {
@@ -471,10 +479,10 @@ function addFilterOptions(command) {
471
479
 
472
480
  function addTableOptions(command, sortChoices, defaultSort) {
473
481
  return command
474
- .option('--ticket-status <statuses>', `Ticket status, comma-separated: ${TICKET_STATUSES.join(', ')}`)
475
- .option('--work-group <groups>', `Work group, comma-separated: ${WORK_GROUPS.join(', ')}`)
482
+ .option('--ticket-status <statuses>', `Ticket status, comma-separated: ${listChoices(TICKET_STATUSES)}`)
483
+ .option('--work-group <groups>', `Work group, comma-separated: ${listChoices(WORK_GROUPS)}`)
476
484
  .option('--search <text>', 'Search text')
477
- .option('--sort <column>', `${sortChoices.join(' | ')} (default ${defaultSort})`)
485
+ .option('--sort <column>', `${listChoices(sortChoices, ' | ')} (default ${dashed(defaultSort)})`)
478
486
  .option('--order <order>', 'desc | asc (default desc)')
479
487
  .option('--page <n>', 'Page number')
480
488
  .option('--page-size <n>', `Rows per page, up to ${MAX_PAGE_SIZE} (default 10)`)
@@ -492,7 +500,7 @@ Examples:
492
500
  $ unbound delivery branches --outcome merged --sort cost
493
501
  $ unbound delivery branches --outcome merged --json | jq '.results[] | {name, pr: .pr.number, cost}'
494
502
  $ unbound delivery branch 4821
495
- $ unbound delivery users --sort merge_rate_pct --team Platform
503
+ $ unbound delivery users --sort merge-rate-pct --team Platform
496
504
  $ unbound delivery spend --by work-group --pr-state merged
497
505
 
498
506
  A PR appears only when an agent's own tool call created it.
@@ -511,10 +519,10 @@ Admin or Analytics Viewer (whole organization).
511
519
  addTableOptions(addFilterOptions(delivery
512
520
  .command('branches')
513
521
  .description('List AI branches created in the window.')
514
- .option('--outcome <outcome>', `PR outcome: ${OUTCOMES.join(', ')}`)), BRANCH_SORTS, 'first_seen')
522
+ .option('--outcome <outcome>', `PR outcome: ${listChoices(OUTCOMES)}`)), BRANCH_SORTS, 'first_seen')
515
523
  .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}
516
524
  Examples:
517
- $ unbound delivery branches --outcome no_pr --sort cost
525
+ $ unbound delivery branches --outcome no-pr --sort cost
518
526
  $ unbound delivery branches --ticket-status done --work-group fix
519
527
  $ unbound delivery branches --repo acme/web --page 2 --json
520
528
 
@@ -545,7 +553,7 @@ With --work-group, branches are windowed by PR time (merged, else opened) instea
545
553
  .command('spend')
546
554
  .description('Show AI spend by PR outcome or by work group.')
547
555
  .option('--by <dimension>', 'outcome | work-group (default outcome)')
548
- .option('--pr-state <state>', `With --by work-group: ${PR_STATES.join(', ')} (default all)`)
556
+ .option('--pr-state <state>', `With --by work-group: ${listChoices(PR_STATES)} (default all)`)
549
557
  .option('--json', 'Output the raw JSON response'))
550
558
  .addHelpText('after', `${WINDOW_HELP}${FILTER_HELP}
551
559
  Examples:
@@ -60,6 +60,7 @@ function register(program) {
60
60
  .option('--domain <url>', 'Backend URL for discovery (defaults to configured backend)')
61
61
  .option('--set-cron', 'Set up a daily background job to keep governance up to date (under sudo, schedules a discovery scan only — not a full tool re-install)')
62
62
  .option('--backfill', 'Seed historical Claude Code / Codex / Copilot sessions from local transcripts into Unbound analytics (Cursor skipped automatically)')
63
+ .option('--skip-cowork', 'With sudo, leave Claude Cowork prompt capture off (it is on by default)')
63
64
  .addOption(new Option('--backend-url <url>', 'Override backend URL for setup scripts (dev only)').hideHelp())
64
65
  .addOption(new Option('--frontend-url <url>', 'Override frontend URL for setup scripts (dev only)').hideHelp())
65
66
  .addOption(new Option('--gateway-url <url>', 'Override gateway URL for setup scripts (dev only)').hideHelp())
@@ -83,6 +84,7 @@ Only your API key is required — for both per-user and sudo/MDM onboarding.
83
84
  Examples:
84
85
  $ unbound onboard --api-key <USER_KEY>
85
86
  $ sudo unbound onboard --api-key <ADMIN_KEY>
87
+ $ sudo unbound onboard --api-key <ADMIN_KEY> --skip-cowork
86
88
  $ unbound onboard --api-key <USER_KEY> --backfill
87
89
  $ unbound onboard --api-key <USER_KEY> --set-cron
88
90
  `)
@@ -153,7 +155,7 @@ Examples:
153
155
  output.info('Step 1/2: Installing MDM tool bundle (all users)');
154
156
  const setUpPi = shouldSetUpPi(MDM_TOOLS.pi.label, { allUsers: true });
155
157
  const { ok, skipped } = await runMdmSetupAllBundle(adminApiKey, {
156
- backendUrl, frontendUrl, gatewayUrl, backfill: !!opts.backfill,
158
+ backendUrl, frontendUrl, gatewayUrl, backfill: !!opts.backfill, skipCowork: !!opts.skipCowork,
157
159
  });
158
160
  // A failed setup must NOT report onboarding success. runBatch already
159
161
  // reported the failure to the ledger and set exitCode; make the
@@ -1,5 +1,6 @@
1
1
  const { spawn, spawnSync } = require('child_process');
2
2
  const { Option } = require('commander');
3
+ const crypto = require('crypto');
3
4
  const fs = require('fs');
4
5
  const os = require('os');
5
6
  const path = require('path');
@@ -8,7 +9,7 @@ const output = require('../output');
8
9
  const telemetry = require('../telemetry');
9
10
  const auth = require('../auth');
10
11
  const { confirm, downloadToFile, withSecureTempFile } = require('../utils');
11
- const { reportSetupFailure, exitCodeForError } = require('../setup-report');
12
+ const { reportSetupFailure, reportRemovals, exitCodeForError } = require('../setup-report');
12
13
  const claudePaths = require('../claudePaths');
13
14
 
14
15
  const SETUP_BASE_URL = 'https://raw.githubusercontent.com/websentry-ai/setup/refs/heads/main';
@@ -21,6 +22,29 @@ const SETUP_BASE_URL = 'https://raw.githubusercontent.com/websentry-ai/setup/ref
21
22
  // branch, so clear/nuke operations never produce this code.
22
23
  const EXIT_MDM_PRESENT = 3;
23
24
 
25
+ // One removal context per clear command run, passed to clear scripts and `unbound-hook clear` via env.
26
+ let clearRun = null;
27
+
28
+ function beginClearRun(command) {
29
+ clearRun = { command, removalId: crypto.randomUUID() };
30
+ return clearRun;
31
+ }
32
+
33
+ // Env for a clear child process; undefined (inherit) when no clear run is active.
34
+ function clearRunEnv() {
35
+ if (!clearRun) return undefined;
36
+ return {
37
+ ...process.env,
38
+ UNBOUND_CLEAR_SOURCE: 'unbound_cli',
39
+ UNBOUND_CLEAR_COMMAND: clearRun.command,
40
+ UNBOUND_REMOVAL_ID: clearRun.removalId,
41
+ };
42
+ }
43
+
44
+ function isClearArgs(args) {
45
+ return /(^|\s)--clear(\s|$)/.test(args);
46
+ }
47
+
24
48
  // WSL reports as Linux via uname; only native Windows (cmd.exe / PowerShell)
25
49
  // takes the Windows code path. WSL keeps using the Linux curl|python3 pipe.
26
50
  function isWindowsNative() {
@@ -55,6 +79,17 @@ const MDM_TOOLS = {
55
79
  'pi': { label: 'Pi Coding Agent', script: 'pi/mdm/setup.py' },
56
80
  };
57
81
 
82
+ // Backend tool_type per hook-mode tool; must match the setup scripts' notify_setup_complete slugs.
83
+ const TOOL_TYPES = {
84
+ 'cursor': 'cursor',
85
+ 'copilot': 'copilot',
86
+ 'augment': 'augment_code',
87
+ 'antigravity': 'antigravity',
88
+ 'claude-code-subscription': 'claude-code',
89
+ 'codex-subscription': 'codex',
90
+ 'pi': 'pi',
91
+ };
92
+
58
93
  // Default MDM tools for `sudo unbound onboard` (subscription mode for Claude Code/Codex since only one can be active)
59
94
  const MDM_ALL_TOOLS = ['cursor', 'claude-code-subscription', 'gemini-cli', 'codex-subscription', 'copilot', 'augment', 'antigravity'];
60
95
 
@@ -221,6 +256,7 @@ async function runPythonScript(scriptPath, args, { capture }) {
221
256
  stdio: capture ? ['pipe', 'pipe', 'pipe'] : 'inherit',
222
257
  shell: false,
223
258
  windowsHide: true,
259
+ env: isClearArgs(args) ? clearRunEnv() : undefined,
224
260
  });
225
261
  let out = '';
226
262
  // stderr is also kept on its own. Python block-buffers stdout when piped,
@@ -288,7 +324,7 @@ async function syncWslLogonTask(tools, clear) {
288
324
  * their browser-auth host) and to MDM scripts as --frontend-url (persist-only,
289
325
  * no auth flow). Either way it lands in ~/.unbound/config.json as frontend_url.
290
326
  */
291
- function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, mdm, backfill, configDir } = {}) {
327
+ function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, mdm, backfill, skipCowork, configDir } = {}) {
292
328
  // --clear runs no auth in the Python scripts, so the key may be absent. Omit
293
329
  // the flag entirely rather than passing --api-key 'undefined'.
294
330
  let args = apiKey ? `--api-key ${shellEscape(apiKey)}` : '';
@@ -298,9 +334,17 @@ function buildScriptArgs(apiKey, { backendUrl, frontendUrl, gatewayUrl, clear, m
298
334
  if (configDir) args += ` --config-dir ${shellEscape(configDir)}`;
299
335
  if (clear) args += ' --clear';
300
336
  if (backfill) args += ' --backfill';
337
+ if (skipCowork) args += ' --skip-cowork';
301
338
  return args.trim();
302
339
  }
303
340
 
341
+ // Only the Claude Code MDM installer writes Claude Desktop's machine-wide config, where Cowork capture is on by default.
342
+ const COWORK_SCRIPT = MDM_TOOLS['claude-code-subscription'].script;
343
+
344
+ function scriptSupportsCowork(scriptPath) {
345
+ return scriptPath === COWORK_SCRIPT;
346
+ }
347
+
304
348
  // User-level Claude install scripts that honor CLAUDE_CONFIG_DIR. MDM variants are
305
349
  // excluded — they install per managed-user home, not the admin's env.
306
350
  const CLAUDE_CONFIG_DIR_SCRIPTS = new Set([
@@ -374,7 +418,7 @@ async function runSetupScript(scriptPath, apiKey, { clear = false, backendUrl, f
374
418
  * download exited 0 because dash has no pipefail — is closed.
375
419
  */
376
420
  function runScriptPiped(scriptPath, args) {
377
- const isClear = /(^|\s)--clear(\s|$)/.test(args);
421
+ const isClear = isClearArgs(args);
378
422
  return runPythonScript(scriptPath, args, { capture: true }).then((r) => {
379
423
  if (!isClear && !(r && r.mdmSkipped)) warnIfHooksMisplaced(scriptPath);
380
424
  return r;
@@ -465,6 +509,21 @@ const BINARY_INSTALL_PATHS = Object.freeze({
465
509
  logDir: '/var/log/unbound',
466
510
  });
467
511
 
512
+ // Receipts MDM clears leave for the next managed setup run; nuke must never delete them.
513
+ const REMOVALS_DIRS = Object.freeze([
514
+ '/Library/Application Support/Unbound/removals',
515
+ '/var/lib/unbound/removals',
516
+ path.win32.join(process.env.ProgramData || 'C:\\ProgramData', 'Unbound', 'removals'),
517
+ ]);
518
+
519
+ function holdsRemovalsDir(target, removalsDirs) {
520
+ // Skip another OS's path: resolving a relative one would join it onto the cwd.
521
+ return removalsDirs.filter((dir) => path.isAbsolute(dir)).some((dir) => {
522
+ const rel = path.relative(path.resolve(target), path.resolve(dir));
523
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
524
+ });
525
+ }
526
+
468
527
  // Tears down the privileged binary install. Best-effort: a failure on any
469
528
  // single path is logged via output.warn AND pushed onto the returned
470
529
  // `failed` array, but never aborts the rest. Bootout the daemon FIRST so
@@ -484,6 +543,7 @@ function removeBinaryInstall({
484
543
  newsyslogConf = BINARY_INSTALL_PATHS.newsyslogConf,
485
544
  logDir = BINARY_INSTALL_PATHS.logDir,
486
545
  runLaunchctl = process.platform === 'darwin',
546
+ removalsDirs = REMOVALS_DIRS,
487
547
  _confirmProductionPaths = false,
488
548
  } = {}) {
489
549
  const usesProdDefaults =
@@ -522,6 +582,11 @@ function removeBinaryInstall({
522
582
  for (const [label, p] of targets) {
523
583
  try {
524
584
  if (!fs.existsSync(p)) continue;
585
+ if (holdsRemovalsDir(p, removalsDirs)) {
586
+ output.warn(`nuke: kept ${label} (${p}): it holds removal receipts.`);
587
+ failed.push(`${label} (${p})`);
588
+ continue;
589
+ }
525
590
  fs.rmSync(p, { recursive: true, force: true });
526
591
  removed.push(`${label} (${p})`);
527
592
  } catch (err) {
@@ -553,7 +618,8 @@ function runBinaryClear({
553
618
  if (!present) return { ran: false, ok: true };
554
619
  try {
555
620
  // timeout so a hung clear can never block nuke from removing the binary.
556
- const r = runner(binaryPath, ['clear'], { stdio: 'pipe', timeout: 120000, killSignal: 'SIGKILL' });
621
+ // No `--initiated-by mdm`: the CLI is always run by a person.
622
+ const r = runner(binaryPath, ['clear'], { stdio: 'pipe', timeout: 120000, killSignal: 'SIGKILL', env: clearRunEnv() });
557
623
  if (r.error) {
558
624
  const why = r.error.code === 'ETIMEDOUT' ? 'timed out (120s)' : r.error.message;
559
625
  output.warn(`nuke: unbound-hook clear ${why}; continuing.`);
@@ -770,7 +836,8 @@ async function clearToolsBestEffort(layer, tools, { mdm, backendUrl, gatewayUrl,
770
836
  return failed;
771
837
  }
772
838
 
773
- function register(program) {
839
+ // nuke's privileged steps are injectable so tests never touch the real machine.
840
+ function register(program, { isRoot = hasRootPrivileges, binaryClear = runBinaryClear, binaryRemove = removeBinaryInstall } = {}) {
774
841
  const setup = program
775
842
  .command('setup')
776
843
  .argument('[tools...]', 'Tools to set up')
@@ -787,6 +854,7 @@ function register(program) {
787
854
  .option('--gateway', 'Use gateway mode for Claude Code / Codex (Unbound as AI provider)')
788
855
  .option('--all', 'Set up the default bundle: Cursor, Copilot, Augment, Antigravity, Claude Code (hooks), Codex (hooks)')
789
856
  .option('--backfill', 'Seed historical Claude Code / Codex / Copilot sessions from local transcripts into Unbound analytics (subscription/hooks mode only; Cursor unsupported)')
857
+ .option('--skip-cowork', 'With sudo, leave Claude Cowork prompt capture off (it is on by default)')
790
858
  .addOption(new Option('--backend-url <url>', 'Override backend URL for setup scripts (dev only)').hideHelp())
791
859
  .addOption(new Option('--frontend-url <url>', 'Override frontend URL for setup scripts (dev only)').hideHelp())
792
860
  .addOption(new Option('--gateway-url <url>', 'Override gateway URL for setup scripts (dev only)').hideHelp())
@@ -833,6 +901,7 @@ Examples:
833
901
  Configure all users on the device (MDM/org scope — run with sudo):
834
902
  $ sudo unbound setup --all --api-key <MDM_KEY> Configure all users (MDM)
835
903
  $ sudo unbound setup cursor codex-subscription --api-key <MDM_KEY> Configure specific tools for all users
904
+ $ sudo unbound setup --all --api-key <MDM_KEY> --skip-cowork Leave Claude Cowork prompt capture off
836
905
  $ sudo unbound setup --clear --all Remove config for all users
837
906
 
838
907
  Seed historical sessions (Claude Code / Codex subscription mode + Copilot):
@@ -861,7 +930,9 @@ Examples:
861
930
 
862
931
  When setting up, if you are not logged in and --api-key is not provided, the
863
932
  browser opens automatically to authenticate first. Clearing (--clear) never
864
- requires authentication.
933
+ requires authentication. Under sudo, clearing a tool reports the removal to
934
+ Unbound when a device key is present. Gateway-mode tools (Claude Code gateway,
935
+ Codex gateway, Gemini CLI) are not reported.
865
936
 
866
937
  If an MDM (organization-managed) setup is already present for a tool, user-level
867
938
  setup for that tool is skipped automatically — the managed configuration already
@@ -890,6 +961,7 @@ must update the MDM configuration.
890
961
  // Scope is auto-detected from privileges: with sudo/root we configure
891
962
  // every user on the device (MDM scope); without it, just the current
892
963
  // user. URLs were already persisted above and apply to both scopes.
964
+ if (opts.clear) beginClearRun('unbound setup --clear');
893
965
  const isMdm = hasRootPrivileges();
894
966
  output.info(scopeNotice(isMdm));
895
967
  if (isMdm) {
@@ -969,6 +1041,7 @@ must update the MDM configuration.
969
1041
  clear: opts.clear,
970
1042
  mdm: true,
971
1043
  backfill: opts.backfill && scriptSupportsBackfill(tool.script),
1044
+ skipCowork: !!opts.skipCowork && !opts.clear && scriptSupportsCowork(tool.script),
972
1045
  configDir: configDirForScript(tool.script),
973
1046
  });
974
1047
  return runScriptPiped(tool.script, toolArgs);
@@ -980,8 +1053,7 @@ must update the MDM configuration.
980
1053
  return;
981
1054
  }
982
1055
 
983
- // Clearing config needs no credentials — the setup scripts remove
984
- // files without calling the API — so don't force a login for --clear.
1056
+ // User-level clear scripts only remove files and call no API, so --clear needs no login.
985
1057
  const apiKey = opts.clear ? config.getDeviceKey() : await auth.resolveDeviceKey({
986
1058
  apiKey: opts.apiKey,
987
1059
  baseUrl: written.base_url,
@@ -1218,9 +1290,11 @@ What it clears:
1218
1290
  - Stored credentials and settings (~/.unbound/config.json and the CLI key in the OS keychain).
1219
1291
 
1220
1292
  After it finishes, run \`unbound login\` (or \`unbound onboard\`) to set things up
1221
- fresh. Clearing never contacts the Unbound API, so no API key is needed. The
1222
- scheduled-scan teardown runs fully offline; the per-tool and MDM clears fetch
1223
- their setup scripts, so those steps still need network.
1293
+ fresh. Nuke itself needs no login or API key. Under sudo, it reports each
1294
+ removal to Unbound before it clears anything, when a device key is present.
1295
+ Gateway-mode tools are not reported. The scheduled-scan teardown runs fully
1296
+ offline; the per-tool and MDM clears fetch their setup scripts, so those steps
1297
+ still need network.
1224
1298
 
1225
1299
  Examples:
1226
1300
  $ sudo unbound nuke Remove everything on the device (asks to confirm)
@@ -1235,7 +1309,7 @@ Examples:
1235
1309
  // remove system-level MDM config for all users; otherwise we clear only
1236
1310
  // this user. Detecting elevation up front keeps the confirmation honest
1237
1311
  // (no promising MDM removal we can't perform).
1238
- const includeMdm = hasRootPrivileges();
1312
+ const includeMdm = isRoot();
1239
1313
 
1240
1314
  if (!opts.yes) {
1241
1315
  output.warn(includeMdm
@@ -1248,12 +1322,28 @@ Examples:
1248
1322
  }
1249
1323
  }
1250
1324
 
1325
+ const run = beginClearRun('unbound nuke');
1326
+
1251
1327
  // Resolve URLs before wiping config so the clear scripts get consistent
1252
1328
  // flags. Clearing is URL-independent, but this matches the other clear paths.
1253
1329
  const backendUrl = config.getBaseUrl();
1254
1330
  const gatewayUrl = config.getGatewayUrl();
1255
1331
  const frontendUrl = config.getFrontendUrl();
1256
1332
 
1333
+ // Root only (the backend drops unmanaged events), and before any clear removes the configs and the key.
1334
+ if (includeMdm) {
1335
+ await reportRemovals({
1336
+ // Gateway-mode tools report no removal, so the backend has nothing to match for them.
1337
+ toolTypes: Object.entries(MDM_TOOLS)
1338
+ .filter(([, tool]) => !tool.script.includes('/gateway/'))
1339
+ .map(([name]) => TOOL_TYPES[name]),
1340
+ removalId: run.removalId,
1341
+ command: run.command,
1342
+ managed: true,
1343
+ backendUrl,
1344
+ });
1345
+ }
1346
+
1257
1347
  console.log('');
1258
1348
  const userTools = Object.keys(SETUP_TOOL_MAP).map(name => ({ name, ...SETUP_TOOL_MAP[name] }));
1259
1349
  const userFailed = await clearToolsBestEffort('user', userTools, { mdm: false, backendUrl, gatewayUrl, frontendUrl });
@@ -1274,8 +1364,8 @@ Examples:
1274
1364
  // Deregister managed configs via the binary's own clear FIRST (works
1275
1365
  // without python3, which a binary-only machine lacks); reuses the same
1276
1366
  // clear_setup() as the python clears. Must precede the rm below.
1277
- const binClear = runBinaryClear();
1278
- const { removed: binaryRemoved, failed: bf } = removeBinaryInstall({ _confirmProductionPaths: true });
1367
+ const binClear = binaryClear();
1368
+ const { removed: binaryRemoved, failed: bf } = binaryRemove({ _confirmProductionPaths: true });
1279
1369
  binaryFailed = bf;
1280
1370
  if (binClear.ran && !binClear.ok) binaryFailed.push('unbound-hook clear');
1281
1371
  if (binaryRemoved.length) {
@@ -1306,7 +1396,7 @@ Examples:
1306
1396
  const keyRemoved = config.clearConfig();
1307
1397
  output.success('Stored credentials and settings removed.');
1308
1398
  // As root, the keychain reached is root's, not the invoking user's.
1309
- if (hasRootPrivileges()) output.info('Run `unbound logout` without sudo to remove your CLI key from the keychain.');
1399
+ if (isRoot()) output.info('Run `unbound logout` without sudo to remove your CLI key from the keychain.');
1310
1400
  else if (!keyRemoved) output.warn('Could not remove the CLI key from the OS keychain. Unlock it and run `unbound logout`.');
1311
1401
 
1312
1402
  console.log('');
@@ -1364,7 +1454,7 @@ async function runSetupAllBundle(apiKey, { backendUrl, frontendUrl, gatewayUrl,
1364
1454
  * Caller must ensure the process is running as root.
1365
1455
  * Returns true on success, false on failure.
1366
1456
  */
1367
- async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gatewayUrl, backfill = false, tools = MDM_ALL_TOOLS } = {}) {
1457
+ async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gatewayUrl, backfill = false, skipCowork = false, tools = MDM_ALL_TOOLS } = {}) {
1368
1458
  const resolvedTools = tools.map(name => ({ name, ...MDM_TOOLS[name] }));
1369
1459
  if (backfill) {
1370
1460
  for (const tool of resolvedTools) {
@@ -1375,6 +1465,7 @@ async function runMdmSetupAllBundle(adminApiKey, { backendUrl, frontendUrl, gate
1375
1465
  const args = buildScriptArgs(adminApiKey, {
1376
1466
  backendUrl, frontendUrl, gatewayUrl, mdm: true,
1377
1467
  backfill: backfill && scriptSupportsBackfill(tool.script),
1468
+ skipCowork: skipCowork && scriptSupportsCowork(tool.script),
1378
1469
  configDir: configDirForScript(tool.script),
1379
1470
  });
1380
1471
  return runScriptPiped(tool.script, args);
@@ -1397,9 +1488,11 @@ module.exports = {
1397
1488
  MDM_ALL_TOOLS,
1398
1489
  SETUP_TOOL_MAP,
1399
1490
  MDM_TOOLS,
1491
+ TOOL_TYPES,
1400
1492
  buildScriptArgs,
1401
1493
  configDirForScript,
1402
1494
  scriptSupportsBackfill,
1495
+ scriptSupportsCowork,
1403
1496
  resolveSetupAllTools,
1404
1497
  clearUnboundEnvsEverywhere,
1405
1498
  failureReason,
@@ -1408,4 +1501,6 @@ module.exports = {
1408
1501
  removeScheduledRun,
1409
1502
  runBinaryClear,
1410
1503
  BINARY_INSTALL_PATHS,
1504
+ REMOVALS_DIRS,
1505
+ beginClearRun,
1411
1506
  };
package/src/index.js CHANGED
@@ -104,7 +104,7 @@ MDM SETUP (all users on the device — run setup with sudo)
104
104
  $ sudo unbound setup --all --api-key KEY
105
105
  $ sudo unbound setup cursor copilot codex-subscription --api-key KEY
106
106
  $ sudo unbound setup claude-code-subscription codex-subscription gemini-cli --api-key KEY
107
- $ sudo unbound setup --clear cursor codex-subscription (no API key needed to clear)
107
+ $ sudo unbound setup --clear cursor codex-subscription (no API key needed; reports the removal when a device key is present)
108
108
 
109
109
  MDM AI TOOLS DISCOVERY
110
110
  --domain defaults to the configured backend URL (set via "unbound config set-backend-url")
@@ -24,6 +24,7 @@
24
24
  const os = require('os');
25
25
  const api = require('./api');
26
26
  const config = require('./config');
27
+ const deviceSerial = require('./device-serial');
27
28
 
28
29
  // The failure report is best-effort telemetry that runs while the user is
29
30
  // already waiting on a real setup failure. Bound it tightly (well under the
@@ -107,8 +108,61 @@ async function reportSetupFailure({ step, exitCode, apiKey, backendUrl } = {}) {
107
108
  }
108
109
  }
109
110
 
111
+ const REMOVAL_TIMEOUT_MS = 5000;
112
+ const REMOVAL_DEADLINE_MS = 8000;
113
+
114
+ function localUser() {
115
+ try {
116
+ return String(process.env.SUDO_USER || os.userInfo().username).slice(0, 100);
117
+ } catch {
118
+ return '';
119
+ }
120
+ }
121
+
122
+ async function sendRemovals({ toolTypes, removalId, command, managed, backendUrl }, signal) {
123
+ const key = config.getDeviceKey();
124
+ if (!key) return;
125
+ const serial = await deviceSerial.getDeviceSerial();
126
+ if (!serial) return;
127
+ const fields = {
128
+ serial_number: serial,
129
+ managed: Boolean(managed),
130
+ initiated_by: 'user',
131
+ source: 'unbound_cli',
132
+ command,
133
+ local_user: localUser(),
134
+ removal_id: removalId,
135
+ cleared_at: new Date().toISOString(),
136
+ };
137
+ await Promise.allSettled(toolTypes.map((toolType) => api.post('/api/v1/setup/removed/', {
138
+ apiKey: key,
139
+ baseUrl: backendUrl,
140
+ timeoutMs: REMOVAL_TIMEOUT_MS,
141
+ signal,
142
+ body: { tool_type: toolType, ...fields },
143
+ })));
144
+ }
145
+
146
+ // Best-effort POST /api/v1/setup/removed/ per tool, in parallel; never rejects, so it can't change the clear's exit code.
147
+ async function reportRemovals(args = {}) {
148
+ let timer;
149
+ const controller = new AbortController();
150
+ // A response that stalls after its headers never settles api.post, so the whole report has a hard deadline.
151
+ const deadline = new Promise((resolve) => { timer = setTimeout(resolve, REMOVAL_DEADLINE_MS); });
152
+ try {
153
+ await Promise.race([sendRemovals(args, controller.signal), deadline]);
154
+ } catch {
155
+ // Same rule as reportSetupFailure: reporting never surfaces over the clear.
156
+ } finally {
157
+ clearTimeout(timer);
158
+ // Destroys any request still open, so a dripping server can't hold the process after nuke.
159
+ controller.abort();
160
+ }
161
+ }
162
+
110
163
  module.exports = {
111
164
  reportSetupFailure,
165
+ reportRemovals,
112
166
  deviceIdentifier,
113
167
  exitCodeForError,
114
168
  EXIT_THROWN,
package/src/toolHealth.js CHANGED
@@ -169,7 +169,7 @@ function keyHelperCheck(label, file, kind = 'structural') {
169
169
  }
170
170
  const ok = body.includes(UNBOUND_KEY_HELPER_TOKEN);
171
171
  return {
172
- name: label, ok, kind,
172
+ name: label, ok, kind, foreign: !ok,
173
173
  detail: ok ? file : `present but not written by Unbound (${file})`,
174
174
  summary: ok ? `${label.toLowerCase()} missing` : `${label.toLowerCase()} not ours`,
175
175
  };
@@ -218,14 +218,15 @@ function configDeviceToken() {
218
218
  // Env wins when present so a stale exported key is still validated; setup keeps the token in ~/.unbound/config.json and removes the env var.
219
219
  function deviceTokenCheck(legacyName) {
220
220
  const check = envKeyCheck('API key env', 'UNBOUND_DEVICE_TOKEN');
221
- if (check.ok) return check;
221
+ // deviceWide: login state shared by every mode, so it doesn't show which mode is installed.
222
+ if (check.ok) return { ...check, deviceWide: true };
222
223
  const legacy = envKeyCheck('API key env', legacyName);
223
224
  if (legacy.ok) return legacy;
224
225
  const value = configDeviceToken();
225
226
  if (!value) return check;
226
227
  return {
227
228
  name: 'API key env', ok: true, kind: 'aux', detail: 'device token set (config.json)', summary: 'API key set',
228
- keyCheck: true, envName: 'device token', value, candidates: [value],
229
+ keyCheck: true, envName: 'device token', value, candidates: [value], deviceWide: true,
229
230
  };
230
231
  }
231
232
 
@@ -349,6 +350,11 @@ function refsUnbound(obj) {
349
350
  // equality-checked (WEB-4949) — per-tool keys can legitimately differ from
350
351
  // the stored login key. Use `validateToolKeys` post-detection to verify each
351
352
  // captured key against the gateway.
353
+ // Root-level openai_base_url, as Codex reads it (a comment or a key in a table doesn't count).
354
+ function codexBaseUrl() {
355
+ try { return TOML.parse((readText('~/.codex/config.toml') || '').replace(/^\uFEFF/, '')).openai_base_url; } catch { return undefined; }
356
+ }
357
+
352
358
  function buildVariants(gatewayUrl, binaryPath) {
353
359
  const gw = (gatewayUrl || GATEWAY_DEFAULT).replace(/\/+$/, ''); // setup rstrips too
354
360
  return [
@@ -388,13 +394,14 @@ function buildVariants(gatewayUrl, binaryPath) {
388
394
  // winning when both are set. Both live under [features], so a hooks key in any
389
395
  // other table isn't this flag; an unparseable config (which Codex couldn't load
390
396
  // either) reads as not enabled.
391
- configCheck('Hooks feature flag', '~/.codex/config.toml', { json: false, test: (t) => {
397
+ // configOnly: a config line like the hooks entry, so on its own it doesn't show the mode is installed.
398
+ { ...configCheck('Hooks feature flag', '~/.codex/config.toml', { json: false, test: (t) => {
392
399
  let cfg;
393
400
  try { cfg = TOML.parse(t.replace(/^\uFEFF/, '')); } catch { return false; } // tolerate a UTF-8 BOM, like readJson
394
401
  const features = cfg.features;
395
402
  if (!features || typeof features !== 'object') return false;
396
403
  return features.hooks === undefined ? features.codex_hooks === true : features.hooks === true;
397
- } }, { short: 'codex hooks not enabled', kind: 'aux' }), // aux: an org install leaves it set with no user hook
404
+ } }, { short: 'codex hooks not enabled', kind: 'aux' }), configOnly: true }, // aux: an org install leaves it set with no user hook
398
405
  scriptCheck('Hook script', '~/.codex/hooks/unbound.py'),
399
406
  deviceTokenCheck('UNBOUND_CODEX_API_KEY'),
400
407
  ],
@@ -402,7 +409,8 @@ function buildVariants(gatewayUrl, binaryPath) {
402
409
  {
403
410
  key: 'codex-gateway', label: 'Codex (gateway)', family: 'codex', mode: 'gateway',
404
411
  checks: () => [
405
- configCheck('Config', '~/.codex/config.toml', { json: false, test: (t) => /openai_base_url\s*=/.test(t) }),
412
+ // foreign: a base url that isn't our gateway is the user's own endpoint, never a leftover to fix.
413
+ { ...configCheck('Config', '~/.codex/config.toml', { json: false, test: (t) => /openai_base_url\s*=/.test(t) }), foreign: codexBaseUrl() !== `${gw}/v1` },
406
414
  envKeyCheck('API key env', 'OPENAI_API_KEY'),
407
415
  ],
408
416
  },
@@ -511,7 +519,15 @@ function detectTools({ gatewayUrl, _mdmDirs, _binaryPath, _codexManagedOnly } =
511
519
  if (present.length) {
512
520
  // Prefer a tampered variant so a conflicting/partial install surfaces (and
513
521
  // `--fix` reinstalls it). Flag when more than one mode is present at once.
514
- const active = present.find((x) => x.status === 'tampered') || present[0];
522
+ // A healthy mode beside config-only leftovers is the real install: report it so `--fix` reinstalls it.
523
+ const leftover = (x) => x.status === 'tampered' && x.checks.every((c, i) => c.deviceWide || c.configOnly || (i === 0 ? c.ok : !c.ok && !c.warn));
524
+ const healthy = present.filter((x) => x.status === 'healthy');
525
+ const keep = present.length > 1 && healthy.length === 1 && !healthy[0].checks.some((c) => c.foreign)
526
+ && present.every((x) => x === healthy[0] || leftover(x));
527
+ // Setup keeps a key helper it didn't write, so a leftover holding one leaves nothing to fix.
528
+ const fixable = !present.some((x) => x.checks.some((c) => c.foreign));
529
+ const active = keep ? Object.assign(healthy[0], { status: fixable ? 'tampered' : 'healthy' })
530
+ : present.find((x) => x.status === 'tampered') || present[0];
515
531
  if (present.length > 1) active.conflict = true;
516
532
  active.label = active.label.replace(/ \(.*\)$/, ''); // mode is shown via .mode
517
533
  families.push(active);