@brunobracaioli/aibrain 0.4.0-beta.28 → 0.4.0-beta.30

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
@@ -238,7 +238,9 @@ connection. Its failure or timeout closes only that auxiliary connection.
238
238
  ```sh
239
239
  # Install the published beta:
240
240
  npm install -g @aisac/cli@beta
241
- aisac setup # configures the clients on PATH; --client claude|codex|both to choose
241
+ aisac setup # browser sign-in, then configures clients on PATH
242
+ aisac setup --login # replace the AI Brain login without changing setup choices
243
+ aisac setup --paste-token # choose the manual masked-token alternative
242
244
  aisac doctor --json
243
245
  aisac claude
244
246
  aisac codex
@@ -249,9 +251,14 @@ then run `npm uninstall -g @brunobracaioli/aibrain` before
249
251
  `npm install -g @aisac/cli@beta`. Setup, notes and checkpoints are kept.
250
252
 
251
253
  Installation does not contact AI Brain, change native client configuration, or
252
- enable all paid accounts. Setup requires an existing AI Brain PAT, explicit
253
- versioned disclosure, and successful provider-free pilot access. Claude and
254
- Codex continue to own their own authentication. Windows native is unsupported;
254
+ enable all paid accounts. At a terminal, `aisac setup` starts a browser sign-in:
255
+ enter the purchase email, compare the short code, and approve the request. The
256
+ token stays out of the clipboard. Browser opening is best effort; copy the printed
257
+ address when no browser opens. Use `--paste-token` for the manual masked prompt,
258
+ or `--token-file` for reviewed noninteractive automation. `aisac setup --login`
259
+ replaces only the AI Brain credential in an existing setup. Setup still requires
260
+ explicit versioned disclosure and successful provider-free pilot access. Claude
261
+ and Codex continue to own their own authentication. Windows native is unsupported;
255
262
  run the beta inside WSL. On macOS, Codex capture locks with the system
256
263
  `/usr/bin/perl` (`flock(2)`) and identifies the lock owner with `sysctl` and
257
264
  `ps`, so nothing extra needs installing. Pricing and general customer
@@ -16,7 +16,7 @@ export const MAX_LOG_FILES = 3;
16
16
  const LOCK_WAIT_MS = 250;
17
17
  const LOCK_STALE_MS = 30_000;
18
18
  const ADMISSION_MS = 60 * 60 * 1000;
19
- export const ADAPTER_VERSION = '0.4.0-beta.28';
19
+ export const ADAPTER_VERSION = '0.4.0-beta.30';
20
20
  const MAX_DIAGNOSTIC_COUNT = 10_000_000;
21
21
  const MAX_DIAGNOSTIC_BYTES = 128 * 1024 * 1024;
22
22
  const CHECKPOINT_BACKENDS = new Set(['native_store', 'private_file']);
package/dist/cli.mjs CHANGED
@@ -2,6 +2,8 @@
2
2
  import { dirname } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { stdin, stdout } from 'node:process';
5
+ import { deviceLogin, isLoginNotStarted, openVerificationPage } from './device-login.mjs';
6
+ import { configAfterDeviceLogin } from './setup-login-state.mjs';
5
7
  import { createInterface } from 'node:readline/promises';
6
8
  import {
7
9
  DISCLOSURE_VERSION,
@@ -25,7 +27,13 @@ import { launchClaude, launchCodex } from './launch.mjs';
25
27
  import { claudeCompatibilityError, resolveClaudeCompatibility } from './claude-compatibility.mjs';
26
28
  import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
27
29
  import { providerFreeProbe } from './mcp.mjs';
28
- import { setupFailureHint, tokenFailureGuide, tokenPromptGuide } from './token-guide.mjs';
30
+ import {
31
+ deviceLoginConnectedLine,
32
+ deviceLoginFallbackLine,
33
+ setupFailureHint,
34
+ tokenFailureGuide,
35
+ tokenPromptGuide,
36
+ } from './token-guide.mjs';
29
37
  import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
30
38
  import { readDiagnostics } from './claude-observation.mjs';
31
39
  import { readCodexDiagnostics } from './codex-diagnostics.mjs';
@@ -87,7 +95,7 @@ import {
87
95
  } from './launch-feedback.mjs';
88
96
  import { parseCodexLaunchArgs } from './codex-permissions.mjs';
89
97
 
90
- const VERSION = '0.4.0-beta.28';
98
+ const VERSION = '0.4.0-beta.30';
91
99
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
92
100
  const COMMAND = 'aisac';
93
101
  /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
@@ -98,7 +106,10 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
98
106
 
99
107
  function usage() {
100
108
  console.log(
101
- `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
109
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} setup --login\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
110
+ );
111
+ console.log(
112
+ '`aisac setup` signs in through the browser at a terminal; use `--paste-token` for the manual prompt, `--token-file` for automation, or `aisac setup --login` to replace an existing login.',
102
113
  );
