starcite 0.0.6 → 0.0.7

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/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import { z as z2 } from "zod";
13
13
  // package.json
14
14
  var package_default = {
15
15
  name: "starcite",
16
- version: "0.0.6",
16
+ version: "0.0.7",
17
17
  description: "CLI for Starcite",
18
18
  license: "Apache-2.0",
19
19
  homepage: "https://starcite.ai",
@@ -56,7 +56,7 @@ var package_default = {
56
56
  },
57
57
  dependencies: {
58
58
  "@clack/prompts": "^1.0.1",
59
- "@starcite/sdk": "^0.0.6",
59
+ "@starcite/sdk": "^0.0.7",
60
60
  commander: "^13.1.0",
61
61
  conf: "^15.1.0",
62
62
  consola: "^3.4.2",
@@ -627,6 +627,11 @@ var defaultCommandRunner = (command, args, options) => new Promise((resolve2) =>
627
627
 
628
628
  // src/cli.ts
629
629
  var defaultLogger = createConsola();
630
+ var defaultStdout = {
631
+ write(message) {
632
+ process.stdout.write(message);
633
+ }
634
+ };
630
635
  var cliVersion = package_default.version;
631
636
  var nonNegativeIntegerSchema = z2.coerce.number().int().nonnegative();
632
637
  var positiveIntegerSchema = z2.coerce.number().int().positive();
@@ -853,6 +858,14 @@ function toApiBaseUrlForContext(baseUrl) {
853
858
  const normalized = parsed.toString().replace(TRAILING_SLASHES_REGEX, "");
854
859
  return normalized.endsWith("/v1") ? normalized : `${normalized}/v1`;
855
860
  }
861
+ function writeJsonOutput(stdout, value, pretty = false) {
862
+ const serialized = JSON.stringify(value, null, pretty ? 2 : void 0);
863
+ if (serialized === void 0) {
864
+ throw new Error("Failed to serialize JSON output");
865
+ }
866
+ stdout.write(`${serialized}
867
+ `);
868
+ }
856
869
  async function resolveSession(client, apiKey, sessionId) {
857
870
  if (!apiKey) {
858
871
  throw new InvalidArgumentError(
@@ -889,6 +902,7 @@ function resolveCreateIdentity(apiKey, agentId = DEFAULT_CREATE_AGENT_ID) {
889
902
  var StarciteCliApp = class {
890
903
  createClient;
891
904
  logger;
905
+ stdout;
892
906
  prompt;
893
907
  runCommand;
894
908
  constructor(deps = {}) {
@@ -897,12 +911,14 @@ var StarciteCliApp = class {
897
911
  apiKey
898
912
  }));
899
913
  this.logger = deps.logger ?? defaultLogger;
914
+ this.stdout = deps.stdout ?? defaultStdout;
900
915
  this.prompt = deps.prompt ?? createDefaultPrompt();
901
916
  this.runCommand = deps.runCommand ?? defaultCommandRunner;
902
917
  }
903
918
  buildProgram() {
904
919
  const createClient = this.createClient;
905
920
  const logger = this.logger;
921
+ const stdout = this.stdout;
906
922
  const prompt = this.prompt;
907
923
  const runCommand = this.runCommand;
908
924
  const program = new Command();
@@ -938,7 +954,7 @@ var StarciteCliApp = class {
938
954
  })
939
955
  ).addCommand(
940
956
  new Command("show").description("Show current configuration").action(async function() {
941
- const { baseUrl, store } = await resolveGlobalOptions(this);
957
+ const { baseUrl, json, store } = await resolveGlobalOptions(this);
942
958
  const config = await store.readConfig();
943
959
  const apiKey = await store.readApiKey();
944
960
  const fromEnv = trimString2(process.env.STARCITE_API_KEY);
@@ -948,19 +964,18 @@ var StarciteCliApp = class {
948
964
  } else if (apiKey) {
949
965
  apiKeySource = "stored";
950
966
  }
951
- logger.info(
952
- JSON.stringify(
953
- {
954
- endpoint: config.baseUrl ?? baseUrl,
955
- producerId: config.producerId ?? null,
956
- apiKey: apiKey ? "***" : null,
957
- apiKeySource,
958
- configDir: store.directory
959
- },
960
- null,
961
- 2
962
- )
963
- );
967
+ const output = {
968
+ endpoint: config.baseUrl ?? baseUrl,
969
+ producerId: config.producerId ?? null,
970
+ apiKey: apiKey ? "***" : null,
971
+ apiKeySource,
972
+ configDir: store.directory
973
+ };
974
+ if (json) {
975
+ writeJsonOutput(stdout, output, true);
976
+ return;
977
+ }
978
+ logger.info(JSON.stringify(output, null, 2));
964
979
  })
965
980
  );
966
981
  program.command("sessions").description("Manage sessions").addCommand(
@@ -983,7 +998,7 @@ var StarciteCliApp = class {
983
998
  metadata
984
999
  });
985
1000
  if (json) {
986
- logger.info(JSON.stringify(page, null, 2));
1001
+ writeJsonOutput(stdout, page, true);
987
1002
  return;
988
1003
  }
989
1004
  if (page.sessions.length === 0) {
@@ -1042,9 +1057,7 @@ var StarciteCliApp = class {
1042
1057
  metadata
1043
1058
  });
1044
1059
  if (json) {
1045
- logger.info(
1046
- JSON.stringify(session.record ?? { id: session.id }, null, 2)
1047
- );
1060
+ writeJsonOutput(stdout, session.record ?? { id: session.id }, true);
1048
1061
  return;
1049
1062
  }
1050
1063
  logger.info(session.id);
@@ -1105,7 +1118,7 @@ var StarciteCliApp = class {
1105
1118
  return appendResponse;
1106
1119
  });
1107
1120
  if (json) {
1108
- logger.info(JSON.stringify(response, null, 2));
1121
+ writeJsonOutput(stdout, response, true);
1109
1122
  return;
1110
1123
  }
1111
1124
  logger.info(`seq=${response.seq} deduped=${response.deduped}`);
@@ -1129,30 +1142,27 @@ var StarciteCliApp = class {
1129
1142
  process.once("SIGINT", onSigint);
1130
1143
  try {
1131
1144
  let emitted = 0;
1132
- await session.tail(
1133
- (event) => {
1134
- if (options.limit !== void 0 && emitted >= options.limit) {
1135
- abortController.abort();
1136
- return;
1137
- }
1138
- if (json) {
1139
- logger.info(JSON.stringify(event));
1140
- } else {
1141
- logger.info(formatTailEvent(event));
1142
- }
1143
- emitted += 1;
1144
- if (options.limit !== void 0 && emitted >= options.limit) {
1145
- abortController.abort();
1146
- }
1147
- },
1148
- {
1149
- cursor: options.cursor ?? 0,
1150
- batchSize: DEFAULT_TAIL_BATCH_SIZE,
1151
- agent: options.agent,
1152
- follow: options.follow,
1153
- signal: abortController.signal
1145
+ for await (const { event } of session.tail({
1146
+ cursor: options.cursor ?? 0,
1147
+ batchSize: DEFAULT_TAIL_BATCH_SIZE,
1148
+ agent: options.agent,
1149
+ follow: options.follow,
1150
+ signal: abortController.signal
1151
+ })) {
1152
+ if (options.limit !== void 0 && emitted >= options.limit) {
1153
+ abortController.abort();
1154
+ break;
1154
1155
  }
1155
- );
1156
+ if (json) {
1157
+ writeJsonOutput(stdout, event);
1158
+ } else {
1159
+ logger.info(formatTailEvent(event));
1160
+ }
1161
+ emitted += 1;
1162
+ if (options.limit !== void 0 && emitted >= options.limit) {
1163
+ abortController.abort();
1164
+ }
1165
+ }
1156
1166
  } finally {
1157
1167
  process.removeListener("SIGINT", onSigint);
1158
1168
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../package.json","../src/store.ts","../src/up.ts","../src/index.ts"],"sourcesContent":["import {\n Starcite,\n StarciteApiError,\n StarciteIdentity,\n type TailEvent,\n} from \"@starcite/sdk\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { createConsola } from \"consola\";\nimport { z } from \"zod\";\nimport starciteCliPackage from \"../package.json\";\nimport {\n buildSeqContextKey,\n resolveConfigDir,\n type StarciteCliConfig,\n StarciteCliStore,\n} from \"./store\";\nimport {\n type CommandRunner,\n createDefaultPrompt,\n DEFAULT_API_PORT,\n defaultCommandRunner,\n type PromptAdapter,\n parsePortOption,\n runDownWizard,\n runUpWizard,\n} from \"./up\";\n\ninterface GlobalOptions {\n baseUrl?: string;\n configDir?: string;\n token?: string;\n json: boolean;\n}\n\ninterface ResolvedGlobalOptions {\n baseUrl: string;\n apiKey?: string;\n json: boolean;\n store: StarciteCliStore;\n}\n\nexport interface LoggerLike {\n info(message: string): void;\n error(message: string): void;\n}\n\ninterface CliDependencies {\n createClient?: (baseUrl: string, apiKey?: string) => Starcite;\n logger?: LoggerLike;\n prompt?: PromptAdapter;\n runCommand?: CommandRunner;\n}\n\ntype CliJsonObject = Record<string, unknown>;\n\nconst defaultLogger: LoggerLike = createConsola();\nconst cliVersion = starciteCliPackage.version;\n\nconst nonNegativeIntegerSchema = z.coerce.number().int().nonnegative();\nconst positiveIntegerSchema = z.coerce.number().int().positive();\nconst jsonObjectSchema = z.record(z.unknown());\nconst GlobalOptionsSchema = z.object({\n baseUrl: z.string().optional(),\n configDir: z.string().optional(),\n token: z.string().optional(),\n json: z.boolean().optional().default(false),\n});\nconst TRAILING_SLASHES_REGEX = /\\/+$/;\nconst DEFAULT_TAIL_BATCH_SIZE = 256;\nconst DEFAULT_CREATE_AGENT_ID = \"starcite-cli\";\n\ntype ConfigSetKey = \"endpoint\" | \"producer-id\" | \"api-key\";\n\ninterface AppendCommandOptions {\n agent?: string;\n text?: string;\n type: string;\n source?: string;\n producerId?: string;\n producerSeq?: number;\n actor?: string;\n payload?: string;\n metadata?: string;\n refs?: string;\n idempotencyKey?: string;\n expectedSeq?: number;\n}\n\ntype ResolvedAppendMode =\n | { kind: \"high-level\"; agent: string; text: string }\n | { kind: \"raw\"; actor: string; payload: string };\n\nfunction parseNonNegativeInteger(value: string, optionName: string): number {\n const parsed = nonNegativeIntegerSchema.safeParse(value);\n\n if (!parsed.success) {\n throw new InvalidArgumentError(\n `${optionName} must be a non-negative integer`\n );\n }\n\n return parsed.data;\n}\n\nfunction parsePositiveInteger(value: string, optionName: string): number {\n const parsed = positiveIntegerSchema.safeParse(value);\n\n if (!parsed.success) {\n throw new InvalidArgumentError(`${optionName} must be a positive integer`);\n }\n\n return parsed.data;\n}\n\nfunction parsePort(value: string, optionName: string): number {\n return parsePortOption(value, optionName);\n}\n\nfunction parseEndpoint(value: string, optionName: string): string {\n const endpoint = trimString(value);\n if (!endpoint) {\n throw new InvalidArgumentError(`${optionName} cannot be empty`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(endpoint);\n } catch {\n throw new InvalidArgumentError(`${optionName} must be a valid URL`);\n }\n\n if (!(parsed.protocol === \"http:\" || parsed.protocol === \"https:\")) {\n throw new InvalidArgumentError(\n `${optionName} must use http:// or https://`\n );\n }\n\n return endpoint.replace(TRAILING_SLASHES_REGEX, \"\");\n}\n\nfunction parseConfigSetKey(value: string): ConfigSetKey {\n const normalized = value.trim().toLowerCase();\n\n if ([\"endpoint\", \"base-url\", \"base_url\"].includes(normalized)) {\n return \"endpoint\";\n }\n\n if ([\"producer-id\", \"producer_id\"].includes(normalized)) {\n return \"producer-id\";\n }\n\n if ([\"api-key\", \"api_key\"].includes(normalized)) {\n return \"api-key\";\n }\n\n throw new InvalidArgumentError(\n \"config key must be one of: endpoint, producer-id, api-key\"\n );\n}\n\nfunction parseJsonObject(value: string, optionName: string): CliJsonObject {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new InvalidArgumentError(`${optionName} must be valid JSON`);\n }\n\n const result = jsonObjectSchema.safeParse(parsed);\n if (!result.success) {\n throw new InvalidArgumentError(`${optionName} must be a JSON object`);\n }\n\n return result.data;\n}\n\nfunction parseSessionMetadataFilters(value: string): Record<string, string> {\n const parsed = parseJsonObject(value, \"--metadata\");\n const filters: Record<string, string> = {};\n\n for (const [key, rawValue] of Object.entries(parsed)) {\n if (key.trim().length === 0) {\n throw new InvalidArgumentError(\"--metadata keys must be non-empty\");\n }\n\n if (typeof rawValue !== \"string\") {\n throw new InvalidArgumentError(\"--metadata values must be strings\");\n }\n\n filters[key] = rawValue;\n }\n\n return filters;\n}\n\nfunction getGlobalOptions(command: Command): GlobalOptions {\n const parsed = GlobalOptionsSchema.safeParse(command.optsWithGlobals());\n if (!parsed.success) {\n const issue = parsed.error.issues[0]?.message ?? \"invalid global options\";\n throw new InvalidArgumentError(`Failed to parse global options: ${issue}`);\n }\n\n return parsed.data;\n}\n\nfunction trimString(value?: string): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction resolveBaseUrl(\n config: StarciteCliConfig,\n options: GlobalOptions\n): string {\n const defaultBaseUrl = `http://localhost:${DEFAULT_API_PORT}`;\n return (\n trimString(options.baseUrl) ??\n trimString(process.env.STARCITE_BASE_URL) ??\n trimString(config.baseUrl) ??\n defaultBaseUrl\n );\n}\n\nasync function resolveGlobalOptions(\n command: Command\n): Promise<ResolvedGlobalOptions> {\n const options = getGlobalOptions(command);\n const configDir = resolveConfigDir(options.configDir);\n const store = new StarciteCliStore(configDir);\n const config = await store.readConfig();\n const apiKey = trimString(options.token) ?? (await store.readApiKey());\n\n return {\n baseUrl: resolveBaseUrl(config, options),\n apiKey,\n json: options.json,\n store,\n };\n}\n\nfunction formatTailEvent(event: TailEvent): string {\n const actorLabel = event.actor.startsWith(\"agent:\")\n ? event.actor.slice(\"agent:\".length)\n : event.actor;\n const maybeText = event.payload?.text;\n\n if (typeof maybeText === \"string\") {\n return `[${actorLabel}] ${maybeText}`;\n }\n\n return `[${actorLabel}] ${JSON.stringify(event.payload)}`;\n}\n\nfunction parseJwtClaims(token: string): Record<string, unknown> | undefined {\n const parts = token.split(\".\");\n if (parts.length < 2) {\n return undefined;\n }\n\n const payload = parts[1];\n if (!payload) {\n return undefined;\n }\n\n try {\n const decoded = Buffer.from(payload, \"base64url\").toString(\"utf8\");\n const parsed = JSON.parse(decoded);\n return typeof parsed === \"object\" && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction tokenTenantId(token: string | undefined): string | undefined {\n if (!token) {\n return undefined;\n }\n\n const claims = parseJwtClaims(token);\n const tenantId = claims?.tenant_id;\n if (typeof tenantId !== \"string\") {\n return undefined;\n }\n\n const trimmed = tenantId.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction tokenScopes(token: string): Set<string> {\n const claims = parseJwtClaims(token);\n if (!claims) {\n return new Set();\n }\n\n const scopes = new Set<string>();\n const scopeClaim = claims.scope;\n if (typeof scopeClaim === \"string\") {\n for (const scope of scopeClaim.split(\" \")) {\n if (scope.length > 0) {\n scopes.add(scope);\n }\n }\n }\n\n const scopesClaim = claims.scopes;\n if (Array.isArray(scopesClaim)) {\n for (const scope of scopesClaim) {\n if (typeof scope === \"string\" && scope.length > 0) {\n scopes.add(scope);\n }\n }\n }\n\n return scopes;\n}\n\nfunction shouldAutoIssueSessionToken(token: string): boolean {\n const scopes = tokenScopes(token);\n return scopes.has(\"auth:issue\");\n}\n\nfunction resolveAppendMode(options: AppendCommandOptions): ResolvedAppendMode {\n const highLevelMode =\n options.agent !== undefined || options.text !== undefined;\n const rawMode = options.actor !== undefined || options.payload !== undefined;\n\n if (highLevelMode && rawMode) {\n throw new InvalidArgumentError(\n \"Choose either high-level mode (--agent and --text) or raw mode (--actor and --payload), not both\"\n );\n }\n\n if (highLevelMode) {\n const agent = trimString(options.agent);\n const text = trimString(options.text);\n if (!(agent && text)) {\n throw new InvalidArgumentError(\n \"--agent and --text are required for high-level append mode\"\n );\n }\n\n return { kind: \"high-level\", agent, text };\n }\n\n if (rawMode) {\n const actor = trimString(options.actor);\n const payload = trimString(options.payload);\n if (!(actor && payload)) {\n throw new InvalidArgumentError(\n \"Raw append mode requires --actor and --payload, or use --agent and --text\"\n );\n }\n\n return { kind: \"raw\", actor, payload };\n }\n\n throw new InvalidArgumentError(\n \"append requires either high-level mode (--agent and --text) or raw mode (--actor and --payload)\"\n );\n}\n\nfunction toApiBaseUrlForContext(baseUrl: string): string {\n const parsed = new URL(baseUrl);\n if (!(parsed.protocol === \"http:\" || parsed.protocol === \"https:\")) {\n throw new InvalidArgumentError(\"base URL must use http:// or https://\");\n }\n\n const normalized = parsed.toString().replace(TRAILING_SLASHES_REGEX, \"\");\n return normalized.endsWith(\"/v1\") ? normalized : `${normalized}/v1`;\n}\n\nasync function resolveSession(\n client: Starcite,\n apiKey: string | undefined,\n sessionId: string\n) {\n if (!apiKey) {\n throw new InvalidArgumentError(\n \"append/tail require --token or a saved API key\"\n );\n }\n\n if (shouldAutoIssueSessionToken(apiKey)) {\n return await client.session({\n identity: resolveCreateIdentity(apiKey),\n id: sessionId,\n });\n }\n\n const session = client.session({ token: apiKey });\n if (session.id !== sessionId) {\n throw new InvalidArgumentError(\n `session token is bound to '${session.id}', expected '${sessionId}'`\n );\n }\n\n return session;\n}\n\nfunction resolveCreateIdentity(\n apiKey: string | undefined,\n agentId = DEFAULT_CREATE_AGENT_ID\n): StarciteIdentity {\n const tenantId = tokenTenantId(apiKey);\n if (!tenantId) {\n throw new InvalidArgumentError(\n \"session identity binding requires an API key with tenant_id claims\"\n );\n }\n\n return new StarciteIdentity({\n tenantId,\n id: agentId,\n type: \"agent\",\n });\n}\n\nclass StarciteCliApp {\n private readonly createClient: (baseUrl: string, apiKey?: string) => Starcite;\n private readonly logger: LoggerLike;\n private readonly prompt: PromptAdapter;\n private readonly runCommand: CommandRunner;\n\n constructor(deps: CliDependencies = {}) {\n this.createClient =\n deps.createClient ??\n ((baseUrl: string, apiKey?: string) =>\n new Starcite({\n baseUrl,\n apiKey,\n }));\n this.logger = deps.logger ?? defaultLogger;\n this.prompt = deps.prompt ?? createDefaultPrompt();\n this.runCommand = deps.runCommand ?? defaultCommandRunner;\n }\n\n buildProgram(): Command {\n const createClient = this.createClient;\n const logger = this.logger;\n const prompt = this.prompt;\n const runCommand = this.runCommand;\n\n const program = new Command();\n\n program\n .name(\"starcite\")\n .description(\"Starcite CLI\")\n .showHelpAfterError()\n .version(cliVersion, \"-v, --version\", \"Print current CLI version\")\n .option(\"-u, --base-url <url>\", \"Starcite API base URL\")\n .option(\"-k, --token <token>\", \"Starcite API key\")\n .option(\n \"--config-dir <path>\",\n \"Starcite CLI config directory (default: ~/.starcite)\"\n )\n .option(\"--json\", \"Output JSON\");\n\n program\n .command(\"version\")\n .description(\"Print current CLI version\")\n .action(() => {\n logger.info(cliVersion);\n });\n\n program\n .command(\"config\")\n .description(\"Manage CLI configuration\")\n .addCommand(\n new Command(\"set\")\n .description(\"Set a configuration value\")\n .argument(\"<key>\", \"endpoint | producer-id | api-key\")\n .argument(\"<value>\", \"value to store\")\n .action(async function (this: Command, key: string, value: string) {\n const { store } = await resolveGlobalOptions(this);\n const parsedKey = parseConfigSetKey(key);\n\n if (parsedKey === \"endpoint\") {\n const endpoint = parseEndpoint(value, \"endpoint\");\n await store.updateConfig({ baseUrl: endpoint });\n logger.info(`Endpoint set to ${endpoint}`);\n return;\n }\n\n if (parsedKey === \"producer-id\") {\n const producerId = trimString(value);\n if (!producerId) {\n throw new InvalidArgumentError(\"producer-id cannot be empty\");\n }\n\n await store.updateConfig({ producerId });\n logger.info(`Producer ID set to ${producerId}`);\n return;\n }\n\n await store.saveApiKey(value);\n await store.updateConfig({ apiKey: undefined });\n logger.info(\"API key saved.\");\n })\n )\n .addCommand(\n new Command(\"show\")\n .description(\"Show current configuration\")\n .action(async function (this: Command) {\n const { baseUrl, store } = await resolveGlobalOptions(this);\n const config = await store.readConfig();\n const apiKey = await store.readApiKey();\n const fromEnv = trimString(process.env.STARCITE_API_KEY);\n let apiKeySource = \"unset\";\n\n if (fromEnv) {\n apiKeySource = \"env\";\n } else if (apiKey) {\n apiKeySource = \"stored\";\n }\n\n logger.info(\n JSON.stringify(\n {\n endpoint: config.baseUrl ?? baseUrl,\n producerId: config.producerId ?? null,\n apiKey: apiKey ? \"***\" : null,\n apiKeySource,\n configDir: store.directory,\n },\n null,\n 2\n )\n );\n })\n );\n\n program\n .command(\"sessions\")\n .description(\"Manage sessions\")\n .addCommand(\n new Command(\"list\")\n .description(\"List sessions\")\n .option(\"--limit <count>\", \"Maximum sessions to return\", (value) =>\n parsePositiveInteger(value, \"--limit\")\n )\n .option(\"--cursor <cursor>\", \"Pagination cursor\")\n .option(\"--metadata <json>\", \"Metadata filter JSON object\")\n .action(async function (\n this: Command,\n options: {\n limit?: number;\n cursor?: string;\n metadata?: string;\n }\n ) {\n const resolved = await resolveGlobalOptions(this);\n const { json } = resolved;\n const client = resolved.apiKey\n ? createClient(resolved.baseUrl, resolved.apiKey)\n : createClient(resolved.baseUrl);\n\n const metadata = options.metadata\n ? parseSessionMetadataFilters(options.metadata)\n : undefined;\n\n const cursor = options.cursor?.trim();\n if (options.cursor !== undefined && !cursor) {\n throw new InvalidArgumentError(\"--cursor must be non-empty\");\n }\n\n const page = await client.listSessions({\n limit: options.limit,\n cursor,\n metadata,\n });\n\n if (json) {\n logger.info(JSON.stringify(page, null, 2));\n return;\n }\n\n if (page.sessions.length === 0) {\n logger.info(\"No sessions found.\");\n return;\n }\n\n logger.info(\"id\\ttitle\\tcreated_at\");\n for (const session of page.sessions) {\n logger.info(\n `${session.id}\\t${session.title ?? \"\"}\\t${session.created_at}`\n );\n }\n\n if (page.next_cursor) {\n logger.info(`next_cursor=${page.next_cursor}`);\n }\n })\n );\n\n program\n .command(\"up\")\n .description(\"Start local Starcite services with Docker\")\n .option(\"-y, --yes\", \"Skip confirmation prompts and use defaults\")\n .option(\"--port <port>\", \"Starcite API port\", (value) =>\n parsePort(value, \"--port\")\n )\n .option(\"--db-port <port>\", \"Postgres port\", (value) =>\n parsePort(value, \"--db-port\")\n )\n .option(\"--image <image>\", \"Override Starcite image\")\n .action(async function (\n this: Command,\n options: {\n yes?: boolean;\n port?: number;\n dbPort?: number;\n image?: string;\n }\n ) {\n const { baseUrl, store } = await resolveGlobalOptions(this);\n await runUpWizard({\n baseUrl,\n logger,\n options,\n prompt,\n runCommand,\n store,\n });\n });\n\n program\n .command(\"down\")\n .description(\"Stop and remove local Starcite services\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"--no-volumes\", \"Keep Postgres volume data\")\n .action(async function (\n this: Command,\n options: { yes?: boolean; volumes?: boolean }\n ) {\n const { store } = await resolveGlobalOptions(this);\n await runDownWizard({\n logger,\n options,\n prompt,\n runCommand,\n store,\n });\n });\n\n program\n .command(\"create\")\n .description(\"Create a session\")\n .option(\"--id <id>\", \"Session ID\")\n .option(\"--title <title>\", \"Session title\")\n .option(\"--metadata <json>\", \"Session metadata JSON object\")\n .action(async function (\n this: Command,\n options: {\n id?: string;\n title?: string;\n metadata?: string;\n }\n ) {\n const resolved = await resolveGlobalOptions(this);\n const { json } = resolved;\n const client = resolved.apiKey\n ? createClient(resolved.baseUrl, resolved.apiKey)\n : createClient(resolved.baseUrl);\n const metadata = options.metadata\n ? parseJsonObject(options.metadata, \"--metadata\")\n : undefined;\n const session = await client.session({\n identity: resolveCreateIdentity(resolved.apiKey),\n id: options.id,\n title: options.title,\n metadata,\n });\n\n if (json) {\n logger.info(\n JSON.stringify(session.record ?? { id: session.id }, null, 2)\n );\n return;\n }\n\n logger.info(session.id);\n });\n\n program\n .command(\"append <sessionId>\")\n .description(\"Append an event\")\n .option(\"--agent <agent>\", \"Agent name (high-level mode)\")\n .option(\"--text <text>\", \"Text content (high-level mode)\")\n .option(\"--type <type>\", \"Event type\", \"content\")\n .option(\"--source <source>\", \"Event source\")\n .option(\n \"--producer-id <id>\",\n \"Producer identity (auto-generated if omitted)\"\n )\n .option(\n \"--producer-seq <seq>\",\n \"Producer sequence (defaults to persisted state, starting at 1)\",\n (value) => parsePositiveInteger(value, \"--producer-seq\")\n )\n .option(\"--actor <actor>\", \"Raw actor field (raw mode)\")\n .option(\"--payload <json>\", \"Raw payload JSON object (raw mode)\")\n .option(\"--metadata <json>\", \"Event metadata JSON object\")\n .option(\"--refs <json>\", \"Event refs JSON object\")\n .option(\"--idempotency-key <key>\", \"Idempotency key\")\n .option(\"--expected-seq <seq>\", \"Expected sequence\", (value) =>\n parseNonNegativeInteger(value, \"--expected-seq\")\n )\n .action(async function (\n this: Command,\n sessionId: string,\n options: AppendCommandOptions\n ) {\n const { baseUrl, apiKey, json, store } =\n await resolveGlobalOptions(this);\n const client = apiKey\n ? createClient(baseUrl, apiKey)\n : createClient(baseUrl);\n\n const metadata = options.metadata\n ? parseJsonObject(options.metadata, \"--metadata\")\n : undefined;\n const refs = options.refs\n ? parseJsonObject(options.refs, \"--refs\")\n : undefined;\n const mode = resolveAppendMode(options);\n const session =\n mode.kind === \"high-level\" &&\n apiKey !== undefined &&\n shouldAutoIssueSessionToken(apiKey)\n ? await client.session({\n identity: resolveCreateIdentity(apiKey, mode.agent),\n id: sessionId,\n })\n : await resolveSession(client, apiKey, sessionId);\n\n const response =\n mode.kind === \"high-level\"\n ? await session.append({\n type: options.type,\n text: mode.text,\n source: options.source,\n metadata,\n refs,\n idempotencyKey: options.idempotencyKey,\n expectedSeq: options.expectedSeq,\n })\n : await store.withStateLock(async () => {\n const producerId = await store.resolveProducerId(\n options.producerId\n );\n const normalizedBaseUrl = toApiBaseUrlForContext(baseUrl);\n const contextKey = buildSeqContextKey(\n normalizedBaseUrl,\n sessionId,\n producerId\n );\n const producerSeq =\n options.producerSeq ?? (await store.readNextSeq(contextKey));\n const appendResponse = await session.appendRaw({\n type: options.type,\n payload: parseJsonObject(mode.payload, \"--payload\"),\n actor: mode.actor,\n producer_id: producerId,\n producer_seq: producerSeq,\n source: options.source,\n metadata,\n refs,\n idempotency_key: options.idempotencyKey,\n expected_seq: options.expectedSeq,\n });\n\n await store.bumpNextSeq(contextKey, producerSeq);\n return appendResponse;\n });\n\n if (json) {\n logger.info(JSON.stringify(response, null, 2));\n return;\n }\n\n logger.info(`seq=${response.seq} deduped=${response.deduped}`);\n });\n\n program\n .command(\"tail <sessionId>\")\n .description(\"Tail events from a session\")\n .option(\"--cursor <cursor>\", \"Replay cursor\", (value) =>\n parseNonNegativeInteger(value, \"--cursor\")\n )\n .option(\"--agent <agent>\", \"Filter by agent name\")\n .option(\"--limit <count>\", \"Stop after N events\", (value) =>\n parseNonNegativeInteger(value, \"--limit\")\n )\n .option(\"--no-follow\", \"Exit after replaying stored events\")\n .action(async function (\n this: Command,\n sessionId: string,\n options: {\n cursor?: number;\n agent?: string;\n limit?: number;\n follow: boolean;\n }\n ) {\n const { baseUrl, apiKey, json } = await resolveGlobalOptions(this);\n const client = apiKey\n ? createClient(baseUrl, apiKey)\n : createClient(baseUrl);\n const session = await resolveSession(client, apiKey, sessionId);\n\n const abortController = new AbortController();\n const onSigint = () => {\n abortController.abort();\n };\n\n process.once(\"SIGINT\", onSigint);\n\n try {\n let emitted = 0;\n\n await session.tail(\n (event) => {\n if (options.limit !== undefined && emitted >= options.limit) {\n abortController.abort();\n return;\n }\n\n if (json) {\n logger.info(JSON.stringify(event));\n } else {\n logger.info(formatTailEvent(event));\n }\n\n emitted += 1;\n\n if (options.limit !== undefined && emitted >= options.limit) {\n abortController.abort();\n }\n },\n {\n cursor: options.cursor ?? 0,\n batchSize: DEFAULT_TAIL_BATCH_SIZE,\n agent: options.agent,\n follow: options.follow,\n signal: abortController.signal,\n }\n );\n } finally {\n process.removeListener(\"SIGINT\", onSigint);\n }\n });\n\n return program;\n }\n\n async run(argv = process.argv): Promise<void> {\n const program = this.buildProgram();\n\n try {\n await program.parseAsync(argv);\n } catch (error) {\n if (error instanceof StarciteApiError) {\n this.logger.error(`${error.code} (${error.status}): ${error.message}`);\n process.exitCode = 1;\n return;\n }\n\n if (error instanceof Error) {\n this.logger.error(error.message);\n process.exitCode = 1;\n return;\n }\n\n this.logger.error(\"Unknown error\");\n process.exitCode = 1;\n }\n }\n}\n\nexport function buildProgram(deps: CliDependencies = {}): Command {\n return new StarciteCliApp(deps).buildProgram();\n}\n\nexport async function run(\n argv = process.argv,\n deps: CliDependencies = {}\n): Promise<void> {\n await new StarciteCliApp(deps).run(argv);\n}\n","{\n \"name\": \"starcite\",\n \"version\": \"0.0.6\",\n \"description\": \"CLI for Starcite\",\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://starcite.ai\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/fastpaca/starcite-clients.git\",\n \"directory\": \"packages/starcite-cli\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/fastpaca/starcite-clients/issues\"\n },\n \"keywords\": [\n \"starcite\",\n \"ai\",\n \"sessions\",\n \"event-log\",\n \"cli\"\n ],\n \"type\": \"module\",\n \"bin\": {\n \"starcite\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"clean\": \"rm -rf dist\",\n \"build\": \"tsup\",\n \"dev\": \"bun run src/index.ts\",\n \"compile\": \"bun run --cwd ../typescript-sdk build && bun build --compile src/index.ts --outfile dist/starcite\",\n \"test\": \"vitest run && bun run test:dist\",\n \"test:live\": \"vitest run test/live.api.integration.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"prepublishOnly\": \"bun run clean && bun run build\",\n \"publish:dry\": \"bun publish --dry-run --access public\",\n \"test:dist\": \"bun run --cwd ../typescript-sdk build && bun run clean && bun run build && node dist/index.js --help > /dev/null\",\n \"lint\": \"ultracite check src test package.json tsconfig.json tsup.config.ts vitest.config.ts README.md\",\n \"format\": \"ultracite fix src test package.json tsconfig.json tsup.config.ts vitest.config.ts README.md\",\n \"check\": \"bun run lint && bun run typecheck && bun run test\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.0.1\",\n \"@starcite/sdk\": \"^0.0.6\",\n \"commander\": \"^13.1.0\",\n \"conf\": \"^15.1.0\",\n \"consola\": \"^3.4.2\",\n \"cosmiconfig\": \"^9.0.0\",\n \"proper-lockfile\": \"^4.1.2\",\n \"toml\": \"^3.0.0\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.15.30\",\n \"@types/proper-lockfile\": \"^4.1.4\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\",\n \"vitest\": \"^2.1.9\"\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { homedir, hostname } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport Conf from \"conf\";\nimport { cosmiconfig, defaultLoaders } from \"cosmiconfig\";\nimport { lock } from \"proper-lockfile\";\nimport { parse as parseToml } from \"toml\";\nimport { z } from \"zod\";\n\nconst DEFAULT_CONFIG_DIRECTORY_NAME = \".starcite\";\nconst CONFIG_JSON_FILENAME = \"config.json\";\nconst CONFIG_TOML_FILENAME = \"config.toml\";\nconst CREDENTIALS_FILENAME = \"credentials\";\nconst IDENTITY_FILENAME = \"identity\";\nconst STATE_FILENAME = \"state\";\nconst STATE_LOCK_FILENAME = \".state.lock\";\nconst TILDE_PREFIX_REGEX = /^~(?=\\/|$)/;\n\nconst ConfigFileSchema = z\n .object({\n baseUrl: z.string().optional(),\n base_url: z.string().optional(),\n producerId: z.string().optional(),\n producer_id: z.string().optional(),\n apiKey: z.string().optional(),\n api_key: z.string().optional(),\n })\n .passthrough();\n\nconst IdentityFileSchema = z.object({\n producerId: z.string().trim().min(1),\n hostname: z.string().trim().min(1),\n uuid: z.string().uuid(),\n createdAt: z.string(),\n});\n\nconst StateFileSchema = z.object({\n nextSeqByContext: z.record(z.number().int().positive()).default({}),\n});\n\nconst CredentialsFileSchema = z.object({\n apiKey: z.string().trim().min(1).optional(),\n});\n\ntype IdentityFile = z.infer<typeof IdentityFileSchema>;\ntype StateFile = z.infer<typeof StateFileSchema>;\ntype CredentialsFile = z.infer<typeof CredentialsFileSchema>;\n\nexport interface StarciteCliConfig {\n baseUrl?: string;\n producerId?: string;\n apiKey?: string;\n}\n\nfunction trimString(value?: string): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeConfig(input: unknown): StarciteCliConfig {\n const parsed = ConfigFileSchema.safeParse(input);\n\n if (!parsed.success) {\n return {};\n }\n\n return {\n baseUrl: trimString(parsed.data.baseUrl ?? parsed.data.base_url),\n producerId: trimString(parsed.data.producerId ?? parsed.data.producer_id),\n apiKey: trimString(parsed.data.apiKey ?? parsed.data.api_key),\n };\n}\n\nfunction defaultConfigDirectory(): string {\n const home = homedir();\n if (home.trim().length > 0) {\n return join(home, DEFAULT_CONFIG_DIRECTORY_NAME);\n }\n\n return resolve(DEFAULT_CONFIG_DIRECTORY_NAME);\n}\n\nexport function resolveConfigDir(input?: string): string {\n const configured = trimString(input) ?? trimString(process.env.STARCITE_HOME);\n const withTilde = configured?.startsWith(\"~\")\n ? configured.replace(TILDE_PREFIX_REGEX, homedir())\n : configured;\n\n return resolve(withTilde ?? defaultConfigDirectory());\n}\n\nexport function buildSeqContextKey(\n baseUrl: string,\n sessionId: string,\n producerId: string\n): string {\n return `${baseUrl}::${sessionId}::${producerId}`;\n}\n\nexport class StarciteCliStore {\n readonly directory: string;\n private readonly lockPath: string;\n private readonly configExplorer = cosmiconfig(\"starcite\", {\n cache: false,\n searchStrategy: \"none\",\n searchPlaces: [CONFIG_JSON_FILENAME, CONFIG_TOML_FILENAME],\n loaders: {\n ...defaultLoaders,\n \".toml\": (_filepath, content) => parseToml(content) as unknown,\n },\n });\n private readonly identityStore: Conf<IdentityFile>;\n private readonly credentialsStore: Conf<CredentialsFile>;\n private readonly stateStore: Conf<StateFile>;\n\n constructor(directory: string) {\n this.directory = directory;\n this.lockPath = join(directory, STATE_LOCK_FILENAME);\n this.identityStore = new Conf<IdentityFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: IDENTITY_FILENAME,\n fileExtension: \"json\",\n });\n this.credentialsStore = new Conf<CredentialsFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: CREDENTIALS_FILENAME,\n fileExtension: \"json\",\n defaults: {},\n });\n this.stateStore = new Conf<StateFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: STATE_FILENAME,\n fileExtension: \"json\",\n defaults: { nextSeqByContext: {} },\n });\n }\n\n async readConfig(): Promise<StarciteCliConfig> {\n await this.ensureConfigDirectory();\n const result = await this.configExplorer.search(this.directory);\n\n if (!result) {\n return {};\n }\n\n return normalizeConfig(result.config);\n }\n\n async writeConfig(config: StarciteCliConfig): Promise<void> {\n await this.ensureConfigDirectory();\n\n const normalized = normalizeConfig(config);\n const serialized: StarciteCliConfig = {};\n\n if (normalized.baseUrl) {\n serialized.baseUrl = normalized.baseUrl;\n }\n\n if (normalized.producerId) {\n serialized.producerId = normalized.producerId;\n }\n\n if (normalized.apiKey) {\n serialized.apiKey = normalized.apiKey;\n }\n\n await writeFile(\n join(this.directory, CONFIG_JSON_FILENAME),\n `${JSON.stringify(serialized, null, 2)}\\n`,\n \"utf8\"\n );\n }\n\n async updateConfig(\n patch: Partial<StarciteCliConfig>\n ): Promise<StarciteCliConfig> {\n const current = await this.readConfig();\n const merged = normalizeConfig({\n ...current,\n ...patch,\n });\n\n await this.writeConfig(merged);\n return merged;\n }\n\n async readApiKey(): Promise<string | undefined> {\n const fromEnv = trimString(process.env.STARCITE_API_KEY);\n if (fromEnv) {\n return fromEnv;\n }\n\n const parsed = CredentialsFileSchema.safeParse(this.credentialsStore.store);\n const fromCredentials = parsed.success\n ? trimString(parsed.data.apiKey)\n : undefined;\n if (fromCredentials) {\n return fromCredentials;\n }\n\n const config = await this.readConfig();\n return trimString(config.apiKey);\n }\n\n async saveApiKey(apiKey: string): Promise<void> {\n await this.ensureConfigDirectory();\n\n const normalized = trimString(apiKey);\n if (!normalized) {\n throw new Error(\"API key cannot be empty\");\n }\n\n this.credentialsStore.set(\"apiKey\", normalized);\n }\n\n async clearApiKey(): Promise<void> {\n await this.ensureConfigDirectory();\n this.credentialsStore.delete(\"apiKey\");\n }\n\n async resolveProducerId(explicitProducerId?: string): Promise<string> {\n const explicit = trimString(explicitProducerId);\n if (explicit) {\n return explicit;\n }\n\n const fromEnv = trimString(process.env.STARCITE_PRODUCER_ID);\n if (fromEnv) {\n return fromEnv;\n }\n\n const config = await this.readConfig();\n const fromConfig = trimString(config.producerId);\n if (fromConfig) {\n return fromConfig;\n }\n\n const identity = await this.readOrCreateIdentity();\n return identity.producerId;\n }\n\n async withStateLock<T>(action: () => Promise<T>): Promise<T> {\n await this.ensureConfigDirectory();\n const release = await lock(this.directory, {\n lockfilePath: this.lockPath,\n realpath: false,\n retries: {\n retries: 50,\n minTimeout: 20,\n maxTimeout: 60,\n },\n });\n\n try {\n return await action();\n } finally {\n await release();\n }\n }\n\n readNextSeq(contextKey: string): Promise<number> {\n const state = this.readState();\n return Promise.resolve(state.nextSeqByContext[contextKey] ?? 1);\n }\n\n bumpNextSeq(contextKey: string, usedSeq: number): Promise<void> {\n const state = this.readState();\n const nextSeqByContext = {\n ...state.nextSeqByContext,\n [contextKey]: Math.max(\n state.nextSeqByContext[contextKey] ?? 1,\n usedSeq + 1\n ),\n };\n\n this.stateStore.set(\"nextSeqByContext\", nextSeqByContext);\n return Promise.resolve();\n }\n\n private readState(): StateFile {\n const parsed = StateFileSchema.safeParse(this.stateStore.store);\n\n if (parsed.success) {\n return parsed.data;\n }\n\n this.stateStore.clear();\n return { nextSeqByContext: {} };\n }\n\n private readOrCreateIdentity(): IdentityFile {\n const parsed = IdentityFileSchema.safeParse(this.identityStore.store);\n if (parsed.success) {\n return parsed.data;\n }\n\n const host = hostname();\n const uuid = randomUUID();\n const identity: IdentityFile = {\n producerId: `cli:${host}:${uuid}`,\n hostname: host,\n uuid,\n createdAt: new Date().toISOString(),\n };\n\n this.identityStore.store = identity;\n return identity;\n }\n\n private async ensureConfigDirectory(): Promise<void> {\n await mkdir(this.directory, { recursive: true });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { mkdir, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n cancel as clackCancel,\n confirm as clackConfirm,\n password as clackPassword,\n text as clackText,\n isCancel,\n} from \"@clack/prompts\";\nimport type { LoggerLike } from \"./cli\";\nimport type { StarciteCliStore } from \"./store\";\n\nexport const DEFAULT_API_PORT = 45_187;\nconst DEFAULT_DB_PORT = 5433;\nconst MIN_PORT = 1;\nconst MAX_PORT = 65_535;\nconst RUNTIME_DIRECTORY_NAME = \"runtime\";\n\nconst DEFAULT_COMPOSE_FILE = `services:\n app:\n image: \\${STARCITE_IMAGE:-ghcr.io/fastpaca/starcite:latest}\n depends_on:\n db:\n condition: service_healthy\n environment:\n SECRET_KEY_BASE: \\${SECRET_KEY_BASE:-xuQnOFm6sH5Qdd7x4WJv5smuG2Xf2nG0BL8rJ4yX6HnKGeTjo6n8r5hQKsxNkZWz}\n PHX_HOST: \\${PHX_HOST:-localhost}\n PORT: 4000\n DATABASE_URL: \\${DATABASE_URL:-ecto://postgres:postgres@db:5432/starcite_dev}\n MIGRATE_ON_BOOT: \\${MIGRATE_ON_BOOT:-true}\n DNS_CLUSTER_QUERY: \\${DNS_CLUSTER_QUERY:-}\n DNS_CLUSTER_NODE_BASENAME: \\${DNS_CLUSTER_NODE_BASENAME:-starcite}\n DNS_POLL_INTERVAL_MS: \\${DNS_POLL_INTERVAL_MS:-5000}\n ports:\n - \"\\${STARCITE_API_PORT:-45187}:4000\"\n restart: unless-stopped\n\n db:\n image: postgres:15\n environment:\n POSTGRES_DB: starcite_dev\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: postgres\n healthcheck:\n test: [\"CMD\", \"pg_isready\", \"-U\", \"postgres\"]\n interval: 10s\n timeout: 5s\n retries: 5\n ports:\n - \"\\${STARCITE_DB_PORT:-5433}:5432\"\n volumes:\n - db-data:/var/lib/postgresql/data\n restart: unless-stopped\n\nvolumes:\n db-data:\n`;\n\ninterface CommandRunOptions {\n cwd?: string;\n}\n\nexport interface CommandResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nexport type CommandRunner = (\n command: string,\n args: string[],\n options?: CommandRunOptions\n) => Promise<CommandResult>;\n\nexport interface PromptAdapter {\n confirm(message: string, defaultValue?: boolean): Promise<boolean>;\n input(message: string, defaultValue?: string): Promise<string>;\n password?(message: string): Promise<string>;\n}\n\nexport interface UpOptions {\n yes?: boolean;\n port?: number;\n dbPort?: number;\n image?: string;\n}\n\nexport interface DownOptions {\n yes?: boolean;\n volumes?: boolean;\n}\n\ninterface UpWizardInput {\n baseUrl: string;\n logger: LoggerLike;\n options: UpOptions;\n prompt: PromptAdapter;\n runCommand: CommandRunner;\n store: StarciteCliStore;\n}\n\ninterface DownWizardInput {\n logger: LoggerLike;\n options: DownOptions;\n prompt: PromptAdapter;\n runCommand: CommandRunner;\n store: StarciteCliStore;\n}\n\nfunction parsePort(value: string, optionName: string): number {\n const parsed = Number(value);\n\n if (!Number.isInteger(parsed) || parsed < MIN_PORT || parsed > MAX_PORT) {\n throw new Error(\n `${optionName} must be an integer between ${MIN_PORT} and ${MAX_PORT}`\n );\n }\n\n return parsed;\n}\n\nfunction baseUrlPort(baseUrl: string): number {\n try {\n const parsed = new URL(baseUrl);\n\n if (parsed.port) {\n return parsePort(parsed.port, \"base URL port\");\n }\n } catch {\n return DEFAULT_API_PORT;\n }\n\n return DEFAULT_API_PORT;\n}\n\nasync function ensureSuccess(\n runCommand: CommandRunner,\n command: string,\n args: string[]\n): Promise<boolean> {\n const result = await runCommand(command, args);\n return result.code === 0;\n}\n\nasync function ensureDockerReady(\n logger: LoggerLike,\n runCommand: CommandRunner\n): Promise<void> {\n const hasDocker = await ensureSuccess(runCommand, \"docker\", [\"--version\"]);\n if (!hasDocker) {\n logger.error(\"You don't have Docker installed, please install it.\");\n throw new Error(\"Docker is required to run this command.\");\n }\n\n const hasDockerCompose = await ensureSuccess(runCommand, \"docker\", [\n \"compose\",\n \"version\",\n ]);\n if (!hasDockerCompose) {\n logger.error(\n \"Docker Compose is not available. Install Docker Compose and retry.\"\n );\n throw new Error(\"Docker Compose is required to run this command.\");\n }\n\n const daemonRunning = await ensureSuccess(runCommand, \"docker\", [\"info\"]);\n if (!daemonRunning) {\n logger.error(\"Docker is installed but the daemon is not running.\");\n throw new Error(\"Start Docker and retry.\");\n }\n}\n\nasync function selectApiPort(\n baseUrl: string,\n options: UpOptions,\n prompt: PromptAdapter\n): Promise<number> {\n if (options.port !== undefined) {\n return options.port;\n }\n\n const fallbackPort = baseUrlPort(baseUrl);\n\n if (options.yes) {\n return fallbackPort;\n }\n\n while (true) {\n const answer = await prompt.input(\n \"What port do you want it on?\",\n `${fallbackPort}`\n );\n\n try {\n return parsePort(answer, \"port\");\n } catch (error) {\n if (error instanceof Error) {\n // keep asking until valid\n }\n }\n }\n}\n\nfunction runtimeDirectory(store: StarciteCliStore): string {\n return join(store.directory, RUNTIME_DIRECTORY_NAME);\n}\n\nasync function runtimeDirectoryExists(\n store: StarciteCliStore\n): Promise<boolean> {\n try {\n const result = await stat(runtimeDirectory(store));\n return result.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function writeComposeFiles(\n store: StarciteCliStore,\n options: { apiPort: number; dbPort: number; image?: string }\n): Promise<string> {\n const directory = runtimeDirectory(store);\n await mkdir(directory, { recursive: true });\n\n await writeFile(\n join(directory, \"docker-compose.yml\"),\n DEFAULT_COMPOSE_FILE,\n \"utf8\"\n );\n\n const envLines = [\n `STARCITE_API_PORT=${options.apiPort}`,\n `STARCITE_DB_PORT=${options.dbPort}`,\n ];\n\n if (options.image?.trim()) {\n envLines.push(`STARCITE_IMAGE=${options.image.trim()}`);\n }\n\n await writeFile(join(directory, \".env\"), `${envLines.join(\"\\n\")}\\n`, \"utf8\");\n return directory;\n}\n\nexport function parsePortOption(value: string, optionName: string): number {\n try {\n return parsePort(value, optionName);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(error.message);\n }\n\n throw error;\n }\n}\n\nexport async function runUpWizard(input: UpWizardInput): Promise<void> {\n const { baseUrl, logger, options, prompt, runCommand, store } = input;\n\n await ensureDockerReady(logger, runCommand);\n\n const confirmed = options.yes\n ? true\n : await prompt.confirm(\n \"Are you sure you want to create the docker containers?\",\n true\n );\n\n if (!confirmed) {\n logger.info(\"Cancelled.\");\n return;\n }\n\n const apiPort = await selectApiPort(baseUrl, options, prompt);\n const dbPort = options.dbPort ?? DEFAULT_DB_PORT;\n const composeDirectory = await writeComposeFiles(store, {\n apiPort,\n dbPort,\n image: options.image,\n });\n\n const result = await runCommand(\"docker\", [\"compose\", \"up\", \"-d\"], {\n cwd: composeDirectory,\n });\n\n if (result.code !== 0) {\n const message =\n result.stderr || result.stdout || \"docker compose up failed\";\n throw new Error(message.trim());\n }\n\n logger.info(`Starcite is starting on http://localhost:${apiPort}`);\n logger.info(`Compose files are in ${composeDirectory}`);\n}\n\nexport async function runDownWizard(input: DownWizardInput): Promise<void> {\n const { logger, options, prompt, runCommand, store } = input;\n\n await ensureDockerReady(logger, runCommand);\n\n const hasRuntimeDirectory = await runtimeDirectoryExists(store);\n if (!hasRuntimeDirectory) {\n logger.info(\n `No Starcite runtime found at ${runtimeDirectory(\n store\n )}. Nothing to tear down.`\n );\n return;\n }\n\n const removeVolumes = options.volumes ?? true;\n const confirmed = options.yes\n ? true\n : await prompt.confirm(\n removeVolumes\n ? \"Are you sure you want to stop and delete Starcite containers and volumes?\"\n : \"Are you sure you want to stop Starcite containers?\",\n false\n );\n\n if (!confirmed) {\n logger.info(\"Cancelled.\");\n return;\n }\n\n const args = [\"compose\", \"down\", \"--remove-orphans\"];\n if (removeVolumes) {\n args.push(\"-v\");\n }\n\n const result = await runCommand(\"docker\", args, {\n cwd: runtimeDirectory(store),\n });\n\n if (result.code !== 0) {\n const message =\n result.stderr || result.stdout || \"docker compose down failed\";\n throw new Error(message.trim());\n }\n\n logger.info(\"Starcite containers stopped.\");\n if (removeVolumes) {\n logger.info(\"Starcite volumes removed.\");\n }\n}\n\nexport function createDefaultPrompt(): PromptAdapter {\n const assertInteractive = (): void => {\n if (!(process.stdin.isTTY && process.stdout.isTTY)) {\n throw new Error(\n \"Interactive mode requires a TTY. Re-run with explicit options (for example: --yes, --endpoint, --api-key).\"\n );\n }\n };\n\n return {\n async confirm(message: string, defaultValue = true): Promise<boolean> {\n assertInteractive();\n\n const answer = await clackConfirm({\n message,\n initialValue: defaultValue,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n return false;\n }\n\n return answer;\n },\n async input(message: string, defaultValue = \"\"): Promise<string> {\n assertInteractive();\n\n const answer = await clackText({\n message,\n defaultValue,\n placeholder: defaultValue || undefined,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n throw new Error(\"Cancelled.\");\n }\n\n const normalized = answer.trim();\n return normalized || defaultValue;\n },\n async password(message: string): Promise<string> {\n assertInteractive();\n\n const answer = await clackPassword({\n message,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n throw new Error(\"Cancelled.\");\n }\n\n return answer.trim();\n },\n };\n}\n\nexport const defaultCommandRunner: CommandRunner = (command, args, options) =>\n new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd: options?.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n const message = error.message || \"command failed to start\";\n resolve({ code: 127, stdout, stderr: `${stderr}${message}` });\n });\n\n child.on(\"close\", (code) => {\n resolve({ code: code ?? 1, stdout, stderr });\n });\n });\n","import { run } from \"./cli\";\n\nrun();\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,SAAS,4BAA4B;AAC9C,SAAS,qBAAqB;AAC9B,SAAS,KAAAA,UAAS;;;ACRlB;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,UAAY;AAAA,EACZ,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,KAAO;AAAA,IACL,UAAY;AAAA,EACd;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,OAAS;AAAA,IACT,KAAO;AAAA,IACP,SAAW;AAAA,IACX,MAAQ;AAAA,IACR,aAAa;AAAA,IACb,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,MAAQ;AAAA,IACR,QAAU;AAAA,IACV,OAAS;AAAA,EACX;AAAA,EACA,cAAgB;AAAA,IACd,kBAAkB;AAAA,IAClB,iBAAiB;AAA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3BA,IAAI;","names":["z","mkdir","writeFile","join","resolve","z","parsePort","trimString"]}
1
+ {"version":3,"sources":["../src/cli.ts","../package.json","../src/store.ts","../src/up.ts","../src/index.ts"],"sourcesContent":["import {\n Starcite,\n StarciteApiError,\n StarciteIdentity,\n type TailEvent,\n} from \"@starcite/sdk\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { createConsola } from \"consola\";\nimport { z } from \"zod\";\nimport starciteCliPackage from \"../package.json\";\nimport {\n buildSeqContextKey,\n resolveConfigDir,\n type StarciteCliConfig,\n StarciteCliStore,\n} from \"./store\";\nimport {\n type CommandRunner,\n createDefaultPrompt,\n DEFAULT_API_PORT,\n defaultCommandRunner,\n type PromptAdapter,\n parsePortOption,\n runDownWizard,\n runUpWizard,\n} from \"./up\";\n\ninterface GlobalOptions {\n baseUrl?: string;\n configDir?: string;\n token?: string;\n json: boolean;\n}\n\ninterface ResolvedGlobalOptions {\n baseUrl: string;\n apiKey?: string;\n json: boolean;\n store: StarciteCliStore;\n}\n\nexport interface LoggerLike {\n info(message: string): void;\n error(message: string): void;\n}\n\ninterface StdoutLike {\n write(message: string): void;\n}\n\ninterface CliDependencies {\n createClient?: (baseUrl: string, apiKey?: string) => Starcite;\n logger?: LoggerLike;\n stdout?: StdoutLike;\n prompt?: PromptAdapter;\n runCommand?: CommandRunner;\n}\n\ntype CliJsonObject = Record<string, unknown>;\n\nconst defaultLogger: LoggerLike = createConsola();\nconst defaultStdout: StdoutLike = {\n write(message: string) {\n process.stdout.write(message);\n },\n};\nconst cliVersion = starciteCliPackage.version;\n\nconst nonNegativeIntegerSchema = z.coerce.number().int().nonnegative();\nconst positiveIntegerSchema = z.coerce.number().int().positive();\nconst jsonObjectSchema = z.record(z.unknown());\nconst GlobalOptionsSchema = z.object({\n baseUrl: z.string().optional(),\n configDir: z.string().optional(),\n token: z.string().optional(),\n json: z.boolean().optional().default(false),\n});\nconst TRAILING_SLASHES_REGEX = /\\/+$/;\nconst DEFAULT_TAIL_BATCH_SIZE = 256;\nconst DEFAULT_CREATE_AGENT_ID = \"starcite-cli\";\n\ntype ConfigSetKey = \"endpoint\" | \"producer-id\" | \"api-key\";\n\ninterface AppendCommandOptions {\n agent?: string;\n text?: string;\n type: string;\n source?: string;\n producerId?: string;\n producerSeq?: number;\n actor?: string;\n payload?: string;\n metadata?: string;\n refs?: string;\n idempotencyKey?: string;\n expectedSeq?: number;\n}\n\ntype ResolvedAppendMode =\n | { kind: \"high-level\"; agent: string; text: string }\n | { kind: \"raw\"; actor: string; payload: string };\n\nfunction parseNonNegativeInteger(value: string, optionName: string): number {\n const parsed = nonNegativeIntegerSchema.safeParse(value);\n\n if (!parsed.success) {\n throw new InvalidArgumentError(\n `${optionName} must be a non-negative integer`\n );\n }\n\n return parsed.data;\n}\n\nfunction parsePositiveInteger(value: string, optionName: string): number {\n const parsed = positiveIntegerSchema.safeParse(value);\n\n if (!parsed.success) {\n throw new InvalidArgumentError(`${optionName} must be a positive integer`);\n }\n\n return parsed.data;\n}\n\nfunction parsePort(value: string, optionName: string): number {\n return parsePortOption(value, optionName);\n}\n\nfunction parseEndpoint(value: string, optionName: string): string {\n const endpoint = trimString(value);\n if (!endpoint) {\n throw new InvalidArgumentError(`${optionName} cannot be empty`);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(endpoint);\n } catch {\n throw new InvalidArgumentError(`${optionName} must be a valid URL`);\n }\n\n if (!(parsed.protocol === \"http:\" || parsed.protocol === \"https:\")) {\n throw new InvalidArgumentError(\n `${optionName} must use http:// or https://`\n );\n }\n\n return endpoint.replace(TRAILING_SLASHES_REGEX, \"\");\n}\n\nfunction parseConfigSetKey(value: string): ConfigSetKey {\n const normalized = value.trim().toLowerCase();\n\n if ([\"endpoint\", \"base-url\", \"base_url\"].includes(normalized)) {\n return \"endpoint\";\n }\n\n if ([\"producer-id\", \"producer_id\"].includes(normalized)) {\n return \"producer-id\";\n }\n\n if ([\"api-key\", \"api_key\"].includes(normalized)) {\n return \"api-key\";\n }\n\n throw new InvalidArgumentError(\n \"config key must be one of: endpoint, producer-id, api-key\"\n );\n}\n\nfunction parseJsonObject(value: string, optionName: string): CliJsonObject {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new InvalidArgumentError(`${optionName} must be valid JSON`);\n }\n\n const result = jsonObjectSchema.safeParse(parsed);\n if (!result.success) {\n throw new InvalidArgumentError(`${optionName} must be a JSON object`);\n }\n\n return result.data;\n}\n\nfunction parseSessionMetadataFilters(value: string): Record<string, string> {\n const parsed = parseJsonObject(value, \"--metadata\");\n const filters: Record<string, string> = {};\n\n for (const [key, rawValue] of Object.entries(parsed)) {\n if (key.trim().length === 0) {\n throw new InvalidArgumentError(\"--metadata keys must be non-empty\");\n }\n\n if (typeof rawValue !== \"string\") {\n throw new InvalidArgumentError(\"--metadata values must be strings\");\n }\n\n filters[key] = rawValue;\n }\n\n return filters;\n}\n\nfunction getGlobalOptions(command: Command): GlobalOptions {\n const parsed = GlobalOptionsSchema.safeParse(command.optsWithGlobals());\n if (!parsed.success) {\n const issue = parsed.error.issues[0]?.message ?? \"invalid global options\";\n throw new InvalidArgumentError(`Failed to parse global options: ${issue}`);\n }\n\n return parsed.data;\n}\n\nfunction trimString(value?: string): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction resolveBaseUrl(\n config: StarciteCliConfig,\n options: GlobalOptions\n): string {\n const defaultBaseUrl = `http://localhost:${DEFAULT_API_PORT}`;\n return (\n trimString(options.baseUrl) ??\n trimString(process.env.STARCITE_BASE_URL) ??\n trimString(config.baseUrl) ??\n defaultBaseUrl\n );\n}\n\nasync function resolveGlobalOptions(\n command: Command\n): Promise<ResolvedGlobalOptions> {\n const options = getGlobalOptions(command);\n const configDir = resolveConfigDir(options.configDir);\n const store = new StarciteCliStore(configDir);\n const config = await store.readConfig();\n const apiKey = trimString(options.token) ?? (await store.readApiKey());\n\n return {\n baseUrl: resolveBaseUrl(config, options),\n apiKey,\n json: options.json,\n store,\n };\n}\n\nfunction formatTailEvent(event: TailEvent): string {\n const actorLabel = event.actor.startsWith(\"agent:\")\n ? event.actor.slice(\"agent:\".length)\n : event.actor;\n const maybeText = event.payload?.text;\n\n if (typeof maybeText === \"string\") {\n return `[${actorLabel}] ${maybeText}`;\n }\n\n return `[${actorLabel}] ${JSON.stringify(event.payload)}`;\n}\n\nfunction parseJwtClaims(token: string): Record<string, unknown> | undefined {\n const parts = token.split(\".\");\n if (parts.length < 2) {\n return undefined;\n }\n\n const payload = parts[1];\n if (!payload) {\n return undefined;\n }\n\n try {\n const decoded = Buffer.from(payload, \"base64url\").toString(\"utf8\");\n const parsed = JSON.parse(decoded);\n return typeof parsed === \"object\" && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction tokenTenantId(token: string | undefined): string | undefined {\n if (!token) {\n return undefined;\n }\n\n const claims = parseJwtClaims(token);\n const tenantId = claims?.tenant_id;\n if (typeof tenantId !== \"string\") {\n return undefined;\n }\n\n const trimmed = tenantId.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction tokenScopes(token: string): Set<string> {\n const claims = parseJwtClaims(token);\n if (!claims) {\n return new Set();\n }\n\n const scopes = new Set<string>();\n const scopeClaim = claims.scope;\n if (typeof scopeClaim === \"string\") {\n for (const scope of scopeClaim.split(\" \")) {\n if (scope.length > 0) {\n scopes.add(scope);\n }\n }\n }\n\n const scopesClaim = claims.scopes;\n if (Array.isArray(scopesClaim)) {\n for (const scope of scopesClaim) {\n if (typeof scope === \"string\" && scope.length > 0) {\n scopes.add(scope);\n }\n }\n }\n\n return scopes;\n}\n\nfunction shouldAutoIssueSessionToken(token: string): boolean {\n const scopes = tokenScopes(token);\n return scopes.has(\"auth:issue\");\n}\n\nfunction resolveAppendMode(options: AppendCommandOptions): ResolvedAppendMode {\n const highLevelMode =\n options.agent !== undefined || options.text !== undefined;\n const rawMode = options.actor !== undefined || options.payload !== undefined;\n\n if (highLevelMode && rawMode) {\n throw new InvalidArgumentError(\n \"Choose either high-level mode (--agent and --text) or raw mode (--actor and --payload), not both\"\n );\n }\n\n if (highLevelMode) {\n const agent = trimString(options.agent);\n const text = trimString(options.text);\n if (!(agent && text)) {\n throw new InvalidArgumentError(\n \"--agent and --text are required for high-level append mode\"\n );\n }\n\n return { kind: \"high-level\", agent, text };\n }\n\n if (rawMode) {\n const actor = trimString(options.actor);\n const payload = trimString(options.payload);\n if (!(actor && payload)) {\n throw new InvalidArgumentError(\n \"Raw append mode requires --actor and --payload, or use --agent and --text\"\n );\n }\n\n return { kind: \"raw\", actor, payload };\n }\n\n throw new InvalidArgumentError(\n \"append requires either high-level mode (--agent and --text) or raw mode (--actor and --payload)\"\n );\n}\n\nfunction toApiBaseUrlForContext(baseUrl: string): string {\n const parsed = new URL(baseUrl);\n if (!(parsed.protocol === \"http:\" || parsed.protocol === \"https:\")) {\n throw new InvalidArgumentError(\"base URL must use http:// or https://\");\n }\n\n const normalized = parsed.toString().replace(TRAILING_SLASHES_REGEX, \"\");\n return normalized.endsWith(\"/v1\") ? normalized : `${normalized}/v1`;\n}\n\nfunction writeJsonOutput(\n stdout: StdoutLike,\n value: unknown,\n pretty = false\n): void {\n const serialized = JSON.stringify(value, null, pretty ? 2 : undefined);\n if (serialized === undefined) {\n throw new Error(\"Failed to serialize JSON output\");\n }\n\n stdout.write(`${serialized}\\n`);\n}\n\nasync function resolveSession(\n client: Starcite,\n apiKey: string | undefined,\n sessionId: string\n) {\n if (!apiKey) {\n throw new InvalidArgumentError(\n \"append/tail require --token or a saved API key\"\n );\n }\n\n if (shouldAutoIssueSessionToken(apiKey)) {\n return await client.session({\n identity: resolveCreateIdentity(apiKey),\n id: sessionId,\n });\n }\n\n const session = client.session({ token: apiKey });\n if (session.id !== sessionId) {\n throw new InvalidArgumentError(\n `session token is bound to '${session.id}', expected '${sessionId}'`\n );\n }\n\n return session;\n}\n\nfunction resolveCreateIdentity(\n apiKey: string | undefined,\n agentId = DEFAULT_CREATE_AGENT_ID\n): StarciteIdentity {\n const tenantId = tokenTenantId(apiKey);\n if (!tenantId) {\n throw new InvalidArgumentError(\n \"session identity binding requires an API key with tenant_id claims\"\n );\n }\n\n return new StarciteIdentity({\n tenantId,\n id: agentId,\n type: \"agent\",\n });\n}\n\nclass StarciteCliApp {\n private readonly createClient: (baseUrl: string, apiKey?: string) => Starcite;\n private readonly logger: LoggerLike;\n private readonly stdout: StdoutLike;\n private readonly prompt: PromptAdapter;\n private readonly runCommand: CommandRunner;\n\n constructor(deps: CliDependencies = {}) {\n this.createClient =\n deps.createClient ??\n ((baseUrl: string, apiKey?: string) =>\n new Starcite({\n baseUrl,\n apiKey,\n }));\n this.logger = deps.logger ?? defaultLogger;\n this.stdout = deps.stdout ?? defaultStdout;\n this.prompt = deps.prompt ?? createDefaultPrompt();\n this.runCommand = deps.runCommand ?? defaultCommandRunner;\n }\n\n buildProgram(): Command {\n const createClient = this.createClient;\n const logger = this.logger;\n const stdout = this.stdout;\n const prompt = this.prompt;\n const runCommand = this.runCommand;\n\n const program = new Command();\n\n program\n .name(\"starcite\")\n .description(\"Starcite CLI\")\n .showHelpAfterError()\n .version(cliVersion, \"-v, --version\", \"Print current CLI version\")\n .option(\"-u, --base-url <url>\", \"Starcite API base URL\")\n .option(\"-k, --token <token>\", \"Starcite API key\")\n .option(\n \"--config-dir <path>\",\n \"Starcite CLI config directory (default: ~/.starcite)\"\n )\n .option(\"--json\", \"Output JSON\");\n\n program\n .command(\"version\")\n .description(\"Print current CLI version\")\n .action(() => {\n logger.info(cliVersion);\n });\n\n program\n .command(\"config\")\n .description(\"Manage CLI configuration\")\n .addCommand(\n new Command(\"set\")\n .description(\"Set a configuration value\")\n .argument(\"<key>\", \"endpoint | producer-id | api-key\")\n .argument(\"<value>\", \"value to store\")\n .action(async function (this: Command, key: string, value: string) {\n const { store } = await resolveGlobalOptions(this);\n const parsedKey = parseConfigSetKey(key);\n\n if (parsedKey === \"endpoint\") {\n const endpoint = parseEndpoint(value, \"endpoint\");\n await store.updateConfig({ baseUrl: endpoint });\n logger.info(`Endpoint set to ${endpoint}`);\n return;\n }\n\n if (parsedKey === \"producer-id\") {\n const producerId = trimString(value);\n if (!producerId) {\n throw new InvalidArgumentError(\"producer-id cannot be empty\");\n }\n\n await store.updateConfig({ producerId });\n logger.info(`Producer ID set to ${producerId}`);\n return;\n }\n\n await store.saveApiKey(value);\n await store.updateConfig({ apiKey: undefined });\n logger.info(\"API key saved.\");\n })\n )\n .addCommand(\n new Command(\"show\")\n .description(\"Show current configuration\")\n .action(async function (this: Command) {\n const { baseUrl, json, store } = await resolveGlobalOptions(this);\n const config = await store.readConfig();\n const apiKey = await store.readApiKey();\n const fromEnv = trimString(process.env.STARCITE_API_KEY);\n let apiKeySource = \"unset\";\n\n if (fromEnv) {\n apiKeySource = \"env\";\n } else if (apiKey) {\n apiKeySource = \"stored\";\n }\n\n const output = {\n endpoint: config.baseUrl ?? baseUrl,\n producerId: config.producerId ?? null,\n apiKey: apiKey ? \"***\" : null,\n apiKeySource,\n configDir: store.directory,\n };\n\n if (json) {\n writeJsonOutput(stdout, output, true);\n return;\n }\n\n logger.info(JSON.stringify(output, null, 2));\n })\n );\n\n program\n .command(\"sessions\")\n .description(\"Manage sessions\")\n .addCommand(\n new Command(\"list\")\n .description(\"List sessions\")\n .option(\"--limit <count>\", \"Maximum sessions to return\", (value) =>\n parsePositiveInteger(value, \"--limit\")\n )\n .option(\"--cursor <cursor>\", \"Pagination cursor\")\n .option(\"--metadata <json>\", \"Metadata filter JSON object\")\n .action(async function (\n this: Command,\n options: {\n limit?: number;\n cursor?: string;\n metadata?: string;\n }\n ) {\n const resolved = await resolveGlobalOptions(this);\n const { json } = resolved;\n const client = resolved.apiKey\n ? createClient(resolved.baseUrl, resolved.apiKey)\n : createClient(resolved.baseUrl);\n\n const metadata = options.metadata\n ? parseSessionMetadataFilters(options.metadata)\n : undefined;\n\n const cursor = options.cursor?.trim();\n if (options.cursor !== undefined && !cursor) {\n throw new InvalidArgumentError(\"--cursor must be non-empty\");\n }\n\n const page = await client.listSessions({\n limit: options.limit,\n cursor,\n metadata,\n });\n\n if (json) {\n writeJsonOutput(stdout, page, true);\n return;\n }\n\n if (page.sessions.length === 0) {\n logger.info(\"No sessions found.\");\n return;\n }\n\n logger.info(\"id\\ttitle\\tcreated_at\");\n for (const session of page.sessions) {\n logger.info(\n `${session.id}\\t${session.title ?? \"\"}\\t${session.created_at}`\n );\n }\n\n if (page.next_cursor) {\n logger.info(`next_cursor=${page.next_cursor}`);\n }\n })\n );\n\n program\n .command(\"up\")\n .description(\"Start local Starcite services with Docker\")\n .option(\"-y, --yes\", \"Skip confirmation prompts and use defaults\")\n .option(\"--port <port>\", \"Starcite API port\", (value) =>\n parsePort(value, \"--port\")\n )\n .option(\"--db-port <port>\", \"Postgres port\", (value) =>\n parsePort(value, \"--db-port\")\n )\n .option(\"--image <image>\", \"Override Starcite image\")\n .action(async function (\n this: Command,\n options: {\n yes?: boolean;\n port?: number;\n dbPort?: number;\n image?: string;\n }\n ) {\n const { baseUrl, store } = await resolveGlobalOptions(this);\n await runUpWizard({\n baseUrl,\n logger,\n options,\n prompt,\n runCommand,\n store,\n });\n });\n\n program\n .command(\"down\")\n .description(\"Stop and remove local Starcite services\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"--no-volumes\", \"Keep Postgres volume data\")\n .action(async function (\n this: Command,\n options: { yes?: boolean; volumes?: boolean }\n ) {\n const { store } = await resolveGlobalOptions(this);\n await runDownWizard({\n logger,\n options,\n prompt,\n runCommand,\n store,\n });\n });\n\n program\n .command(\"create\")\n .description(\"Create a session\")\n .option(\"--id <id>\", \"Session ID\")\n .option(\"--title <title>\", \"Session title\")\n .option(\"--metadata <json>\", \"Session metadata JSON object\")\n .action(async function (\n this: Command,\n options: {\n id?: string;\n title?: string;\n metadata?: string;\n }\n ) {\n const resolved = await resolveGlobalOptions(this);\n const { json } = resolved;\n const client = resolved.apiKey\n ? createClient(resolved.baseUrl, resolved.apiKey)\n : createClient(resolved.baseUrl);\n const metadata = options.metadata\n ? parseJsonObject(options.metadata, \"--metadata\")\n : undefined;\n const session = await client.session({\n identity: resolveCreateIdentity(resolved.apiKey),\n id: options.id,\n title: options.title,\n metadata,\n });\n\n if (json) {\n writeJsonOutput(stdout, session.record ?? { id: session.id }, true);\n return;\n }\n\n logger.info(session.id);\n });\n\n program\n .command(\"append <sessionId>\")\n .description(\"Append an event\")\n .option(\"--agent <agent>\", \"Agent name (high-level mode)\")\n .option(\"--text <text>\", \"Text content (high-level mode)\")\n .option(\"--type <type>\", \"Event type\", \"content\")\n .option(\"--source <source>\", \"Event source\")\n .option(\n \"--producer-id <id>\",\n \"Producer identity (auto-generated if omitted)\"\n )\n .option(\n \"--producer-seq <seq>\",\n \"Producer sequence (defaults to persisted state, starting at 1)\",\n (value) => parsePositiveInteger(value, \"--producer-seq\")\n )\n .option(\"--actor <actor>\", \"Raw actor field (raw mode)\")\n .option(\"--payload <json>\", \"Raw payload JSON object (raw mode)\")\n .option(\"--metadata <json>\", \"Event metadata JSON object\")\n .option(\"--refs <json>\", \"Event refs JSON object\")\n .option(\"--idempotency-key <key>\", \"Idempotency key\")\n .option(\"--expected-seq <seq>\", \"Expected sequence\", (value) =>\n parseNonNegativeInteger(value, \"--expected-seq\")\n )\n .action(async function (\n this: Command,\n sessionId: string,\n options: AppendCommandOptions\n ) {\n const { baseUrl, apiKey, json, store } =\n await resolveGlobalOptions(this);\n const client = apiKey\n ? createClient(baseUrl, apiKey)\n : createClient(baseUrl);\n\n const metadata = options.metadata\n ? parseJsonObject(options.metadata, \"--metadata\")\n : undefined;\n const refs = options.refs\n ? parseJsonObject(options.refs, \"--refs\")\n : undefined;\n const mode = resolveAppendMode(options);\n const session =\n mode.kind === \"high-level\" &&\n apiKey !== undefined &&\n shouldAutoIssueSessionToken(apiKey)\n ? await client.session({\n identity: resolveCreateIdentity(apiKey, mode.agent),\n id: sessionId,\n })\n : await resolveSession(client, apiKey, sessionId);\n\n const response =\n mode.kind === \"high-level\"\n ? await session.append({\n type: options.type,\n text: mode.text,\n source: options.source,\n metadata,\n refs,\n idempotencyKey: options.idempotencyKey,\n expectedSeq: options.expectedSeq,\n })\n : await store.withStateLock(async () => {\n const producerId = await store.resolveProducerId(\n options.producerId\n );\n const normalizedBaseUrl = toApiBaseUrlForContext(baseUrl);\n const contextKey = buildSeqContextKey(\n normalizedBaseUrl,\n sessionId,\n producerId\n );\n const producerSeq =\n options.producerSeq ?? (await store.readNextSeq(contextKey));\n const appendResponse = await session.appendRaw({\n type: options.type,\n payload: parseJsonObject(mode.payload, \"--payload\"),\n actor: mode.actor,\n producer_id: producerId,\n producer_seq: producerSeq,\n source: options.source,\n metadata,\n refs,\n idempotency_key: options.idempotencyKey,\n expected_seq: options.expectedSeq,\n });\n\n await store.bumpNextSeq(contextKey, producerSeq);\n return appendResponse;\n });\n\n if (json) {\n writeJsonOutput(stdout, response, true);\n return;\n }\n\n logger.info(`seq=${response.seq} deduped=${response.deduped}`);\n });\n\n program\n .command(\"tail <sessionId>\")\n .description(\"Tail events from a session\")\n .option(\"--cursor <cursor>\", \"Replay cursor\", (value) =>\n parseNonNegativeInteger(value, \"--cursor\")\n )\n .option(\"--agent <agent>\", \"Filter by agent name\")\n .option(\"--limit <count>\", \"Stop after N events\", (value) =>\n parseNonNegativeInteger(value, \"--limit\")\n )\n .option(\"--no-follow\", \"Exit after replaying stored events\")\n .action(async function (\n this: Command,\n sessionId: string,\n options: {\n cursor?: number;\n agent?: string;\n limit?: number;\n follow: boolean;\n }\n ) {\n const { baseUrl, apiKey, json } = await resolveGlobalOptions(this);\n const client = apiKey\n ? createClient(baseUrl, apiKey)\n : createClient(baseUrl);\n const session = await resolveSession(client, apiKey, sessionId);\n\n const abortController = new AbortController();\n const onSigint = () => {\n abortController.abort();\n };\n\n process.once(\"SIGINT\", onSigint);\n\n try {\n let emitted = 0;\n\n for await (const { event } of session.tail({\n cursor: options.cursor ?? 0,\n batchSize: DEFAULT_TAIL_BATCH_SIZE,\n agent: options.agent,\n follow: options.follow,\n signal: abortController.signal,\n })) {\n if (options.limit !== undefined && emitted >= options.limit) {\n abortController.abort();\n break;\n }\n\n if (json) {\n writeJsonOutput(stdout, event);\n } else {\n logger.info(formatTailEvent(event));\n }\n\n emitted += 1;\n\n if (options.limit !== undefined && emitted >= options.limit) {\n abortController.abort();\n }\n }\n } finally {\n process.removeListener(\"SIGINT\", onSigint);\n }\n });\n\n return program;\n }\n\n async run(argv = process.argv): Promise<void> {\n const program = this.buildProgram();\n\n try {\n await program.parseAsync(argv);\n } catch (error) {\n if (error instanceof StarciteApiError) {\n this.logger.error(`${error.code} (${error.status}): ${error.message}`);\n process.exitCode = 1;\n return;\n }\n\n if (error instanceof Error) {\n this.logger.error(error.message);\n process.exitCode = 1;\n return;\n }\n\n this.logger.error(\"Unknown error\");\n process.exitCode = 1;\n }\n }\n}\n\nexport function buildProgram(deps: CliDependencies = {}): Command {\n return new StarciteCliApp(deps).buildProgram();\n}\n\nexport async function run(\n argv = process.argv,\n deps: CliDependencies = {}\n): Promise<void> {\n await new StarciteCliApp(deps).run(argv);\n}\n","{\n \"name\": \"starcite\",\n \"version\": \"0.0.7\",\n \"description\": \"CLI for Starcite\",\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://starcite.ai\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/fastpaca/starcite-clients.git\",\n \"directory\": \"packages/starcite-cli\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/fastpaca/starcite-clients/issues\"\n },\n \"keywords\": [\n \"starcite\",\n \"ai\",\n \"sessions\",\n \"event-log\",\n \"cli\"\n ],\n \"type\": \"module\",\n \"bin\": {\n \"starcite\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"clean\": \"rm -rf dist\",\n \"build\": \"tsup\",\n \"dev\": \"bun run src/index.ts\",\n \"compile\": \"bun run --cwd ../typescript-sdk build && bun build --compile src/index.ts --outfile dist/starcite\",\n \"test\": \"vitest run && bun run test:dist\",\n \"test:live\": \"vitest run test/live.api.integration.test.ts\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"prepublishOnly\": \"bun run clean && bun run build\",\n \"publish:dry\": \"bun publish --dry-run --access public\",\n \"test:dist\": \"bun run --cwd ../typescript-sdk build && bun run clean && bun run build && node dist/index.js --help > /dev/null\",\n \"lint\": \"ultracite check src test package.json tsconfig.json tsup.config.ts vitest.config.ts README.md\",\n \"format\": \"ultracite fix src test package.json tsconfig.json tsup.config.ts vitest.config.ts README.md\",\n \"check\": \"bun run lint && bun run typecheck && bun run test\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.0.1\",\n \"@starcite/sdk\": \"^0.0.7\",\n \"commander\": \"^13.1.0\",\n \"conf\": \"^15.1.0\",\n \"consola\": \"^3.4.2\",\n \"cosmiconfig\": \"^9.0.0\",\n \"proper-lockfile\": \"^4.1.2\",\n \"toml\": \"^3.0.0\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.15.30\",\n \"@types/proper-lockfile\": \"^4.1.4\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\",\n \"vitest\": \"^2.1.9\"\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { homedir, hostname } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport Conf from \"conf\";\nimport { cosmiconfig, defaultLoaders } from \"cosmiconfig\";\nimport { lock } from \"proper-lockfile\";\nimport { parse as parseToml } from \"toml\";\nimport { z } from \"zod\";\n\nconst DEFAULT_CONFIG_DIRECTORY_NAME = \".starcite\";\nconst CONFIG_JSON_FILENAME = \"config.json\";\nconst CONFIG_TOML_FILENAME = \"config.toml\";\nconst CREDENTIALS_FILENAME = \"credentials\";\nconst IDENTITY_FILENAME = \"identity\";\nconst STATE_FILENAME = \"state\";\nconst STATE_LOCK_FILENAME = \".state.lock\";\nconst TILDE_PREFIX_REGEX = /^~(?=\\/|$)/;\n\nconst ConfigFileSchema = z\n .object({\n baseUrl: z.string().optional(),\n base_url: z.string().optional(),\n producerId: z.string().optional(),\n producer_id: z.string().optional(),\n apiKey: z.string().optional(),\n api_key: z.string().optional(),\n })\n .passthrough();\n\nconst IdentityFileSchema = z.object({\n producerId: z.string().trim().min(1),\n hostname: z.string().trim().min(1),\n uuid: z.string().uuid(),\n createdAt: z.string(),\n});\n\nconst StateFileSchema = z.object({\n nextSeqByContext: z.record(z.number().int().positive()).default({}),\n});\n\nconst CredentialsFileSchema = z.object({\n apiKey: z.string().trim().min(1).optional(),\n});\n\ntype IdentityFile = z.infer<typeof IdentityFileSchema>;\ntype StateFile = z.infer<typeof StateFileSchema>;\ntype CredentialsFile = z.infer<typeof CredentialsFileSchema>;\n\nexport interface StarciteCliConfig {\n baseUrl?: string;\n producerId?: string;\n apiKey?: string;\n}\n\nfunction trimString(value?: string): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeConfig(input: unknown): StarciteCliConfig {\n const parsed = ConfigFileSchema.safeParse(input);\n\n if (!parsed.success) {\n return {};\n }\n\n return {\n baseUrl: trimString(parsed.data.baseUrl ?? parsed.data.base_url),\n producerId: trimString(parsed.data.producerId ?? parsed.data.producer_id),\n apiKey: trimString(parsed.data.apiKey ?? parsed.data.api_key),\n };\n}\n\nfunction defaultConfigDirectory(): string {\n const home = homedir();\n if (home.trim().length > 0) {\n return join(home, DEFAULT_CONFIG_DIRECTORY_NAME);\n }\n\n return resolve(DEFAULT_CONFIG_DIRECTORY_NAME);\n}\n\nexport function resolveConfigDir(input?: string): string {\n const configured = trimString(input) ?? trimString(process.env.STARCITE_HOME);\n const withTilde = configured?.startsWith(\"~\")\n ? configured.replace(TILDE_PREFIX_REGEX, homedir())\n : configured;\n\n return resolve(withTilde ?? defaultConfigDirectory());\n}\n\nexport function buildSeqContextKey(\n baseUrl: string,\n sessionId: string,\n producerId: string\n): string {\n return `${baseUrl}::${sessionId}::${producerId}`;\n}\n\nexport class StarciteCliStore {\n readonly directory: string;\n private readonly lockPath: string;\n private readonly configExplorer = cosmiconfig(\"starcite\", {\n cache: false,\n searchStrategy: \"none\",\n searchPlaces: [CONFIG_JSON_FILENAME, CONFIG_TOML_FILENAME],\n loaders: {\n ...defaultLoaders,\n \".toml\": (_filepath, content) => parseToml(content) as unknown,\n },\n });\n private readonly identityStore: Conf<IdentityFile>;\n private readonly credentialsStore: Conf<CredentialsFile>;\n private readonly stateStore: Conf<StateFile>;\n\n constructor(directory: string) {\n this.directory = directory;\n this.lockPath = join(directory, STATE_LOCK_FILENAME);\n this.identityStore = new Conf<IdentityFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: IDENTITY_FILENAME,\n fileExtension: \"json\",\n });\n this.credentialsStore = new Conf<CredentialsFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: CREDENTIALS_FILENAME,\n fileExtension: \"json\",\n defaults: {},\n });\n this.stateStore = new Conf<StateFile>({\n cwd: directory,\n clearInvalidConfig: true,\n configName: STATE_FILENAME,\n fileExtension: \"json\",\n defaults: { nextSeqByContext: {} },\n });\n }\n\n async readConfig(): Promise<StarciteCliConfig> {\n await this.ensureConfigDirectory();\n const result = await this.configExplorer.search(this.directory);\n\n if (!result) {\n return {};\n }\n\n return normalizeConfig(result.config);\n }\n\n async writeConfig(config: StarciteCliConfig): Promise<void> {\n await this.ensureConfigDirectory();\n\n const normalized = normalizeConfig(config);\n const serialized: StarciteCliConfig = {};\n\n if (normalized.baseUrl) {\n serialized.baseUrl = normalized.baseUrl;\n }\n\n if (normalized.producerId) {\n serialized.producerId = normalized.producerId;\n }\n\n if (normalized.apiKey) {\n serialized.apiKey = normalized.apiKey;\n }\n\n await writeFile(\n join(this.directory, CONFIG_JSON_FILENAME),\n `${JSON.stringify(serialized, null, 2)}\\n`,\n \"utf8\"\n );\n }\n\n async updateConfig(\n patch: Partial<StarciteCliConfig>\n ): Promise<StarciteCliConfig> {\n const current = await this.readConfig();\n const merged = normalizeConfig({\n ...current,\n ...patch,\n });\n\n await this.writeConfig(merged);\n return merged;\n }\n\n async readApiKey(): Promise<string | undefined> {\n const fromEnv = trimString(process.env.STARCITE_API_KEY);\n if (fromEnv) {\n return fromEnv;\n }\n\n const parsed = CredentialsFileSchema.safeParse(this.credentialsStore.store);\n const fromCredentials = parsed.success\n ? trimString(parsed.data.apiKey)\n : undefined;\n if (fromCredentials) {\n return fromCredentials;\n }\n\n const config = await this.readConfig();\n return trimString(config.apiKey);\n }\n\n async saveApiKey(apiKey: string): Promise<void> {\n await this.ensureConfigDirectory();\n\n const normalized = trimString(apiKey);\n if (!normalized) {\n throw new Error(\"API key cannot be empty\");\n }\n\n this.credentialsStore.set(\"apiKey\", normalized);\n }\n\n async clearApiKey(): Promise<void> {\n await this.ensureConfigDirectory();\n this.credentialsStore.delete(\"apiKey\");\n }\n\n async resolveProducerId(explicitProducerId?: string): Promise<string> {\n const explicit = trimString(explicitProducerId);\n if (explicit) {\n return explicit;\n }\n\n const fromEnv = trimString(process.env.STARCITE_PRODUCER_ID);\n if (fromEnv) {\n return fromEnv;\n }\n\n const config = await this.readConfig();\n const fromConfig = trimString(config.producerId);\n if (fromConfig) {\n return fromConfig;\n }\n\n const identity = await this.readOrCreateIdentity();\n return identity.producerId;\n }\n\n async withStateLock<T>(action: () => Promise<T>): Promise<T> {\n await this.ensureConfigDirectory();\n const release = await lock(this.directory, {\n lockfilePath: this.lockPath,\n realpath: false,\n retries: {\n retries: 50,\n minTimeout: 20,\n maxTimeout: 60,\n },\n });\n\n try {\n return await action();\n } finally {\n await release();\n }\n }\n\n readNextSeq(contextKey: string): Promise<number> {\n const state = this.readState();\n return Promise.resolve(state.nextSeqByContext[contextKey] ?? 1);\n }\n\n bumpNextSeq(contextKey: string, usedSeq: number): Promise<void> {\n const state = this.readState();\n const nextSeqByContext = {\n ...state.nextSeqByContext,\n [contextKey]: Math.max(\n state.nextSeqByContext[contextKey] ?? 1,\n usedSeq + 1\n ),\n };\n\n this.stateStore.set(\"nextSeqByContext\", nextSeqByContext);\n return Promise.resolve();\n }\n\n private readState(): StateFile {\n const parsed = StateFileSchema.safeParse(this.stateStore.store);\n\n if (parsed.success) {\n return parsed.data;\n }\n\n this.stateStore.clear();\n return { nextSeqByContext: {} };\n }\n\n private readOrCreateIdentity(): IdentityFile {\n const parsed = IdentityFileSchema.safeParse(this.identityStore.store);\n if (parsed.success) {\n return parsed.data;\n }\n\n const host = hostname();\n const uuid = randomUUID();\n const identity: IdentityFile = {\n producerId: `cli:${host}:${uuid}`,\n hostname: host,\n uuid,\n createdAt: new Date().toISOString(),\n };\n\n this.identityStore.store = identity;\n return identity;\n }\n\n private async ensureConfigDirectory(): Promise<void> {\n await mkdir(this.directory, { recursive: true });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { mkdir, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n cancel as clackCancel,\n confirm as clackConfirm,\n password as clackPassword,\n text as clackText,\n isCancel,\n} from \"@clack/prompts\";\nimport type { LoggerLike } from \"./cli\";\nimport type { StarciteCliStore } from \"./store\";\n\nexport const DEFAULT_API_PORT = 45_187;\nconst DEFAULT_DB_PORT = 5433;\nconst MIN_PORT = 1;\nconst MAX_PORT = 65_535;\nconst RUNTIME_DIRECTORY_NAME = \"runtime\";\n\nconst DEFAULT_COMPOSE_FILE = `services:\n app:\n image: \\${STARCITE_IMAGE:-ghcr.io/fastpaca/starcite:latest}\n depends_on:\n db:\n condition: service_healthy\n environment:\n SECRET_KEY_BASE: \\${SECRET_KEY_BASE:-xuQnOFm6sH5Qdd7x4WJv5smuG2Xf2nG0BL8rJ4yX6HnKGeTjo6n8r5hQKsxNkZWz}\n PHX_HOST: \\${PHX_HOST:-localhost}\n PORT: 4000\n DATABASE_URL: \\${DATABASE_URL:-ecto://postgres:postgres@db:5432/starcite_dev}\n MIGRATE_ON_BOOT: \\${MIGRATE_ON_BOOT:-true}\n DNS_CLUSTER_QUERY: \\${DNS_CLUSTER_QUERY:-}\n DNS_CLUSTER_NODE_BASENAME: \\${DNS_CLUSTER_NODE_BASENAME:-starcite}\n DNS_POLL_INTERVAL_MS: \\${DNS_POLL_INTERVAL_MS:-5000}\n ports:\n - \"\\${STARCITE_API_PORT:-45187}:4000\"\n restart: unless-stopped\n\n db:\n image: postgres:15\n environment:\n POSTGRES_DB: starcite_dev\n POSTGRES_USER: postgres\n POSTGRES_PASSWORD: postgres\n healthcheck:\n test: [\"CMD\", \"pg_isready\", \"-U\", \"postgres\"]\n interval: 10s\n timeout: 5s\n retries: 5\n ports:\n - \"\\${STARCITE_DB_PORT:-5433}:5432\"\n volumes:\n - db-data:/var/lib/postgresql/data\n restart: unless-stopped\n\nvolumes:\n db-data:\n`;\n\ninterface CommandRunOptions {\n cwd?: string;\n}\n\nexport interface CommandResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nexport type CommandRunner = (\n command: string,\n args: string[],\n options?: CommandRunOptions\n) => Promise<CommandResult>;\n\nexport interface PromptAdapter {\n confirm(message: string, defaultValue?: boolean): Promise<boolean>;\n input(message: string, defaultValue?: string): Promise<string>;\n password?(message: string): Promise<string>;\n}\n\nexport interface UpOptions {\n yes?: boolean;\n port?: number;\n dbPort?: number;\n image?: string;\n}\n\nexport interface DownOptions {\n yes?: boolean;\n volumes?: boolean;\n}\n\ninterface UpWizardInput {\n baseUrl: string;\n logger: LoggerLike;\n options: UpOptions;\n prompt: PromptAdapter;\n runCommand: CommandRunner;\n store: StarciteCliStore;\n}\n\ninterface DownWizardInput {\n logger: LoggerLike;\n options: DownOptions;\n prompt: PromptAdapter;\n runCommand: CommandRunner;\n store: StarciteCliStore;\n}\n\nfunction parsePort(value: string, optionName: string): number {\n const parsed = Number(value);\n\n if (!Number.isInteger(parsed) || parsed < MIN_PORT || parsed > MAX_PORT) {\n throw new Error(\n `${optionName} must be an integer between ${MIN_PORT} and ${MAX_PORT}`\n );\n }\n\n return parsed;\n}\n\nfunction baseUrlPort(baseUrl: string): number {\n try {\n const parsed = new URL(baseUrl);\n\n if (parsed.port) {\n return parsePort(parsed.port, \"base URL port\");\n }\n } catch {\n return DEFAULT_API_PORT;\n }\n\n return DEFAULT_API_PORT;\n}\n\nasync function ensureSuccess(\n runCommand: CommandRunner,\n command: string,\n args: string[]\n): Promise<boolean> {\n const result = await runCommand(command, args);\n return result.code === 0;\n}\n\nasync function ensureDockerReady(\n logger: LoggerLike,\n runCommand: CommandRunner\n): Promise<void> {\n const hasDocker = await ensureSuccess(runCommand, \"docker\", [\"--version\"]);\n if (!hasDocker) {\n logger.error(\"You don't have Docker installed, please install it.\");\n throw new Error(\"Docker is required to run this command.\");\n }\n\n const hasDockerCompose = await ensureSuccess(runCommand, \"docker\", [\n \"compose\",\n \"version\",\n ]);\n if (!hasDockerCompose) {\n logger.error(\n \"Docker Compose is not available. Install Docker Compose and retry.\"\n );\n throw new Error(\"Docker Compose is required to run this command.\");\n }\n\n const daemonRunning = await ensureSuccess(runCommand, \"docker\", [\"info\"]);\n if (!daemonRunning) {\n logger.error(\"Docker is installed but the daemon is not running.\");\n throw new Error(\"Start Docker and retry.\");\n }\n}\n\nasync function selectApiPort(\n baseUrl: string,\n options: UpOptions,\n prompt: PromptAdapter\n): Promise<number> {\n if (options.port !== undefined) {\n return options.port;\n }\n\n const fallbackPort = baseUrlPort(baseUrl);\n\n if (options.yes) {\n return fallbackPort;\n }\n\n while (true) {\n const answer = await prompt.input(\n \"What port do you want it on?\",\n `${fallbackPort}`\n );\n\n try {\n return parsePort(answer, \"port\");\n } catch (error) {\n if (error instanceof Error) {\n // keep asking until valid\n }\n }\n }\n}\n\nfunction runtimeDirectory(store: StarciteCliStore): string {\n return join(store.directory, RUNTIME_DIRECTORY_NAME);\n}\n\nasync function runtimeDirectoryExists(\n store: StarciteCliStore\n): Promise<boolean> {\n try {\n const result = await stat(runtimeDirectory(store));\n return result.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function writeComposeFiles(\n store: StarciteCliStore,\n options: { apiPort: number; dbPort: number; image?: string }\n): Promise<string> {\n const directory = runtimeDirectory(store);\n await mkdir(directory, { recursive: true });\n\n await writeFile(\n join(directory, \"docker-compose.yml\"),\n DEFAULT_COMPOSE_FILE,\n \"utf8\"\n );\n\n const envLines = [\n `STARCITE_API_PORT=${options.apiPort}`,\n `STARCITE_DB_PORT=${options.dbPort}`,\n ];\n\n if (options.image?.trim()) {\n envLines.push(`STARCITE_IMAGE=${options.image.trim()}`);\n }\n\n await writeFile(join(directory, \".env\"), `${envLines.join(\"\\n\")}\\n`, \"utf8\");\n return directory;\n}\n\nexport function parsePortOption(value: string, optionName: string): number {\n try {\n return parsePort(value, optionName);\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(error.message);\n }\n\n throw error;\n }\n}\n\nexport async function runUpWizard(input: UpWizardInput): Promise<void> {\n const { baseUrl, logger, options, prompt, runCommand, store } = input;\n\n await ensureDockerReady(logger, runCommand);\n\n const confirmed = options.yes\n ? true\n : await prompt.confirm(\n \"Are you sure you want to create the docker containers?\",\n true\n );\n\n if (!confirmed) {\n logger.info(\"Cancelled.\");\n return;\n }\n\n const apiPort = await selectApiPort(baseUrl, options, prompt);\n const dbPort = options.dbPort ?? DEFAULT_DB_PORT;\n const composeDirectory = await writeComposeFiles(store, {\n apiPort,\n dbPort,\n image: options.image,\n });\n\n const result = await runCommand(\"docker\", [\"compose\", \"up\", \"-d\"], {\n cwd: composeDirectory,\n });\n\n if (result.code !== 0) {\n const message =\n result.stderr || result.stdout || \"docker compose up failed\";\n throw new Error(message.trim());\n }\n\n logger.info(`Starcite is starting on http://localhost:${apiPort}`);\n logger.info(`Compose files are in ${composeDirectory}`);\n}\n\nexport async function runDownWizard(input: DownWizardInput): Promise<void> {\n const { logger, options, prompt, runCommand, store } = input;\n\n await ensureDockerReady(logger, runCommand);\n\n const hasRuntimeDirectory = await runtimeDirectoryExists(store);\n if (!hasRuntimeDirectory) {\n logger.info(\n `No Starcite runtime found at ${runtimeDirectory(\n store\n )}. Nothing to tear down.`\n );\n return;\n }\n\n const removeVolumes = options.volumes ?? true;\n const confirmed = options.yes\n ? true\n : await prompt.confirm(\n removeVolumes\n ? \"Are you sure you want to stop and delete Starcite containers and volumes?\"\n : \"Are you sure you want to stop Starcite containers?\",\n false\n );\n\n if (!confirmed) {\n logger.info(\"Cancelled.\");\n return;\n }\n\n const args = [\"compose\", \"down\", \"--remove-orphans\"];\n if (removeVolumes) {\n args.push(\"-v\");\n }\n\n const result = await runCommand(\"docker\", args, {\n cwd: runtimeDirectory(store),\n });\n\n if (result.code !== 0) {\n const message =\n result.stderr || result.stdout || \"docker compose down failed\";\n throw new Error(message.trim());\n }\n\n logger.info(\"Starcite containers stopped.\");\n if (removeVolumes) {\n logger.info(\"Starcite volumes removed.\");\n }\n}\n\nexport function createDefaultPrompt(): PromptAdapter {\n const assertInteractive = (): void => {\n if (!(process.stdin.isTTY && process.stdout.isTTY)) {\n throw new Error(\n \"Interactive mode requires a TTY. Re-run with explicit options (for example: --yes, --endpoint, --api-key).\"\n );\n }\n };\n\n return {\n async confirm(message: string, defaultValue = true): Promise<boolean> {\n assertInteractive();\n\n const answer = await clackConfirm({\n message,\n initialValue: defaultValue,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n return false;\n }\n\n return answer;\n },\n async input(message: string, defaultValue = \"\"): Promise<string> {\n assertInteractive();\n\n const answer = await clackText({\n message,\n defaultValue,\n placeholder: defaultValue || undefined,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n throw new Error(\"Cancelled.\");\n }\n\n const normalized = answer.trim();\n return normalized || defaultValue;\n },\n async password(message: string): Promise<string> {\n assertInteractive();\n\n const answer = await clackPassword({\n message,\n input: process.stdin,\n output: process.stdout,\n });\n\n if (isCancel(answer)) {\n clackCancel(\"Cancelled.\");\n throw new Error(\"Cancelled.\");\n }\n\n return answer.trim();\n },\n };\n}\n\nexport const defaultCommandRunner: CommandRunner = (command, args, options) =>\n new Promise((resolve) => {\n const child = spawn(command, args, {\n cwd: options?.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n const message = error.message || \"command failed to start\";\n resolve({ code: 127, stdout, stderr: `${stderr}${message}` });\n });\n\n child.on(\"close\", (code) => {\n resolve({ code: code ?? 1, stdout, stderr });\n });\n });\n","import { run } from \"./cli\";\n\nrun();\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,SAAS,4BAA4B;AAC9C,SAAS,qBAAqB;AAC9B,SAAS,KAAAA,UAAS;;;ACRlB;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,UAAY;AAAA,EACZ,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,KAAO;AAAA,IACL,UAAY;AAAA,EACd;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,OAAS;AAAA,IACT,KAAO;AAAA,IACP,SAAW;AAAA,IACX,MAAQ;AAAA,IACR,aAAa;AAAA,IACb,WAAa;AAAA,IACb,gBAAkB;AAAA,IAClB,eAAe;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Q,WAAW,IAAI;AAAA,IAC/B,SAAS,OAAO;AACd,UAAI,iBAAiB,kBAAkB;AACrC,aAAK,OAAO,MAAM,GAAG,MAAM,IAAI,KAAK,MAAM,MAAM,MAAM,MAAM,OAAO,EAAE;AACrE,gBAAQ,WAAW;AACnB;AAAA,MACF;AAEA,UAAI,iBAAiB,OAAO;AAC1B,aAAK,OAAO,MAAM,MAAM,OAAO;AAC/B,gBAAQ,WAAW;AACnB;AAAA,MACF;AAEA,WAAK,OAAO,MAAM,eAAe;AACjC,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;AAMA,eAAsB,IACpB,OAAO,QAAQ,MACf,OAAwB,CAAC,GACV;AACf,QAAM,IAAI,eAAe,IAAI,EAAE,IAAI,IAAI;AACzC;;;AI94BA,IAAI;","names":["z","mkdir","writeFile","join","resolve","z","parsePort","trimString"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starcite",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "CLI for Starcite",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://starcite.ai",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@clack/prompts": "^1.0.1",
46
- "@starcite/sdk": "^0.0.6",
46
+ "@starcite/sdk": "^0.0.7",
47
47
  "commander": "^13.1.0",
48
48
  "conf": "^15.1.0",
49
49
  "consola": "^3.4.2",