@stevezhou/sisu 0.2.2 → 0.3.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/NOTICE CHANGED
@@ -5,8 +5,9 @@ This product includes grok-build first-party source (Apache-2.0)
5
5
  from https://github.com/xai-org/grok-build, Copyright 2023-2026 SpaceXAI.
6
6
 
7
7
  The grok-build tree lives at vendor/grok-build/ together with its
8
- LICENSE and THIRD-PARTY-NOTICES. SiSu二次开发 replaces xAI login,
8
+ LICENSE and THIRD-PARTY-NOTICES. The npm package ships the same
9
+ attribution from third_party/grok-build/. SiSu二次开发 replaces xAI login,
9
10
  telemetry defaults, branding, and the model/quota endpoint so the
10
11
  user-facing binary is SiSu (`sisu`), not the official `grok` client.
11
12
 
12
- See vendor/grok-build/NOTICE for the grok-build-specific attribution.
13
+ See third_party/grok-build/NOTICE for the grok-build-specific attribution.
package/dist/commands.js CHANGED
@@ -339,7 +339,8 @@ async function setTrainingCommand(optIn, http = http_1.defaultHttp) {
339
339
  }
340
340
  async function listModelsCommand(http = http_1.defaultHttp) {
341
341
  const { models, defaultModel } = await (0, models_1.fetchModelCatalog)(http);
342
- const current = (0, store_1.readSession)().last_model || defaultModel;
342
+ const last = (0, store_1.readSession)().last_model || '';
343
+ const current = models.some((row) => row.name === last) ? last : defaultModel;
343
344
  if (!current && !models.length)
344
345
  return 'no models available';
345
346
  const lines = models.map((row) => {
@@ -347,9 +348,6 @@ async function listModelsCommand(http = http_1.defaultHttp) {
347
348
  const extra = row.label !== row.name ? ` ${row.label}` : '';
348
349
  return `${mark}${row.name}${extra}`;
349
350
  });
350
- if (current && !models.some((row) => row.name === current)) {
351
- lines.unshift(`* ${current}`);
352
- }
353
351
  return lines.join('\n') || `* ${current}`;
354
352
  }
355
353
  async function setModelCommand(query, http = http_1.defaultHttp) {
package/dist/http.js CHANGED
@@ -46,6 +46,12 @@ async function defaultHttp(url, init) {
46
46
  function errorDetail(body, fallback) {
47
47
  if (typeof body?.detail === 'string')
48
48
  return body.detail;
49
+ // FastAPI object detail (e.g. 402 quota_exhausted: { message, code }).
50
+ if (body?.detail && typeof body.detail === 'object') {
51
+ if (typeof body.detail.message === 'string' && body.detail.message.trim()) {
52
+ return body.detail.message;
53
+ }
54
+ }
49
55
  if (typeof body?.error === 'string')
50
56
  return body.error;
51
57
  if (typeof body?.message === 'string')
package/dist/main.js CHANGED
@@ -3,12 +3,18 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.helpText = helpText;
5
5
  exports.runCli = runCli;
6
+ const module_1 = require("module");
6
7
  const commands_1 = require("./commands");
7
8
  const http_1 = require("./http");
8
9
  const client_1 = require("./client");
9
10
  const logo_1 = require("./logo");
10
11
  const store_1 = require("./store");
11
12
  const tui_1 = require("./tui");
13
+ const req = (0, module_1.createRequire)(__filename);
14
+ function defaultInstallPager(options) {
15
+ const { installPager } = req('../scripts/install-pager.js');
16
+ return installPager(options);
17
+ }
12
18
  function helpText() {
13
19
  return `${(0, logo_1.sisuProductSurfaces)().helpAbout}
14
20
 
@@ -24,6 +30,7 @@ Usage:
24
30
  sisu login --token <jwt> [--api <url>]
25
31
  sisu logout
26
32
  sisu status
33
+ sisu update reinstall the stamped local pager
27
34
  sisu open <dir> --project <project-id>
28
35
  sisu ls [--project <project-id>]
29
36
  sisu exec "<prompt>" [--project <id>] [--model <name>] [--new] [--stub]
@@ -82,6 +89,18 @@ async function runCli(argv, deps = {}) {
82
89
  if (!command || command === 'tui') {
83
90
  return (0, tui_1.runTui)((0, tui_1.defaultTuiIo)());
84
91
  }
92
+ if (command === 'update') {
93
+ const install = deps.installPager ?? defaultInstallPager;
94
+ const result = await install({ force: true });
95
+ if (result.ok) {
96
+ process.stdout.write(result.skipped
97
+ ? `pager already current${result.dest ? ` at ${result.dest}` : ''}\n`
98
+ : `installed pager${result.dest ? ` to ${result.dest}` : ''}\n`);
99
+ return 0;
100
+ }
101
+ process.stderr.write(`sisu update: ${result.reason || 'pager install failed'}\n`);
102
+ return result.skipped ? 0 : 1;
103
+ }
85
104
  if (command === 'status') {
86
105
  process.stdout.write(`${await (0, commands_1.statusCommand)(http_1.defaultHttp)}\n`);
87
106
  return 0;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toProviderMessages = toProviderMessages;
4
4
  exports.completeUrl = completeUrl;
5
5
  exports.openaiCompatUrl = openaiCompatUrl;
6
+ exports.completeHeaders = completeHeaders;
6
7
  exports.buildCompleteRequest = buildCompleteRequest;
7
8
  exports.isServerSideAgentPayload = isServerSideAgentPayload;
8
9
  exports.parseCompleteSse = parseCompleteSse;
@@ -11,6 +12,7 @@ exports.createSisuCloudModel = createSisuCloudModel;
11
12
  const client_1 = require("../client");
12
13
  const http_1 = require("../http");
13
14
  const sse_1 = require("../sse");
15
+ const store_1 = require("../store");
14
16
  const suite_1 = require("./suite");
15
17
  /** OpenAI/Poe wire: assistant.tool_calls is {id,type,function:{name,arguments:string}}. */
16
18
  function toProviderMessages(messages) {
@@ -39,6 +41,12 @@ function completeUrl(apiBase) {
39
41
  function openaiCompatUrl(apiBase) {
40
42
  return `${apiBase.replace(/\/+$/, '')}${suite_1.OPENAI_COMPAT_PATH}`;
41
43
  }
44
+ function completeHeaders(token) {
45
+ return {
46
+ ...(0, http_1.authHeaders)(token),
47
+ 'x-sisu-conversation-id': (0, store_1.ensureConversationId)(),
48
+ };
49
+ }
42
50
  function buildCompleteRequest(request, options = {}) {
43
51
  const stamp = (0, client_1.clientStamp)(options.client || 'cli');
44
52
  return {
@@ -135,7 +143,7 @@ function createSisuCloudModel(http, options) {
135
143
  }
136
144
  const sent = await http(completeUrl(options.apiBase), {
137
145
  method: 'POST',
138
- headers: (0, http_1.authHeaders)(options.token),
146
+ headers: completeHeaders(options.token),
139
147
  body: JSON.stringify(payload),
140
148
  });
141
149
  if (!sent.ok) {
@@ -3,18 +3,54 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RuntimeUnavailable = void 0;
7
+ exports.assertRuntimeAvailable = assertRuntimeAvailable;
6
8
  exports.grokBuildBinaryCandidates = grokBuildBinaryCandidates;
7
9
  exports.findGrokBuildBinary = findGrokBuildBinary;
8
10
  exports.sisuRuntimeApiBase = sisuRuntimeApiBase;
9
11
  exports.writeSisuGrokConfig = writeSisuGrokConfig;
12
+ exports.migrateGrokScratchToEngine = migrateGrokScratchToEngine;
13
+ exports.purgeChangelogCache = purgeChangelogCache;
14
+ exports.installedPagerPath = installedPagerPath;
15
+ exports.pagerStampPath = pagerStampPath;
16
+ exports.installedPagerStamp = installedPagerStamp;
17
+ exports.comparePagerStamp = comparePagerStamp;
18
+ exports.pagerStampMeetsRelease = pagerStampMeetsRelease;
19
+ exports.accessPointBfullEnabled = accessPointBfullEnabled;
20
+ exports.pagerStampAllowsSpawn = pagerStampAllowsSpawn;
10
21
  exports.sisuGrokBuildEnv = sisuGrokBuildEnv;
11
22
  exports.launchGrokBuildHeadless = launchGrokBuildHeadless;
12
23
  const child_process_1 = require("child_process");
13
24
  const fs_1 = __importDefault(require("fs"));
14
25
  const path_1 = __importDefault(require("path"));
26
+ const client_1 = require("../client");
15
27
  const store_1 = require("../store");
16
28
  const suite_1 = require("./suite");
17
29
  const adapter_1 = require("./adapter");
30
+ const SCRATCH_DIRS = ['sessions', 'worktrees', 'hooks', 'logs'];
31
+ class RuntimeUnavailable extends Error {
32
+ constructor(message = 'SiSu runtime is not available') {
33
+ super(message);
34
+ this.name = 'RuntimeUnavailable';
35
+ }
36
+ }
37
+ exports.RuntimeUnavailable = RuntimeUnavailable;
38
+ async function assertRuntimeAvailable(http, apiBase) {
39
+ const url = `${apiBase.replace(/\/+$/, '')}/api/runtime/health`;
40
+ let response;
41
+ try {
42
+ response = await http(url, { headers: { Accept: 'application/json' } });
43
+ }
44
+ catch (error) {
45
+ throw new RuntimeUnavailable(error instanceof Error ? error.message : String(error));
46
+ }
47
+ if (!response || !response.ok) {
48
+ throw new RuntimeUnavailable(`health ${response?.status ?? 'unreachable'}`);
49
+ }
50
+ const body = (await response.json().catch(() => null));
51
+ if (!body || body.ok !== true)
52
+ throw new RuntimeUnavailable('health body missing ok');
53
+ }
18
54
  function grokBuildBinaryCandidates() {
19
55
  const env = (process.env.SISU_GROK_BIN || '').trim();
20
56
  const root = (0, suite_1.grokBuildRoot)();
@@ -41,10 +77,10 @@ function sisuRuntimeApiBase(apiBase) {
41
77
  }
42
78
  function writeSisuGrokConfig() {
43
79
  const auth = (0, store_1.readAuth)();
44
- const home = (0, store_1.getSisuHome)();
45
- fs_1.default.mkdirSync(home, { recursive: true, mode: 0o700 });
46
- const file = path_1.default.join(home, 'config.toml');
47
- const runtimeBase = sisuRuntimeApiBase(auth?.api_base || process.env.SISU_API_BASE || 'https://www.sisu.chat');
80
+ const engine = (0, store_1.sisuEngineHome)();
81
+ fs_1.default.mkdirSync(engine, { recursive: true, mode: 0o700 });
82
+ const file = path_1.default.join(engine, 'config.toml');
83
+ const runtimeBase = sisuRuntimeApiBase(auth?.api_base || process.env.SISU_API_BASE || store_1.DEFAULT_API_BASE);
48
84
  const body = [
49
85
  '# sisu-managed grok-build config — SiSu auth + models + quota',
50
86
  '[endpoints]',
@@ -57,23 +93,124 @@ function writeSisuGrokConfig() {
57
93
  }
58
94
  return file;
59
95
  }
96
+ function migrateGrokScratchToEngine(home) {
97
+ const engine = path_1.default.join(home, 'engine');
98
+ fs_1.default.mkdirSync(engine, { recursive: true, mode: 0o700 });
99
+ for (const name of SCRATCH_DIRS) {
100
+ const from = path_1.default.join(home, name);
101
+ const to = path_1.default.join(engine, name);
102
+ if (!fs_1.default.existsSync(from))
103
+ continue;
104
+ if (fs_1.default.existsSync(to)) {
105
+ for (const entry of fs_1.default.readdirSync(from)) {
106
+ const src = path_1.default.join(from, entry);
107
+ const dest = path_1.default.join(to, entry);
108
+ if (!fs_1.default.existsSync(dest))
109
+ fs_1.default.renameSync(src, dest);
110
+ }
111
+ // Keep leftover colliding entries. Never rm -rf a tree we skipped.
112
+ if (fs_1.default.readdirSync(from).length === 0)
113
+ fs_1.default.rmdirSync(from);
114
+ }
115
+ else {
116
+ fs_1.default.renameSync(from, to);
117
+ }
118
+ }
119
+ }
120
+ function purgeChangelogCache(home, engine) {
121
+ for (const root of [home, engine]) {
122
+ if (!fs_1.default.existsSync(root))
123
+ continue;
124
+ for (const entry of fs_1.default.readdirSync(root)) {
125
+ if (!entry.startsWith('CHANGELOG'))
126
+ continue;
127
+ try {
128
+ fs_1.default.unlinkSync(path_1.default.join(root, entry));
129
+ }
130
+ catch {
131
+ // ignore missing / busy
132
+ }
133
+ }
134
+ }
135
+ }
136
+ function installedPagerPath() {
137
+ return path_1.default.join((0, store_1.getSisuHome)(), 'bin', process.platform === 'win32' ? 'xai-grok-pager.exe' : 'xai-grok-pager');
138
+ }
139
+ function pagerStampPath(dest = installedPagerPath()) {
140
+ return `${dest}.version`;
141
+ }
142
+ function installedPagerStamp(dest = installedPagerPath()) {
143
+ try {
144
+ return fs_1.default.readFileSync(pagerStampPath(dest), 'utf8').trim();
145
+ }
146
+ catch {
147
+ return '';
148
+ }
149
+ }
150
+ function comparePagerStamp(stamped, release) {
151
+ const parse = (value) => value.trim().split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
152
+ const left = parse(stamped);
153
+ const right = parse(release);
154
+ const n = Math.max(left.length, right.length);
155
+ for (let i = 0; i < n; i += 1) {
156
+ const delta = (left[i] ?? 0) - (right[i] ?? 0);
157
+ if (delta !== 0)
158
+ return delta;
159
+ }
160
+ return 0;
161
+ }
162
+ function pagerStampMeetsRelease(stamped = installedPagerStamp(), release = client_1.SISU_CLIENT_VERSION) {
163
+ if (!stamped || !release)
164
+ return false;
165
+ return comparePagerStamp(stamped, release) >= 0;
166
+ }
167
+ /** B-full only when the host env flag is on or the installed pager stamp matches this package. */
168
+ function accessPointBfullEnabled() {
169
+ return process.env.SISU_ACCESS_POINT_BFULL === '1' || pagerStampMeetsRelease();
170
+ }
171
+ /** Installed ~/.sisu/bin pager must be this release; other paths (SISU_GROK_BIN / cargo) are dev. */
172
+ function pagerStampAllowsSpawn(binary) {
173
+ if (path_1.default.resolve(binary) !== path_1.default.resolve(installedPagerPath()))
174
+ return true;
175
+ return pagerStampMeetsRelease(installedPagerStamp(binary));
176
+ }
60
177
  function sisuGrokBuildEnv() {
61
178
  const auth = (0, store_1.readAuth)();
62
- const home = (0, store_1.getSisuHome)();
63
- const runtimeBase = auth ? sisuRuntimeApiBase(auth.api_base) : '';
179
+ const engine = (0, store_1.sisuEngineHome)();
180
+ const apiBase = auth?.api_base || process.env.SISU_API_BASE || store_1.DEFAULT_API_BASE;
181
+ const runtime = sisuRuntimeApiBase(apiBase);
182
+ const env = { ...process.env };
183
+ delete env.SISU_HOME;
184
+ delete env.GROK_CODE_XAI_API_KEY;
185
+ delete env.GROK_DEFAULT_MODEL;
186
+ delete env.SISU_TOKEN;
187
+ if (accessPointBfullEnabled()) {
188
+ delete env.XAI_API_KEY;
189
+ env.SISU_TOKEN = auth?.token || '';
190
+ }
191
+ else {
192
+ env.XAI_API_KEY = auth?.token || '';
193
+ }
64
194
  return {
65
- ...process.env,
66
- GROK_HOME: process.env.GROK_HOME || home,
67
- SISU_HOME: home,
68
- GROK_TELEMETRY_ENABLED: process.env.GROK_TELEMETRY_ENABLED || '0',
69
- XAI_API_KEY: process.env.XAI_API_KEY || auth?.token || '',
70
- SISU_API_BASE: auth?.api_base || process.env.SISU_API_BASE || 'https://www.sisu.chat',
71
- ...(runtimeBase
72
- ? {
73
- GROK_XAI_API_BASE_URL: runtimeBase,
74
- XAI_API_BASE_URL: runtimeBase,
75
- }
76
- : {}),
195
+ ...env,
196
+ SISU_ACCESS_POINT: '1',
197
+ GROK_HOME: engine,
198
+ GROK_AUTH_PATH: path_1.default.join(engine, 'auth.json'),
199
+ SISU_AUTH_PATH: (0, store_1.sisuAuthPath)(),
200
+ SISU_ACCOUNT_EMAIL: auth?.email || '',
201
+ SISU_ACCOUNT_PLAN: auth?.plan_code || '',
202
+ SISU_API_BASE: apiBase,
203
+ SISU_CLIENT_VERSION: client_1.SISU_CLIENT_VERSION,
204
+ SISU_CONVERSATION_ID: (0, store_1.ensureConversationId)(),
205
+ GROK_XAI_API_BASE_URL: runtime,
206
+ XAI_API_BASE_URL: runtime,
207
+ GROK_MODELS_BASE_URL: runtime,
208
+ GROK_MODELS_LIST_URL: `${runtime}/models`,
209
+ GROK_CLI_CHAT_PROXY_BASE_URL: runtime,
210
+ GROK_DISABLE_CLI_CHAT_PROXY: '1',
211
+ GROK_TELEMETRY_ENABLED: '0',
212
+ GROK_CHANGELOG_OFFLINE: '1',
213
+ GROK_DISABLE_API_KEY_AUTH: '1',
77
214
  };
78
215
  }
79
216
  function launchGrokBuildHeadless(prompt, cwd) {
@@ -8,23 +8,27 @@ const store_1 = require("../store");
8
8
  function normalizeModelKey(value) {
9
9
  return value.toLowerCase().replace(/[-_.\s]/g, '');
10
10
  }
11
- async function fetchModelCatalog(http = http_1.defaultHttp) {
12
- const auth = (0, store_1.requireAuth)();
13
- const response = await http(`${auth.api_base}/api/chat/models`, { headers: (0, http_1.authHeaders)(auth.token) });
14
- const body = await response.json().catch(() => ({}));
15
- if (!response.ok)
16
- throw new Error((0, http_1.errorDetail)(body, `models failed (${response.status})`));
17
- const rows = Array.isArray(body?.models) ? body.models : [];
11
+ function parseRuntimeCatalog(body) {
12
+ const rows = Array.isArray(body?.data) ? body.data : [];
18
13
  const models = rows
19
14
  .map((row) => {
20
- const name = String(row?.name || '').trim();
15
+ const name = String(row?.id || row?.name || '').trim();
21
16
  if (!name)
22
17
  return null;
23
- return { name, label: String(row.display_name || row.label || name) };
18
+ return { name, label: String(row?.name || row?.id || name).trim() || name };
24
19
  })
25
20
  .filter((row) => Boolean(row));
26
21
  return { models, defaultModel: String(body?.default_model || '') };
27
22
  }
23
+ async function fetchModelCatalog(http = http_1.defaultHttp) {
24
+ const auth = (0, store_1.requireAuth)();
25
+ const headers = (0, http_1.authHeaders)(auth.token);
26
+ const runtime = await http(`${auth.api_base}/api/runtime/v1/models`, { headers });
27
+ if (runtime.ok)
28
+ return parseRuntimeCatalog(await runtime.json().catch(() => ({})));
29
+ const body = await runtime.json().catch(() => ({}));
30
+ throw new Error((0, http_1.errorDetail)(body, `models failed (${runtime.status})`));
31
+ }
28
32
  function resolveCatalogModel(query, models) {
29
33
  const needle = normalizeModelKey(query);
30
34
  if (!needle)
package/dist/store.js CHANGED
@@ -5,15 +5,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEFAULT_API_BASE = void 0;
7
7
  exports.getSisuHome = getSisuHome;
8
+ exports.sisuEngineHome = sisuEngineHome;
9
+ exports.sisuAuthPath = sisuAuthPath;
8
10
  exports.readAuth = readAuth;
9
11
  exports.writeAuth = writeAuth;
10
12
  exports.readSession = readSession;
11
13
  exports.writeSession = writeSession;
14
+ exports.ensureConversationId = ensureConversationId;
12
15
  exports.clearAuth = clearAuth;
13
16
  exports.readWorkspaces = readWorkspaces;
14
17
  exports.bindWorkspace = bindWorkspace;
15
18
  exports.requireAuth = requireAuth;
16
19
  exports.describeStatus = describeStatus;
20
+ const crypto_1 = require("crypto");
17
21
  const fs_1 = __importDefault(require("fs"));
18
22
  const os_1 = __importDefault(require("os"));
19
23
  const path_1 = __importDefault(require("path"));
@@ -22,9 +26,15 @@ function getSisuHome() {
22
26
  const override = (process.env.SISU_HOME || '').trim();
23
27
  return override || path_1.default.join(os_1.default.homedir(), '.sisu');
24
28
  }
25
- function authPath() {
29
+ function sisuEngineHome() {
30
+ return path_1.default.join(getSisuHome(), 'engine');
31
+ }
32
+ function sisuAuthPath() {
26
33
  return path_1.default.join(getSisuHome(), 'auth.json');
27
34
  }
35
+ function authPath() {
36
+ return sisuAuthPath();
37
+ }
28
38
  function workspacePath() {
29
39
  return path_1.default.join(getSisuHome(), 'workspace-paths.json');
30
40
  }
@@ -79,6 +89,7 @@ function readAuth() {
79
89
  };
80
90
  }
81
91
  function writeAuth(record) {
92
+ const previous = readAuth();
82
93
  writeJson(authPath(), {
83
94
  token: record.token,
84
95
  email: record.email,
@@ -87,6 +98,12 @@ function writeAuth(record) {
87
98
  plan_code: record.plan_code || '',
88
99
  name: record.name || '',
89
100
  });
101
+ if (previous && previous.user_id !== record.user_id) {
102
+ const session = readSession();
103
+ if (session.last_conversation_id) {
104
+ writeSession({ ...session, last_conversation_id: undefined });
105
+ }
106
+ }
90
107
  }
91
108
  function readSession() {
92
109
  return readJson(sessionPath(), {});
@@ -94,6 +111,16 @@ function readSession() {
94
111
  function writeSession(record) {
95
112
  writeJson(sessionPath(), record);
96
113
  }
114
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
115
+ function ensureConversationId() {
116
+ const session = readSession();
117
+ const current = String(session.last_conversation_id || '').trim();
118
+ if (UUID_RE.test(current))
119
+ return current;
120
+ const id = (0, crypto_1.randomUUID)();
121
+ writeSession({ ...session, last_conversation_id: id });
122
+ return id;
123
+ }
97
124
  function clearAuth() {
98
125
  try {
99
126
  fs_1.default.unlinkSync(authPath());
package/dist/tui.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SISU_LOGIN_EXIT_CODE = void 0;
6
7
  exports.shouldAnimateSplash = shouldAnimateSplash;
7
8
  exports.playMobiusIntro = playMobiusIntro;
8
9
  exports.playTreeIntro = playTreeIntro;
@@ -20,6 +21,8 @@ const store_1 = require("./store");
20
21
  const launch_1 = require("./runtime/launch");
21
22
  const transport_1 = require("./runtime/transport");
22
23
  const child_process_1 = require("child_process");
24
+ /** Pager exits with this code so the host runs `sisu login` and respawns. */
25
+ exports.SISU_LOGIN_EXIT_CODE = 10;
23
26
  function shouldAnimateSplash(env = process.env, tty = Boolean(process.stdout.isTTY)) {
24
27
  if (env.SISU_TUI_STATIC === '1')
25
28
  return false;
@@ -199,11 +202,48 @@ async function runTui(io, deps = {}) {
199
202
  const training = deps.training ?? commands_1.setTrainingCommand;
200
203
  const auth = deps.auth ?? store_1.readAuth;
201
204
  const webLogin = deps.webLogin ?? commands_1.webLoginCommand;
205
+ const probe = deps.probe ?? launch_1.assertRuntimeAvailable;
202
206
  const columns = deps.columns ?? process.stdout.columns ?? 80;
203
207
  const animate = deps.animate ?? shouldAnimateSplash();
204
208
  try {
205
- const account = auth();
206
- const usePager = Boolean(deps.pager || shouldUsePager(deps));
209
+ const startWebLogin = async (notify) => {
210
+ return webLogin({
211
+ onStart: (info) => {
212
+ notify(`Open ${info.verification_uri_complete}`);
213
+ notify(`Confirm code ${info.user_code}`);
214
+ },
215
+ }, http);
216
+ };
217
+ let account = auth();
218
+ if (!account) {
219
+ try {
220
+ const email = await startWebLogin((line) => io.write(`${line}\n`));
221
+ io.write(`logged in as ${email}\n`);
222
+ }
223
+ catch (error) {
224
+ io.write(`${error instanceof Error ? error.message : String(error)}\n`);
225
+ io.write('login failed — run `sisu login`\n');
226
+ return 1;
227
+ }
228
+ account = auth();
229
+ if (!account) {
230
+ io.write('login failed — run `sisu login`\n');
231
+ return 1;
232
+ }
233
+ }
234
+ let runtimeOk = true;
235
+ try {
236
+ await probe(http, account.api_base);
237
+ }
238
+ catch (error) {
239
+ if (!(error instanceof launch_1.RuntimeUnavailable))
240
+ throw error;
241
+ runtimeOk = false;
242
+ io.write(`SiSu runtime is not available at ${account.api_base}/api/runtime. ` +
243
+ `This CLI will not fall back to xAI. Using the Node TUI.\n`);
244
+ }
245
+ // Health failure never spawns the pager (injected or grok binary).
246
+ const usePager = runtimeOk && Boolean(deps.pager || deps.spawnGrokPager || shouldUsePager(deps));
207
247
  if (!usePager) {
208
248
  if (animate) {
209
249
  await playTreeIntro(io, {
@@ -216,24 +256,51 @@ async function runTui(io, deps = {}) {
216
256
  io.write(`${(0, logo_1.sisuSplash)(columns, true)}\n`);
217
257
  }
218
258
  }
219
- const startWebLogin = async (notify) => {
220
- return webLogin({
221
- onStart: (info) => {
222
- notify(`Open ${info.verification_uri_complete}`);
223
- notify(`Confirm code ${info.user_code}`);
224
- },
225
- }, http);
226
- };
227
259
  if (usePager && !deps.pager) {
228
- const grokBin = (0, launch_1.findGrokBuildBinary)();
229
- if (grokBin && process.stdout.isTTY) {
230
- (0, launch_1.writeSisuGrokConfig)();
231
- io.close?.();
232
- const child = (0, child_process_1.spawn)(grokBin, [], { stdio: 'inherit', env: (0, launch_1.sisuGrokBuildEnv)(), cwd: process.cwd() });
233
- return await new Promise((resolve) => {
234
- child.on('exit', (code) => resolve(code ?? 1));
235
- child.on('error', () => resolve(1));
260
+ const spawnOnce = deps.spawnGrokPager ??
261
+ (() => {
262
+ const grokBin = (0, launch_1.findGrokBuildBinary)();
263
+ if (!grokBin || !process.stdout.isTTY) {
264
+ return Promise.resolve(null);
265
+ }
266
+ if (!(0, launch_1.pagerStampAllowsSpawn)(grokBin)) {
267
+ io.write('sisu: refusing to spawn a pager older than this CLI. Reinstall the pager or run `sisu` after postinstall.\n');
268
+ return Promise.resolve(null);
269
+ }
270
+ const home = (0, store_1.getSisuHome)();
271
+ const engine = (0, store_1.sisuEngineHome)();
272
+ (0, launch_1.migrateGrokScratchToEngine)(home);
273
+ (0, launch_1.purgeChangelogCache)(home, engine);
274
+ (0, launch_1.writeSisuGrokConfig)();
275
+ io.close?.();
276
+ const child = (0, child_process_1.spawn)(grokBin, [], {
277
+ stdio: 'inherit',
278
+ env: (0, launch_1.sisuGrokBuildEnv)(),
279
+ cwd: process.cwd(),
280
+ });
281
+ return new Promise((resolve) => {
282
+ child.on('exit', (code) => resolve(code ?? 1));
283
+ child.on('error', () => resolve(1));
284
+ });
236
285
  });
286
+ if (deps.spawnGrokPager || ((0, launch_1.findGrokBuildBinary)() && process.stdout.isTTY)) {
287
+ // Login handoff: pager exits 10 → host web login → respawn.
288
+ while (true) {
289
+ const code = await spawnOnce();
290
+ if (code === null)
291
+ break;
292
+ if (code !== exports.SISU_LOGIN_EXIT_CODE)
293
+ return code;
294
+ try {
295
+ const email = await startWebLogin((line) => io.write(`${line}\n`));
296
+ io.write(`logged in as ${email}\n`);
297
+ }
298
+ catch (error) {
299
+ io.write(`${error instanceof Error ? error.message : String(error)}\n`);
300
+ io.write('login failed — run `sisu login`\n');
301
+ return 1;
302
+ }
303
+ }
237
304
  }
238
305
  }
239
306
  if (usePager) {
@@ -262,8 +329,6 @@ async function runTui(io, deps = {}) {
262
329
  });
263
330
  }
264
331
  io.write(`${await status(http)}\n`);
265
- if (!account)
266
- io.write('Not logged in. Type /login to sign in with your browser.\n');
267
332
  io.write(`${tuiHelp()}\n\n`);
268
333
  let newConversation = false;
269
334
  while (true) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stevezhou/sisu",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "SiSu CLI — 思溯 / SiSu · 思有所溯",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://www.sisu.chat",
@@ -24,6 +24,7 @@
24
24
  "dist",
25
25
  "README.md",
26
26
  "NOTICE",
27
+ "third_party/grok-build",
27
28
  "scripts/postinstall.js",
28
29
  "scripts/install-pager.js"
29
30
  ],
@@ -8,7 +8,7 @@ const os = require('os')
8
8
  const path = require('path')
9
9
  const zlib = require('zlib')
10
10
 
11
- const SUPPORTED = new Set(['darwin-arm64'])
11
+ const SUPPORTED = new Set(['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64'])
12
12
  const BIN = process.platform === 'win32' ? 'xai-grok-pager.exe' : 'xai-grok-pager'
13
13
 
14
14
  function readVersion() {