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