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