@theokit/sdk 4.11.1 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/eval.js CHANGED
@@ -3,7 +3,7 @@ import { createRequire } from 'module';
3
3
  import { randomUUID, createHash, randomBytes } from 'crypto';
4
4
  import { mkdir, writeFile, stat, readFile, rename, readdir, open, unlink, statfs, access } from 'fs/promises';
5
5
  import { join, dirname, resolve, sep, relative, isAbsolute } from 'path';
6
- import { readFileSync, mkdirSync, appendFileSync, existsSync, realpathSync, lstatSync, readlinkSync, readdirSync } from 'fs';
6
+ import { readFileSync, mkdirSync, appendFileSync, existsSync, realpathSync, lstatSync, readlinkSync, readdirSync, statSync, chmodSync, openSync, writeFileSync, fsyncSync, closeSync, renameSync, unlinkSync } from 'fs';
7
7
  import { AsyncLocalStorage } from 'async_hooks';
8
8
  import { homedir } from 'os';
9
9
  import { execFile, spawn } from 'child_process';
@@ -566,10 +566,10 @@ function buildToolPrompt(prompt) {
566
566
  Respond by calling the \`output\` tool with the structured answer that matches the schema.`;
567
567
  }
568
568
  function setupStructuredOutput(schema, maxRetries) {
569
- const z9 = requireZod();
569
+ const z10 = requireZod();
570
570
  const jsonSchema = toJsonSchema(schema, { unrepresentable: "any" });
571
571
  return {
572
- z: z9,
572
+ z: z10,
573
573
  jsonSchema,
574
574
  maxRetries: maxRetries ?? 1,
575
575
  initialUsage: { inputTokens: 0, outputTokens: 0 }
@@ -11371,6 +11371,358 @@ var OPENAI = {
11371
11371
  hostname: "api.openai.com",
11372
11372
  fallbackModels: ["gpt-4o", "gpt-4o-mini"]
11373
11373
  };
11374
+ function credentialHome(config, env = {}) {
11375
+ const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
11376
+ return override !== void 0 && override.length > 0 ? override : join(config.home, config.dirName);
11377
+ }
11378
+ function authFilePath(config, env = {}) {
11379
+ return join(credentialHome(config, env), config.fileName);
11380
+ }
11381
+ var CredentialError = class extends Error {
11382
+ constructor(message) {
11383
+ super(message);
11384
+ this.name = "CredentialError";
11385
+ }
11386
+ };
11387
+ var apiFileSchema = z.object({
11388
+ type: z.literal("api").optional(),
11389
+ provider: z.string().min(1).optional(),
11390
+ api_key: z.string()
11391
+ }).strict();
11392
+ var oauthFileSchema = z.object({
11393
+ type: z.literal("oauth"),
11394
+ provider: z.string().min(1),
11395
+ access: z.string().min(1),
11396
+ refresh: z.string().min(1),
11397
+ expires: z.number(),
11398
+ account_id: z.string().optional()
11399
+ }).strict();
11400
+ var fileSchema = z.union([oauthFileSchema, apiFileSchema]);
11401
+ function assertSecureModes(dirPath, path) {
11402
+ const dirMode = statSync(dirPath).mode & 511;
11403
+ if ((dirMode & 18) !== 0) {
11404
+ throw new CredentialError(
11405
+ `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file inside it can be replaced. Fix it with: chmod 700 ${dirPath}`
11406
+ );
11407
+ }
11408
+ const mode = statSync(path).mode & 511;
11409
+ if ((mode & 63) !== 0) {
11410
+ throw new CredentialError(
11411
+ `${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
11412
+ );
11413
+ }
11414
+ }
11415
+ function describeUnionError(parsed, err, path) {
11416
+ const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
11417
+ const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
11418
+ let issue;
11419
+ if (!specific.success) {
11420
+ issue = specific.error.issues[0];
11421
+ } else if (err instanceof z.ZodError) {
11422
+ issue = err.issues[0];
11423
+ }
11424
+ return new CredentialError(
11425
+ `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
11426
+ );
11427
+ }
11428
+ function parseStoredFile(raw, path) {
11429
+ let parsed;
11430
+ try {
11431
+ parsed = JSON.parse(raw);
11432
+ } catch {
11433
+ throw new CredentialError(
11434
+ `${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
11435
+ );
11436
+ }
11437
+ try {
11438
+ return fileSchema.parse(parsed);
11439
+ } catch (err) {
11440
+ throw describeUnionError(parsed, err, path);
11441
+ }
11442
+ }
11443
+ function readAuthFile(config, env = {}) {
11444
+ const path = authFilePath(config, env);
11445
+ let raw;
11446
+ try {
11447
+ raw = readFileSync(path, "utf8");
11448
+ } catch (err) {
11449
+ if (err.code === "ENOENT") return void 0;
11450
+ throw new CredentialError(`cannot read ${path}: ${err.message}`);
11451
+ }
11452
+ assertSecureModes(credentialHome(config, env), path);
11453
+ return parseStoredFile(raw, path);
11454
+ }
11455
+ function readStoredOAuth(config, env = {}) {
11456
+ const stored = readAuthFile(config, env);
11457
+ return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
11458
+ }
11459
+ function isOAuthWrite(c) {
11460
+ return "type" in c && c.type === "oauth";
11461
+ }
11462
+ function buildStorePayload(cred) {
11463
+ if (isOAuthWrite(cred)) {
11464
+ if (cred.access.length === 0 || cred.refresh.length === 0) {
11465
+ throw new CredentialError(
11466
+ "refusing to write an oauth credential with an empty access/refresh token"
11467
+ );
11468
+ }
11469
+ return {
11470
+ type: "oauth",
11471
+ provider: cred.provider,
11472
+ access: cred.access,
11473
+ refresh: cred.refresh,
11474
+ expires: cred.expires,
11475
+ ...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
11476
+ };
11477
+ }
11478
+ if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
11479
+ throw new CredentialError("refusing to write an empty API key");
11480
+ }
11481
+ return { provider: cred.provider, api_key: cred.apiKey };
11482
+ }
11483
+ function writeCredential(cred, config, env = {}) {
11484
+ const payload = buildStorePayload(cred);
11485
+ const dir = credentialHome(config, env);
11486
+ mkdirSync(dir, { recursive: true, mode: 448 });
11487
+ chmodSync(dir, 448);
11488
+ const path = authFilePath(config, env);
11489
+ const tmp = `${path}.tmp-${randomBytes(8).toString("hex")}`;
11490
+ try {
11491
+ const fd = openSync(tmp, "wx", 384);
11492
+ try {
11493
+ writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
11494
+ `);
11495
+ fsyncSync(fd);
11496
+ } finally {
11497
+ closeSync(fd);
11498
+ }
11499
+ chmodSync(tmp, 384);
11500
+ renameSync(tmp, path);
11501
+ } catch (err) {
11502
+ try {
11503
+ unlinkSync(tmp);
11504
+ } catch {
11505
+ }
11506
+ throw new CredentialError(`cannot write ${path}: ${err.message}`);
11507
+ }
11508
+ return path;
11509
+ }
11510
+
11511
+ // src/server/auth/errors.ts
11512
+ var AuthCallbackError = class extends Error {
11513
+ name = "AuthCallbackError";
11514
+ code;
11515
+ constructor(code, message) {
11516
+ super(message ?? `OAuth callback error: ${code}`);
11517
+ this.code = code;
11518
+ }
11519
+ };
11520
+
11521
+ // src/internal/auth/oauth-engine.ts
11522
+ var REFRESH_SKEW_MS = 6e4;
11523
+ function parseTokenResponse(body, now) {
11524
+ const b = body;
11525
+ if (typeof b.access_token !== "string" || b.access_token.length === 0) {
11526
+ throw new AuthCallbackError(
11527
+ "oauth_token_exchange_failed",
11528
+ "token response had no access_token"
11529
+ );
11530
+ }
11531
+ if (typeof b.refresh_token !== "string" || b.refresh_token.length === 0) {
11532
+ throw new AuthCallbackError(
11533
+ "oauth_token_exchange_failed",
11534
+ "token response had no refresh_token"
11535
+ );
11536
+ }
11537
+ const expiresIn = typeof b.expires_in === "number" ? b.expires_in : 3600;
11538
+ return {
11539
+ access: b.access_token,
11540
+ refresh: b.refresh_token,
11541
+ expires: now + expiresIn * 1e3,
11542
+ ...typeof b.account_id === "string" ? { accountId: b.account_id } : {}
11543
+ };
11544
+ }
11545
+ async function postGrant(config, form, deps) {
11546
+ let res;
11547
+ try {
11548
+ res = await deps.fetch(config.tokenEndpoint, {
11549
+ method: "POST",
11550
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
11551
+ body: new URLSearchParams(form).toString()
11552
+ });
11553
+ } catch (err) {
11554
+ throw new AuthCallbackError(
11555
+ "oauth_token_exchange_failed",
11556
+ `token endpoint request failed: ${err.message}`
11557
+ );
11558
+ }
11559
+ if (!res.ok) {
11560
+ throw new AuthCallbackError(
11561
+ "oauth_token_exchange_failed",
11562
+ `token endpoint returned HTTP ${res.status}`
11563
+ );
11564
+ }
11565
+ let json;
11566
+ try {
11567
+ json = await res.json();
11568
+ } catch {
11569
+ throw new AuthCallbackError("oauth_token_exchange_failed", "token response was not valid JSON");
11570
+ }
11571
+ return parseTokenResponse(json, deps.now());
11572
+ }
11573
+ function refreshOAuthTokens(config, refresh, deps) {
11574
+ return postGrant(
11575
+ config,
11576
+ { grant_type: "refresh_token", refresh_token: refresh, client_id: config.clientId },
11577
+ deps
11578
+ );
11579
+ }
11580
+ function persistOAuthTokens(provider, tokens, store, env = {}) {
11581
+ return writeCredential(
11582
+ {
11583
+ type: "oauth",
11584
+ provider,
11585
+ access: tokens.access,
11586
+ refresh: tokens.refresh,
11587
+ expires: tokens.expires,
11588
+ ...tokens.accountId !== void 0 ? { account_id: tokens.accountId } : {}
11589
+ },
11590
+ store,
11591
+ env
11592
+ );
11593
+ }
11594
+ var inFlightRefresh = /* @__PURE__ */ new Map();
11595
+ async function ensureFreshCredential(resolved, opts, deps) {
11596
+ if (resolved.kind !== "oauth") return resolved;
11597
+ const now = deps.now();
11598
+ if (resolved.expiresAt !== void 0 && resolved.expiresAt > now + REFRESH_SKEW_MS) {
11599
+ return resolved;
11600
+ }
11601
+ const env = opts.env ?? {};
11602
+ const path = authFilePath(opts.store, env);
11603
+ let refresh = inFlightRefresh.get(path);
11604
+ if (refresh === void 0) {
11605
+ refresh = (async () => {
11606
+ const stored = readStoredOAuth(opts.store, env);
11607
+ if (stored === void 0) {
11608
+ throw new AuthCallbackError(
11609
+ "oauth_token_exchange_failed",
11610
+ "no stored oauth credential to refresh"
11611
+ );
11612
+ }
11613
+ const fresh2 = await refreshOAuthTokens(opts.config, stored.refresh, deps);
11614
+ const merged = {
11615
+ ...fresh2,
11616
+ accountId: fresh2.accountId ?? stored.account_id
11617
+ };
11618
+ persistOAuthTokens(resolved.provider, merged, opts.store, env);
11619
+ return merged;
11620
+ })();
11621
+ inFlightRefresh.set(path, refresh);
11622
+ refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {
11623
+ });
11624
+ }
11625
+ const fresh = await refresh;
11626
+ return {
11627
+ kind: "oauth",
11628
+ provider: resolved.provider,
11629
+ apiKey: fresh.access,
11630
+ source: resolved.source,
11631
+ inferred: false,
11632
+ expiresAt: fresh.expires
11633
+ };
11634
+ }
11635
+
11636
+ // src/internal/auth/resolve-credential.ts
11637
+ async function resolveOAuth(stored, path, opts, env) {
11638
+ if (stored.provider !== opts.provider) return void 0;
11639
+ const base = {
11640
+ kind: "oauth",
11641
+ provider: opts.provider,
11642
+ apiKey: stored.access,
11643
+ source: path,
11644
+ inferred: false,
11645
+ expiresAt: stored.expires
11646
+ };
11647
+ if (opts.oauth === void 0) return base;
11648
+ const deps = {
11649
+ fetch: opts.deps?.fetch ?? fetch,
11650
+ now: opts.deps?.now ?? (() => Date.now())
11651
+ };
11652
+ return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);
11653
+ }
11654
+ async function resolveCredential(opts) {
11655
+ const env = opts.env ?? {};
11656
+ const stored = readAuthFile(opts.store, env);
11657
+ if (stored === void 0) return void 0;
11658
+ const path = authFilePath(opts.store, env);
11659
+ if (stored.type === "oauth") {
11660
+ return resolveOAuth(stored, path, opts, env);
11661
+ }
11662
+ if (stored.api_key.length === 0) return void 0;
11663
+ if (stored.provider !== opts.provider) return void 0;
11664
+ return {
11665
+ kind: "api",
11666
+ provider: opts.provider,
11667
+ apiKey: stored.api_key,
11668
+ source: path,
11669
+ inferred: false
11670
+ };
11671
+ }
11672
+
11673
+ // src/internal/providers/builtin/openai-chatgpt.ts
11674
+ var DEFAULT_STORE = {
11675
+ home: homedir(),
11676
+ dirName: ".theokit",
11677
+ fileName: "auth.json",
11678
+ homeEnvVar: "THEOKIT_HOME"
11679
+ };
11680
+ var OPENAI_OAUTH_CONFIG = {
11681
+ provider: "openai",
11682
+ authorizeEndpoint: "https://auth.openai.com/oauth/authorize",
11683
+ tokenEndpoint: "https://auth.openai.com/oauth/token",
11684
+ clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
11685
+ scopes: ["openid", "profile", "email", "offline_access"],
11686
+ redirectUri: "https://auth.openai.com/deviceauth/callback"
11687
+ };
11688
+ function codexFetch() {
11689
+ return (async (input, init) => {
11690
+ const env = process.env;
11691
+ const resolved = await resolveCredential({
11692
+ provider: "openai",
11693
+ store: DEFAULT_STORE,
11694
+ oauth: OPENAI_OAUTH_CONFIG,
11695
+ env
11696
+ });
11697
+ if (resolved === void 0) {
11698
+ throw new Error(
11699
+ 'openai-chatgpt: no ChatGPT credential found \u2014 run the OpenAI device login (e.g. "/login openai") first.'
11700
+ );
11701
+ }
11702
+ const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;
11703
+ const headers = new Headers(init?.headers);
11704
+ headers.set("authorization", `Bearer ${resolved.apiKey}`);
11705
+ if (accountId !== void 0) headers.set("ChatGPT-Account-Id", accountId);
11706
+ return fetch(input, { ...init, headers });
11707
+ });
11708
+ }
11709
+ var OPENAI_CHATGPT = {
11710
+ name: "openai-chatgpt",
11711
+ apiMode: "responses_api",
11712
+ authType: "oauth_device_code",
11713
+ baseUrl: "https://chatgpt.com/backend-api/codex",
11714
+ envVars: [],
11715
+ fallbackModels: [
11716
+ "openai-chatgpt/gpt-5.4",
11717
+ "openai-chatgpt/gpt-5.4-mini",
11718
+ "openai-chatgpt/gpt-5.5"
11719
+ ],
11720
+ extraHeaders: { originator: "codex_cli_rs" },
11721
+ transform: {
11722
+ // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.
11723
+ fetch: () => codexFetch()
11724
+ }
11725
+ };
11374
11726
 
11375
11727
  // src/internal/providers/builtin/openrouter.ts
11376
11728
  var OPENROUTER = {
@@ -11424,6 +11776,7 @@ function registerBuiltins() {
11424
11776
  registered2 = true;
11425
11777
  registerProvider(ANTHROPIC);
11426
11778
  registerProvider(OPENAI);
11779
+ registerProvider(OPENAI_CHATGPT);
11427
11780
  registerProvider(OPENROUTER);
11428
11781
  registerProvider(GEMINI);
11429
11782
  registerProvider(OLLAMA);