@theokit/sdk 4.11.1 → 4.12.1

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.cjs CHANGED
@@ -576,10 +576,10 @@ function buildToolPrompt(prompt) {
576
576
  Respond by calling the \`output\` tool with the structured answer that matches the schema.`;
577
577
  }
578
578
  function setupStructuredOutput(schema, maxRetries) {
579
- const z11 = requireZod();
579
+ const z12 = requireZod();
580
580
  const jsonSchema = toJsonSchema(schema, { unrepresentable: "any" });
581
581
  return {
582
- z: z11,
582
+ z: z12,
583
583
  jsonSchema,
584
584
  maxRetries: maxRetries ?? 1,
585
585
  initialUsage: { inputTokens: 0, outputTokens: 0 }
@@ -13975,6 +13975,358 @@ var OPENAI = {
13975
13975
  hostname: "api.openai.com",
13976
13976
  fallbackModels: ["gpt-4o", "gpt-4o-mini"]
13977
13977
  };
13978
+ function credentialHome(config, env = {}) {
13979
+ const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
13980
+ return override !== void 0 && override.length > 0 ? override : path.join(config.home, config.dirName);
13981
+ }
13982
+ function authFilePath(config, env = {}) {
13983
+ return path.join(credentialHome(config, env), config.fileName);
13984
+ }
13985
+ var CredentialError = class extends Error {
13986
+ constructor(message) {
13987
+ super(message);
13988
+ this.name = "CredentialError";
13989
+ }
13990
+ };
13991
+ var apiFileSchema = zod.z.object({
13992
+ type: zod.z.literal("api").optional(),
13993
+ provider: zod.z.string().min(1).optional(),
13994
+ api_key: zod.z.string()
13995
+ }).strict();
13996
+ var oauthFileSchema = zod.z.object({
13997
+ type: zod.z.literal("oauth"),
13998
+ provider: zod.z.string().min(1),
13999
+ access: zod.z.string().min(1),
14000
+ refresh: zod.z.string().min(1),
14001
+ expires: zod.z.number(),
14002
+ account_id: zod.z.string().optional()
14003
+ }).strict();
14004
+ var fileSchema = zod.z.union([oauthFileSchema, apiFileSchema]);
14005
+ function assertSecureModes(dirPath, path) {
14006
+ const dirMode = fs.statSync(dirPath).mode & 511;
14007
+ if ((dirMode & 18) !== 0) {
14008
+ throw new CredentialError(
14009
+ `${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}`
14010
+ );
14011
+ }
14012
+ const mode = fs.statSync(path).mode & 511;
14013
+ if ((mode & 63) !== 0) {
14014
+ throw new CredentialError(
14015
+ `${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
14016
+ );
14017
+ }
14018
+ }
14019
+ function describeUnionError(parsed, err, path) {
14020
+ const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
14021
+ const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
14022
+ let issue;
14023
+ if (!specific.success) {
14024
+ issue = specific.error.issues[0];
14025
+ } else if (err instanceof zod.z.ZodError) {
14026
+ issue = err.issues[0];
14027
+ }
14028
+ return new CredentialError(
14029
+ `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
14030
+ );
14031
+ }
14032
+ function parseStoredFile(raw, path) {
14033
+ let parsed;
14034
+ try {
14035
+ parsed = JSON.parse(raw);
14036
+ } catch {
14037
+ throw new CredentialError(
14038
+ `${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
14039
+ );
14040
+ }
14041
+ try {
14042
+ return fileSchema.parse(parsed);
14043
+ } catch (err) {
14044
+ throw describeUnionError(parsed, err, path);
14045
+ }
14046
+ }
14047
+ function readAuthFile(config, env = {}) {
14048
+ const path = authFilePath(config, env);
14049
+ let raw;
14050
+ try {
14051
+ raw = fs.readFileSync(path, "utf8");
14052
+ } catch (err) {
14053
+ if (err.code === "ENOENT") return void 0;
14054
+ throw new CredentialError(`cannot read ${path}: ${err.message}`);
14055
+ }
14056
+ assertSecureModes(credentialHome(config, env), path);
14057
+ return parseStoredFile(raw, path);
14058
+ }
14059
+ function readStoredOAuth(config, env = {}) {
14060
+ const stored = readAuthFile(config, env);
14061
+ return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
14062
+ }
14063
+ function isOAuthWrite(c) {
14064
+ return "type" in c && c.type === "oauth";
14065
+ }
14066
+ function buildStorePayload(cred) {
14067
+ if (isOAuthWrite(cred)) {
14068
+ if (cred.access.length === 0 || cred.refresh.length === 0) {
14069
+ throw new CredentialError(
14070
+ "refusing to write an oauth credential with an empty access/refresh token"
14071
+ );
14072
+ }
14073
+ return {
14074
+ type: "oauth",
14075
+ provider: cred.provider,
14076
+ access: cred.access,
14077
+ refresh: cred.refresh,
14078
+ expires: cred.expires,
14079
+ ...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
14080
+ };
14081
+ }
14082
+ if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
14083
+ throw new CredentialError("refusing to write an empty API key");
14084
+ }
14085
+ return { provider: cred.provider, api_key: cred.apiKey };
14086
+ }
14087
+ function writeCredential(cred, config, env = {}) {
14088
+ const payload = buildStorePayload(cred);
14089
+ const dir = credentialHome(config, env);
14090
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
14091
+ fs.chmodSync(dir, 448);
14092
+ const path = authFilePath(config, env);
14093
+ const tmp = `${path}.tmp-${crypto.randomBytes(8).toString("hex")}`;
14094
+ try {
14095
+ const fd = fs.openSync(tmp, "wx", 384);
14096
+ try {
14097
+ fs.writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
14098
+ `);
14099
+ fs.fsyncSync(fd);
14100
+ } finally {
14101
+ fs.closeSync(fd);
14102
+ }
14103
+ fs.chmodSync(tmp, 384);
14104
+ fs.renameSync(tmp, path);
14105
+ } catch (err) {
14106
+ try {
14107
+ fs.unlinkSync(tmp);
14108
+ } catch {
14109
+ }
14110
+ throw new CredentialError(`cannot write ${path}: ${err.message}`);
14111
+ }
14112
+ return path;
14113
+ }
14114
+
14115
+ // src/server/auth/errors.ts
14116
+ var AuthCallbackError = class extends Error {
14117
+ name = "AuthCallbackError";
14118
+ code;
14119
+ constructor(code, message) {
14120
+ super(message ?? `OAuth callback error: ${code}`);
14121
+ this.code = code;
14122
+ }
14123
+ };
14124
+
14125
+ // src/internal/auth/oauth-engine.ts
14126
+ var REFRESH_SKEW_MS = 6e4;
14127
+ function parseTokenResponse(body, now) {
14128
+ const b = body;
14129
+ if (typeof b.access_token !== "string" || b.access_token.length === 0) {
14130
+ throw new AuthCallbackError(
14131
+ "oauth_token_exchange_failed",
14132
+ "token response had no access_token"
14133
+ );
14134
+ }
14135
+ if (typeof b.refresh_token !== "string" || b.refresh_token.length === 0) {
14136
+ throw new AuthCallbackError(
14137
+ "oauth_token_exchange_failed",
14138
+ "token response had no refresh_token"
14139
+ );
14140
+ }
14141
+ const expiresIn = typeof b.expires_in === "number" ? b.expires_in : 3600;
14142
+ return {
14143
+ access: b.access_token,
14144
+ refresh: b.refresh_token,
14145
+ expires: now + expiresIn * 1e3,
14146
+ ...typeof b.account_id === "string" ? { accountId: b.account_id } : {}
14147
+ };
14148
+ }
14149
+ async function postGrant(config, form, deps) {
14150
+ let res;
14151
+ try {
14152
+ res = await deps.fetch(config.tokenEndpoint, {
14153
+ method: "POST",
14154
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
14155
+ body: new URLSearchParams(form).toString()
14156
+ });
14157
+ } catch (err) {
14158
+ throw new AuthCallbackError(
14159
+ "oauth_token_exchange_failed",
14160
+ `token endpoint request failed: ${err.message}`
14161
+ );
14162
+ }
14163
+ if (!res.ok) {
14164
+ throw new AuthCallbackError(
14165
+ "oauth_token_exchange_failed",
14166
+ `token endpoint returned HTTP ${res.status}`
14167
+ );
14168
+ }
14169
+ let json;
14170
+ try {
14171
+ json = await res.json();
14172
+ } catch {
14173
+ throw new AuthCallbackError("oauth_token_exchange_failed", "token response was not valid JSON");
14174
+ }
14175
+ return parseTokenResponse(json, deps.now());
14176
+ }
14177
+ function refreshOAuthTokens(config, refresh, deps) {
14178
+ return postGrant(
14179
+ config,
14180
+ { grant_type: "refresh_token", refresh_token: refresh, client_id: config.clientId },
14181
+ deps
14182
+ );
14183
+ }
14184
+ function persistOAuthTokens(provider, tokens, store, env = {}) {
14185
+ return writeCredential(
14186
+ {
14187
+ type: "oauth",
14188
+ provider,
14189
+ access: tokens.access,
14190
+ refresh: tokens.refresh,
14191
+ expires: tokens.expires,
14192
+ ...tokens.accountId !== void 0 ? { account_id: tokens.accountId } : {}
14193
+ },
14194
+ store,
14195
+ env
14196
+ );
14197
+ }
14198
+ var inFlightRefresh = /* @__PURE__ */ new Map();
14199
+ async function ensureFreshCredential(resolved, opts, deps) {
14200
+ if (resolved.kind !== "oauth") return resolved;
14201
+ const now = deps.now();
14202
+ if (resolved.expiresAt !== void 0 && resolved.expiresAt > now + REFRESH_SKEW_MS) {
14203
+ return resolved;
14204
+ }
14205
+ const env = opts.env ?? {};
14206
+ const path = authFilePath(opts.store, env);
14207
+ let refresh = inFlightRefresh.get(path);
14208
+ if (refresh === void 0) {
14209
+ refresh = (async () => {
14210
+ const stored = readStoredOAuth(opts.store, env);
14211
+ if (stored === void 0) {
14212
+ throw new AuthCallbackError(
14213
+ "oauth_token_exchange_failed",
14214
+ "no stored oauth credential to refresh"
14215
+ );
14216
+ }
14217
+ const fresh2 = await refreshOAuthTokens(opts.config, stored.refresh, deps);
14218
+ const merged = {
14219
+ ...fresh2,
14220
+ accountId: fresh2.accountId ?? stored.account_id
14221
+ };
14222
+ persistOAuthTokens(resolved.provider, merged, opts.store, env);
14223
+ return merged;
14224
+ })();
14225
+ inFlightRefresh.set(path, refresh);
14226
+ refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {
14227
+ });
14228
+ }
14229
+ const fresh = await refresh;
14230
+ return {
14231
+ kind: "oauth",
14232
+ provider: resolved.provider,
14233
+ apiKey: fresh.access,
14234
+ source: resolved.source,
14235
+ inferred: false,
14236
+ expiresAt: fresh.expires
14237
+ };
14238
+ }
14239
+
14240
+ // src/internal/auth/resolve-credential.ts
14241
+ async function resolveOAuth(stored, path, opts, env) {
14242
+ if (stored.provider !== opts.provider) return void 0;
14243
+ const base = {
14244
+ kind: "oauth",
14245
+ provider: opts.provider,
14246
+ apiKey: stored.access,
14247
+ source: path,
14248
+ inferred: false,
14249
+ expiresAt: stored.expires
14250
+ };
14251
+ if (opts.oauth === void 0) return base;
14252
+ const deps = {
14253
+ fetch: opts.deps?.fetch ?? fetch,
14254
+ now: opts.deps?.now ?? (() => Date.now())
14255
+ };
14256
+ return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);
14257
+ }
14258
+ async function resolveCredential(opts) {
14259
+ const env = opts.env ?? {};
14260
+ const stored = readAuthFile(opts.store, env);
14261
+ if (stored === void 0) return void 0;
14262
+ const path = authFilePath(opts.store, env);
14263
+ if (stored.type === "oauth") {
14264
+ return resolveOAuth(stored, path, opts, env);
14265
+ }
14266
+ if (stored.api_key.length === 0) return void 0;
14267
+ if (stored.provider !== opts.provider) return void 0;
14268
+ return {
14269
+ kind: "api",
14270
+ provider: opts.provider,
14271
+ apiKey: stored.api_key,
14272
+ source: path,
14273
+ inferred: false
14274
+ };
14275
+ }
14276
+
14277
+ // src/internal/providers/builtin/openai-chatgpt.ts
14278
+ var DEFAULT_STORE = {
14279
+ home: os.homedir(),
14280
+ dirName: ".theokit",
14281
+ fileName: "auth.json",
14282
+ homeEnvVar: "THEOKIT_HOME"
14283
+ };
14284
+ var OPENAI_OAUTH_CONFIG = {
14285
+ provider: "openai",
14286
+ authorizeEndpoint: "https://auth.openai.com/oauth/authorize",
14287
+ tokenEndpoint: "https://auth.openai.com/oauth/token",
14288
+ clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
14289
+ scopes: ["openid", "profile", "email", "offline_access"],
14290
+ redirectUri: "https://auth.openai.com/deviceauth/callback"
14291
+ };
14292
+ function codexFetch() {
14293
+ return (async (input, init) => {
14294
+ const env = process.env;
14295
+ const resolved = await resolveCredential({
14296
+ provider: "openai",
14297
+ store: DEFAULT_STORE,
14298
+ oauth: OPENAI_OAUTH_CONFIG,
14299
+ env
14300
+ });
14301
+ if (resolved === void 0) {
14302
+ throw new Error(
14303
+ 'openai-chatgpt: no ChatGPT credential found \u2014 run the OpenAI device login (e.g. "/login openai") first.'
14304
+ );
14305
+ }
14306
+ const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;
14307
+ const headers = new Headers(init?.headers);
14308
+ headers.set("authorization", `Bearer ${resolved.apiKey}`);
14309
+ if (accountId !== void 0) headers.set("ChatGPT-Account-Id", accountId);
14310
+ return fetch(input, { ...init, headers });
14311
+ });
14312
+ }
14313
+ var OPENAI_CHATGPT = {
14314
+ name: "openai-chatgpt",
14315
+ apiMode: "responses_api",
14316
+ authType: "oauth_device_code",
14317
+ baseUrl: "https://chatgpt.com/backend-api/codex",
14318
+ envVars: [],
14319
+ fallbackModels: [
14320
+ "openai-chatgpt/gpt-5.4",
14321
+ "openai-chatgpt/gpt-5.4-mini",
14322
+ "openai-chatgpt/gpt-5.5"
14323
+ ],
14324
+ extraHeaders: { originator: "codex_cli_rs" },
14325
+ transform: {
14326
+ // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.
14327
+ fetch: () => codexFetch()
14328
+ }
14329
+ };
13978
14330
 
