@theokit/agents 9.1.0 → 9.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,64 @@
1
1
  # @theokit/agents
2
2
 
3
+ ## 9.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - bb01ce8: **`resolveAgentCredential` — a montagem de autenticacao, para um app novo nao reescrever nenhuma.**
8
+
9
+ O framework ja entregava as PECAS (store no 0600, device flow RFC 8628, refresh, `writeCredential`) e
10
+ nao entregava a MONTAGEM. Medido no consumidor mais proximo: ele importa seis simbolos nossos e
11
+ escreve ~250 linhas em cima, e nenhuma delas e sobre o dominio dele — sao a politica de resolucao que
12
+ todo app de agente de terminal precisa e nenhum consegue importar.
13
+
14
+ Adicionado:
15
+
16
+ - **`DEFAULT_PROVIDERS`** — openrouter, anthropic, openai com variavel de ambiente, prioridade e
17
+ prefixo de chave. O consumidor abre com TRES tabelas escritas a mao dizendo isto; agora um app novo
18
+ nao escreve nenhuma. Prioridades espacadas de 10 para caber um provider entre dois padroes sem
19
+ renumerar.
20
+ - **`resolveAgentCredential({ env })`** — a chamada unica. Aplica os padroes e mantem todos
21
+ sobrescreviveis: `providers` para estreitar (um produto que so fala com um provider) ou estender
22
+ (um gateway self-hosted).
23
+ - **O pin de provider** (`THEOKIT_PROVIDER` por padrao) que se RECUSA a cair para outro. Cair
24
+ mandaria a requisicao — e a conta, e os dados — para um provider que o operador nao escolheu. Um
25
+ typo no nome tambem e recusado: um erro de digitacao nao pode desligar o pin em silencio.
26
+ - **Coerencia chave↔provider** via `keyPrefix`. `ANTHROPIC_API_KEY=sk-proj-…` e uma colagem na
27
+ variavel errada, pega aqui de graca em vez de virar um 401 remoto cuja mensagem nao fala do
28
+ desencontro.
29
+ - **`requireCredential`** e `CredentialNotFoundError` carregando ONDE procurou. "Nenhuma credencial
30
+ encontrada" sem a lista e a frase menos util que um CLI pode imprimir, e e por isso que o consumidor
31
+ carregava a propria.
32
+
33
+ `resolveCredential` segue devolvendo `undefined` — a forma nao-lancante e o que o caminho de primeira
34
+ execucao quer, e `requireCredential` e o opt-in de quem nao pode continuar. Duas funcoes em vez de uma
35
+ flag: a intencao fica visivel no call site.
36
+
37
+ Os prefixos vivem aqui E no SDK (`providerFromApiKeyPrefix`), o que nao e ideal e esta guardado: um
38
+ teste falha quando as duas tabelas discordam. Uma tabela so seria melhor, mas o simbolo do SDK esta
39
+ exportado em runtime e AUSENTE do `auth/index.d.ts` (medido contra 4.52.0), entao um import tipado nao
40
+ resolve. Guardado por CI em vez de esperado.
41
+
42
+ ## 9.1.1
43
+
44
+ ### Patch Changes
45
+
46
+ - **`readSecureJson` passa a recusar um store que outro usuario local pode ESCREVER.**
47
+
48
+ `ensureSecureDir` segurava o diretorio em owner-only e a leitura entao abria o arquivo sem olhar o
49
+ modo dele. Um `hook-approvals.json` deixado group- ou world-writable — por uma versao antiga, por um
50
+ umask ruim, por quem tivesse acesso de escrita — era lido como autoritativo. Esse arquivo decide
51
+ quais linhas de comando chegam ao `spawn(cmd, { shell: true })`.
52
+
53
+ Falha FECHADA e reporta, em vez de lancar: um store ilegivel ja significa "nada aprovado", o turno
54
+ do chamador nao deve terminar por causa disso, e `lastReadError` e como o operador descobre que as
55
+ aprovacoes dele pararam de valer. Silencio tornaria um store adulterado indistinguivel de um vazio.
56
+
57
+ Recusado em vez de reparado: apertar o modo em silencio esconderia que algo o mudou, que e o fato
58
+ que importa saber.
59
+
60
+ Achado por um teste do consumidor (B-019) falhando enquanto ele migrava para este helper.
61
+
3
62
  ## 9.1.0
4
63
 
5
64
  ### Minor Changes
