@theokit/agents 8.5.2 → 8.7.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/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # `@theokit/agents`
2
+
3
+ The layer between `@theokit/sdk` and an application that hosts an agent.
4
+
5
+ The SDK is the **runtime** — it calls the model, dispatches tools, stores the conversation, streams
6
+ the response. This package is the **home**: the surfaces an app needs around that runtime — where
7
+ credentials come from, which tools are in scope and under what sandbox, when a human is asked, what
8
+ happens to a session after it ends.
9
+
10
+ The division is not stylistic. `@theokit/agents` never re-implements a runtime concern; when it
11
+ looks like it does, that is a bug. What it does is **enrich**: adding the object-shaped surface where
12
+ there is state or orchestration to hold, and forwarding the rest unchanged.
13
+
14
+ > **Enriching never reduces.** A symbol the SDK exposes and this layer does not forward is
15
+ > unreachable to whoever consumes the layer — and the only legal way out for them is to reimplement
16
+ > it. That happened: when `./auth` exported one value against the SDK's nineteen, a downstream
17
+ > product rewrote ~120 lines of credential mechanics. `scripts/check-surface-parity.mjs` in the
18
+ > repository root now requires a written decision per SDK symbol, so the next gap breaks CI instead
19
+ > of quietly costing someone a week.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pnpm add @theokit/agents
25
+ ```
26
+
27
+ Peer dependencies: `zod` (schemas), `react` (only for `./client/react`), `@theokit/http` (only when
28
+ you mount HTTP surfaces).
29
+
30
+ ## Subpath map
31
+
32
+ Nineteen entry points. Import the one you need — the barrel is not the API.
33
+
34
+ | Subpath | What lives there |
35
+ |---|---|
36
+ | `.` | The fluent `agent()` / `tool()` builders, the error hierarchy, shared types |
37
+ | `./bridge` | The SDK seam — `createSdkAgentStream`, event translation, the agent builder internals |
38
+ | `./testing` | Test seams: compiled-agent inspection, mock streams |
39
+ | `./sandbox` | Sandbox backends, postures, `sandboxWritePolicy` |
40
+ | `./persistence` | Transcript storage primitives forwarded from the SDK |
41
+ | `./interactive` | The interactive-shell backend contract |
42
+ | `./pty` | The node-pty implementation of that contract |
43
+ | `./auth` | Credential store, OAuth/device flow, `resolveCredential`, `assertSecureModes` |
44
+ | `./tools` | Built-in tool factories (read, list, grep, git, patch, edit, shell, …) |
45
+ | `./client` | Transports for driving an agent from a client |
46
+ | `./client/react` | `useAgent` and the React bindings |
47
+ | `./session` | Session lifecycle, listing, fork/rewind, transcript GC with a retention floor |
48
+ | `./hooks` | The lifecycle-hook engine and its fingerprint gate |
49
+ | `./ask` | The human-in-the-loop rendezvous — ask a question, settle it, abandon it safely |
50
+ | `./tool-scope` | `bindToolScope` — bind `{projectRoot, writeRoot, sandbox}` once so an unconfined shell is unrepresentable |
51
+ | `./mcp-health` | MCP server health probing |
52
+ | `./commands` | Command routing and the shutdown/cleanup contract |
53
+ | `./doctor` | Environment diagnostics |
54
+ | `./usage` | Token and cost accounting |
55
+
56
+ ## The shapes worth knowing before you start
57
+
58
+ **Tool scope is bound once, not per tool.** `bindToolScope({ projectRoot, writeRoot, sandbox })`
59
+ returns a binder; every factory it binds inherits the scope. `sandbox` is **required** — a scope
60
+ without one would be an unconfined shell, and making it unrepresentable is cheaper than detecting it.
61
+
62
+ **Human gates come in three layers, and they compose.** You *declare* which tools need approval on
63
+ the builder, the *posture* decides whether auto-approval is even permissible (it carries the sandbox
64
+ posture as evidence, so "auto-approve without confinement" cannot be expressed), and the *resolver*
65
+ settles an individual request. `./ask` is the inverse channel — the agent asking you.
66
+
67
+ **Sessions are deleted carefully or not at all.** `./session` refuses to collect a transcript that a
68
+ live writer holds, floors both `keepLast` and `maxAgeDays`, and plans before it applies. When your
69
+ app knows about live sessions this package cannot see, inject them — protection is additive and
70
+ never subtractive.
71
+
72
+ **Credentials answer two questions.** Which credential to use, and where it came from. The second
73
+ matters more than it looks: without provenance, "why is it calling Anthropic?" has no answer in the
74
+ data, and a user cannot tell an explicit choice from a precedence fallback.
75
+
76
+ ## What changed recently
77
+
78
+ See [`CHANGELOG.md`](./CHANGELOG.md) — shipped inside this package, so `node_modules` answers the
79
+ question without a round trip to the repository.
80
+
81
+ For "which symbol delivers capability X, and in which version did it land", the repository publishes
82
+ a capability index at `wiki/capability-index.md`.
83
+
84
+ ## Boundaries this package keeps
85
+
86
+ - It does **not** call an LLM provider, run a tool-dispatch loop, or own the conversation store.
87
+ Those are the SDK's, and a PR that adds one here is rejected on sight.
88
+ - It does **not** depend on the `theokit` web framework. The dependency runs the other way.
89
+ - Web Standards over Node APIs inside `src/` — `Request`/`Response`, `fetch`, `crypto.randomUUID`.
90
+ Node APIs live in adapters.
91
+
92
+ ## Licence
93
+
94
+ See `LICENSE`.
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { OAuthProviderConfig, CredentialStoreConfig, ResolvedCredential, ensureFreshCredential, OpenAIDeviceConfig, openaiDeviceLogin, OAuthTokens, DeviceDeps } from '@theokit/sdk/auth';
2
- export { CredentialError, CredentialStoreConfig, DeviceCodeGrant, DeviceDeps, DeviceOAuthConfig, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolveCredentialOptions, ResolvedCredential, assertSecureModes, authFilePath, credentialHome, deviceLogin, ensureFreshCredential, extractAccountId, openaiDeviceLogin, persistOAuthTokens, pollDeviceToken, readAuthFile, readStoredOAuth, refreshOAuthTokens, requestDeviceCode, writeCredential } from '@theokit/sdk/auth';
2
+ export { CredentialError, CredentialStoreConfig, DeviceCodeGrant, DeviceDeps, DeviceOAuthConfig, OAuthProviderConfig, OAuthTokens, OpenAIDeviceConfig, ResolveCredentialOptions, ResolvedCredential, StoredCredential, StoredOAuthCredential, assertSecureModes, authFilePath, credentialHome, deviceLogin, ensureFreshCredential, extractAccountId, openaiDeviceLogin, persistOAuthTokens, pollDeviceToken, readAuthFile, readStoredOAuth, refreshOAuthTokens, requestDeviceCode, writeCredential } from '@theokit/sdk/auth';
3
3
  import { TheokitAgentError } from '@theokit/sdk/errors';
4
4
 
5
5
  /**
@@ -251,7 +251,42 @@ interface ResolveCredentialInput {
251
251
  readonly providers: readonly ProviderDescriptor[];
252
252
  /** Model id, when known. Its prefix is checked against the resolved provider. */
253
253
  readonly model?: string;
254
+ /**
255
+ * Where the persisted credential store lives, when the app has one.
256
+ *
257
+ * OPT-IN, and the reason is compatibility: absent, this resolver behaves byte-identically to
258
+ * before it could read a store. Present, an OAuth credential written by `theokit auth login`
259
+ * becomes reachable — which is what makes the published `kind: 'oauth'` variant producible instead
260
+ * of a promise the type made and no code path kept.
261
+ *
262
+ * The environment still wins: it is the more explicit and more immediate signal, and it matches
263
+ * the precedence a consumer already implements (declared env → per-provider env → file).
264
+ */
265
+ readonly store?: CredentialStoreConfig;
266
+ }
267
+ /** What `credentialSources` needs — the same declarations the resolver consults. */
268
+ interface CredentialSourcesInput {
269
+ readonly providers: readonly ProviderDescriptor[];
270
+ /** Present only when the app configured a persisted store, exactly as for `resolveCredential`. */
271
+ readonly store?: CredentialStoreConfig;
254
272
  }
273
+ /**
274
+ * Every place `resolveCredential` would look, in the order it looks.
275
+ *
276
+ * `resolveCredential` returns `undefined` when nothing is configured, and that stays — a missing key
277
+ * is the ordinary first-run state, and a throw makes the caller's next move harder. What `undefined`
278
+ * cannot say is WHERE it looked, so a product rendering "no credential found" either prints exactly
279
+ * that — the least useful sentence available — or rebuilds the resolver's precedence to name the
280
+ * places. The measured consumer built the second, carrying its own `attempts` list.
281
+ *
282
+ * Reporting is deliberately a SECOND question rather than a richer return type: changing the
283
+ * resolver's shape would break every existing caller to serve an error path, and the answer here is
284
+ * pure — no filesystem, no environment — so a caller can render it before or after a failed resolve.
285
+ *
286
+ * The order is the resolution order, because the list is printed: any other order reads as a
287
+ * precedence claim the resolver does not honour.
288
+ */
289
+ declare function credentialSources(input: CredentialSourcesInput): readonly string[];
255
290
  /**
256
291
  * Resolve which credential to use, and record where it came from.
257
292
  *
@@ -262,4 +297,51 @@ interface ResolveCredentialInput {
262
297
  */
263
298
  declare function resolveCredential(input: ResolveCredentialInput): CredentialResolution | undefined;
264
299
 
265
- export { type AuthMethod, AuthProvider, CODEX_CLIENT_ID_ENV_VAR, CODEX_PROVIDER, type ProviderDescriptor as CredentialProviderDescriptor, type CredentialResolution, type DeviceAuthProvider, type PromptHooks, ProviderPrefixMismatchError, type ResolveCredentialInput, type SourceOrigin, loginWithDevice, resolveCredential };
300
+ /** What a caller asks about: may THIS tool run THIS command in THIS place? */
301
+ interface PermissionQuery {
302
+ readonly tool: string;
303
+ /** Directory the call runs in. Canonicalised before it becomes part of the key. */
304
+ readonly scope: string;
305
+ readonly command: string;
306
+ }
307
+ interface GrantOptions {
308
+ /** Milliseconds from now. Absent ⇒ the grant does not expire. */
309
+ readonly ttlMs?: number;
310
+ }
311
+ /** One standing grant, as persisted. */
312
+ interface Grant {
313
+ readonly tool: string;
314
+ readonly scope: string;
315
+ readonly command: string;
316
+ readonly grantedAt: string;
317
+ /** Epoch millis. Absent ⇒ never expires. */
318
+ readonly expiresAt?: number;
319
+ }
320
+ interface PermissionStoreOptions {
321
+ /** Root under which `.theokit/tool-permissions.json` lives. Injectable so tests never touch `~`. */
322
+ readonly home: string;
323
+ /** Injectable clock — a store whose expiry cannot be tested is a store whose expiry is untested. */
324
+ readonly now?: () => number;
325
+ }
326
+ declare class PermissionStore {
327
+ #private;
328
+ /** Absolute path of the backing file. Public so a test can corrupt it deliberately. */
329
+ readonly path: string;
330
+ /** Why the last read failed, when it did. Carried, never thrown — a bad store must not end a turn. */
331
+ lastReadError?: Error;
332
+ constructor(options: PermissionStoreOptions);
333
+ isGranted(query: PermissionQuery): boolean;
334
+ grant(query: PermissionQuery, options?: GrantOptions): void;
335
+ revoke(query: PermissionQuery): void;
336
+ /** Every grant on record, expired ones included — `list()` reports, it does not judge. */
337
+ list(): readonly Grant[];
338
+ /**
339
+ * Grants that have expired.
340
+ *
341
+ * Surfaced rather than swept: an expired grant that vanishes silently is a permission the user
342
+ * believes they still have. The same discipline the repository applies to allowlist sunsets.
343
+ */
344
+ expired(): readonly Grant[];
345
+ }
346
+
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 };
package/dist/auth.js CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ readSecureJson,
3
+ writeSecureJson
4
+ } from "./chunk-KMJVKPKH.js";
1
5
  import {
2
6
  __name
3
7
  } from "./chunk-Z4QWC7IK.js";
@@ -123,7 +127,7 @@ var AuthProvider = class _AuthProvider {
123
127
  };
124
128
 
125
129
  // src/auth-entry.ts
126
- import { assertSecureModes, authFilePath as authFilePath2, CredentialError, credentialHome, readAuthFile, readStoredOAuth as readStoredOAuth2, writeCredential } from "@theokit/sdk/auth";
130
+ import { assertSecureModes, authFilePath as authFilePath2, CredentialError, credentialHome, readAuthFile, readStoredOAuth as readStoredOAuth3, writeCredential } from "@theokit/sdk/auth";
127
131
  import { deviceLogin, openaiDeviceLogin as openaiDeviceLogin3, pollDeviceToken, requestDeviceCode } from "@theokit/sdk/auth";
128
132
  import { ensureFreshCredential as ensureFreshCredential2, extractAccountId, persistOAuthTokens as persistOAuthTokens2, refreshOAuthTokens } from "@theokit/sdk/auth";
129
133
 
@@ -200,6 +204,7 @@ __name(loginWithDevice, "loginWithDevice");
200
204
  // src/auth/resolve-credential.ts
201
205
  import { readFileSync } from "fs";
202
206
  import { join } from "path";
207
+ import { readStoredOAuth as readStoredOAuth2 } from "@theokit/sdk/auth";
203
208
  import { TheokitAgentError } from "@theokit/sdk/errors";
204
209
  var ProviderPrefixMismatchError = class extends TheokitAgentError {
205
210
  static {
@@ -229,6 +234,17 @@ function declaredNames(path) {
229
234
  return names;
230
235
  }
231
236
  __name(declaredNames, "declaredNames");
237
+ function credentialSources(input) {
238
+ const sources = [
239
+ ...input.providers
240
+ ].sort((a, b) => a.priority - b.priority).map((descriptor) => descriptor.envKey);
241
+ if (input.store !== void 0) {
242
+ const config = input.store;
243
+ sources.push(join(config.dirName ?? ".theokit", config.fileName ?? "auth.json"));
244
+ }
245
+ return sources;
246
+ }
247
+ __name(credentialSources, "credentialSources");
232
248
  function resolveCredential(input) {
233
249
  const byPriority = [
234
250
  ...input.providers
@@ -247,7 +263,7 @@ function resolveCredential(input) {
247
263
  if (claimed !== void 0 && found === void 0) {
248
264
  throw new ProviderPrefixMismatchError(claimed.name, claimed.envKey, input.model ?? "");
249
265
  }
250
- if (found === void 0) return void 0;
266
+ if (found === void 0) return storedOAuthResolution(input, byPriority);
251
267
  return {
252
268
  kind: "api-key",
253
269
  provider: found.descriptor.name,
@@ -257,6 +273,39 @@ function resolveCredential(input) {
257
273
  };
258
274
  }
259
275
  __name(resolveCredential, "resolveCredential");
276
+ function diagnose(message) {
277
+ console.warn(`[@theokit/agents] ${message}`);
278
+ }
279
+ __name(diagnose, "diagnose");
280
+ function storedOAuthResolution(input, providers) {
281
+ if (input.store === void 0) return void 0;
282
+ let stored;
283
+ try {
284
+ stored = readStoredOAuth2(input.store, input.env);
285
+ } catch (cause) {
286
+ diagnose(`the configured credential store could not be read; treating it as absent. Cause: ${cause instanceof Error ? cause.message : String(cause)}`);
287
+ return void 0;
288
+ }
289
+ if (stored === void 0) return void 0;
290
+ if (stored.type !== "oauth" || typeof stored.access !== "string" || stored.access === "") {
291
+ return void 0;
292
+ }
293
+ const found = providers.find((p) => p.name === stored.provider);
294
+ if (found === void 0) return void 0;
295
+ return {
296
+ kind: "oauth",
297
+ provider: found.name,
298
+ // The ACCESS token is what a caller sends; the refresh token never leaves the store.
299
+ apiKey: stored.access,
300
+ source: {
301
+ kind: "oauth",
302
+ provider: found.name
303
+ },
304
+ // The store names the provider explicitly, so nothing was inferred.
305
+ inferred: false
306
+ };
307
+ }
308
+ __name(storedOAuthResolution, "storedOAuthResolution");
260
309
  function claimedProvider(model, providers) {
261
310
  if (model === void 0) return void 0;
262
311
  return providers.find((p) => p.modelPrefix !== void 0 && model.startsWith(p.modelPrefix));
@@ -277,15 +326,115 @@ function originOf(varName, home) {
277
326
  };
278
327
  }
279
328
  __name(originOf, "originOf");
329
+
330
+ // src/auth/permission-store.ts
331
+ import { realpathSync } from "fs";
332
+ import { join as join2 } from "path";
333
+ function signatureOf(command) {
334
+ return command.trim().replace(/\s+/g, " ");
335
+ }
336
+ __name(signatureOf, "signatureOf");
337
+ var PermissionStore = class {
338
+ static {
339
+ __name(this, "PermissionStore");
340
+ }
341
+ /** Absolute path of the backing file. Public so a test can corrupt it deliberately. */
342
+ path;
343
+ /** Why the last read failed, when it did. Carried, never thrown — a bad store must not end a turn. */
344
+ lastReadError;
345
+ #now;
346
+ constructor(options) {
347
+ this.path = join2(options.home, ".theokit", "tool-permissions.json");
348
+ this.#now = options.now ?? Date.now;
349
+ }
350
+ /**
351
+ * Resolve a scope to the directory it actually names.
352
+ *
353
+ * @throws when it does not resolve. Falling back to the raw string would silently restore the
354
+ * string comparison this method exists to remove — and a grant keyed on an unresolvable path
355
+ * can never be matched by a real call anyway, so the "lenient" branch only ever misleads.
356
+ */
357
+ #canonicalScope(scope) {
358
+ try {
359
+ return realpathSync(scope);
360
+ } catch (cause) {
361
+ throw new Error(`permission scope ${scope} does not resolve to a real directory, so it cannot key a grant. Cause: ${cause instanceof Error ? cause.message : String(cause)}`);
362
+ }
363
+ }
364
+ isGranted(query) {
365
+ let scope;
366
+ try {
367
+ scope = this.#canonicalScope(query.scope);
368
+ } catch {
369
+ return false;
370
+ }
371
+ const grant = this.#find(this.#load(), query.tool, scope, signatureOf(query.command));
372
+ if (grant === void 0) return false;
373
+ if (grant.expiresAt !== void 0 && grant.expiresAt <= this.#now()) return false;
374
+ return true;
375
+ }
376
+ grant(query, options = {}) {
377
+ const scope = this.#canonicalScope(query.scope);
378
+ const grants = this.#load().filter((g) => !(g.tool === query.tool && g.scope === scope && g.command === signatureOf(query.command)));
379
+ grants.push({
380
+ tool: query.tool,
381
+ scope,
382
+ command: signatureOf(query.command),
383
+ grantedAt: new Date(this.#now()).toISOString(),
384
+ ...options.ttlMs === void 0 ? {} : {
385
+ expiresAt: this.#now() + options.ttlMs
386
+ }
387
+ });
388
+ this.#persist(grants);
389
+ }
390
+ revoke(query) {
391
+ const scope = this.#canonicalScope(query.scope);
392
+ const signature = signatureOf(query.command);
393
+ const kept = this.#load().filter((g) => !(g.tool === query.tool && g.scope === scope && g.command === signature));
394
+ this.#persist(kept);
395
+ }
396
+ /** Every grant on record, expired ones included — `list()` reports, it does not judge. */
397
+ list() {
398
+ return this.#load();
399
+ }
400
+ /**
401
+ * Grants that have expired.
402
+ *
403
+ * Surfaced rather than swept: an expired grant that vanishes silently is a permission the user
404
+ * believes they still have. The same discipline the repository applies to allowlist sunsets.
405
+ */
406
+ expired() {
407
+ const now = this.#now();
408
+ return this.#load().filter((g) => g.expiresAt !== void 0 && g.expiresAt <= now);
409
+ }
410
+ #find(grants, tool, scope, signature) {
411
+ return grants.find((g) => g.tool === tool && g.scope === scope && g.command === signature);
412
+ }
413
+ #load() {
414
+ const { value, error } = readSecureJson(this.path, (raw) => {
415
+ const parsed = JSON.parse(raw);
416
+ if (!Array.isArray(parsed)) throw new Error("expected an array of grants");
417
+ return parsed;
418
+ }, []);
419
+ this.lastReadError = error;
420
+ return value;
421
+ }
422
+ #persist(grants) {
423
+ writeSecureJson(this.path, () => `${JSON.stringify(grants, null, 2)}
424
+ `);
425
+ }
426
+ };
280
427
  export {
281
428
  AuthProvider,
282
429
  CODEX_CLIENT_ID_ENV_VAR,
283
430
  CODEX_PROVIDER,
284
431
  CredentialError,
432
+ PermissionStore,
285
433
  ProviderPrefixMismatchError,
286
434
  assertSecureModes,
287
435
  authFilePath2 as authFilePath,
288
436
  credentialHome,
437
+ credentialSources,
289
438
  deviceLogin,
290
439
  ensureFreshCredential2 as ensureFreshCredential,
291
440
  extractAccountId,
@@ -294,7 +443,7 @@ export {
294
443
  persistOAuthTokens2 as persistOAuthTokens,
295
444
  pollDeviceToken,
296
445
  readAuthFile,
297
- readStoredOAuth2 as readStoredOAuth,
446
+ readStoredOAuth3 as readStoredOAuth,
298
447
  refreshOAuthTokens,
299
448
  requestDeviceCode,
300
449
  resolveCredential,
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"],"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;SAFiB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ACxB;AACF;AAjCgBb;AA0ChB,SAASe,gBACPjC,OACAqB,WAAwC;AAExC,MAAIrB,UAAU+B,OAAW,QAAOA;AAChC,SAAOV,UAAUc,KAAK,CAACO,MAAMA,EAAEC,gBAAgBZ,UAAa/B,MAAMW,WAAW+B,EAAEC,WAAW,CAAA;AAC5F;AANSV;AAST,SAASM,SAASK,SAAiBJ,MAAwB;AACzD,MAAIA,SAAST,OAAW,QAAO;IAAEM,MAAM;IAAOO;EAAQ;AACtD,QAAMC,SAASC,KAAKN,MAAM,MAAA;AAC1B,SAAOvC,cAAc4C,MAAAA,EAAQE,IAAIH,OAAAA,IAC7B;IAAEP,MAAM;IAAQnC,MAAM2C;EAAO,IAC7B;IAAER,MAAM;IAAOO;EAAQ;AAC7B;AANSL;","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","TheokitAgentError","ProviderPrefixMismatchError","TheokitAgentError","name","provider","envKey","model","declaredNames","path","raw","readFileSync","Set","names","line","split","trimmed","trim","startsWith","withoutExport","slice","length","eq","indexOf","add","resolveCredential","input","byPriority","providers","sort","a","b","priority","available","flatMap","descriptor","apiKey","env","undefined","claimed","claimedProvider","found","find","candidate","kind","source","originOf","home","inferred","p","modelPrefix","varName","dotenv","join","has"]}
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,SAA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A4B;AAC1B,UAAMzB,MAAM,KAAK,KAAI;AACrB,WAAO,KAAK,MAAK,EAAGe,OAAO,CAACC,MAAMA,EAAEH,cAAcD,UAAaI,EAAEH,aAAab,GAAAA;EAChF;EAEA,MACEc,QACAH,MACAT,OACAoB,WAAiB;AAEjB,WAAOR,OAAOY,KAAK,CAACV,MAAMA,EAAEL,SAASA,QAAQK,EAAEd,UAAUA,SAASc,EAAEzB,YAAY+B,SAAAA;EAClF;EAEA,QAAK;AACH,UAAM,EAAEK,OAAOC,MAAK,IAAKC,eACvB,KAAKlC,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"]}
@@ -1355,6 +1355,21 @@ interface DelegateOptions {
1355
1355
  parentBudgetRemaining?: number;
1356
1356
  /** Parent's tools (for sharing — sub-agent inherits these). */
1357
1357
  parentTools?: CompiledTool[];
1358
+ /**
1359
+ * Parent's hooks. The member inherits them, and inheritance may only TIGHTEN: both
1360
+ * `pre_tool_call` gates run and the first refusal wins, so a member cannot widen what the parent
1361
+ * refused.
1362
+ *
1363
+ * Symmetric with `parentTools` on purpose — `delegate` already carried the parent's tools and its
1364
+ * budget into the member's run and left its AUTHORITY behind, which is how a squad member could
1365
+ * call a tool the supervisor had vetoed. The failure was silent: nothing threw, and the member's
1366
+ * own suite passed because the member never declared the gate.
1367
+ *
1368
+ * To scope a member differently, pass its handlers on `spec.compiled.hooks` — they compose with
1369
+ * these rather than replacing them, because a widening that a call site cannot see is the state
1370
+ * this option exists to remove.
1371
+ */
1372
+ parentHooks?: HookHandlers;
1358
1373
  /** LLM API key (inherited from parent). */
1359
1374
  apiKey?: string;
1360
1375
  /** Session ID override (default: crypto.randomUUID for isolation). */
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinitionError, g as AgentExecutionContext, h as AgentManifest, A as AgentManifestEntry, i as AgentManifestSource, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentsPluginOptions, q as ApiErrorContext, r as ApiErrorDecision, t as ApiErrorPolicy, c as ApprovalPosture, u as ApprovalRequiredEvent, v as ArtifactChunkEvent, w as ArtifactStartEvent, B as BackgroundDelegation, x as BeforeToolCallContext, y as BudgetExceededError, z as CheckpointSavedEvent, E as CompiledContextWindow, F as ContextualTool, I as DefinitionOrThunk, J as DelegateFn, K as DelegateOptions, M as DelegationBudgetExceededError, N as DelegationError, O as DelegationPort, D as DelegationResult, P as DelegationTarget, Q as DelegationTimeoutError, T as DoneEvent, U as EphemeralAgent, V as ErrorEvent, W as FileEditEvent, X as IterationEvent, Y as LLMCallContext, a0 as McpApprovalSpec, a1 as McpFileError, a2 as McpRegistryConfig, a3 as McpRequestContext, a4 as McpSelection, a5 as PartialToolCallEvent, a6 as ProcessInputContext, aa as RunStartedEvent, ab as ScoreVerdict, ac as ScoredDelegation, ad as Scorer, ae as SdkAgentHandle, af as SdkMessage, ag as SdkSendOptions, ah as SdkTurnHandle, ai as Segment, aj as StateUpdateEvent, S as StreamEvent, ak as TextDeltaEvent, al as ThinkingEvent, am as ToolCallEvent, an as ToolCallVeto, ao as ToolHooks, ap as ToolHooksPlugin, aq as ToolResultEvent, ar as agentsPlugin, as as buildModelSelection, at as compileAgentModule, au as compileContextWindow, av as compileProjectContext, aw as compileSkills, ax as createAgentExecutionContext, ay as createApiErrorHandler, az as createSdkAgentStream, aA as createThinkTagExtractor, aB as createToolHooksPlugin, aC as delegate, aD as delegateBackground, aE as delegateWithScoring, aF as extractThinkTagStream, aG as generateAgentManifest, aH as generateAgentRoutes, aI as isAgentContext, aJ as isApprovalRequired, aK as isDone, aL as isError, aM as isPartialToolCall, aN as isTextDelta, aO as isToolCall, aP as isToolResult, aR as loadMcpJson, aT as mcpRegistry, aU as mcpToolApprovals, aW as presentUIMessageStream, aX as projectContextMetadataOnlyKnobs, aY as reasoningEffortOf, a$ as resolveMcpServers, b0 as runWithApiErrorHandling, b1 as streamAgentResponse, s as streamAgentUIMessages, b2 as toAgentFactory, b3 as translateSdkEvent, b4 as withClockCap, b5 as withEphemeralAgent } from './bridge-entry-BEniSXWE.js';
1
+ export { d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinitionError, g as AgentExecutionContext, h as AgentManifest, A as AgentManifestEntry, i as AgentManifestSource, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentsPluginOptions, q as ApiErrorContext, r as ApiErrorDecision, t as ApiErrorPolicy, c as ApprovalPosture, u as ApprovalRequiredEvent, v as ArtifactChunkEvent, w as ArtifactStartEvent, B as BackgroundDelegation, x as BeforeToolCallContext, y as BudgetExceededError, z as CheckpointSavedEvent, E as CompiledContextWindow, F as ContextualTool, I as DefinitionOrThunk, J as DelegateFn, K as DelegateOptions, M as DelegationBudgetExceededError, N as DelegationError, O as DelegationPort, D as DelegationResult, P as DelegationTarget, Q as DelegationTimeoutError, T as DoneEvent, U as EphemeralAgent, V as ErrorEvent, W as FileEditEvent, X as IterationEvent, Y as LLMCallContext, a0 as McpApprovalSpec, a1 as McpFileError, a2 as McpRegistryConfig, a3 as McpRequestContext, a4 as McpSelection, a5 as PartialToolCallEvent, a6 as ProcessInputContext, aa as RunStartedEvent, ab as ScoreVerdict, ac as ScoredDelegation, ad as Scorer, ae as SdkAgentHandle, af as SdkMessage, ag as SdkSendOptions, ah as SdkTurnHandle, ai as Segment, aj as StateUpdateEvent, S as StreamEvent, ak as TextDeltaEvent, al as ThinkingEvent, am as ToolCallEvent, an as ToolCallVeto, ao as ToolHooks, ap as ToolHooksPlugin, aq as ToolResultEvent, ar as agentsPlugin, as as buildModelSelection, at as compileAgentModule, au as compileContextWindow, av as compileProjectContext, aw as compileSkills, ax as createAgentExecutionContext, ay as createApiErrorHandler, az as createSdkAgentStream, aA as createThinkTagExtractor, aB as createToolHooksPlugin, aC as delegate, aD as delegateBackground, aE as delegateWithScoring, aF as extractThinkTagStream, aG as generateAgentManifest, aH as generateAgentRoutes, aI as isAgentContext, aJ as isApprovalRequired, aK as isDone, aL as isError, aM as isPartialToolCall, aN as isTextDelta, aO as isToolCall, aP as isToolResult, aR as loadMcpJson, aT as mcpRegistry, aU as mcpToolApprovals, aW as presentUIMessageStream, aX as projectContextMetadataOnlyKnobs, aY as reasoningEffortOf, a$ as resolveMcpServers, b0 as runWithApiErrorHandling, b1 as streamAgentResponse, s as streamAgentUIMessages, b2 as toAgentFactory, b3 as translateSdkEvent, b4 as withClockCap, b5 as withEphemeralAgent } from './bridge-entry-51lU7LQw.js';
2
2
  export { c as AGENT_BRAND, A as AgentDefinition, C as CompiledAgentOptions, a as CompiledTool, D as DefineAgentConfig, I as InferAgentInput, j as InferAgentToolNames, m as ProjectSettingsGrant, n as SettingSourceCapability, S as SettingSourcesSelection, r as ToolWalkResult, t as ToolboxWalkResult, U as UntrustedSettingSourceError, u as compileAgentDefinition, v as compileTools, w as isAgentDefinition, y as resolveSettingSources } from './define-agent-3Kuf6iKM.js';
3
3
  import '@theokit/http';
4
4
  import '@theokit/sdk';
package/dist/bridge.js CHANGED
@@ -47,7 +47,8 @@ import {
47
47
  translateSdkEvent,
48
48
  withClockCap,
49
49
  withEphemeralAgent
50
- } from "./chunk-C7UXZWVY.js";
50
+ } from "./chunk-RZCNKKOG.js";
51
+ import "./chunk-RKWCXVYG.js";
51
52
  import {
52
53
  AGENT_BRAND,
53
54
  UntrustedSettingSourceError,
@@ -0,0 +1,72 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-Z4QWC7IK.js";
4
+
5
+ // src/hooks/secure-store.ts
6
+ import { randomUUID } from "crypto";
7
+ import { chmodSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
8
+ import { dirname, join } from "path";
9
+ var FORBIDDEN_WRITE_BITS = 18;
10
+ var DIR_MODE = 448;
11
+ var FILE_MODE = 384;
12
+ function ensureSecureDir(filePath) {
13
+ const dir = dirname(filePath);
14
+ mkdirSync(dir, {
15
+ recursive: true,
16
+ mode: DIR_MODE
17
+ });
18
+ const mode = statSync(dir).mode & 511;
19
+ if ((mode & FORBIDDEN_WRITE_BITS) !== 0) {
20
+ chmodSync(dir, DIR_MODE);
21
+ const repaired = statSync(dir).mode & 511;
22
+ if ((repaired & FORBIDDEN_WRITE_BITS) !== 0) {
23
+ throw new Error(`${dir} is mode ${repaired.toString(8)} \u2014 group or world writable, and the repair did not hold. This directory decides which commands may run, so a writable one is a way to grant that to yourself. Fix with \`chmod 700 ${dir}\`.`);
24
+ }
25
+ }
26
+ }
27
+ __name(ensureSecureDir, "ensureSecureDir");
28
+ function readSecureJson(filePath, parse, empty) {
29
+ let raw;
30
+ try {
31
+ raw = readFileSync(filePath, "utf8");
32
+ } catch {
33
+ return {
34
+ value: empty
35
+ };
36
+ }
37
+ if (raw.trim().length === 0) return {
38
+ value: empty
39
+ };
40
+ try {
41
+ return {
42
+ value: parse(raw)
43
+ };
44
+ } catch (cause) {
45
+ return {
46
+ value: empty,
47
+ error: new Error(`${filePath} could not be parsed and is being treated as empty \u2014 every entry in it has stopped applying. Inspect or delete it. Cause: ${cause instanceof Error ? cause.message : String(cause)}`)
48
+ };
49
+ }
50
+ }
51
+ __name(readSecureJson, "readSecureJson");
52
+ function tempPathFor(filePath) {
53
+ return join(dirname(filePath), `.${randomUUID()}.tmp`);
54
+ }
55
+ __name(tempPathFor, "tempPathFor");
56
+ function writeSecureJson(filePath, serialize) {
57
+ ensureSecureDir(filePath);
58
+ const tmp = tempPathFor(filePath);
59
+ writeFileSync(tmp, serialize(), {
60
+ encoding: "utf8",
61
+ mode: FILE_MODE
62
+ });
63
+ renameSync(tmp, filePath);
64
+ chmodSync(filePath, FILE_MODE);
65
+ }
66
+ __name(writeSecureJson, "writeSecureJson");
67
+
68
+ export {
69
+ readSecureJson,
70
+ writeSecureJson
71
+ };
72
+ //# sourceMappingURL=chunk-KMJVKPKH.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,WAAW;AACjB,IAAMC,YAAY;AAqBX,SAASC,gBAAgBC,UAAgB;AAC9C,QAAMC,MAAMC,QAAQF,QAAAA;AAEpBG,YAAUF,KAAK;IAAEG,WAAW;IAAMC,MAAMR;EAAS,CAAA;AAGjD,QAAMQ,OAAOC,SAASL,GAAAA,EAAKI,OAAO;AAClC,OAAKA,OAAOT,0BAA0B,GAAG;AAEvCW,cAAUN,KAAKJ,QAAAA;AAEf,UAAMW,WAAWF,SAASL,GAAAA,EAAKI,OAAO;AACtC,SAAKG,WAAWZ,0BAA0B,GAAG;AAC3C,YAAM,IAAIa,MACR,GAAGR,GAAAA,YAAeO,SAASE,SAAS,CAAA,CAAA,2LAEQT,GAAAA,KAAQ;IAExD;EACF;AACF;AApBgBF;AA2BT,SAASY,eACdX,UACAY,OACAC,OAAQ;AAER,MAAIC;AACJ,MAAI;AAEFA,UAAMC,aAAaf,UAAU,MAAA;EAC/B,QAAQ;AAEN,WAAO;MAAEgB,OAAOH;IAAM;EACxB;AAGA,MAAIC,IAAIG,KAAI,EAAGC,WAAW,EAAG,QAAO;IAAEF,OAAOH;EAAM;AAEnD,MAAI;AACF,WAAO;MAAEG,OAAOJ,MAAME,GAAAA;IAAK;EAC7B,SAASK,OAAO;AACd,WAAO;MACLH,OAAOH;MACPO,OAAO,IAAIX,MACT,GAAGT,QAAAA,kIACiDmB,iBAAiBV,QAAQU,MAAME,UAAUC,OAAOH,KAAAA,CAAAA,EAAQ;IAEhH;EACF;AACF;AA5BgBR;AA6CT,SAASY,YAAYvB,UAAgB;AAC1C,SAAOwB,KAAKtB,QAAQF,QAAAA,GAAW,IAAIyB,WAAAA,CAAAA,MAAkB;AACvD;AAFgBF;AAKT,SAASG,gBAAgB1B,UAAkB2B,WAAuB;AACvE5B,kBAAgBC,QAAAA;AAChB,QAAM4B,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"]}