@sortlist/cli 0.26.0

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.
Files changed (46) hide show
  1. package/.published +1 -0
  2. package/README.md +145 -0
  3. package/bin/sl.mjs +73 -0
  4. package/codegen.ts +36 -0
  5. package/package.json +62 -0
  6. package/src/commands/chat/chat.ts +302 -0
  7. package/src/commands/chat/interactive/App.tsx +119 -0
  8. package/src/commands/chat/interactive/components/ChatInput.tsx +115 -0
  9. package/src/commands/chat/interactive/components/ChoicePrompt.tsx +35 -0
  10. package/src/commands/chat/interactive/components/MessageView.tsx +63 -0
  11. package/src/commands/chat/interactive/components/ThinkingBox.tsx +54 -0
  12. package/src/commands/chat/interactive/connection.ts +111 -0
  13. package/src/commands/chat/interactive/debug-log.ts +19 -0
  14. package/src/commands/chat/interactive/hooks/useChat.ts +440 -0
  15. package/src/commands/chat/interactive/hooks/useTerminalSize.ts +23 -0
  16. package/src/commands/chat/interactive/index.tsx +26 -0
  17. package/src/commands/chat/interactive/markdown.ts +29 -0
  18. package/src/commands/chat/interactive/types.ts +34 -0
  19. package/src/commands/config.ts +94 -0
  20. package/src/commands/dynamic.ts +396 -0
  21. package/src/commands/login.ts +191 -0
  22. package/src/commands/logout.ts +43 -0
  23. package/src/commands/offer.ts +96 -0
  24. package/src/commands/switch.ts +72 -0
  25. package/src/commands/token.ts +23 -0
  26. package/src/commands/whoami.ts +50 -0
  27. package/src/graphql/client.ts +257 -0
  28. package/src/graphql/generated/gql.ts +106 -0
  29. package/src/graphql/generated/graphql.ts +7732 -0
  30. package/src/graphql/generated/index.ts +1 -0
  31. package/src/graphql/introspection.ts +240 -0
  32. package/src/graphql/operations/common.ts +115 -0
  33. package/src/graphql/operations/hermes.ts +54 -0
  34. package/src/graphql/query-builder.ts +236 -0
  35. package/src/index.ts +176 -0
  36. package/src/lib/auth.ts +58 -0
  37. package/src/lib/browser.ts +6 -0
  38. package/src/lib/company.ts +35 -0
  39. package/src/lib/config.ts +73 -0
  40. package/src/lib/env.ts +10 -0
  41. package/src/lib/output.ts +84 -0
  42. package/src/lib/parse.ts +8 -0
  43. package/src/lib/sentry.ts +77 -0
  44. package/src/lib/sequence-buffer.ts +95 -0
  45. package/src/lib/version-check.ts +88 -0
  46. package/src/types/marked-terminal.d.ts +20 -0