13979
14331
  // src/internal/providers/builtin/openrouter.ts
13980
14332
  var OPENROUTER = {
@@ -14028,6 +14380,7 @@ function registerBuiltins() {
14028
14380
  registered2 = true;
14029
14381
  registerProvider(ANTHROPIC);
14030
14382
  registerProvider(OPENAI);
14383
+ registerProvider(OPENAI_CHATGPT);
14031
14384
  registerProvider(OPENROUTER);
14032
14385
  registerProvider(GEMINI);
14033
14386
  registerProvider(OLLAMA);
@@ -21007,6 +21360,18 @@ var Provider = class {
21007
21360
  static create(profile, opts) {
21008
21361
  return defineProvider(profile, opts);
21009
21362
  }
21363
+ /**
21364
+ * Every first-party builtin provider (anthropic, openai, openrouter, gemini, ollama, the ChatGPT/Codex
21365
+ * `openai-chatgpt`, …) as model-provider plugins, ready to hand to `Agent.create({ plugins })` or any
21366
+ * runtime that consumes model-provider plugins (e.g. the `theokit` agent server / `@theokit/agents`, whose
21367
+ * own model resolution does NOT share this registry). Enables a consumer to route to ANY SDK builtin —
21368
+ * including one added later in a single SDK file — with ZERO provider-specific code: just
21369
+ * `.plugins(Provider.builtins())` once, then pick a `provider/model` id. @public
21370
+ */
21371
+ static builtins() {
21372
+ registerBuiltins();
21373
+ return listProviders().map((profile) => defineProvider(profile));
21374
+ }
21010
21375
  };
21011
21376
 
21012
21377
  // src/define-skill-read-tool.ts