103
114
  console.log(
104
115
  'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
@@ -227,6 +238,94 @@ function setupTokenError(code, locale, endpoint) {
227
238
  return error;
228
239
  }
229
240
 
241
+ /**
242
+ * Run device login while converting Ctrl-C into a clean exit status and stable
243
+ * user-facing errors. Browser opener failures remain silent in the login module.
244
+ * When the browser flow never started (the server has it off, is rate limiting or
245
+ * is unreachable), fall back to the masked token prompt instead of failing setup.
246
+ * @param {string} endpoint
247
+ * @param {'claude' | 'codex' | 'both'} agent
248
+ * @param {'pt-BR' | 'en'} locale
249
+ * @returns {Promise<{ token: string, accountHint: string | null }>}
250
+ */
251
+ async function runDeviceLogin(endpoint, agent, locale) {
252
+ if (!stdin.isTTY || !stdout.isTTY)
253
+ throw setupTokenError('token_file_required_in_noninteractive_mode', locale, endpoint);
254
+ const controller = new AbortController();
255
+ const onInterrupt = () => {
256
+ stdout.write('\n');
257
+ controller.abort();
258
+ };
259
+ process.on('SIGINT', onInterrupt);
260
+ try {
261
+ return await deviceLogin({
262
+ endpoint,
263
+ agent,
264
+ clientVersion: VERSION,
265
+ locale,
266
+ signal: controller.signal,
267
+ openBrowser: async (url, signal) => {
268
+ await openVerificationPage(url, signal === undefined ? {} : { signal });
269
+ },
270
+ writeLine: (line) => stdout.write(`${line}\n`),
271
+ });
272
+ } catch (error) {
273
+ const code = errorMessage(error);
274
+ if (code === 'login_cancelled') {
275
+ const cancelled = new Error('login_cancelled');
276
+ Object.defineProperty(cancelled, 'exitCode', { value: 130 });
277
+ throw cancelled;
278
+ }
279
+ if (!isLoginNotStarted(error)) throw setupTokenError(code, locale, endpoint);
280
+ } finally {
281
+ process.off('SIGINT', onInterrupt);
282
+ }
283
+ stdout.write(`${deviceLoginFallbackLine(locale)}\n\n${tokenPromptGuide(locale, endpoint)}\n\n`);
284
+ return { token: await maskedPrompt(), accountHint: null };
285
+ }
286
+
287
+ /** @param {Awaited<ReturnType<typeof readConfig>>} previous */
288
+ async function replaceSetupToken(previous) {
289
+ const locale = resolvePackLocale(await readStoredLocale(stateRoot()));
290
+ if (previous === null)
291
+ throw setupTokenError('setup_login_requires_existing_setup', locale, ENDPOINT);
292
+ if (!stdin.isTTY || !stdout.isTTY)
293
+ throw setupTokenError('token_file_required_in_noninteractive_mode', locale, previous.endpoint);
294
+ const endpoint = previous.endpoint;
295
+ validateEndpoint(endpoint);
296
+ const { token, accountHint } = await runDeviceLogin(endpoint, previous.clientSelection, locale);
297
+ try {
298
+ if (previous.schemaVersion === 2)
299
+ await providerFreeProbe(
300
+ endpoint,
301
+ token,
302
+ previous.context ?? makePolicy('conservative'),
303
+ previous.clientSelection,
304
+ );
305
+ else await providerFreeProbe(endpoint, token);
306
+ } catch (error) {
307
+ throw setupTokenError(`provider_free_probe_failed:${errorMessage(error)}`, locale, endpoint);
308
+ }
309
+ const tokenSha256 = await tokenDigest(token);
310
+ const current = await readConfig();
311
+ let configWithToken;
312
+ try {
313
+ configWithToken = configAfterDeviceLogin(
314
+ /** @type {Record<string, unknown>} */ (previous),
315
+ /** @type {Record<string, unknown> | null} */ (current),
316
+ token,
317
+ tokenSha256,
318
+ );
319
+ } catch (error) {
320
+ throw setupTokenError(errorMessage(error), locale, endpoint);
321
+ }
322
+ if (!isValidConfig(configWithToken)) throw new Error('config_validation_failed');
323
+ const root = stateRoot();
324
+ await atomicJson(`${root}/config.json`, configWithToken);
325
+ if (accountHint !== null) console.log(deviceLoginConnectedLine(locale, accountHint));
326
+ console.log(`Updated the AI Brain login in ${root}; the rest of the setup was preserved.`);
327
+ }
328
+
230
329
  /** @param {string[]} args @param {string} name */
231
330
  function option(args, name) {
232
331
  const index = args.indexOf(name);
@@ -737,6 +836,8 @@ async function setup(args) {
737
836
  new Set([
738
837
  '--client',
739
838
  '--token-file',
839
+ '--paste-token',
840
+ '--login',
740
841
  '--accept-disclosure',
741
842
  '--endpoint',
742
843
  '--yes',
@@ -770,6 +871,12 @@ async function setup(args) {
770
871
  '--host-codex',
771
872
  ]),
772
873
  );
874
+ if (args.includes('--login')) {
875
+ if (args.length !== 1) throw new Error('setup_login_cannot_have_options');
876
+ return replaceSetupToken(await readConfig());
877
+ }
878
+ if (args.includes('--paste-token') && args.includes('--token-file'))
879
+ throw new Error('setup_token_sources_conflict');
773
880
  if (args.includes('--undo') && args.length !== 1)
774
881
  throw new Error('setup_undo_cannot_have_options');
775
882
  const lang = option(args, '--lang');
@@ -878,13 +985,30 @@ async function setup(args) {
878
985
  throw new Error('disclosure_not_accepted');
879
986
  const root = await ensureStateRoot();
880
987
  const tokenPath = option(args, '--token-file');
881
- if (!tokenPath && stdin.isTTY && stdout.isTTY)
988
+ const pasteToken = args.includes('--paste-token');
989
+ if (!tokenPath && pasteToken && stdin.isTTY && stdout.isTTY)
882
990
  console.log(`\n${tokenPromptGuide(locale, endpoint)}\n`);
883
991
  let token;
992
+ /** @type {string | null} */
993
+ let accountHint = null;
884
994
  try {
885
- token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
995
+ if (tokenPath) token = await readPrivateToken(tokenPath);
996
+ else if (pasteToken) token = await maskedPrompt();
997
+ else {
998
+ const login = await runDeviceLogin(endpoint, clients, locale);
999
+ token = login.token;
1000
+ accountHint = login.accountHint;
1001
+ }
886
1002
  } catch (error) {
887
- throw setupTokenError(errorMessage(error), locale, endpoint);
1003
+ if (errorMessage(error) === 'login_cancelled') {
1004
+ const cancelled = new Error('login_cancelled');
1005
+ Object.defineProperty(cancelled, 'exitCode', { value: 130 });
1006
+ throw cancelled;
1007
+ }
1008
+ const code = errorMessage(error);
1009
+ throw error instanceof Error && 'guide' in error
1010
+ ? error
1011
+ : setupTokenError(code, locale, endpoint);
888
1012
  }
889
1013
  token = token.trim();
890
1014
  if (!token) throw setupTokenError('empty_token', locale, endpoint);
@@ -1006,6 +1130,7 @@ async function setup(args) {
1006
1130
  } catch (error) {
1007
1131
  throw new Error(`state_write_failed:${errorMessage(error)}`);
1008
1132
  }
1133
+ if (accountHint !== null) console.log(deviceLoginConnectedLine(locale, accountHint));
1009
1134
  console.log(
1010
1135
  `Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
1011
1136
  );
@@ -1667,9 +1792,10 @@ main(cliArgs).catch((error) => {
1667
1792
  }),
1668
1793
  );
1669
1794
  } else {
1670
- console.error(`${COMMAND}: ${errorMessage(error)}`);
1795
+ const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1796
+ if (exitCode !== 130) console.error(`${COMMAND}: ${errorMessage(error)}`);
1671
1797
  const guide = /** @type {{ guide?: unknown }} */ (error ?? {}).guide;
1672
- if (typeof guide === 'string') console.error(`\n${guide}`);
1798
+ if (exitCode !== 130 && typeof guide === 'string') console.error(`\n${guide}`);
1673
1799
  }
1674
1800
  // Usage errors exit 2 (init spec FR3, scan spec FR1). `aisac scan` exits 3
1675
1801
  // when it cannot scan as asked (scan spec D6: no scanner, a tool failure, no
@@ -1677,7 +1803,9 @@ main(cliArgs).catch((error) => {
1677
1803
  // else exits 1.
1678
1804
  const exitCode = /** @type {{ exitCode?: unknown }} */ (error ?? {}).exitCode;
1679
1805
  process.exitCode =
1680
- typeof exitCode === 'number' && Number.isInteger(exitCode) && exitCode >= 1 && exitCode <= 3
1806
+ typeof exitCode === 'number' &&
1807
+ Number.isInteger(exitCode) &&
1808
+ ((exitCode >= 1 && exitCode <= 3) || exitCode === 130)
1681
1809
  ? exitCode
1682
1810
  : 1;
1683
1811
  });
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "version": 3,
3
- "native": "0.167.1",
3
+ "native": "0.172.0",
4
4
  "consumed_pagination": {
5
5
  "method": "thread/turns/list",
6
6
  "request_schema": "v2/ThreadTurnsListParams.json",
7
7
  "response_schema": "v2/ThreadTurnsListResponse.json",
8
8
  "request_schema_sha256": "29717980579b77eb4c7cbd1118dd238fcb3e010f3ef5236d74bd4e4f6e02c005",
9
- "response_schema_sha256": "f5962f70e196a7ca5136d489b37e437e2d3ec2f5e9137ccdb967bee1b1d8b648",
10
- "graph_sha256": "d279eb0972737e1867af66d833d23bd0fccc5209618b010a422b44b4616f2c8e",
9
+ "response_schema_sha256": "b5f274ba151d52b1249dfd768f4ac3b322b1019a4fb959ddbd63ce933ba89271",
10
+ "graph_sha256": "384bbb9beb7b79a165ac16acb106c22233490ad4b79463bb9b0675f848327da4",
11
11
  "ordering": "asc",
12
12
  "items_view": "full"
13
13
  },
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "v2/ThreadTurnsListResponse.json": {
20
20
  "methods": null,
21
- "sha256": "f5962f70e196a7ca5136d489b37e437e2d3ec2f5e9137ccdb967bee1b1d8b648"
21
+ "sha256": "b5f274ba151d52b1249dfd768f4ac3b322b1019a4fb959ddbd63ce933ba89271"
22
22
  },
23
23
  "ClientRequest.json": {
24
24
  "methods": [
@@ -39,7 +39,7 @@
39
39
  "config/read",
40
40
  "account/read"
41
41
  ],
42
- "sha256": "774fc331b29586c30b71bcf71c153cfe476ef3e2de142cd6419e2b347fdedeb0"
42
+ "sha256": "56f5c58904db2ee4752e72922eaec41ab40ae6f102eb4e11d5852d08f6a59aa8"
43
43
  },
44
44
  "ClientNotification.json": {
45
45
  "methods": ["initialized"],
@@ -55,11 +55,10 @@
55
55
  "item/tool/call",
56
56
  "account/chatgptAuthTokens/refresh",
57
57
  "attestation/generate",
58
- "currentTime/read",
59
58
  "applyPatchApproval",
60
59
  "execCommandApproval"
61
60
  ],
62
- "sha256": "e9e5653f9dd4f2e103e6a2fd53ff234f6b859a959e47a0cd7f2526b0e96bab7f"
61
+ "sha256": "6e4d6ada8e1364f4629fd3acf6a0b9c8775304e51f2d67e265b6f1fc44b0cd8a"
63
62
  },
64
63
  "ServerNotification.json": {
65
64
  "methods": [
@@ -78,7 +77,7 @@
78
77
  "thread/compacted",
79
78
  "warning"
80
79
  ],
81
- "sha256": "645ee7185608ff0c7020926bde9f692e314c533bb0ed2445273db3d6d952f298"
80
+ "sha256": "acd7e9ad2150f33c6b521361b05e64aa1d2355bec848afe8510e770b7b74e532"
82
81
  },
83
82
  "JSONRPCResponse.json": {
84
83
  "methods": null,
@@ -94,7 +93,7 @@
94
93
  },
95
94
  "v2/ConfigReadResponse.json": {
96
95
  "methods": null,
97
- "sha256": "9fc9bdea31211e362cc7d5d66d0c0213c1dafc0b902e3a981866a88328476ea6"
96
+ "sha256": "a8ad5bc23d47a7c5006da3382dbf4f29f72316c73136c48946bacd738217718d"
98
97
  },
99
98
  "v2/McpServerToolCallResponse.json": {
100
99
  "methods": null,
@@ -106,7 +105,7 @@
106
105
  },
107
106
  "v2/ThreadForkResponse.json": {
108
107
  "methods": null,
109
- "sha256": "e146932d810efb495172cd1e2c041adbd02956c8adc4b0602832ce99d22a9390"
108
+ "sha256": "c1766fd5f6e28101f99a5d30140fd2499edb08bfa1581900331c338889693df3"
110
109
  },
111
110
  "v2/ThreadInjectItemsResponse.json": {
112
111
  "methods": null,
@@ -114,15 +113,15 @@
114
113
  },
115
114
  "v2/ThreadReadResponse.json": {
116
115
  "methods": null,
117
- "sha256": "435ee103c2d1f722f10b0a2665c86365d935853e33019fa3a95b7747f0b4d74a"
116
+ "sha256": "2ec4917d5f7d66484aa36f248b4bbcfb2c1ccbbd8756e0be35fda7ac954ee914"
118
117
  },
119
118
  "v2/ThreadResumeResponse.json": {
120
119
  "methods": null,
121
- "sha256": "ef1e9b714f7a3555bc0d4e30ae40174aaa5c504a3ae103f4c4981201d20549a8"
120
+ "sha256": "a4bb455a1b165b38b8a9e124cb1cf9848d50c68297f38ad47c9e38f1d52e4212"
122
121
  },
123
122
  "v2/ThreadStartResponse.json": {
124
123
  "methods": null,
125
- "sha256": "e146932d810efb495172cd1e2c041adbd02956c8adc4b0602832ce99d22a9390"
124
+ "sha256": "c1766fd5f6e28101f99a5d30140fd2499edb08bfa1581900331c338889693df3"
126
125
  }
127
126
  },
128
127
  "requiredClientFlags": ["app-server", "--listen", "stdio://"],
@@ -0,0 +1,511 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { deviceLoginInstructions } from './token-guide.mjs';
5
+
6
+ const REQUEST_TIMEOUT_MS = 10_000;
7
+ const MAX_RESPONSE_BYTES = 8 * 1024;
8
+ const MAX_DEVICE_LIFETIME_SECONDS = 600;
9
+ const MAX_POLL_INTERVAL_SECONDS = 600;
10
+ const USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/u;
11
+ const DEVICE_CODE = /^braindc_[A-Za-z0-9_-]{43}$/u;
12
+ const ACCESS_TOKEN = /^brain_[A-Za-z0-9_-]{32,256}$/u;
13
+ const ACCOUNT_HINT = /^[^\p{Cc}\p{Cf}\s@*]\*\*\*@[\p{L}\p{M}\p{N}.-]+$/u;
14
+
15
+ /** @typedef {'pt-BR' | 'en'} DeviceLoginLocale */
16
+
17
+ /**
18
+ * @param {string} code
19
+ * @param {number} [exitCode]
20
+ */
21
+ function loginError(code, exitCode) {
22
+ const error = new Error(code);
23
+ if (exitCode !== undefined) Object.defineProperty(error, 'exitCode', { value: exitCode });
24
+ return error;
25
+ }
26
+
27
+ /**
28
+ * A failure before any code was shown: the server has the flow off, is rate
29
+ * limiting, or cannot be reached. No grant exists yet, so the caller may offer
30
+ * the manual token instead.
31
+ * @param {string} code
32
+ */
33
+ function notStartedError(code) {
34
+ const error = loginError(code);
35
+ Object.defineProperty(error, 'loginNotStarted', { value: true });
36
+ return error;
37
+ }
38
+
39
+ /** @param {unknown} error */
40
+ export function isLoginNotStarted(error) {
41
+ return error instanceof Error && 'loginNotStarted' in error && error.loginNotStarted === true;
42
+ }
43
+
44
+ /** @param {AbortSignal | undefined} signal */
45
+ function assertNotAborted(signal) {
46
+ if (signal?.aborted) throw loginError('login_cancelled', 130);
47
+ }
48
+
49
+ /** @param {AbortSignal | undefined} signal */
50
+ function requestSignal(signal) {
51
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
52
+ return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
53
+ }
54
+
55
+ /** @param {number} milliseconds @param {AbortSignal | undefined} signal */
56
+ function wait(milliseconds, signal) {
57
+ assertNotAborted(signal);
58
+ /** @type {Promise<void>} */
59
+ const pending = new Promise((resolve, reject) => {
60
+ const timer = setTimeout(
61
+ () => {
62
+ signal?.removeEventListener('abort', onAbort);
63
+ resolve();
64
+ },
65
+ Math.max(0, milliseconds),
66
+ );
67
+ const onAbort = () => {
68
+ clearTimeout(timer);
69
+ reject(loginError('login_cancelled', 130));
70
+ };
71
+ signal?.addEventListener('abort', onAbort, { once: true });
72
+ });
73
+ return pending;
74
+ }
75
+
76
+ /** @param {string} endpoint */
77
+ function endpointOrigin(endpoint) {
78
+ let url;
79
+ try {
80
+ url = new URL(endpoint);
81
+ } catch {
82
+ throw loginError('login_endpoint_invalid');
83
+ }
84
+ const localHttp =
85
+ url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
86
+ if (
87
+ (url.protocol !== 'https:' && !localHttp) ||
88
+ url.username !== '' ||
89
+ url.password !== '' ||
90
+ url.search !== '' ||
91
+ url.hash !== ''
92
+ )
93
+ throw loginError('login_endpoint_invalid');
94
+ return url.origin;
95
+ }
96
+
97
+ /** @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
98
+ function throwIfAborted(requestSignal, cancelSignal) {
99
+ if (cancelSignal?.aborted) throw loginError('login_cancelled', 130);
100
+ if (requestSignal?.aborted) throw loginError('login_response_unavailable');
101
+ }
102
+
103
+ /** @param {ReadableStreamDefaultReader<Uint8Array>} reader @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
104
+ function readWithSignals(reader, requestSignal, cancelSignal) {
105
+ throwIfAborted(requestSignal, cancelSignal);
106
+ if (requestSignal === undefined && cancelSignal === undefined) return reader.read();
107
+ return new Promise((resolve, reject) => {
108
+ let settled = false;
109
+ const cleanup = () => {
110
+ requestSignal?.removeEventListener('abort', onAbort);
111
+ cancelSignal?.removeEventListener('abort', onAbort);
112
+ };
113
+ const onAbort = () => {
114
+ if (settled) return;
115
+ settled = true;
116
+ cleanup();
117
+ void reader.cancel().catch(() => undefined);
118
+ reject(
119
+ cancelSignal?.aborted
120
+ ? loginError('login_cancelled', 130)
121
+ : loginError('login_response_unavailable'),
122
+ );
123
+ };
124
+ requestSignal?.addEventListener('abort', onAbort, { once: true });
125
+ cancelSignal?.addEventListener('abort', onAbort, { once: true });
126
+ reader.read().then(
127
+ (result) => {
128
+ if (settled) return;
129
+ settled = true;
130
+ cleanup();
131
+ resolve(result);
132
+ },
133
+ (error) => {
134
+ if (settled) return;
135
+ settled = true;
136
+ cleanup();
137
+ reject(error);
138
+ },
139
+ );
140
+ });
141
+ }
142
+
143
+ /** @param {Response} response @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
144
+ async function readJson(response, requestSignal, cancelSignal) {
145
+ const declaredLength = Number(response.headers.get('content-length'));
146
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
147
+ await response.body?.cancel().catch(() => undefined);
148
+ throw loginError('login_response_invalid');
149
+ }
150
+ if (response.body === null) throw loginError('login_response_invalid');
151
+ const reader = response.body.getReader();
152
+ /** @type {Uint8Array[]} */
153
+ const chunks = [];
154
+ let totalBytes = 0;
155
+ try {
156
+ while (true) {
157
+ throwIfAborted(requestSignal, cancelSignal);
158
+ const { done, value } = await readWithSignals(reader, requestSignal, cancelSignal);
159
+ if (done) break;
160
+ totalBytes += value.byteLength;
161
+ if (totalBytes > MAX_RESPONSE_BYTES) {
162
+ await reader.cancel().catch(() => undefined);
163
+ throw loginError('login_response_invalid');
164
+ }
165
+ chunks.push(value);
166
+ }
167
+ } catch (error) {
168
+ await reader.cancel().catch(() => undefined);
169
+ if (cancelSignal?.aborted) throw loginError('login_cancelled', 130);
170
+ if (requestSignal?.aborted) throw loginError('login_response_unavailable');
171
+ if (error instanceof Error && error.message === 'login_response_invalid') throw error;
172
+ throw loginError('login_response_unavailable');
173
+ }
174
+ const bytes = new Uint8Array(totalBytes);
175
+ let offset = 0;
176
+ for (const chunk of chunks) {
177
+ bytes.set(chunk, offset);
178
+ offset += chunk.byteLength;
179
+ }
180
+ let value;
181
+ try {
182
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
183
+ } catch {
184
+ throw loginError('login_response_invalid');
185
+ }
186
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
187
+ throw loginError('login_response_invalid');
188
+ return /** @type {Record<string, unknown>} */ (value);
189
+ }
190
+
191
+ /** @param {string | null} value @param {number} fallbackSeconds */
192
+ function retryAfterSeconds(value, fallbackSeconds) {
193
+ if (value === null) return fallbackSeconds;
194
+ const seconds = Number(value);
195
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds, MAX_POLL_INTERVAL_SECONDS);
196
+ const date = Date.parse(value);
197
+ if (Number.isFinite(date))
198
+ return Math.min(Math.max(0, (date - Date.now()) / 1000), MAX_POLL_INTERVAL_SECONDS);
199
+ return fallbackSeconds;
200
+ }
201
+
202
+ /** @param {Response} response */
203
+ async function discardResponse(response) {
204
+ await response.body?.cancel().catch(() => undefined);
205
+ }
206
+
207
+ /**
208
+ * Run an opener without a shell. Its output and failures are deliberately ignored.
209
+ * @param {string} file
210
+ * @param {string[]} args
211
+ * @param {AbortSignal | undefined} signal
212
+ * @returns {Promise<boolean>} Whether the opener command completed successfully.
213
+ */
214
+ async function runOpener(file, args, signal) {
215
+ assertNotAborted(signal);
216
+ /** @type {import('node:child_process').ChildProcess | undefined} */
217
+ let child;
218
+ try {
219
+ await new Promise((resolve, reject) => {
220
+ child = execFile(
221
+ file,
222
+ args,
223
+ { timeout: 4_000, windowsHide: true, encoding: 'utf8' },
224
+ (error) => (error ? reject(error) : resolve(undefined)),
225
+ );
226
+ const onAbort = () => {
227
+ child?.kill();
228
+ reject(loginError('login_cancelled', 130));
229
+ };
230
+ signal?.addEventListener('abort', onAbort, { once: true });
231
+ child.once('close', () => signal?.removeEventListener('abort', onAbort));
232
+ });
233
+ return true;
234
+ } catch {
235
+ if (signal?.aborted) throw loginError('login_cancelled', 130);
236
+ // Browser opening is best-effort; the terminal always displays the address.
237
+ return false;
238
+ }
239
+ }
240
+
241
+ /** @param {NodeJS.ProcessEnv} env */
242
+ async function isWsl(env) {
243
+ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
244
+ try {
245
+ return /microsoft|wsl/iu.test(await readFile('/proc/version', 'utf8'));
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Open the verification page with fixed arguments and no shell. This function never
253
+ * prints opener errors; the user can use the address shown in the terminal.
254
+ * @param {string} url
255
+ * @param {{ platform?: NodeJS.Platform | undefined, env?: NodeJS.ProcessEnv | undefined, signal?: AbortSignal | undefined, runCommand?: typeof runOpener | undefined }} [options]
256
+ */
257
+ export async function openVerificationPage(url, options = {}) {
258
+ const platform = options.platform ?? process.platform;
259
+ const env = options.env ?? process.env;
260
+ const signal = options.signal;
261
+ const runCommand = options.runCommand ?? runOpener;
262
+ if (platform === 'darwin') return runCommand('open', [url], signal);
263
+ if (platform !== 'linux') return;
264
+ if (await isWsl(env)) {
265
+ if (await runCommand('wslview', [url], signal)) return;
266
+ if (!safeWindowsOpenUrl(url)) return;
267
+ return runCommand('cmd.exe', ['/c', 'start', '', url], signal);
268
+ }
269
+ return runCommand('xdg-open', [url], signal);
270
+ }
271
+
272
+ /**
273
+ * `cmd.exe /c start` parses a command string even though Node invokes cmd.exe via
274
+ * `execFile`. Permit only the locally constructed verification URL grammar.
275
+ * @param {string} value
276
+ */
277
+ function safeWindowsOpenUrl(value) {
278
+ try {
279
+ const url = new URL(value);
280
+ const hostname = url.hostname;
281
+ const dnsName = hostname
282
+ .split('.')
283
+ .every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(label));
284
+ const ipv4 = /^(?:\d{1,3}\.){3}\d{1,3}$/u.test(hostname);
285
+ const ipv6Loopback = hostname === '[::1]';
286
+ const loopback = hostname === 'localhost' || hostname === '127.0.0.1' || ipv6Loopback;
287
+ const portValid =
288
+ url.port === '' || (/^\d{1,5}$/u.test(url.port) && Number(url.port) <= 65_535);
289
+ return (
290
+ (url.protocol === 'https:' || (url.protocol === 'http:' && loopback)) &&
291
+ url.username === '' &&
292
+ url.password === '' &&
293
+ url.pathname === '/device' &&
294
+ url.search === '' &&
295
+ url.hash === '' &&
296
+ portValid &&
297
+ (dnsName || ipv4 || ipv6Loopback) &&
298
+ value === url.href
299
+ );
300
+ } catch {
301
+ return false;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * @param {{
307
+ * endpoint: string,
308
+ * clientVersion: string,
309
+ * agent: 'claude' | 'codex' | 'both',
310
+ * locale: DeviceLoginLocale,
311
+ * fetchImpl?: typeof fetch,
312
+ * openBrowser?: (url: string, signal?: AbortSignal) => Promise<void>,
313
+ * writeLine?: (line: string) => void,
314
+ * sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>,
315
+ * now?: () => number,
316
+ * signal?: AbortSignal
317
+ * }} options
318
+ * @returns {Promise<{ token: string, accountHint: string }>} The token is returned only to the caller.
319
+ */
320
+ export async function deviceLogin(options) {
321
+ const origin = endpointOrigin(options.endpoint);
322
+ const codeUrl = new URL('/device/code', origin).href;
323
+ const tokenUrl = new URL('/device/token', origin).href;
324
+ const verificationUrl = new URL('/device', origin).href;
325
+ const fetchImpl = options.fetchImpl ?? fetch;
326
+ const openBrowser =
327
+ options.openBrowser ??
328
+ (async (url, signal) => {
329
+ await openVerificationPage(url, signal === undefined ? {} : { signal });
330
+ });
331
+ const writeLine = options.writeLine ?? ((line) => process.stdout.write(`${line}\n`));
332
+ const sleep = options.sleep ?? wait;
333
+ const now = options.now ?? (() => performance.now());
334
+ const startForm = new URLSearchParams({
335
+ client_id: 'aisac-cli',
336
+ client_version: options.clientVersion,
337
+ agent: options.agent,
338
+ });
339
+ assertNotAborted(options.signal);
340
+
341
+ let startResponse;
342
+ const startSignal = requestSignal(options.signal);
343
+ try {
344
+ startResponse = await fetchImpl(codeUrl, {
345
+ method: 'POST',
346
+ redirect: 'error',
347
+ cache: 'no-store',
348
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
349
+ body: startForm,
350
+ signal: startSignal,
351
+ });
352
+ } catch {
353
+ assertNotAborted(options.signal);
354
+ throw notStartedError('login_unavailable');
355
+ }
356
+ if (startResponse.status !== 200) {
357
+ await discardResponse(startResponse);
358
+ if (startResponse.status === 429) throw notStartedError('login_rate_limited');
359
+ if (startResponse.status >= 500) throw notStartedError('login_unavailable');
360
+ throw notStartedError('login_request_rejected');
361
+ }
362
+ let start;
363
+ try {
364
+ start = await readJson(startResponse, startSignal, options.signal);
365
+ } catch (error) {
366
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
367
+ if (error instanceof Error && error.message === 'login_response_unavailable')
368
+ throw notStartedError('login_unavailable');
369
+ throw error;
370
+ }
371
+ const deviceCode = start.device_code;
372
+ const userCode = start.user_code;
373
+ const expiresIn = start.expires_in;
374
+ const interval = start.interval;
375
+ if (
376
+ typeof deviceCode !== 'string' ||
377
+ !DEVICE_CODE.test(deviceCode) ||
378
+ typeof userCode !== 'string' ||
379
+ !USER_CODE.test(userCode) ||
380
+ typeof expiresIn !== 'number' ||
381
+ !Number.isSafeInteger(expiresIn) ||
382
+ expiresIn < 1 ||
383
+ expiresIn > MAX_DEVICE_LIFETIME_SECONDS ||
384
+ typeof interval !== 'number' ||
385
+ !Number.isSafeInteger(interval) ||
386
+ interval < 1 ||
387
+ interval > MAX_POLL_INTERVAL_SECONDS ||
388
+ typeof start.verification_uri !== 'string'
389
+ )
390
+ throw loginError('login_response_invalid');
391
+
392
+ let returnedVerification;
393
+ try {
394
+ returnedVerification = new URL(start.verification_uri);
395
+ } catch {
396
+ throw loginError('login_response_invalid');
397
+ }
398
+ if (returnedVerification.origin !== origin) throw loginError('login_origin_mismatch');
399
+
400
+ const deadline = now() + expiresIn * 1000;
401
+ writeLine(deviceLoginInstructions(options.locale, verificationUrl, userCode));
402
+ assertNotAborted(options.signal);
403
+ try {
404
+ await openBrowser(verificationUrl, options.signal);
405
+ } catch {
406
+ assertNotAborted(options.signal);
407
+ // The displayed address is the fallback when no browser can be opened.
408
+ }
409
+
410
+ let pollIntervalSeconds = interval;
411
+ const pollForm = () =>
412
+ new URLSearchParams({
413
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
414
+ device_code: deviceCode,
415
+ client_id: 'aisac-cli',
416
+ });
417
+
418
+ while (now() < deadline) {
419
+ assertNotAborted(options.signal);
420
+ const remaining = deadline - now();
421
+ await sleep(Math.min(pollIntervalSeconds * 1000, remaining), options.signal);
422
+ assertNotAborted(options.signal);
423
+ if (now() >= deadline) break;
424
+ let response;
425
+ const pollSignal = requestSignal(options.signal);
426
+ try {
427
+ response = await fetchImpl(tokenUrl, {
428
+ method: 'POST',
429
+ redirect: 'error',
430
+ cache: 'no-store',
431
+ headers: {
432
+ 'Content-Type': 'application/x-www-form-urlencoded',
433
+ Accept: 'application/json',
434
+ },
435
+ body: pollForm(),
436
+ signal: pollSignal,
437
+ });
438
+ } catch {
439
+ assertNotAborted(options.signal);
440
+ continue;
441
+ }
442
+ if (response.status >= 500) {
443
+ await discardResponse(response);
444
+ continue;
445
+ }
446
+ if (response.status === 429) {
447
+ await discardResponse(response);
448
+ pollIntervalSeconds = Math.max(
449
+ pollIntervalSeconds,
450
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds),
451
+ );
452
+ continue;
453
+ }
454
+ if (response.status === 200) {
455
+ let result;
456
+ try {
457
+ result = await readJson(response, pollSignal, options.signal);
458
+ } catch (error) {
459
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
460
+ if (error instanceof Error && error.message === 'login_response_unavailable') continue;
461
+ throw error;
462
+ }
463
+ if (
464
+ result.token_type !== 'Bearer' ||
465
+ typeof result.access_token !== 'string' ||
466
+ !ACCESS_TOKEN.test(result.access_token) ||
467
+ typeof result.account_hint !== 'string' ||
468
+ result.account_hint.length > 258 ||
469
+ !ACCOUNT_HINT.test(result.account_hint)
470
+ )
471
+ throw loginError('login_response_invalid');
472
+ return { token: result.access_token, accountHint: result.account_hint };
473
+ }
474
+ if (response.status !== 400) {
475
+ await discardResponse(response);
476
+ throw loginError('login_response_invalid');
477
+ }
478
+
479
+ let result;
480
+ try {
481
+ result = await readJson(response, pollSignal, options.signal);
482
+ } catch (error) {
483
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
484
+ if (error instanceof Error && error.message === 'login_response_unavailable') continue;
485
+ throw error;
486
+ }
487
+ if (typeof result.error !== 'string') throw loginError('login_response_invalid');
488
+ if (result.error === 'authorization_pending') {
489
+ pollIntervalSeconds = Math.max(
490
+ pollIntervalSeconds,
491
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds),
492
+ );
493
+ continue;
494
+ }
495
+ if (result.error === 'slow_down') {
496
+ pollIntervalSeconds = Math.min(
497
+ MAX_POLL_INTERVAL_SECONDS,
498
+ Math.max(
499
+ pollIntervalSeconds + 5,
500
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds + 5),
501
+ ),
502
+ );
503
+ continue;
504
+ }
505
+ if (result.error === 'access_denied') throw loginError('login_denied');
506
+ if (result.error === 'expired_token') throw loginError('login_expired');
507
+ if (result.error === 'invalid_grant') throw loginError('login_invalid_grant');
508
+ throw loginError('login_response_invalid');
509
+ }
510
+ throw loginError('login_expired');
511
+ }
@@ -74,7 +74,7 @@ export const MIN_WORKER_CODEX_VERSION = '0.166.0';
74
74
  * The Codex releases the role's host gate ran on (docs/reference/codex-manager-gate.md).
75
75
  * Doctor shows them; they do not decide who gets the role.
76
76
  */
77
- export const MEASURED_WORKER_CODEX_VERSIONS = Object.freeze(['0.166.0', '0.167.1']);
77
+ export const MEASURED_WORKER_CODEX_VERSIONS = Object.freeze(['0.166.0', '0.167.1', '0.172.0']);
78
78
  /** The first Codex release measured for the manager host (MG11). */
79
79
  export const MIN_MANAGER_CODEX_VERSION = '0.166.0';
80
80
  /** First Claude Code release measured with MG13 delivery and replies. */
package/dist/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@brunobracaioli/aibrain",
3
- "version": "0.4.0-beta.28",
3
+ "version": "0.4.0-beta.30",
4
4
  "type": "module"
5
5
  }
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "kind": "aisac-release-manifest",
3
3
  "schema_version": 1,
4
- "sequence": 6,
5
- "issued_at": "2026-11-17T21:50:00Z",
6
- "expires_at": "2026-12-17T21:50:00Z",
4
+ "sequence": 8,
5
+ "issued_at": "2026-12-01T13:21:00Z",
6
+ "expires_at": "2026-12-31T13:21:00Z",
7
7
  "key_id": "94f9ccf331e4f7f3",
8
8
  "features": {
9
9
  "self_update": true,
@@ -20,10 +20,10 @@
20
20
  "minimum_version": "0.4.0-beta.18",
21
21
  "channels": {
22
22
  "beta": {
23
- "version": "0.4.0-beta.25",
23
+ "version": "0.4.0-beta.28",
24
24
  "integrity": {
25
- "@aisac/cli": "sha512-gayPm+NtADbWlLtaNmJYyGUYk5LypyM30iEaEdSTKrdh+G7GHD/tPemvEHwrkSMfdX9oluGiyddJbGH/v7HivQ==",
26
- "@brunobracaioli/aibrain": "sha512-JYWUyPT5D0c4b25RUMK8ZbLLn6DfmRWZWUHcajIlcUKWXkypsYMG5S/ExNfuHnOnauXhRyR/QEXaK9DdXSoRpw=="
25
+ "@aisac/cli": "sha512-XiaSAXGRFqxIgw3YLUItwTbt3+rTSgP/0siz82RJZtwvH20wnKGn7qGlBGpGTjZDJ7VMUdf3gTulntOC2aEKNg==",
26
+ "@brunobracaioli/aibrain": "sha512-5Eu1qxShLlXAB8akYD+tVobFTJQ3pBAtDVtvXYNc2VeWup1fl5xVl9JXnQDT7V11iacc66JJ+8jmh/WcWAYYKw=="
27
27
  }
28
28
  }
29
29
  }
@@ -43,11 +43,15 @@
43
43
  "2.1.303",
44
44
  "2.1.311",
45
45
  "2.1.322",
46
- "2.1.323"
46
+ "2.1.323",
47
+ "2.1.330",
48
+ "2.1.333"
47
49
  ],
48
50
  "minimum_client": {
49
51
  "2.1.323": "0.4.0-beta.18",
50
- "2.1.322": "0.4.0-beta.17"
52
+ "2.1.322": "0.4.0-beta.17",
53
+ "2.1.330": "0.4.0-beta.29",
54
+ "2.1.333": "0.4.0-beta.29"
51
55
  },
52
56
  "versions": {
53
57
  "2.1.323": {
@@ -184,11 +188,13 @@
184
188
  "0.163.0",
185
189
  "0.164.0",
186
190
  "0.166.0",
187
- "0.167.1"
191
+ "0.167.1",
192
+ "0.172.0"
188
193
  ],
189
194
  "minimum_client": {
190
195
  "0.167.1": "0.4.0-beta.17",
191
- "0.166.0": "0.4.0-beta.9"
196
+ "0.166.0": "0.4.0-beta.9",
197
+ "0.172.0": "0.4.0-beta.29"
192
198
  },
193
199
  "versions": {
194
200
  "0.167.1": {
@@ -324,5 +330,5 @@
324
330
  }
325
331
  }
326
332
  },
327
- "signature": "X3S7kAy2ojleh6ymHMuXEkqf081ZU93FFHh6u4O4cuNlDgYRVqNk78nqOkantlC/wmNwycISo1wPdmDUdGiSCA=="
333
+ "signature": "+vQ+BC4+9IsXib0P/BdmorfWSF5aMEbxCFvRqwB1S9e+KVNi5LC8TuuJXJXwMKUeUW6mgD7fluh7PVrUkMXoAg=="
328
334
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Apply a device-login credential to the most recent setup snapshot. The current
3
+ * snapshot may contain unrelated changes made while the browser was open.
4
+ * @param {Record<string, unknown>} started
5
+ * @param {Record<string, unknown> | null} current
6
+ * @param {string} token
7
+ * @param {string} tokenSha256
8
+ */
9
+ export function configAfterDeviceLogin(started, current, token, tokenSha256) {
10
+ if (
11
+ current === null ||
12
+ current.endpoint !== started.endpoint ||
13
+ current.packageRoot !== started.packageRoot ||
14
+ current.clientSelection !== started.clientSelection ||
15
+ current.tokenSha256 !== started.tokenSha256
16
+ )
17
+ throw new Error('setup_login_setup_changed');
18
+ return { ...current, token, tokenSha256 };
19
+ }
@@ -1,92 +1,132 @@
1
- // Step-by-step guidance for obtaining an AI Brain PAT during `aisac setup`.
2
- // Spec aibrain-subscriber-beta § Setup step 3: guide users to the existing
3
- // dashboard token flow instead of failing with a bare error code. The text
4
- // never contains the token or any account data; the URL is the endpoint origin.
1
+ // Guidance for the browser-first `aisac setup` flow and its manual token alternative.
2
+ // The text never contains a token or other account data; URLs use the endpoint origin.
5
3
 
6
4
  const DEFAULT_DASHBOARD = 'https://mcp.ai-brain.aisac.cloud';
7
5
 
8
6
  /** @typedef {'pt-BR' | 'en'} GuideLocale */
9
7
 
10
- /** Setup failures that mean "you need a (different) token", mapped to a reason key. */
8
+ /** Setup failures mapped to a localized user-facing reason. */
11
9
  const TOKEN_FAILURES = Object.freeze({
12
10
  empty_token: 'empty',
13
11
  token_file_required_in_noninteractive_mode: 'noninteractive',
14
12
  'provider_free_probe_failed:mcp_auth_denied': 'denied',
15
13
  'provider_free_probe_failed:mcp_paid_plan_required': 'unlicensed',
14
+ login_denied: 'loginDenied',
15
+ login_expired: 'loginExpired',
16
+ login_invalid_grant: 'loginInvalidGrant',
17
+ login_rate_limited: 'loginRateLimited',
18
+ login_unavailable: 'loginUnavailable',
19
+ login_origin_mismatch: 'loginOriginMismatch',
20
+ login_response_invalid: 'loginResponseInvalid',
21
+ login_request_rejected: 'loginRequestRejected',
22
+ setup_login_setup_changed: 'loginSetupChanged',
16
23
  });
17
24
 
18
25
  /**
19
- * Setup failures that are not about the token but have one usual cause worth
20
- * naming. `INVALID_INPUT` from the probe is almost always a system clock that
21
- * is ahead of the server (the server rejects `observed_at` more than 30 s in
22
- * the future); WSL2 drifts after a sleep.
26
+ * Setup failures that have one usual cause worth naming. `INVALID_INPUT` from the
27
+ * probe is almost always a system clock that is ahead of the server.
23
28
  */
24
29
  const SETUP_HINTS = Object.freeze({
25
30
  'provider_free_probe_failed:mcp_invalid_input': 'clock',
26
- // `aisac claude|codex` before any setup (spec aisac-host-upgrade-resilience C9).
27
31
  setup_required: 'setup',
32
+ setup_login_requires_existing_setup: 'loginSetup',
28
33
  });
29
34
 
30
35
  const TEXT = Object.freeze({
31
36
  'pt-BR': {
32
- intro: 'O aisac precisa de um token pessoal (PAT) do seu AI Brain.',
33
- missing: 'Não tem um? Gere em um minuto:',
37
+ intro: 'O aisac conecta ao AI Brain pelo navegador e guarda o token localmente.',
38
+ missing: 'Se preferir criar um token manualmente:',
34
39
  mothership:
35
- ' Entrou pelo AISAC Mothership? O link "AI Brain" do chat já abre o painel com a sessão feita; siga do passo 2.',
40
+ ' Entrou pelo AISAC Mothership? O link "AI Brain" do chat já abre o painel com a sessão feita; siga do passo 1.',
36
41
  login: (/** @type {string} */ url) =>
37
42
  ` 1. Abra ${url} e entre com o MESMO e-mail usado na compra\n (chega um código de 6 dígitos). A licença fica vinculada a esse e-mail.`,
38
43
  label:
39
44
  ' 2. No painel, dê um rótulo (ex.: meu-mac) e escolha o agente\n (Anthropic para Claude Code, OpenAI para Codex). Isso só organiza a atribuição.',
40
45
  generate: ' 3. Clique em "Gerar token" e copie na hora: ele aparece uma única vez.',
41
- pasteHere: ' 4. Cole abaixo em "AI Brain PAT". A digitação fica oculta.',
42
- rerun: ' 4. Rode `aisac setup` de novo e cole o token em "AI Brain PAT" (fica oculto).',
46
+ pasteHere: ' 4. Rode `aisac setup --paste-token` e cole no prompt oculto.',
47
+ rerun: ' 4. Rode `aisac setup --paste-token` e cole no prompt oculto.',
43
48
  safety:
44
49
  'Nunca coloque o token em argumento de comando, arquivo do repositório ou perfil do shell.',
45
50
  support: 'Se o e-mail da compra não entrar ou não tiver a licença, fale com o suporte AISAC.',
46
51
  reasons: {
47
52
  empty: 'Nenhum token foi informado.',
48
53
  noninteractive:
49
- 'Sem um terminal interativo, o token precisa vir de `--token-file` (um arquivo privado, modo 600).',
54
+ 'Sem um terminal interativo, use `--token-file` com um arquivo privado (modo 600).',
50
55
  denied:
51
- 'O AI Brain recusou este token: ele está incompleto, foi revogado ou não existe. Gere um novo.',
56
+ 'O AI Brain recusou este token: ele está incompleto, foi revogado ou não existe. Rode `aisac setup` para autorizar outro pelo navegador.',
52
57
  unlicensed:
53
- 'Este token pertence a uma conta sem a licença. Gere o token entrando com o e-mail usado na compra.',
58
+ 'Esta conta não tem a licença. Rode `aisac setup` e entre com o e-mail usado na compra.',
59
+ loginDenied: 'A autorização foi recusada. Rode `aisac setup` para tentar novamente.',
60
+ loginExpired: 'O código expirou. Rode `aisac setup` para gerar outro.',
61
+ loginInvalidGrant:
62
+ 'Esta autorização não está mais disponível. Rode `aisac setup` para gerar outro código.',
63
+ loginRateLimited:
64
+ 'Muitas tentativas foram iniciadas. Aguarde alguns minutos e rode `aisac setup` novamente.',
65
+ loginUnavailable:
66
+ 'Não foi possível iniciar a conexão com o AI Brain. Confira a rede e rode `aisac setup` novamente.',
67
+ loginOriginMismatch:
68
+ 'O endereço de autorização não corresponde ao servidor configurado. Confira `--endpoint` e tente novamente.',
69
+ loginResponseInvalid:
70
+ 'O servidor retornou uma resposta de autorização inválida. Rode `aisac setup` novamente.',
71
+ loginRequestRejected:
72
+ 'O servidor recusou o início da autorização. Confira o endpoint e tente novamente.',
73
+ loginSetupChanged:
74
+ 'A configuração mudou enquanto o navegador estava aberto. Rode `aisac setup --login` novamente para proteger as alterações mais recentes.',
54
75
  },
55
76
  hints: {
56
77
  clock:
57
78
  'O AI Brain recusou a sondagem como entrada inválida (INVALID_INPUT). Causa mais comum: o relógio do sistema está adiantado em relação ao servidor; no WSL2 isso acontece depois de suspender o computador. Acerte o relógio (ex.: `sudo hwclock -s` ou reinicie o WSL) e rode `aisac setup` de novo. O token não precisa mudar.',
58
79
  setup:
59
80
  'O aisac ainda não está configurado neste computador. Execute `aisac setup` e depois rode este comando de novo.',
81
+ loginSetup:
82
+ 'Este computador ainda não tem uma configuração do aisac. Rode `aisac setup` primeiro.',
60
83
  },
61
84
  },
62
85
  en: {
63
- intro: 'aisac needs a personal access token (PAT) from your AI Brain.',
64
- missing: "Don't have one? Create it in a minute:",
86
+ intro: 'aisac connects to AI Brain in your browser and stores the token locally.',
87
+ missing: 'To create a token manually instead:',
65
88
  mothership:
66
- ' Signed up through the AISAC Mothership? The "AI Brain" link in the chat opens the dashboard already signed in; continue from step 2.',
89
+ ' Signed up through the AISAC Mothership? The "AI Brain" link in the chat opens the dashboard already signed in; continue from step 1.',
67
90
  login: (/** @type {string} */ url) =>
68
91
  ` 1. Open ${url} and sign in with the SAME email you used to buy\n (a 6-digit code arrives by email). The license is tied to that email.`,
69
92
  label:
70
93
  ' 2. In the dashboard, enter a label (e.g. my-mac) and pick the agent\n (Anthropic for Claude Code, OpenAI for Codex). It only organizes attribution.',
71
94
  generate: ' 3. Click "Gerar token" and copy it right away: it is shown only once.',
72
- pasteHere: ' 4. Paste it below at "AI Brain PAT". Typing stays hidden.',
73
- rerun: ' 4. Run `aisac setup` again and paste the token at "AI Brain PAT" (hidden).',
95
+ pasteHere: ' 4. Run `aisac setup --paste-token` and paste it at the hidden prompt.',
96
+ rerun: ' 4. Run `aisac setup --paste-token` and paste it at the hidden prompt.',
74
97
  safety: 'Never put the token in command arguments, a repository file or a shell profile.',
75
98
  support: 'If the purchase email cannot sign in or has no license, contact AISAC support.',
76
99
  reasons: {
77
100
  empty: 'No token was entered.',
78
101
  noninteractive:
79
- 'Without an interactive terminal the token must come from `--token-file` (a private file, mode 600).',
102
+ 'Without an interactive terminal, use `--token-file` with a private file (mode 600).',
80
103
  denied:
81
- 'AI Brain rejected this token: it is incomplete, revoked or unknown. Create a new one.',
104
+ 'AI Brain rejected this token: it is incomplete, revoked or unknown. Run `aisac setup` to authorize a new one in your browser.',
82
105
  unlicensed:
83
- 'This token belongs to an account without the license. Create the token signed in with the purchase email.',
106
+ 'This account does not have the license. Run `aisac setup` and sign in with your purchase email.',
107
+ loginDenied: 'Authorization was denied. Run `aisac setup` to try again.',
108
+ loginExpired: 'The code expired. Run `aisac setup` to generate a new one.',
109
+ loginInvalidGrant:
110
+ 'This authorization is no longer available. Run `aisac setup` to generate a new code.',
111
+ loginRateLimited:
112
+ 'Too many login attempts were started. Wait a few minutes, then run `aisac setup` again.',
113
+ loginUnavailable:
114
+ 'Could not start the AI Brain connection. Check your network and run `aisac setup` again.',
115
+ loginOriginMismatch:
116
+ 'The authorization address does not match the configured server. Check `--endpoint` and try again.',
117
+ loginResponseInvalid:
118
+ 'The server returned an invalid authorization response. Run `aisac setup` again.',
119
+ loginRequestRejected:
120
+ 'The server rejected the authorization request. Check the endpoint and try again.',
121
+ loginSetupChanged:
122
+ 'The setup changed while the browser was open. Run `aisac setup --login` again to preserve the latest changes.',
84
123
  },
85
124
  hints: {
86
125
  clock:
87
126
  'AI Brain rejected the probe as invalid input (INVALID_INPUT). Most common cause: the system clock is ahead of the server; on WSL2 this happens after the computer sleeps. Fix the clock (e.g. `sudo hwclock -s` or restart WSL) and run `aisac setup` again. The token does not need to change.',
88
127
  setup:
89
128
  'aisac is not set up on this computer yet. Run `aisac setup`, then run this command again.',
129
+ loginSetup: 'aisac is not set up on this computer yet. Run `aisac setup` first.',
90
130
  },
91
131
  },
92
132
  });
@@ -121,20 +161,38 @@ export function tokenPromptGuide(locale, endpoint) {
121
161
  return steps(locale, endpoint, 'prompt');
122
162
  }
123
163
 
164
+ /** @param {GuideLocale} locale @param {string} verificationUrl @param {string} userCode */
165
+ export function deviceLoginInstructions(locale, verificationUrl, userCode) {
166
+ return locale === 'pt-BR'
167
+ ? `Entrar no AI Brain pelo navegador\n 1. Abra ${verificationUrl} (o navegador deve abrir sozinho)\n 2. Entre com o e-mail da compra e confira o código ${userCode}\nAguardando a autorização… (Ctrl-C cancela; --paste-token cola um token)`
168
+ : `Sign in to AI Brain in your browser\n 1. Open ${verificationUrl} (the browser should open automatically)\n 2. Sign in with your purchase email and check the code ${userCode}\nWaiting for authorization… (Ctrl-C cancels; --paste-token pastes a token)`;
169
+ }
170
+
124
171
  /**
125
- * One-paragraph hint for a setup failure with a usual non-token cause, or null.
126
- * @param {string} code @param {GuideLocale} locale
172
+ * The line printed when the browser sign-in could not start and setup falls
173
+ * back to the manual token prompt.
174
+ * @param {GuideLocale} locale
127
175
  */
176
+ export function deviceLoginFallbackLine(locale) {
177
+ return locale === 'pt-BR'
178
+ ? 'aisac: o login pelo navegador não está disponível agora; siga com um token criado no painel.'
179
+ : 'aisac: browser sign-in is not available right now; continue with a token created in the panel.';
180
+ }
181
+
182
+ /** @param {GuideLocale} locale @param {string} accountHint */
183
+ export function deviceLoginConnectedLine(locale, accountHint) {
184
+ return locale === 'pt-BR'
185
+ ? `aisac: conectado como ${accountHint}`
186
+ : `aisac: connected as ${accountHint}`;
187
+ }
188
+
189
+ /** One-paragraph hint for a setup failure with a usual cause, or null. @param {string} code @param {GuideLocale} locale */
128
190
  export function setupFailureHint(code, locale) {
129
191
  const hint = /** @type {Record<string, keyof typeof TEXT.en.hints>} */ (SETUP_HINTS)[code];
130
192
  return hint === undefined ? null : TEXT[locale].hints[hint];
131
193
  }
132
194
 
133
- /**
134
- * Guidance for a setup failure caused by a missing, rejected or unlicensed token,
135
- * or null when the failure has another cause.
136
- * @param {string} code @param {GuideLocale} locale @param {string} endpoint
137
- */
195
+ /** Guidance for a missing, rejected or unlicensed token, or null for other failures. @param {string} code @param {GuideLocale} locale @param {string} endpoint */
138
196
  export function tokenFailureGuide(code, locale, endpoint) {
139
197
  const reason = /** @type {Record<string, keyof typeof TEXT.en.reasons>} */ (TOKEN_FAILURES)[code];
140
198
  if (reason === undefined) return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brunobracaioli/aibrain",
3
- "version": "0.4.0-beta.28",
3
+ "version": "0.4.0-beta.30",
4
4
  "private": false,
5
5
  "description": "AISAC client for Claude Code and Codex: AI Brain memory, context management and AISAC Engineering",
6
6
  "license": "UNLICENSED",
@@ -16,7 +16,7 @@
16
16
  "node": ">=22"
17
17
  },
18
18
  "dependencies": {
19
- "ws": "8.22.0"
19
+ "ws": "8.23.0"
20
20
  },
21
21
  "scripts": {
22
22
  "build": "node build.mjs",