package/.published ADDED
@@ -0,0 +1 @@
1
+ true
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # Sortlist CLI (`sl`)
2
+
3
+ Command-line interface for the Sortlist platform. Talks to the GraphQL federation endpoint and dynamically discovers available operations via introspection.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @sortlist/cli
9
+ sl <command>
10
+ ```
11
+
12
+ ## Local development
13
+
14
+ ```bash
15
+ cd cli
16
+ npm install
17
+
18
+ npx sl <command>
19
+ ```
20
+
21
+ Tip: add an alias to your shell profile for convenience:
22
+
23
+ ```bash
24
+ alias sl='npx sl'
25
+ ```
26
+
27
+ ## Authentication
28
+
29
+ Uses the [Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) flow via Hermes. Tokens are stored at `~/.sortlist/credentials.json`.
30
+
31
+ ```bash
32
+ sl login # opens browser for authentication
33
+ sl logout # clears stored credentials
34
+ sl whoami # shows current user
35
+ sl token # prints access token to stdout (useful for curl/scripts)
36
+ sl switch # switch active agency context
37
+ ```
38
+
39
+ ## Service operations
40
+
41
+ Every query and mutation from the federated GraphQL schema is available as a CLI command. Operations are discovered at runtime via introspection and grouped by service based on the `[service]` prefix in field descriptions:
42
+
43
+ ```bash
44
+ sl atlas <operation> # company and contact enrichment
45
+ sl chat <operation> # AI assistant (conversations, messages, configuration)
46
+ sl marketplace <operation> # agencies, projects, opportunities, quotes
47
+ sl hermes <operation> # OAuth/auth operations
48
+ ```
49
+
50
+ Use `--help` on any service to list available operations (grouped by queries and mutations):
51
+
52
+ ```bash
53
+ sl atlas --help
54
+ sl marketplace --help
55
+ ```
56
+
57
+ Each operation supports:
58
+
59
+ | Flag | Description |
60
+ | ------------------- | ---------------------------------------------- |
61
+ | `--depth <n>` | Selection depth for nested fields (default: 0) |
62
+ | `--fields <a,b,c>` | Comma-separated fields to include |
63
+ | `--exclude <a,b,c>` | Comma-separated fields to exclude |
64
+
65
+ ## Schema management
66
+
67
+ The CLI fetches the GraphQL schema via introspection on startup and caches it locally at `~/.sortlist/schema.json` (1-hour TTL). To force a refresh:
68
+
69
+ ```bash
70
+ sl schema refresh
71
+ ```
72
+
73
+ The endpoint can be configured via `--endpoint`, `SL_ENDPOINT` env var, or `~/.sortlist/config.json`.
74
+
75
+ ## Interactive chat
76
+
77
+ The `chat conversation` command is a hand-written interactive chat client (not auto-generated). It replaces the auto-generated basic `conversation` sub-command on the `chat` service.
78
+
79
+ ### Basic mode
80
+
81
+ Plain readline-based chat with streaming responses:
82
+
83
+ ```bash
84
+ sl chat conversation # new conversation
85
+ sl chat conversation --conversation-id <id> # resume existing conversation
86
+ sl chat conversation --title "Debug session" # new conversation with title
87
+ ```
88
+
89
+ ### Interactive mode
90
+
91
+ Rich terminal UI with markdown rendering, thinking/tool-call visualization, and spinners:
92
+
93
+ ```bash
94
+ sl chat conversation -i # new conversation
95
+ sl chat conversation -i --conversation-id <id> # resume existing conversation
96
+ ```
97
+
98
+ Interactive mode features:
99
+
100
+ - Markdown rendering of assistant responses
101
+ - Thinking box showing tool calls with animated spinners
102
+ - Event reordering via sequence buffer (handles out-of-order WebSocket delivery)
103
+ - `/quit` or Ctrl+C to exit
104
+
105
+ ## Debug logs
106
+
107
+ The interactive chat writes debug logs to files in the `cli/` directory (both gitignored):
108
+
109
+ | File | Contents |
110
+ | ----------------- | ------------------------------------------------------------------------ |
111
+ | `debug.log` | Raw WebSocket events, sequence buffer warnings, finalization diagnostics |
112
+ | `debug-tools.log` | Tool call arguments and full tool results |
113
+
114
+ Logs are cleared automatically when a new conversation starts.
115
+
116
+ ```bash
117
+ tail -f debug.log # watch WebSocket events in real time
118
+ cat debug-tools.log # review tool calls and results
119
+ ```
120
+
121
+ ## Global options
122
+
123
+ | Flag | Description |
124
+ | ------------------ | ----------------------------------------------------------------------- |
125
+ | `--endpoint <url>` | Override federation endpoint (default: `http://localhost:4020/graphql`) |
126
+ | `--json` | Force JSON output (auto-enabled when non-TTY) |
127
+ | `--no-color` | Disable colored output |
128
+
129
+ The endpoint can also be set via the `SL_ENDPOINT` environment variable or `~/.sortlist/config.json`.
130
+
131
+ ## Code generation
132
+
133
+ The only build-time step is `npm run codegen`, which generates TypeScript types for hand-written operations (auth flow, interactive chat) using `graphql-codegen`. It reads the schema from `../backend/supergraph.graphql`.
134
+
135
+ ```bash
136
+ npm run generate # alias for npm run codegen
137
+ npm run codegen # regenerate TypeScript types for hand-written operations
138
+ ```
139
+
140
+ This is only needed when:
141
+
142
+ - The hand-written operations in `src/graphql/operations/` change
143
+ - The schema types referenced by those operations change in the supergraph
144
+
145
+ All dynamically generated commands (service operations) require no build step — they are derived entirely from runtime introspection.
package/bin/sl.mjs ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ const selfRoot = resolve(__dirname, '..');
9
+
10
+ /**
11
+ * Walk upward from `start` looking for a @sortlist/cli checkout
12
+ * (package.json with name === "@sortlist/cli" and no .published sentinel).
13
+ * Returns the package root, or null.
14
+ */
15
+ function findLocalCheckout(start) {
16
+ let dir = start;
17
+ while (true) {
18
+ const pkgPath = resolve(dir, 'package.json');
19
+ if (existsSync(pkgPath)) {
20
+ try {
21
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
22
+ if (pkg.name === '@sortlist/cli' && !existsSync(resolve(dir, '.published'))) {
23
+ return dir;
24
+ }
25
+ } catch {
26
+ // unreadable package.json — keep walking
27
+ }
28
+ }
29
+ const parent = dirname(dir);
30
+ if (parent === dir) return null;
31
+ dir = parent;
32
+ }
33
+ }
34
+
35
+ // Re-exec the local checkout's bin if we're invoked from within one,
36
+ // unless explicitly opted out or already running from that checkout.
37
+ if (process.env.SL_PREFER_LOCAL !== '0') {
38
+ const localRoot = findLocalCheckout(process.cwd());
39
+ if (localRoot && localRoot !== selfRoot) {
40
+ const localBin = resolve(localRoot, 'bin/sl.mjs');
41
+ if (existsSync(localBin)) {
42
+ try {
43
+ execFileSync(process.execPath, [localBin, ...process.argv.slice(2)], {
44
+ stdio: 'inherit',
45
+ env: { ...process.env, SL_PREFER_LOCAL: '0' },
46
+ });
47
+ process.exit(0);
48
+ } catch (err) {
49
+ process.exit(err.status ?? 1);
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ const tsxPath = resolve(selfRoot, 'node_modules/.bin/tsx');
56
+ const entryPoint = resolve(selfRoot, 'src/index.ts');
57
+
58
+ if (!existsSync(tsxPath)) {
59
+ console.error(`sl: missing dependency at ${tsxPath} — run \`npm install\` in ${selfRoot}`);
60
+ process.exit(1);
61
+ }
62
+
63
+ try {
64
+ execFileSync(tsxPath, [entryPoint, ...process.argv.slice(2)], {
65
+ stdio: 'inherit',
66
+ env: { ...process.env, NODE_OPTIONS: [process.env.NODE_OPTIONS, '--enable-source-maps'].filter(Boolean).join(' ') },
67
+ });
68
+ } catch (err) {
69
+ if (err.code === 'ENOENT') {
70
+ console.error(`sl: failed to spawn tsx (${err.message})`);
71
+ }
72
+ process.exit(err.status ?? 1);
73
+ }
package/codegen.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { CodegenConfig } from "@graphql-codegen/cli";
2
+ import fs from "fs";
3
+
4
+ // Schema resolution: SUPERGRAPH_PATH env → ../backend/supergraph.graphql
5
+ function resolveSchema(): string {
6
+ if (process.env.SUPERGRAPH_PATH && fs.existsSync(process.env.SUPERGRAPH_PATH)) {
7
+ return process.env.SUPERGRAPH_PATH;
8
+ }
9
+ const local = "../backend/supergraph.graphql";
10
+ if (fs.existsSync(local)) return local;
11
+ throw new Error(
12
+ "Supergraph not found. Set SUPERGRAPH_PATH or ensure ../backend/supergraph.graphql exists.",
13
+ );
14
+ }
15
+
16
+ const config: CodegenConfig = {
17
+ overwrite: true,
18
+ schema: resolveSchema(),
19
+ documents: ["src/graphql/operations/*.ts"],
20
+ emitLegacyCommonJSImports: false,
21
+ generates: {
22
+ "src/graphql/generated/": {
23
+ preset: "client",
24
+ config: {
25
+ useTypeImports: true,
26
+ enumsAsTypes: true,
27
+ },
28
+ presetConfig: {
29
+ gqlTagName: "gql",
30
+ fragmentMasking: false,
31
+ },
32
+ },
33
+ },
34
+ };
35
+
36
+ export default config;
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@sortlist/cli",
3
+ "version": "0.26.0",
4
+ "description": "Sortlist platform CLI — GraphQL federation client and Clara AI chat",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "bin": {
10
+ "sl": "./bin/sl.mjs"
11
+ },
12
+ "files": [
13
+ "bin/",
14
+ "src/",
15
+ "codegen.ts",
16
+ ".published"
17
+ ],
18
+ "scripts": {
19
+ "codegen": "graphql-codegen --config codegen.ts",
20
+ "generate": "npm run codegen",
21
+ "type-check": "tsc --noEmit",
22
+ "lint": "eslint . --ext .ts,.tsx,.js,.cjs --quiet",
23
+ "format": "prettier --write \"src/**/*.{ts,tsx,js,cjs,json}\"",
24
+ "format:check": "prettier --check \"src/**/*.{ts,tsx,js,cjs,json}\"",
25
+ "prepare": "[ -n \"$CI\" ] && exit 0; command -v git >/dev/null 2>&1 && git config --unset core.hooksPath || true; command -v lefthook >/dev/null 2>&1 && lefthook install || true"
26
+ },
27
+ "dependencies": {
28
+ "@sentry/node": "^10.29.0",
29
+ "@graphql-codegen/cli": "^6.2.1",
30
+ "@graphql-codegen/client-preset": "^5.2.4",
31
+ "@graphql-typed-document-node/core": "^3.2.0",
32
+ "@inkjs/ui": "^2.0.0",
33
+ "@types/react": "^19.2.14",
34
+ "commander": "^13.0.0",
35
+ "graphql": "^16.13.2",
36
+ "ink": "^5.2.1",
37
+ "marked": "^15.0.12",
38
+ "marked-terminal": "^7.3.0",
39
+ "react": "^18.3.1",
40
+ "tsx": "^4.19.0"
41
+ },
42
+ "devDependencies": {
43
+ "@commitlint/config-conventional": "^18.6.1",
44
+ "@ianvs/prettier-plugin-sort-imports": "^4.1.1",
45
+ "@types/node": "^22.10.0",
46
+ "@typescript-eslint/eslint-plugin": "^8.13.0",
47
+ "@typescript-eslint/parser": "^8.13.0",
48
+ "branch-name-lint": "^2.1.1",
49
+ "commitlint": "^18.6.1",
50
+ "eslint": "^8.56.0",
51
+ "eslint-config-prettier": "^9.1.0",
52
+ "eslint-import-resolver-typescript": "^3.6.1",
53
+ "eslint-plugin-import": "^2.29.1",
54
+ "eslint-plugin-prettier": "^5.1.3",
55
+ "eslint-plugin-react": "7.35.0",
56
+ "eslint-plugin-react-hooks": "^4.6.0",
57
+ "eslint-plugin-sonarjs": "^0.24.0",
58
+ "lefthook": "^1.11.5",
59
+ "prettier": "^3.5.3",
60
+ "typescript": "^5.7.0"
61
+ }
62
+ }
@@ -0,0 +1,302 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { Command } from 'commander';
3
+
4
+ import { graphql } from '../../graphql/client.ts';
5
+ import { Conversation, Me, SendMessage } from '../../graphql/operations/common.ts';
6
+ import { ensureAuthenticated, isExpired } from '../../lib/auth.ts';
7
+ import { resolveCompanyId } from '../../lib/company.ts';
8
+ import { getEndpoint, getUserContext } from '../../lib/config.ts';
9
+ import { error, hint, info } from '../../lib/output.ts';
10
+ import { captureException } from '../../lib/sentry.ts';
11
+ import { SequenceBuffer } from '../../lib/sequence-buffer.ts';
12
+ import { connectChatStream } from './interactive/connection.ts';
13
+ import type { ChatConnection, ChatEvent } from './interactive/types.ts';
14
+
15
+ // ── Colors (conditional on --no-color / NO_COLOR) ──
16
+
17
+ function colors(enabled: boolean) {
18
+ if (!enabled) return { reset: '', dim: '', cyan: '', green: '', yellow: '', red: '' };
19
+ return {
20
+ reset: '\x1b[0m',
21
+ dim: '\x1b[2m',
22
+ cyan: '\x1b[36m',
23
+ green: '\x1b[32m',
24
+ yellow: '\x1b[33m',
25
+ red: '\x1b[31m',
26
+ };
27
+ }
28
+
29
+ // ── Interactive chat command ──
30
+
31
+ export const chatCommand = new Command('conversation')
32
+ .summary('Start an interactive conversation with Sortlist AI')
33
+ .description(
34
+ 'Start an interactive conversation with Sortlist AI\n\n' +
35
+ 'Opens a live chat session over GraphQL-SSE through the federation router.\n' +
36
+ 'Type your messages and receive streaming responses. Use /quit or /exit to leave.\n\n' +
37
+ 'Examples:\n' +
38
+ ' sl chat conversation Start a new conversation (basic mode)\n' +
39
+ ' sl chat conversation -i Start with rich markdown rendering\n' +
40
+ ' sl chat conversation --conversation-id <id> Resume a previous conversation',
41
+ )
42
+ .option('--company-id <id>', 'Use a specific company by UUID (overrides your context)')
43
+ .option('--company-slug <slug>', 'Use a specific company by slug (resolved server-side)')
44
+ .option('--conversation-id <id>', 'Resume an existing conversation by its ID')
45
+ .option('--title <title>', 'Set a title for the new conversation')
46
+ .option('--debug', 'Log raw SSE frames to stderr')
47
+ .option('-i, --interactive', 'Rich UI with markdown rendering (recommended)')
48
+ .action(async function (this: Command) {
49
+ const opts = this.optsWithGlobals();
50
+ const ctx = getUserContext();
51
+ const endpoint = getEndpoint(opts.endpoint);
52
+ const debug = opts.debug === true;
53
+
54
+ if (opts.companyId && opts.companySlug) {
55
+ error('Pass either `--company-id` or `--company-slug`, not both.');
56
+ process.exit(2);
57
+ }
58
+
59
+ const companyId = await resolveCompanyId({
60
+ companyId: opts.companyId as string | undefined,
61
+ companySlug: opts.companySlug as string | undefined,
62
+ ctx,
63
+ endpoint,
64
+ });
65
+ if (!companyId) {
66
+ error('No company selected.');
67
+ hint('Pick one with `sl switch`, or pass `--company-id <id>` / `--company-slug <slug>`.');
68
+ process.exit(2);
69
+ }
70
+
71
+ // Launch interactive Ink UI if requested
72
+ if (opts.interactive) {
73
+ const { launchInteractive } = await import('./interactive/index.tsx');
74
+ launchInteractive({
75
+ companyId,
76
+ conversationId: opts.conversationId,
77
+ conversationTitle: opts.title,
78
+ endpoint,
79
+ });
80
+ return;
81
+ }
82
+
83
+ const c = colors(opts.color !== false && !process.env.NO_COLOR);
84
+
85
+ const creds = ensureAuthenticated();
86
+ if (isExpired(creds)) {
87
+ error('Your session has expired.');
88
+ hint('Run `sl login` to re-authenticate.');
89
+ process.exit(2);
90
+ }
91
+
92
+ let conversationId = opts.conversationId as string | undefined;
93
+
94
+ // Create or resume conversation — resolve conversation id from the company's membership
95
+ if (!conversationId) {
96
+ const userData = await graphql(Me, undefined, { endpoint });
97
+ const membership = (userData.me?.memberships?.nodes ?? []).find((m) => m?.company?.id === companyId);
98
+ conversationId = membership?.conversation?.id ?? undefined;
99
+ if (!conversationId) {
100
+ error('Could not resolve a conversation for this company.');
101
+ hint('Make sure you are a member of the selected company.');
102
+ process.exit(1);
103
+ }
104
+ info(`${c.dim}Default conversation: ${conversationId}${c.reset}`);
105
+ } else {
106
+ const data = await graphql(Conversation, { id: conversationId }, { endpoint });
107
+ const conversation = data.node?.__typename === 'Conversation' ? data.node : null;
108
+
109
+ if (!conversation) {
110
+ error(`Conversation not found: ${conversationId}`);
111
+ hint('The conversation may have been deleted, or the ID is incorrect.');
112
+ hint('Start a new conversation with: sl chat conversation');
113
+ process.exit(1);
114
+ }
115
+
116
+ info(`${c.dim}Resuming: ${conversation.title ?? conversationId}${c.reset}\n`);
117
+ for (const msg of (conversation.messages?.nodes ?? []).filter((m): m is NonNullable<typeof m> => m != null)) {
118
+ if (msg.role === 'user' && msg.content) {
119
+ info(`${c.green}You:${c.reset} ${msg.content}`);
120
+ } else if (msg.role === 'assistant' && msg.content) {
121
+ info(`${c.cyan}Chat:${c.reset} ${msg.content}`);
122
+ }
123
+ }
124
+ info('');
125
+ }
126
+
127
+ // Subscribe to the conversation event stream via the federation router.
128
+ // The router negotiates with the chat subgraph using the HTTP callback
129
+ // protocol; this client only sees a plain GraphQL-SSE response.
130
+ let connection: ChatConnection;
131
+ try {
132
+ connection = await connectChatStream(endpoint, creds.accessToken, conversationId!, (line) => {
133
+ if (debug) process.stderr.write(`${c.dim}${line}${c.reset}\n`);
134
+ });
135
+ } catch (err) {
136
+ captureException(err, { context: 'chat_stream_connect', conversationId });
137
+ error(`Failed to connect to the chat stream.`);
138
+ hint(`Reason: ${err instanceof Error ? err.message : err}`);
139
+ hint('Check your network connection and try again.');
140
+ hint('If the problem persists, verify your endpoint: sl config show');
141
+ process.exit(3);
142
+ }
143
+
144
+ let streaming = false;
145
+
146
+ const sequenceBuffer = new SequenceBuffer<ChatEvent>({
147
+ onEvent: processEvent,
148
+ onGap(from, to) {
149
+ const count = to - from + 1;
150
+ const range = to > from ? `→${to}` : '';
151
+ process.stderr.write(`${c.yellow} ⚠ ${count} event(s) lost (#${from}${range})${c.reset}\n`);
152
+ },
153
+ });
154
+
155
+ function processEvent(event: ChatEvent) {
156
+ switch (event.__typename) {
157
+ case 'AgentLoopStartedEvent':
158
+ case 'MessageStartedEvent':
159
+ case 'MessageEndedEvent':
160
+ if (streaming) process.stdout.write('\n');
161
+ streaming = false;
162
+ break;
163
+ case 'AgentPickedEvent': {
164
+ if (streaming) process.stdout.write('\n');
165
+ streaming = false;
166
+ const label = `turn ${event.turn ?? '?'}: ${event.agent}`;
167
+ const detail = event.reason ? ` — ${event.reason}` : '';
168
+ info(`${c.yellow}▸ ${label}${c.reset}${c.dim}${detail}${c.reset}`);
169
+ break;
170
+ }
171
+ case 'SupervisorVerdictEvent': {
172
+ if (streaming) process.stdout.write('\n');
173
+ streaming = false;
174
+ const color = event.verdict === 'complete' ? c.green : c.yellow;
175
+ const glyph = event.verdict === 'complete' ? '✓' : '↻';
176
+ const label = `turn ${event.turn ?? '?'}: supervisor → ${event.verdict}`;
177
+ const detail = event.reason ? ` — ${event.reason}` : '';
178
+ info(`${color}${glyph} ${label}${c.reset}${c.dim}${detail}${c.reset}`);
179
+ break;
180
+ }
181
+ case 'MessageChunkEvent':
182
+ if (!streaming) {
183
+ process.stdout.write(`${c.cyan}Chat:${c.reset} `);
184
+ streaming = true;
185
+ }
186
+ process.stdout.write(event.content ?? '');
187
+ break;
188
+ case 'ToolCallEvent':
189
+ if (streaming) process.stdout.write('\n');
190
+ info(`${c.dim} ⚙ ${event.toolName}(${JSON.stringify(event.arguments)})${c.reset}`);
191
+ streaming = false;
192
+ break;
193
+ case 'ToolResultEvent':
194
+ info(`${c.dim} ← ${event.content}${c.reset}`);
195
+ break;
196
+ case 'AgentLoopCompletedEvent':
197
+ if (streaming) {
198
+ process.stdout.write('\n\n');
199
+ streaming = false;
200
+ }
201
+ sequenceBuffer.reset();
202
+ rl.prompt();
203
+ break;
204
+ case 'AgentLoopCancelledEvent':
205
+ if (streaming) process.stdout.write('\n');
206
+ info(`${c.yellow}✖ Cancelled.${c.reset}`);
207
+ streaming = false;
208
+ sequenceBuffer.reset();
209
+ rl.prompt();
210
+ break;
211
+ case 'AgentLoopPausedEvent':
212
+ if (streaming) process.stdout.write('\n');
213
+ streaming = false;
214
+ info(
215
+ `${c.yellow}⏸ Waiting for input. Interactive prompts (${c.reset}${c.dim}--interactive${c.reset}${c.yellow}) are required to respond to tool calls.${c.reset}`,
216
+ );
217
+ sequenceBuffer.reset();
218
+ rl.prompt();
219
+ break;
220
+ case 'AgentLoopResumedEvent':
221
+ // No user-visible noise — the UI effect comes from the next message/tool events.
222
+ break;
223
+ case 'AgentLoopFailedEvent':
224
+ captureException(new Error(`Chat stream error: ${event.message}`), {
225
+ conversationId,
226
+ event,
227
+ });
228
+ if (streaming) process.stdout.write('\n');
229
+ process.stderr.write(`${c.red}Error: ${event.message}${c.reset}\n`);
230
+ streaming = false;
231
+ sequenceBuffer.reset();
232
+ rl.prompt();
233
+ break;
234
+ default: {
235
+ if (streaming) process.stdout.write('\n');
236
+ streaming = false;
237
+ const unknown = event as { __typename?: string };
238
+ process.stderr.write(
239
+ `${c.dim}? unknown event "${unknown.__typename}" — run \`sl update\` to pick up schema changes${c.reset}\n`,
240
+ );
241
+ }
242
+ }
243
+ }
244
+
245
+ let lastAgentLoopId: string | null = null;
246
+ connection.onMessage((event) => {
247
+ if (event.agentLoopId && event.agentLoopId !== lastAgentLoopId) {
248
+ sequenceBuffer.reset();
249
+ lastAgentLoopId = event.agentLoopId;
250
+ }
251
+ sequenceBuffer.push(event);
252
+ });
253
+
254
+ connection.onClose(() => {
255
+ if (streaming) process.stdout.write('\n');
256
+ info(`${c.dim}Connection closed.${c.reset}`);
257
+ process.exit(0);
258
+ });
259
+
260
+ const rl = createInterface({
261
+ input: process.stdin,
262
+ output: process.stdout,
263
+ prompt: `${c.green}You: ${c.reset}`,
264
+ });
265
+
266
+ rl.prompt();
267
+
268
+ rl.on('line', async (line) => {
269
+ const content = line.trim();
270
+ if (!content) {
271
+ rl.prompt();
272
+ return;
273
+ }
274
+
275
+ if (content === '/quit' || content === '/exit') {
276
+ rl.close();
277
+ return;
278
+ }
279
+
280
+ try {
281
+ await graphql(
282
+ SendMessage,
283
+ {
284
+ input: {
285
+ conversationId: conversationId!,
286
+ content,
287
+ },
288
+ },
289
+ { endpoint },
290
+ );
291
+ } catch {
292
+ process.stderr.write(`${c.red}Failed to send message.${c.reset}\n`);
293
+ rl.prompt();
294
+ }
295
+ });
296
+
297
+ rl.on('close', () => {
298
+ connection.close();
299
+ info(`${c.dim}Goodbye!${c.reset}`);
300
+ process.exit(0);
301
+ });
302
+ });