@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/src/index.ts ADDED
@@ -0,0 +1,176 @@
1
+ import fs from 'node:fs';
2
+ import { Command } from 'commander';
3
+
4
+ import { chatCommand } from './commands/chat/chat.ts';
5
+ import { configCommand } from './commands/config.ts';
6
+ import { buildServiceCommands } from './commands/dynamic.ts';
7
+ import { loginCommand } from './commands/login.ts';
8
+ import { logoutCommand } from './commands/logout.ts';
9
+ import { offerCommand } from './commands/offer.ts';
10
+ import { switchCommand } from './commands/switch.ts';
11
+ import { tokenCommand } from './commands/token.ts';
12
+ import { whoamiCommand } from './commands/whoami.ts';
13
+ import { getIntrospectedSchema, refreshSchema } from './graphql/introspection.ts';
14
+ import { error, hint, info } from './lib/output.ts';
15
+ import { captureException, flushSentry, initSentry } from './lib/sentry.ts';
16
+ import { checkForUpdates } from './lib/version-check.ts';
17
+
18
+ initSentry();
19
+
20
+ // ── Colored help output ──
21
+
22
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
23
+ const ansi = {
24
+ reset: '\x1b[0m',
25
+ bold: '\x1b[1m',
26
+ dim: '\x1b[2m',
27
+ cyan: '\x1b[36m',
28
+ yellow: '\x1b[33m',
29
+ green: '\x1b[32m',
30
+ };
31
+
32
+ function colorizeHelp(text: string): string {
33
+ if (!useColor) return text;
34
+ return text.replace(
35
+ /^(Usage|Options|Commands|Arguments|Quick start|Services|Examples|Queries|Mutations):(.*)$/gm,
36
+ `${ansi.cyan}${ansi.bold}$1:$2${ansi.reset}`,
37
+ );
38
+ }
39
+
40
+ const colorOutput = {
41
+ writeOut: (str: string) => process.stdout.write(colorizeHelp(str)),
42
+ writeErr: (str: string) => process.stderr.write(colorizeHelp(str)),
43
+ };
44
+
45
+ function applyColorToAllCommands(cmd: Command): void {
46
+ cmd.configureOutput(colorOutput);
47
+ for (const sub of cmd.commands) {
48
+ applyColorToAllCommands(sub as Command);
49
+ }
50
+ }
51
+
52
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
53
+
54
+ const BASE_DESCRIPTION =
55
+ 'Sortlist CLI — query and manage the Sortlist platform from your terminal\n\n' +
56
+ 'Quick start:\n' +
57
+ ' sl login Authenticate with your Sortlist account\n' +
58
+ " sl whoami Check who you're logged in as";
59
+
60
+ function buildRootDescription(services: Map<string, { exampleQuery: string | null; description: string }>): string {
61
+ const parts = [BASE_DESCRIPTION];
62
+
63
+ if (services.size > 0) {
64
+ const entries = [...services.entries()];
65
+ const labels = entries.map(([name]) => `sl ${name} <operation>`);
66
+ const pad = Math.max(...labels.map((l) => l.length));
67
+
68
+ parts.push(
69
+ 'Services:\n' + entries.map(([name, info], i) => ` ${labels[i].padEnd(pad)} ${info.description}`).join('\n'),
70
+ );
71
+
72
+ const examples: string[] = [];
73
+ for (const [name, info] of entries) {
74
+ if (info.exampleQuery) examples.push(` sl ${name} ${info.exampleQuery}`);
75
+ if (examples.length >= 2) break;
76
+ }
77
+ examples.push(' sl config show View current endpoint and agency context');
78
+ parts.push('Examples:\n' + examples.join('\n'));
79
+ }
80
+
81
+ return parts.join('\n\n');
82
+ }
83
+
84
+ const program = new Command()
85
+ .name('sl')
86
+ .configureOutput({
87
+ writeOut: (str) => process.stdout.write(colorizeHelp(str)),
88
+ writeErr: (str) => process.stderr.write(colorizeHelp(str)),
89
+ })
90
+ .description(BASE_DESCRIPTION)
91
+ .version(pkg.version)
92
+ .option('--endpoint <url>', 'Override the federation endpoint URL')
93
+ .option('--json', 'Output as JSON (auto-enabled when stdout is not a TTY)')
94
+ .option('--no-color', 'Disable colored output');
95
+
96
+ // Auth commands (hand-written — interactive flows)
97
+ program.addCommand(loginCommand);
98
+ program.addCommand(logoutCommand);
99
+ program.addCommand(whoamiCommand);
100
+ program.addCommand(switchCommand);
101
+ program.addCommand(tokenCommand);
102
+ program.addCommand(configCommand);
103
+ program.addCommand(offerCommand);
104
+
105
+ // Schema refresh command
106
+ const schemaCommand = new Command('schema').description('Manage the cached GraphQL schema');
107
+
108
+ schemaCommand
109
+ .command('refresh')
110
+ .description('Force-refresh the cached schema from the federation endpoint')
111
+ .action(async function (this: Command) {
112
+ const opts = this.optsWithGlobals();
113
+ try {
114
+ await refreshSchema(opts.endpoint);
115
+ info('Schema refreshed successfully.');
116
+ } catch (err) {
117
+ error(`Failed to refresh schema: ${(err as Error).message}`);
118
+ hint('Check your network connection and endpoint: sl config show');
119
+ process.exit(1);
120
+ }
121
+ });
122
+
123
+ program.addCommand(schemaCommand);
124
+
125
+ // Parse --endpoint early so introspection uses the right URL
126
+ const endpointIdx = process.argv.indexOf('--endpoint');
127
+ const endpointOverride = endpointIdx !== -1 ? process.argv[endpointIdx + 1] : undefined;
128
+
129
+ // Dynamically register subgraph commands from introspected schema
130
+ try {
131
+ const { schema, fieldServices } = await getIntrospectedSchema(endpointOverride);
132
+ const serviceCommands = buildServiceCommands(schema, fieldServices);
133
+
134
+ const servicesForHelp = new Map<string, { exampleQuery: string | null; description: string }>();
135
+
136
+ for (const [name, entry] of serviceCommands) {
137
+ const cmd = entry.command;
138
+ // Chat: replace the generated basic `conversation` command with the interactive one
139
+ if (name === 'chat') {
140
+ const chatCmds = cmd.commands as unknown as Command[];
141
+ const convIdx = chatCmds.findIndex((c) => c.name() === 'conversation');
142
+ if (convIdx !== -1) chatCmds.splice(convIdx, 1);
143
+ cmd.addCommand(chatCommand);
144
+ }
145
+ program.addCommand(cmd);
146
+ servicesForHelp.set(name, {
147
+ exampleQuery: entry.exampleQuery,
148
+ description: cmd.description(),
149
+ });
150
+ }
151
+
152
+ program.description(buildRootDescription(servicesForHelp));
153
+ } catch (err) {
154
+ // Schema fetch failed — still allow non-subgraph commands (login, config, etc.)
155
+ const message = (err as Error).message;
156
+ if (!process.argv.some((a) => ['login', 'logout', 'config', 'token', 'whoami', 'switch', 'schema'].includes(a))) {
157
+ error(`Could not fetch schema: ${message}`);
158
+ hint('Check your network connection and endpoint: sl config show');
159
+ hint('You can still use: sl login, sl config, sl schema refresh');
160
+ process.exit(1);
161
+ }
162
+ }
163
+
164
+ applyColorToAllCommands(program);
165
+
166
+ await checkForUpdates();
167
+
168
+ try {
169
+ await program.parseAsync(process.argv);
170
+ } catch (err) {
171
+ captureException(err);
172
+ await flushSentry();
173
+ throw err;
174
+ }
175
+
176
+ await flushSentry();
@@ -0,0 +1,58 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+
5
+ import { error, hint } from './output.ts';
6
+
7
+ const CREDENTIALS_PATH = path.join(os.homedir(), '.sortlist', 'credentials.json');
8
+
9
+ export interface Credentials {
10
+ accessToken: string;
11
+ refreshToken: string;
12
+ idToken: string;
13
+ expiresAt: number;
14
+ }
15
+
16
+ function ensureDir(): void {
17
+ const dir = path.dirname(CREDENTIALS_PATH);
18
+ if (!fs.existsSync(dir)) {
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ }
21
+ }
22
+
23
+ export function saveCredentials(creds: Credentials): void {
24
+ ensureDir();
25
+ fs.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + '\n', { mode: 0o600 });
26
+ }
27
+
28
+ export function loadCredentials(): Credentials | null {
29
+ try {
30
+ const raw = fs.readFileSync(CREDENTIALS_PATH, 'utf-8');
31
+ return JSON.parse(raw) as Credentials;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ export function clearCredentials(): void {
38
+ try {
39
+ fs.unlinkSync(CREDENTIALS_PATH);
40
+ } catch {
41
+ // already gone
42
+ }
43
+ }
44
+
45
+ export function isExpired(creds: Credentials): boolean {
46
+ // 60s buffer before actual expiry
47
+ return Date.now() >= (creds.expiresAt - 60) * 1000;
48
+ }
49
+
50
+ export function ensureAuthenticated(): Credentials {
51
+ const creds = loadCredentials();
52
+ if (!creds) {
53
+ error('You are not logged in.');
54
+ hint('Run `sl login` to authenticate with your Sortlist account.');
55
+ process.exit(2);
56
+ }
57
+ return creds;
58
+ }
@@ -0,0 +1,6 @@
1
+ import { exec } from 'node:child_process';
2
+
3
+ export function openBrowser(url: string): void {
4
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
5
+ exec(`${cmd} "${url}"`);
6
+ }
@@ -0,0 +1,35 @@
1
+ import { graphql } from '../graphql/client.ts';
2
+ import { Me } from '../graphql/operations/common.ts';
3
+ import { type UserContext } from './config.ts';
4
+
5
+ /**
6
+ * Resolve the active company id for a request.
7
+ *
8
+ * Resolution order:
9
+ * 1. --company-id flag
10
+ * 2. --company-slug flag → resolved via me.companies
11
+ * 3. config.companyId
12
+ * 4. config.companySlug → resolved via me.companies
13
+ * 5. user has exactly one company → that one
14
+ */
15
+ export async function resolveCompanyId(opts: {
16
+ companyId?: string | undefined;
17
+ companySlug?: string | undefined;
18
+ ctx: UserContext | undefined;
19
+ endpoint?: string | undefined;
20
+ }): Promise<string | undefined> {
21
+ if (opts.companyId) return opts.companyId;
22
+
23
+ const slug = opts.companySlug || opts.ctx?.companySlug;
24
+
25
+ if (!slug && opts.ctx?.companyId) return opts.ctx.companyId;
26
+
27
+ const data = await graphql(Me, undefined, { endpoint: opts.endpoint });
28
+ const companies = (data.me?.companies?.nodes ?? []).filter(
29
+ (c): c is { id: string; name: string; slug: string } => c != null,
30
+ );
31
+
32
+ if (slug) return companies.find((c) => c.slug === slug)?.id;
33
+ if (companies.length === 1) return companies[0].id;
34
+ return undefined;
35
+ }
@@ -0,0 +1,73 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+
5
+ const SORTLIST_DIR = path.join(os.homedir(), '.sortlist');
6
+ const CONFIG_PATH = path.join(SORTLIST_DIR, 'config.json');
7
+
8
+ export interface CliConfig {
9
+ endpoint: string;
10
+ oauthId?: string;
11
+ companyId?: string;
12
+ companySlug?: string;
13
+ companyName?: string;
14
+ }
15
+
16
+ const DEFAULT_CONFIG: CliConfig = {
17
+ endpoint: 'https://federation.sortlist.com/graphql',
18
+ };
19
+
20
+ function ensureDir(): void {
21
+ if (!fs.existsSync(SORTLIST_DIR)) {
22
+ fs.mkdirSync(SORTLIST_DIR, { recursive: true });
23
+ }
24
+ }
25
+
26
+ export function loadConfig(): CliConfig {
27
+ try {
28
+ const raw = fs.readFileSync(CONFIG_PATH, 'utf-8');
29
+ return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
30
+ } catch {
31
+ return { ...DEFAULT_CONFIG };
32
+ }
33
+ }
34
+
35
+ export function saveConfig(config: Partial<CliConfig>): void {
36
+ ensureDir();
37
+ const current = loadConfig();
38
+ const merged = { ...current, ...config };
39
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(merged, null, 2) + '\n');
40
+ }
41
+
42
+ export function resetConfig(): void {
43
+ try {
44
+ fs.unlinkSync(CONFIG_PATH);
45
+ } catch {
46
+ // already gone
47
+ }
48
+ }
49
+
50
+ export function getEndpoint(override?: string): string {
51
+ if (override) return override;
52
+ if (process.env.SL_ENDPOINT) return process.env.SL_ENDPOINT;
53
+ return loadConfig().endpoint;
54
+ }
55
+
56
+ /**
57
+ * Context variables that are auto-injected into generated commands.
58
+ * These are read from config and can be overridden via CLI flags.
59
+ */
60
+ export interface UserContext {
61
+ oauthId?: string;
62
+ companyId?: string;
63
+ companySlug?: string;
64
+ }
65
+
66
+ export function getUserContext(): UserContext {
67
+ const config = loadConfig();
68
+ return {
69
+ oauthId: config.oauthId,
70
+ companyId: config.companyId,
71
+ companySlug: config.companySlug,
72
+ };
73
+ }
package/src/lib/env.ts ADDED
@@ -0,0 +1,10 @@
1
+ import fs from 'node:fs';
2
+
3
+ /**
4
+ * Whether the CLI is running from the platform monorepo (dev checkout)
5
+ * vs a globally-installed npm package.
6
+ *
7
+ * Published builds contain a `.published` sentinel file stamped by CI.
8
+ * Its absence means we're running from source.
9
+ */
10
+ export const isLocalDev = !fs.existsSync(new URL('../../.published', import.meta.url));
@@ -0,0 +1,84 @@
1
+ // ── Color helpers (respect --no-color / NO_COLOR) ──
2
+
3
+ function colorEnabled(): boolean {
4
+ return process.stderr.isTTY === true && !process.env.NO_COLOR;
5
+ }
6
+
7
+ const ansi = {
8
+ reset: '\x1b[0m',
9
+ dim: '\x1b[2m',
10
+ red: '\x1b[31m',
11
+ green: '\x1b[32m',
12
+ yellow: '\x1b[33m',
13
+ cyan: '\x1b[36m',
14
+ };
15
+
16
+ function c(code: keyof typeof ansi, text: string): string {
17
+ if (!colorEnabled()) return text;
18
+ return `${ansi[code]}${text}${ansi.reset}`;
19
+ }
20
+
21
+ // ── JSON mode detection ──
22
+
23
+ export function isJsonMode(options: { json?: boolean }): boolean {
24
+ if (options.json) return true;
25
+ return !process.stdout.isTTY;
26
+ }
27
+
28
+ export function printJson(data: unknown): void {
29
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
30
+ }
31
+
32
+ // ── Table output (human-readable, no box-drawing characters) ──
33
+
34
+ export function printTable(headers: string[], rows: string[][]): void {
35
+ const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
36
+
37
+ const separator = colWidths.map((w) => '-'.repeat(w + 2)).join('+');
38
+ const formatRow = (row: string[]) => row.map((cell, i) => ` ${(cell ?? '').padEnd(colWidths[i])} `).join('|');
39
+
40
+ process.stdout.write(formatRow(headers) + '\n');
41
+ process.stdout.write(separator + '\n');
42
+ for (const row of rows) {
43
+ process.stdout.write(formatRow(row) + '\n');
44
+ }
45
+ }
46
+
47
+ // ── Message helpers ──
48
+ // Every function uses a text prefix so status is conveyed independent of color.
49
+ // Color is enhancement only — never the sole status indicator.
50
+
51
+ /** General informational message (no prefix). */
52
+ export function info(msg: string): void {
53
+ process.stderr.write(`${msg}\n`);
54
+ }
55
+
56
+ /** Success: confirms an outcome. Use after a completed action. */
57
+ export function success(msg: string): void {
58
+ process.stderr.write(`${c('green', '\u2713')} ${msg}\n`);
59
+ }
60
+
61
+ /** Warning: something is off but not fatal. */
62
+ export function warn(msg: string): void {
63
+ process.stderr.write(`${c('yellow', '\u26A0')} ${msg}\n`);
64
+ }
65
+
66
+ /** Error: state what failed, why, and what to do next. */
67
+ export function error(msg: string): void {
68
+ process.stderr.write(`${c('red', '\u2717')} Error: ${msg}\n`);
69
+ }
70
+
71
+ /** Hint: suggest a next step or recovery action. Indented for readability. */
72
+ export function hint(msg: string): void {
73
+ process.stderr.write(`${c('dim', ' ' + msg)}\n`);
74
+ }
75
+
76
+ /** Dim text (e.g. secondary details, IDs). */
77
+ export function dim(msg: string): void {
78
+ process.stderr.write(`${c('dim', msg)}\n`);
79
+ }
80
+
81
+ /** Section heading for grouping output. */
82
+ export function heading(msg: string): void {
83
+ process.stderr.write(`\n${c('cyan', msg)}\n`);
84
+ }
@@ -0,0 +1,8 @@
1
+ import fs from 'fs';
2
+
3
+ export function parseRawData(value: string): unknown {
4
+ if (value.startsWith('@')) {
5
+ return JSON.parse(fs.readFileSync(value.slice(1), 'utf-8'));
6
+ }
7
+ return JSON.parse(value);
8
+ }
@@ -0,0 +1,77 @@
1
+ import fs from 'node:fs';
2
+ import * as Sentry from '@sentry/node';
3
+
4
+ import { isLocalDev } from './env.ts';
5
+
6
+ const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'));
7
+
8
+ const SENTRY_DSN = 'https://306d2e4389b8baa0bf14e587c2ceff04@o27611.ingest.us.sentry.io/4511229468409856';
9
+ const SENTRY_ENVIRONMENT = process.env.SL_SENTRY_ENV ?? (isLocalDev ? 'development' : 'production');
10
+
11
+ const IGNORED_ERRORS = [
12
+ /Network Error/i,
13
+ /Failed to fetch/i,
14
+ /fetch failed/i,
15
+ /ECONNREFUSED/i,
16
+ /ENOTFOUND/i,
17
+ /ETIMEDOUT/i,
18
+ /Request aborted/i,
19
+ ];
20
+
21
+ function isIgnoredError(message: string): boolean {
22
+ return IGNORED_ERRORS.some((pattern) =>
23
+ typeof pattern === 'string' ? message.includes(pattern) : pattern.test(message),
24
+ );
25
+ }
26
+
27
+ export function initSentry(): void {
28
+ if (isLocalDev) {
29
+ return;
30
+ }
31
+
32
+ Sentry.init({
33
+ dsn: SENTRY_DSN,
34
+ environment: SENTRY_ENVIRONMENT,
35
+ release: `${pkg.name}@${pkg.version}`,
36
+ tracesSampleRate: 0,
37
+ maxBreadcrumbs: 50,
38
+ attachStacktrace: true,
39
+ beforeSend(event) {
40
+ const message = event.exception?.values?.[0]?.value ?? '';
41
+ if (isIgnoredError(message)) {
42
+ return null;
43
+ }
44
+ return event;
45
+ },
46
+ });
47
+
48
+ Sentry.setTag('cli_version', pkg.version);
49
+ }
50
+
51
+ export function captureException(error: unknown, extra?: Record<string, unknown>): void {
52
+ if (isLocalDev) {
53
+ return;
54
+ }
55
+ Sentry.captureException(error, extra ? { extra } : undefined);
56
+ }
57
+
58
+ export function setUser(user: { id?: string; email?: string }): void {
59
+ if (isLocalDev) {
60
+ return;
61
+ }
62
+ Sentry.setUser(user);
63
+ }
64
+
65
+ export function addBreadcrumb(breadcrumb: Sentry.Breadcrumb): void {
66
+ if (isLocalDev) {
67
+ return;
68
+ }
69
+ Sentry.addBreadcrumb(breadcrumb);
70
+ }
71
+
72
+ export async function flushSentry(timeout = 2000): Promise<void> {
73
+ if (isLocalDev) {
74
+ return;
75
+ }
76
+ await Sentry.flush(timeout);
77
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Reorders out-of-sequence streaming events before they reach the event handler.
3
+ *
4
+ * Every subscription event carries an `agentLoopSequence` (monotonic integer starting
5
+ * at 1) and an `agentLoopId` (UUID constant for a single outer agent loop run). When
6
+ * an event arrives with a sequence higher than expected, it is buffered. If the
7
+ * expected event arrives within the timeout, all buffered events are flushed in order.
8
+ * If the timeout expires, the gap is marked as unrecoverable and buffered events are
9
+ * flushed anyway.
10
+ */
11
+
12
+ const SEQUENCE_WAIT_MS = 1500;
13
+
14
+ export interface SequencedEvent {
15
+ agentLoopSequence?: number | null;
16
+ agentLoopId?: string | null;
17
+ }
18
+
19
+ export interface SequenceBufferOptions<T extends SequencedEvent> {
20
+ onEvent: (event: T) => void;
21
+ onGap: (from: number, to: number) => void;
22
+ }
23
+
24
+ export class SequenceBuffer<T extends SequencedEvent> {
25
+ private buffer = new Map<number, T>();
26
+ private expected = 1;
27
+ private timer: ReturnType<typeof setTimeout> | null = null;
28
+ private onEvent: (event: T) => void;
29
+ private onGap: (from: number, to: number) => void;
30
+
31
+ constructor({ onEvent, onGap }: SequenceBufferOptions<T>) {
32
+ this.onEvent = onEvent;
33
+ this.onGap = onGap;
34
+ }
35
+
36
+ push(event: T): void {
37
+ const seq = event.agentLoopSequence;
38
+
39
+ // No sequence info — pass through (old server or non-sequenced event)
40
+ if (seq == null) {
41
+ this.onEvent(event);
42
+ return;
43
+ }
44
+
45
+ if (seq === this.expected) {
46
+ this.clearTimer();
47
+ this.onEvent(event);
48
+ this.expected++;
49
+ this.flush();
50
+ } else if (seq > this.expected) {
51
+ this.buffer.set(seq, event);
52
+ this.startTimer();
53
+ }
54
+ // seq < expected: duplicate, ignore
55
+ }
56
+
57
+ reset(): void {
58
+ this.buffer.clear();
59
+ this.expected = 1;
60
+ this.clearTimer();
61
+ }
62
+
63
+ private flush(): void {
64
+ while (this.buffer.has(this.expected)) {
65
+ const event = this.buffer.get(this.expected)!;
66
+ this.buffer.delete(this.expected);
67
+ this.onEvent(event);
68
+ this.expected++;
69
+ }
70
+ if (this.buffer.size > 0) {
71
+ this.startTimer();
72
+ } else {
73
+ this.clearTimer();
74
+ }
75
+ }
76
+
77
+ private startTimer(): void {
78
+ if (this.timer) return;
79
+ this.timer = setTimeout(() => {
80
+ this.timer = null;
81
+ const missing = this.expected;
82
+ const nextAvailable = Math.min(...this.buffer.keys());
83
+ this.onGap(missing, nextAvailable - 1);
84
+ this.expected = nextAvailable;
85
+ this.flush();
86
+ }, SEQUENCE_WAIT_MS);
87
+ }
88
+
89
+ private clearTimer(): void {
90
+ if (this.timer) {
91
+ clearTimeout(this.timer);
92
+ this.timer = null;
93
+ }
94
+ }
95
+ }