package/dist/auth.d.ts CHANGED
@@ -216,6 +216,15 @@ interface ProviderDescriptor {
216
216
  readonly priority: number;
217
217
  /** Model-id prefix this provider claims (`openai/`). Absent ⇒ it claims none. */
218
218
  readonly modelPrefix?: string;
219
+ /**
220
+ * Prefix this provider stamps on its API keys (`sk-ant-`, `sk-or-`, `sk-`).
221
+ *
222
+ * Enables the coherence check: a key sitting in `ANTHROPIC_API_KEY` that starts with `sk-proj-`
223
+ * is a paste into the wrong variable, caught here for free instead of as a 401 from the wrong
224
+ * endpoint whose message says nothing about the mismatch. Absent means "this provider stamps no
225
+ * recognisable prefix", and nothing is checked — never a silent pass disguised as a check.
226
+ */
227
+ readonly keyPrefix?: string;
219
228
  }
220
229
  /**
221
230
  * The answer, with its provenance attached.
@@ -242,6 +251,30 @@ declare class ProviderPrefixMismatchError extends TheokitAgentError {
242
251
  readonly name = "ProviderPrefixMismatchError";
243
252
  constructor(provider: string, envKey: string, model: string);
244
253
  }
254
+ /** Raised when a key's prefix contradicts the provider it was declared for. */
255
+ declare class ProviderKeyMismatchError extends TheokitAgentError {
256
+ readonly provider: string;
257
+ readonly where: string;
258
+ readonly expectedPrefix: string;
259
+ readonly name = "ProviderKeyMismatchError";
260
+ constructor(provider: string, where: string, expectedPrefix: string);
261
+ }
262
+ /** Raised when a pinned provider has no credential, or names one the app never declared. */
263
+ declare class DeclaredProviderError extends TheokitAgentError {
264
+ readonly name = "DeclaredProviderError";
265
+ constructor(message: string);
266
+ }
267
+ /**
268
+ * Raised by {@link requireCredential} when nothing is configured, carrying WHERE it looked.
269
+ *
270
+ * The list is the point. "No credential found" without it is the least useful sentence available,
271
+ * and it is why the closest measured consumer carried its own `attempts` array.
272
+ */
273
+ declare class CredentialNotFoundError extends TheokitAgentError {
274
+ readonly attempts: readonly string[];
275
+ readonly name = "CredentialNotFoundError";
276
+ constructor(attempts: readonly string[]);
277
+ }
245
278
  interface ResolveCredentialInput {
246
279
  /** The environment as the process sees it — already loaded, already interpolated. */
247
280
  readonly env: Readonly<Record<string, string | undefined>>;
@@ -263,6 +296,17 @@ interface ResolveCredentialInput {
263
296
  * the precedence a consumer already implements (declared env → per-provider env → file).
264
297
  */
265
298
  readonly store?: CredentialStoreConfig;
299
+ /**
300
+ * Name of the variable that PINS a provider (`PROVIDER`, `THEOCODE_PROVIDER`, …).
301
+ *
302
+ * When set and present, the pinned provider is the only one considered: if it has no credential,
303
+ * resolution THROWS rather than falling back. Falling back would send the request — and the bill,
304
+ * and the data — to a provider the operator did not choose, which is the one outcome a pin exists
305
+ * to prevent.
306
+ *
307
+ * The variable NAME is the app's (products disagree on it); the semantics are not.
308
+ */
309
+ readonly declaredProviderEnvVar?: string;
266
310
  }
267
311
  /** What `credentialSources` needs — the same declarations the resolver consults. */
268
312
  interface CredentialSourcesInput {
@@ -287,15 +331,70 @@ interface CredentialSourcesInput {
287
331
  * precedence claim the resolver does not honour.
288
332
  */
289
333
  declare function credentialSources(input: CredentialSourcesInput): readonly string[];
334
+ declare function resolveCredential(input: ResolveCredentialInput): CredentialResolution | undefined;
290
335
  /**
291
- * Resolve which credential to use, and record where it came from.
336
+ * Like {@link resolveCredential}, but THROWS when nothing is configured — carrying where it looked.
337
+ *
338
+ * Two functions rather than a flag: the non-throwing shape is what a first-run path wants ("no key
339
+ * yet" is the ordinary state, and the next move is `theokit auth login`), and the throwing shape is
340
+ * what a path that cannot continue wants. A boolean parameter would make the caller's intent
341
+ * invisible at the call site, and the two intents are genuinely different.
292
342
  *
293
- * Returns `undefined` when nothing is configured: a missing key is the ordinary first-run state, and
294
- * the caller's next move is to print "run `theokit auth login`" which a thrown error makes harder,
295
- * not easier. A prefix that names a provider with no credential DOES throw, because that is a
296
- * contradiction rather than an absence.
343
+ * The attempts list is the reason this exists: "no credential found" without saying WHERE it looked
344
+ * is the least useful sentence a CLI can print, and it is why the closest measured consumer carried
345
+ * its own.
297
346
  */
298
- declare function resolveCredential(input: ResolveCredentialInput): CredentialResolution | undefined;
347
+ declare function requireCredential(input: ResolveCredentialInput): CredentialResolution;
348
+ /**
349
+ * The providers a TheoKit agent app starts with — so a new app writes no table at all.
350
+ *
351
+ * Measured against the closest real consumer: it opens with three hand-written tables (`PROVIDERS`,
352
+ * `PREFIXES`, `ENV_KEYS`) saying what every terminal agent app says. That is not its domain; it is
353
+ * the cost of shipping a resolver whose only input is the argument the app must build.
354
+ *
355
+ * ## Why the prefixes live here as well as in the SDK
356
+ *
357
+ * `providerFromApiKeyPrefix` owns the same knowledge, and one table would be better. It cannot be
358
+ * the only one today: the symbol is exported at runtime and absent from the SDK's `auth/index.d.ts`
359
+ * (measured against 4.52.0), so a typed import does not resolve. Rather than block, the table is
360
+ * here AND a drift-guard test fails when the two disagree — the same hand-maintained-table hazard
361
+ * that produced the longest-prefix bug is caught by CI instead of hoped away.
362
+ *
363
+ * ## Priorities, and why they are spaced
364
+ *
365
+ * Distinct and 10 apart: an app that wants to slot a provider between two defaults can, without
366
+ * renumbering. Order is `openrouter → anthropic → openai`, matching the consumer's measured chain.
367
+ */
368
+ declare const DEFAULT_PROVIDERS: readonly ProviderDescriptor[];
369
+ /** Everything {@link resolveAgentCredential} needs, and nothing an app has to invent. */
370
+ interface AgentCredentialInput {
371
+ readonly env: Readonly<Record<string, string | undefined>>;
372
+ readonly home?: string;
373
+ readonly model?: string;
374
+ readonly store?: CredentialStoreConfig;
375
+ /**
376
+ * Providers to accept. Defaults to {@link DEFAULT_PROVIDERS}.
377
+ *
378
+ * Present so an app can NARROW (a product that only talks to Anthropic) or EXTEND (a self-hosted
379
+ * gateway) — the two real reasons to disagree with the default. Which providers exist stays app
380
+ * policy; not having to state it to get started is the point.
381
+ */
382
+ readonly providers?: readonly ProviderDescriptor[];
383
+ /** Variable that pins a provider. Defaults to `THEOKIT_PROVIDER`. */
384
+ readonly declaredProviderEnvVar?: string;
385
+ }
386
+ /**
387
+ * The one call a new app makes: given the environment, which credential do I use?
388
+ *
389
+ * `resolveCredential` takes the full policy as arguments, which is right for an app that has
390
+ * opinions and wrong as a starting point — a new app should not have to state a provider table, a
391
+ * precedence order and a pin variable before it can read a key. This applies the defaults and keeps
392
+ * every one of them overridable.
393
+ *
394
+ * Throws when nothing is configured, carrying WHERE it looked: a new app's first run is exactly the
395
+ * case that needs the list, and printing the error is the whole handling it needs.
396
+ */
397
+ declare function resolveAgentCredential(input: AgentCredentialInput): CredentialResolution;
299
398
 
300
399
  /** What a caller asks about: may THIS tool run THIS command in THIS place? */
301
400
  interface PermissionQuery {
@@ -344,4 +443,4 @@ declare class PermissionStore {
344
443
  expired(): readonly Grant[];
345
444
  }
346
445
 
347
- export { type AuthMethod, AuthProvider, CODEX_CLIENT_ID_ENV_VAR, CODEX_PROVIDER, type ProviderDescriptor as CredentialProviderDescriptor, type CredentialResolution, type CredentialSourcesInput, type DeviceAuthProvider, type Grant, type GrantOptions, type PermissionQuery, PermissionStore, type PermissionStoreOptions, type PromptHooks, ProviderPrefixMismatchError, type ResolveCredentialInput, type SourceOrigin, credentialSources, loginWithDevice, resolveCredential };
446
+ export { type AgentCredentialInput, type AuthMethod, AuthProvider, CODEX_CLIENT_ID_ENV_VAR, CODEX_PROVIDER, CredentialNotFoundError, type ProviderDescriptor as CredentialProviderDescriptor, type CredentialResolution, type CredentialSourcesInput, DEFAULT_PROVIDERS, DeclaredProviderError, type DeviceAuthProvider, type Grant, type GrantOptions, type PermissionQuery, PermissionStore, type PermissionStoreOptions, type PromptHooks, ProviderKeyMismatchError, ProviderPrefixMismatchError, type ResolveCredentialInput, type SourceOrigin, credentialSources, loginWithDevice, requireCredential, resolveAgentCredential, resolveCredential };
package/dist/auth.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readSecureJson,
3
3
  writeSecureJson
4
- } from "./chunk-AJIQS3WB.js";
4
+ } from "./chunk-QXGSF6WX.js";
5
5
  import {
6
6
  __name
7
7
  } from "./chunk-Z4QWC7IK.js";
@@ -215,6 +215,47 @@ var ProviderPrefixMismatchError = class extends TheokitAgentError {
215
215
  super(`model "${model}" names provider "${provider}", but no credential for it was found. Set ${envKey}, or drop the prefix to let the resolver pick by precedence. Falling back to another provider would send the request to a model you did not ask for \u2014 and bill you for it.`);
216
216
  }
217
217
  };
218
+ var ProviderKeyMismatchError = class extends TheokitAgentError {
219
+ static {
220
+ __name(this, "ProviderKeyMismatchError");
221
+ }
222
+ provider;
223
+ where;
224
+ expectedPrefix;
225
+ name = "ProviderKeyMismatchError";
226
+ constructor(provider, where, expectedPrefix) {
227
+ super(`${where}: the key declared for provider "${provider}" does not start with "${expectedPrefix}". Either the provider or the key is wrong, and sending it would fail mid-request against the wrong endpoint.`, {
228
+ code: "provider_key_mismatch",
229
+ isRetryable: false
230
+ }), this.provider = provider, this.where = where, this.expectedPrefix = expectedPrefix;
231
+ }
232
+ };
233
+ var DeclaredProviderError = class extends TheokitAgentError {
234
+ static {
235
+ __name(this, "DeclaredProviderError");
236
+ }
237
+ name = "DeclaredProviderError";
238
+ constructor(message) {
239
+ super(message, {
240
+ code: "declared_provider_unusable",
241
+ isRetryable: false
242
+ });
243
+ }
244
+ };
245
+ var CredentialNotFoundError = class extends TheokitAgentError {
246
+ static {
247
+ __name(this, "CredentialNotFoundError");
248
+ }
249
+ attempts;
250
+ name = "CredentialNotFoundError";
251
+ constructor(attempts) {
252
+ super(`no provider credential found. Tried, in order:
253
+ ` + attempts.map((a, i) => ` ${String(i + 1)}. ${a}`).join("\n"), {
254
+ code: "credential_not_found",
255
+ isRetryable: false
256
+ }), this.attempts = attempts;
257
+ }
258
+ };
218
259
  function declaredNames(path) {
219
260
  let raw;
220
261
  try {
@@ -245,10 +286,42 @@ function credentialSources(input) {
245
286
  return sources;
246
287
  }
247
288
  __name(credentialSources, "credentialSources");
289
+ function assertKeyMatchesProvider(descriptor, apiKey, where) {
290
+ if (descriptor.keyPrefix === void 0) return;
291
+ if (apiKey.startsWith(descriptor.keyPrefix)) return;
292
+ throw new ProviderKeyMismatchError(descriptor.name, where, descriptor.keyPrefix);
293
+ }
294
+ __name(assertKeyMatchesProvider, "assertKeyMatchesProvider");
295
+ function pinnedProvider(input, byPriority) {
296
+ if (input.declaredProviderEnvVar === void 0) return void 0;
297
+ const declared = input.env[input.declaredProviderEnvVar]?.trim();
298
+ if (declared === void 0 || declared === "") return void 0;
299
+ const descriptor = byPriority.find((d) => d.name === declared);
300
+ if (descriptor === void 0) {
301
+ throw new DeclaredProviderError(`${input.declaredProviderEnvVar} is "${declared}" \u2014 expected one of ${byPriority.map((d) => d.name).join(", ")}.`);
302
+ }
303
+ return descriptor;
304
+ }
305
+ __name(pinnedProvider, "pinnedProvider");
248
306
  function resolveCredential(input) {
249
307
  const byPriority = [
250
308
  ...input.providers
251
309
  ].sort((a, b) => a.priority - b.priority);
310
+ const pinned = pinnedProvider(input, byPriority);
311
+ if (pinned !== void 0) {
312
+ const apiKey = input.env[pinned.envKey];
313
+ if (apiKey === void 0 || apiKey === "") {
314
+ throw new DeclaredProviderError(`provider "${pinned.name}" is pinned via ${String(input.declaredProviderEnvVar)} but no key for it was found (looked at ${pinned.envKey}). Refusing to fall back to a different provider's credential.`);
315
+ }
316
+ assertKeyMatchesProvider(pinned, apiKey, pinned.envKey);
317
+ return {
318
+ kind: "api-key",
319
+ provider: pinned.name,
320
+ apiKey,
321
+ source: originOf(pinned.envKey, input.home),
322
+ inferred: false
323
+ };
324
+ }
252
325
  const available = byPriority.flatMap((descriptor) => {
253
326
  const apiKey = input.env[descriptor.envKey];
254
327
  return apiKey === void 0 || apiKey === "" ? [] : [
@@ -264,6 +337,7 @@ function resolveCredential(input) {
264
337
  throw new ProviderPrefixMismatchError(claimed.name, claimed.envKey, input.model ?? "");
265
338
  }
266
339
  if (found === void 0) return storedOAuthResolution(input, byPriority);
340
+ assertKeyMatchesProvider(found.descriptor, found.apiKey, found.descriptor.envKey);
267
341
  return {
268
342
  kind: "api-key",
269
343
  provider: found.descriptor.name,
@@ -326,6 +400,56 @@ function originOf(varName, home) {
326
400
  };
327
401
  }
328
402
  __name(originOf, "originOf");
403
+ function requireCredential(input) {
404
+ const resolved = resolveCredential(input);
405
+ if (resolved !== void 0) return resolved;
406
+ throw new CredentialNotFoundError(credentialSources({
407
+ providers: input.providers,
408
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- `CredentialStoreConfig` does not resolve (see the import note at the top of this file); the value is only forwarded, never inspected
409
+ ...input.store === void 0 ? {} : {
410
+ store: input.store
411
+ }
412
+ }));
413
+ }
414
+ __name(requireCredential, "requireCredential");
415
+ var DEFAULT_PROVIDERS = [
416
+ {
417
+ name: "openrouter",
418
+ envKey: "OPENROUTER_API_KEY",
419
+ priority: 10,
420
+ keyPrefix: "sk-or-"
421
+ },
422
+ {
423
+ name: "anthropic",
424
+ envKey: "ANTHROPIC_API_KEY",
425
+ priority: 20,
426
+ keyPrefix: "sk-ant-"
427
+ },
428
+ {
429
+ name: "openai",
430
+ envKey: "OPENAI_API_KEY",
431
+ priority: 30,
432
+ keyPrefix: "sk-"
433
+ }
434
+ ];
435
+ function resolveAgentCredential(input) {
436
+ return requireCredential({
437
+ env: input.env,
438
+ providers: input.providers ?? DEFAULT_PROVIDERS,
439
+ declaredProviderEnvVar: input.declaredProviderEnvVar ?? "THEOKIT_PROVIDER",
440
+ ...input.home === void 0 ? {} : {
441
+ home: input.home
442
+ },
443
+ ...input.model === void 0 ? {} : {
444
+ model: input.model
445
+ },
446
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- same unresolved `CredentialStoreConfig`; forwarded verbatim to the resolver
447
+ ...input.store === void 0 ? {} : {
448
+ store: input.store
449
+ }
450
+ });
451
+ }
452
+ __name(resolveAgentCredential, "resolveAgentCredential");
329
453
 
330
454
  // src/auth/permission-store.ts
331
455
  import { realpathSync } from "fs";
@@ -429,7 +553,11 @@ export {
429
553
  CODEX_CLIENT_ID_ENV_VAR,
430
554
  CODEX_PROVIDER,
431
555
  CredentialError,
556
+ CredentialNotFoundError,
557
+ DEFAULT_PROVIDERS,
558
+ DeclaredProviderError,
432
559
  PermissionStore,
560
+ ProviderKeyMismatchError,
433
561
  ProviderPrefixMismatchError,
434
562
  assertSecureModes,
435
563
  authFilePath2 as authFilePath,
@@ -446,6 +574,8 @@ export {
446
574
  readStoredOAuth3 as readStoredOAuth,
447
575
  refreshOAuthTokens,
448
576
  requestDeviceCode,
577
+ requireCredential,
578
+ resolveAgentCredential,
449
579
  resolveCredential,
450
580
  writeCredential
451
581
  };
package/dist/auth.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/auth/auth-provider.ts","../src/auth-entry.ts","../src/auth/device-provider.ts","../src/auth/resolve-credential.ts","../src/auth/permission-store.ts"],"mappings":";;;;;;;;;AAAA,SACEA,cACAC,uBACAC,mBACAC,oBACAC,uBACK;AAQP,SAASC,oBAAoB;AAkCtB,IAAMC,iBAAN,cAA6BC,MAAAA;EAhDpC,OAgDoCA;;;;EAClC,YACEC,SAESC,WACT;AACA,UAAMD,OAAAA,GAAAA,KAFGC,YAAAA;AAGT,SAAKC,OAAO;EACd;AACF;AAMA,IAAMC,oBAAoB;EACxB;EACA;EACA;EACA;EACA;EACA;;AAIK,SAASC,uBAAuBC,KAAY;AACjD,QAAMC,OAAOD,eAAeN,QAAQ,GAAGM,IAAIH,IAAI,KAAKG,IAAIL,OAAO,KAAKO,OAAOF,GAAAA;AAC3E,MAAI,qDAAqDG,KAAKF,IAAAA,GAAO;AACnE,WAAO,IAAIR,eACT,mGACA,KAAA;EAEJ;AACA,QAAMG,YACJE,kBAAkBM,KAAK,CAACC,MAAMJ,KAAKK,SAASD,CAAAA,CAAAA,KAAO,gCAAgCF,KAAKF,IAAAA;AAC1F,SAAO,IAAIR,eACTG,YAAY,gDAAgD,qCAC5DA,SAAAA;AAEJ;AAdgBG;AAiBT,SAASQ,eAAeC,SAAiBC,SAAS,KAAKC,SAASC,KAAKD,QAAM;AAChF,QAAME,OAAOH,SAAS,KAAKD;AAC3B,SAAOG,KAAKE,MAAMD,QAAQ,OAAOF,OAAAA,IAAW,IAAE;AAChD;AAHgBH;AAKT,IAAMO,eAAN,MAAMA,cAAAA;EA/Fb,OA+FaA;;;;;EACX,YACmBC,QACAC,OACjB;SAFiBD,SAAAA;SACAC,QAAAA;EAChB;;;;;;EAOH,MAAMC,YACJC,UACAC,MACAC,KAC6B;AAC7B,QAAIF,SAASG,SAAS,SAAS;AAI7B,aAAOC,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MACL,CAACmC,QAAAA;AACC,YAAMC,SAAkBC,KAAKC,MAAMH,GAAAA;AACnC,UAAI,CAACI,MAAMC,QAAQJ,MAAAA,EAAS,OAAM,IAAI1B,MAAM,6BAAA;AAC5C,aAAO0B;IACT,GACA,CAAA,CAAE;AAEJ,SAAKnC,gBAAgBgC;AACrB,WAAOD;EACT;EAEA,SAASb,QAAwB;AAC/BsB,oBAAgB,KAAKzC,MAAM,MAAM,GAAGqC,KAAKK,UAAUvB,QAAQ,MAAM,CAAA,CAAA;CAAM;EACzE;AACF;","names":["authFilePath","ensureFreshCredential","openaiDeviceLogin","persistOAuthTokens","readStoredOAuth","withFileLock","RefreshFailure","Error","message","transient","name","TRANSIENT_REASONS","classifyRefreshFailure","err","text","String","test","some","m","includes","waitWithJitter","attempt","baseMs","random","Math","base","round","AuthProvider","config","store","ensureFresh","resolved","deps","env","kind","ensureFreshCredential","filePath","authFilePath","inFlight","refreshInFlight","get","undefined","promise","refreshUnderLock","set","delete","Map","withFileLock","doDisco","readStoredOAuth","current","apiKey","access","expiresAt","expires","MAX_ATTEMPTS","failure","Promise","resolve","setTimeout","deviceLogin","deviceConfig","hooks","openaiDeviceLogin","persist","provider","tokens","persistOAuthTokens","assertSecureModes","authFilePath","CredentialError","credentialHome","readAuthFile","readStoredOAuth","writeCredential","deviceLogin","openaiDeviceLogin","pollDeviceToken","requestDeviceCode","ensureFreshCredential","extractAccountId","persistOAuthTokens","refreshOAuthTokens","openaiDeviceLogin","CODEX_CLIENT_ID","CODEX_ISSUER","CODEX_CLIENT_ID_ENV_VAR","CODEX_OAUTH","provider","clientId","process","env","authorizeEndpoint","tokenEndpoint","scopes","redirectUri","CODEX_DEVICE","deviceUsercodeEndpoint","devicePollEndpoint","verificationUri","CODEX_PROVIDER","Object","freeze","name","oauth","methods","label","type","authorize","deps","hooks","openaiDeviceLogin","comDefaults","fetch","sleep","ms","Promise","resolve","setTimeout","now","Date","loginWithDevice","method","store","opts","length","TypeError","includes","tokens","path","AuthProvider","persist","accountId","undefined","readFileSync","join","readStoredOAuth","TheokitAgentError","ProviderPrefixMismatchError","TheokitAgentError","name","provider","envKey","model","declaredNames","path","raw","readFileSync","Set","names","line","split","trimmed","trim","startsWith","withoutExport","slice","length","eq","indexOf","add","credentialSources","input","sources","providers","sort","a","b","priority","map","descriptor","store","undefined","config","push","join","dirName","fileName","resolveCredential","byPriority","available","flatMap","apiKey","env","claimed","claimedProvider","found","find","candidate","storedOAuthResolution","kind","source","originOf","home","inferred","diagnose","message","console","warn","stored","readStoredOAuth","cause","Error","String","type","access","p","modelPrefix","varName","dotenv","has","realpathSync","join","signatureOf","command","trim","replace","PermissionStore","path","lastReadError","options","join","home","now","Date","scope","realpathSync","cause","Error","message","String","isGranted","query","grant","tool","undefined","expiresAt","grants","filter","g","push","grantedAt","toISOString","ttlMs","revoke","signature","kept","list","expired","find","value","error","readSecureJson","raw","parsed","JSON","parse","Array","isArray","writeSecureJson","stringify"]}
1
+ {"version":3,"sources":["../src/auth/auth-provider.ts","../src/auth-entry.ts","../src/auth/device-provider.ts","../src/auth/resolve-credential.ts","../src/auth/permission-store.ts"],"mappings":";;;;;;;;;AAAA,SACEA,cACAC,uBACAC,mBACAC,oBACAC,uBACK;AAQP,SAASC,oBAAoB;AAkCtB,IAAMC,iBAAN,cAA6BC,MAAAA;EAhDpC,OAgDoCA;;;;EAClC,YACEC,SAESC,WACT;AACA,UAAMD,OAAAA,GAAAA,KAFGC,YAAAA;AAGT,SAAKC,OAAO;EACd;AACF;AAMA,IAAMC,oBAAoB;EACxB;EACA;EACA;EACA;EACA;EACA;;AAIK,SAASC,uBAAuBC,KAAY;AACjD,QAAMC,OAAOD,eAAeN,QAAQ,GAAGM,IAAIH,IAAI,KAAKG,IAAIL,OAAO,KAAKO,OAAOF,GAAAA;AAC3E,MAAI,qDAAqDG,KAAKF,IAAAA,GAAO;AACnE,WAAO,IAAIR,eACT,mGACA,KAAA;EAEJ;AACA,QAAMG,YACJE,kBAAkBM,KAAK,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b,QAAwB;AAC/BsB,oBAAgB,KAAKzC,MAAM,MAAM,GAAGqC,KAAKK,UAAUvB,QAAQ,MAAM,CAAA,CAAA;CAAM;EACzE;AACF;","names":["authFilePath","ensureFreshCredential","openaiDeviceLogin","persistOAuthTokens","readStoredOAuth","withFileLock","RefreshFailure","Error","message","transient","name","TRANSIENT_REASONS","classifyRefreshFailure","err","text","String","test","some","m","includes","waitWithJitter","attempt","baseMs","random","Math","base","round","AuthProvider","config","store","ensureFresh","resolved","deps","env","kind","ensureFreshCredential","filePath","authFilePath","inFlight","refreshInFlight","get","undefined","promise","refreshUnderLock","set","delete","Map","withFileLock","doDisco","readStoredOAuth","current","apiKey","access","expiresAt","expires","MAX_ATTEMPTS","failure","Promise","resolve","setTimeout","deviceLogin","deviceConfig","hooks","openaiDeviceLogin","persist","provider","tokens","persistOAuthTokens","assertSecureModes","authFilePath","CredentialError","credentialHome","readAuthFile","readStoredOAuth","writeCredential","deviceLogin","openaiDeviceLogin","pollDeviceToken","requestDeviceCode","ensureFreshCredential","extractAccountId","persistOAuthTokens","refreshOAuthTokens","openaiDeviceLogin","CODEX_CLIENT_ID","CODEX_ISSUER","CODEX_CLIENT_ID_ENV_VAR","CODEX_OAUTH","provider","clientId","process","env","authorizeEndpoint","tokenEndpoint","scopes","redirectUri","CODEX_DEVICE","deviceUsercodeEndpoint","devicePollEndpoint","verificationUri","CODEX_PROVIDER","Object","freeze","name","oauth","methods","label","type","authorize","deps","hooks","openaiDeviceLogin","comDefaults","fetch","sleep","ms","Promise","resolve","setTimeout","now","Date","loginWithDevice","method","store","opts","length","TypeError","includes","tokens","path","AuthProvider","persist","accountId","undefined","readFileSync","join","readStoredOAuth","TheokitAgentError","ProviderPrefixMismatchError","TheokitAgentError","name","provider","envKey","model","ProviderKeyMismatchError","where","expectedPrefix","code","isRetryable","DeclaredProviderError","message","CredentialNotFoundError","attempts","map","a","i","String","join","declaredNames","path","raw","readFileSync","Set","names","line","split","trimmed","trim","startsWith","withoutExport","slice","length","eq","indexOf","add","credentialSources","input","sources","providers","sort","b","priority","descriptor","store","undefined","config","push","dirName","fileName","assertKeyMatchesProvider","apiKey","keyPrefix","pinnedProvider","byPriority","declaredProviderEnvVar","declared","env","find","d","resolveCredential","pinned","kind","source","originOf","home","inferred","available","flatMap","claimed","claimedProvider","found","candidate","storedOAuthResolution","diagnose","console","warn","stored","readStoredOAuth","cause","Error","type","access","p","modelPrefix","varName","dotenv","has","requireCredential","resolved","DEFAULT_PROVIDERS","resolveAgentCredential","realpathSync","join","signatureOf","command","trim","replace","PermissionStore","path","lastReadError","options","join","home","now","Date","scope","realpathSync","cause","Error","message","String","isGranted","query","grant","tool","undefined","expiresAt","grants","filter","g","push","grantedAt","toISOString","ttlMs","revoke","signature","kept","list","expired","find","value","error","readSecureJson","raw","parsed","JSON","parse","Array","isArray","writeSecureJson","stringify"]}
@@ -34,6 +34,13 @@ function readSecureJson(filePath, parse, empty) {
34
34
  value: empty
35
35
  };
36
36
  }
37
+ const fileMode = statSync(filePath).mode & 511;
38
+ if ((fileMode & FORBIDDEN_WRITE_BITS) !== 0) {
39
+ return {
40
+ value: empty,
41
+ error: new Error(`${filePath} is mode ${fileMode.toString(8)} \u2014 group or world writable, so another local user can decide what it says. It is being treated as empty: every entry in it has stopped applying. Fix with \`chmod 600 ${filePath}\`.`)
42
+ };
43
+ }
37
44
  if (raw.trim().length === 0) return {
38
45
  value: empty
39
46
  };
@@ -70,4 +77,4 @@ export {
70
77
  readSecureJson,
71
78
  writeSecureJson
72
79
  };
73
- //# sourceMappingURL=chunk-AJIQS3WB.js.map
80
+ //# sourceMappingURL=chunk-QXGSF6WX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/secure-store.ts"],"mappings":";;;;;AAuBA,SAASA,kBAAkB;AAC3B,SAASC,WAAWC,WAAWC,cAAcC,YAAYC,UAAUC,qBAAqB;AACxF,SAASC,SAASC,YAAY;AAG9B,IAAMC,uBAAuB;AAG7B,IAAMC,WAA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,CAAAA,MAAkB;AACvD;AAFgBF;AAKT,SAASG,gBAAgB3B,UAAkB4B,WAAuB;AACvE7B,kBAAgBC,QAAAA;AAChB,QAAM6B,MAAML,YAAYxB,QAAAA;AAExB8B,gBAAcD,KAAKD,UAAAA,GAAa;IAAEG,UAAU;IAAQ1B,MAAMP;EAAU,CAAA;AAEpEkC,aAAWH,KAAK7B,QAAAA;AAQhBO,YAAUP,UAAUF,SAAAA;AACtB;AAfgB6B;","names":["randomUUID","chmodSync","mkdirSync","readFileSync","renameSync","statSync","writeFileSync","dirname","join","FORBIDDEN_WRITE_BITS","DIR_MODE","FILE_MODE","ensureSecureDir","filePath","dir","dirname","mkdirSync","recursive","mode","statSync","chmodSync","repaired","Error","toString","readSecureJson","parse","empty","raw","readFileSync","value","fileMode","error","trim","length","cause","message","String","tempPathFor","join","randomUUID","writeSecureJson","serialize","tmp","writeFileSync","encoding","renameSync"]}
package/dist/config.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ensureSecureDir
3
- } from "./chunk-AJIQS3WB.js";
3
+ } from "./chunk-QXGSF6WX.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-Z4QWC7IK.js";
package/dist/hooks.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readSecureJson,
3
3
  writeSecureJson
4
- } from "./chunk-AJIQS3WB.js";
4
+ } from "./chunk-QXGSF6WX.js";
5
5
  import {
6
6
  hooksPlugin,
7
7
  inheritHooks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/agents",
3
- "version": "9.1.0",
3
+ "version": "9.2.0",
4
4
  "description": "AI agents as first-class citizens of the TheoKit pipeline. The fluent agent()/tool() builders compile to SDK Agent.create() (M31 builder-only authoring API).",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/secure-store.ts"],"mappings":";;;;;AAuBA,SAASA,kBAAkB;AAC3B,SAAS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,MAAML,YAAYvB,QAAAA;AAExB6B,gBAAcD,KAAKD,UAAAA,GAAa;IAAEG,UAAU;IAAQzB,MAAMP;EAAU,CAAA;AAEpEiC,aAAWH,KAAK5B,QAAAA;AAQhBO,YAAUP,UAAUF,SAAAA;AACtB;AAfgB4B;","names":["randomUUID","chmodSync","mkdirSync","readFileSync","renameSync","statSync","writeFileSync","dirname","join","FORBIDDEN_WRITE_BITS","DIR_MODE","FILE_MODE","ensureSecureDir","filePath","dir","dirname","mkdirSync","recursive","mode","statSync","chmodSync","repaired","Error","toString","readSecureJson","parse","empty","raw","readFileSync","value","trim","length","cause","error","message","String","tempPathFor","join","randomUUID","writeSecureJson","serialize","tmp","writeFileSync","encoding","renameSync"]}