@theokit/agents 16.5.2 → 16.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +88 -5
  3. package/dist/{agent-compiler-C-4X_vKz.d.ts → agent-compiler-aubY9WIa.d.ts} +13 -1
  4. package/dist/{agent-handle-rEWdERuv.d.ts → agent-handle-C343-xUh.d.ts} +16 -1
  5. package/dist/{agent-orchestrator-BHF1bS6k.d.ts → agent-orchestrator-DQtfrPaq.d.ts} +2 -2
  6. package/dist/{agent-runner-BoMoOnHV.d.ts → agent-runner-BuuqK_Dp.d.ts} +3 -3
  7. package/dist/{agent-sse-handler-BRp9vHrb.d.ts → agent-sse-handler-BtIpJZxO.d.ts} +3 -1
  8. package/dist/auth.d.ts +21 -1
  9. package/dist/auth.js +23 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/{bridge-entry-DO1LjHkc.d.ts → bridge-entry-nkeH6pAk.d.ts} +50 -7
  12. package/dist/bridge.d.ts +6 -6
  13. package/dist/bridge.js +9 -5
  14. package/dist/{chunk-KXE52FP2.js → chunk-4DOKIDGC.js} +59 -1
  15. package/dist/chunk-4DOKIDGC.js.map +1 -0
  16. package/dist/{chunk-NIQJ4GZX.js → chunk-JJ6Y6EBP.js} +4 -1
  17. package/dist/chunk-JJ6Y6EBP.js.map +1 -0
  18. package/dist/{chunk-ZLKZOSWR.js → chunk-RXD6S6RV.js} +2 -2
  19. package/dist/{chunk-K4MY4CV7.js → chunk-UARNAQ6O.js} +3 -3
  20. package/dist/{chunk-AZ2FOUSN.js → chunk-W533YIGA.js} +32 -5
  21. package/dist/chunk-W533YIGA.js.map +1 -0
  22. package/dist/{chunk-RZWD73QG.js → chunk-XGW7IZP6.js} +70 -5
  23. package/dist/chunk-XGW7IZP6.js.map +1 -0
  24. package/dist/client-react.d.ts +1 -1
  25. package/dist/client-react.js +1 -1
  26. package/dist/client.d.ts +14 -4
  27. package/dist/client.js +49 -2
  28. package/dist/client.js.map +1 -1
  29. package/dist/commands.d.ts +64 -12
  30. package/dist/commands.js +104 -12
  31. package/dist/commands.js.map +1 -1
  32. package/dist/config.d.ts +105 -1
  33. package/dist/config.js +460 -62
  34. package/dist/config.js.map +1 -1
  35. package/dist/{delegation-scoring-BBPJ9eug.d.ts → delegation-scoring-DPckVefy.d.ts} +1 -1
  36. package/dist/evals.d.ts +3 -3
  37. package/dist/evals.js +2 -2
  38. package/dist/handoff.d.ts +4 -4
  39. package/dist/handoff.js +3 -3
  40. package/dist/hooks.d.ts +24 -1
  41. package/dist/hooks.js +78 -3
  42. package/dist/hooks.js.map +1 -1
  43. package/dist/index.d.ts +22 -12
  44. package/dist/index.js +17 -5
  45. package/dist/index.js.map +1 -1
  46. package/dist/{sdk-adapter-C57SpmLH.d.ts → sdk-adapter-B0i8J7N0.d.ts} +2 -2
  47. package/dist/session.d.ts +17 -1
  48. package/dist/session.js +15 -0
  49. package/dist/session.js.map +1 -1
  50. package/dist/testing.d.ts +1 -1
  51. package/dist/testing.js +1 -1
  52. package/dist/tools.d.ts +4 -4
  53. package/dist/tools.js +4 -4
  54. package/package.json +3 -3
  55. package/dist/chunk-AZ2FOUSN.js.map +0 -1
  56. package/dist/chunk-KXE52FP2.js.map +0 -1
  57. package/dist/chunk-NIQJ4GZX.js.map +0 -1
  58. package/dist/chunk-RZWD73QG.js.map +0 -1
  59. /package/dist/{chunk-ZLKZOSWR.js.map → chunk-RXD6S6RV.js.map} +0 -0
  60. /package/dist/{chunk-K4MY4CV7.js.map → chunk-UARNAQ6O.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @theokit/agents
2
2
 
3
+ ## 16.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 817296c: Add `defineAppBootstrap`, `assertBootstrapped` and `projectEnvStep` to `@theokit/agents/config`, so every entry of an agent app runs the same setup once, in order.
8
+ - 98829ee: `AgentClient.sendAndWait` resolves when its own turn settles, and `asGoalLoopAgent` adapts a client to the SDK `GoalLoopAgent` contract so `runGoalLoop` can drive a UI client without polling.
9
+ - e104596: `@theokit/agents/commands` adds `createCommandRegistry` and `CommandRegistryError`. Command definitions take `aliases`, `hidden` and `run`; `routeCommand` resolves aliases.
10
+ - 2da7cde: Add `listUserTurns` to `@theokit/agents/session`, listing the user turns `forkBeforeUserTurn` counts.
11
+ - b4526ae: `@theokit/agents/bridge` exports `loadMcpScopes`, which merges personal and project MCP servers with a trust gate for the project and a clash rule (personal wins by default).
12
+ - f5452e3: `@theokit/agents/hooks` exports `runHostHooks`, which runs the approved hooks of one event the host owns (such as session start) outside an agent loop, with the same trust and approval gate as `buildHookHandlers` and an explicit, required environment.
13
+ - 787c3c6: `@theokit/agents/config` adds `settingsCandidates`, `readSettingsFile` and `firstSettingsFile` to read `settings.json` under an own root and the `.claude` root, reporting `ignored` and `unrecognised` keys and unsupported permission entries. `CLAUDE_SETTINGS_KEYS` and `FOREIGN_KEY_DECISIONS` are exported.
14
+ - fd25499: `Shutdown.register` now returns a disposer, and `@theokit/agents/commands` exports `exitAfterDrain` for a normal exit that lets output drain. `createShutdown` takes `drain: true` to use it.
15
+ - aa5755c: `AgentBuilder.withholdBuiltinTools(names)` withholds SDK builtin tools (such as `shell`) on every run path, not only `toAgentFactory`. Unknown names are refused with a `ConfigurationError`; `withholdBuiltinShell` is unioned with it.
16
+
17
+ ## 16.6.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 5d55198: Export `ERROR_CODE_DATA_PART` from `@theokit/agents/bridge`; it is now an alias of `WIRE_ERROR_CODE_PART` from `@theokit/presenter/wire`.
22
+ - 82e9aa1: `RefreshFailure` now extends `TheokitAgentError` (code `oauth_refresh_failed`, `isRetryable` mirrors `.transient`, `cause` is the original error), so `isTransientError` works on a refresh failure. It is exported from `@theokit/agents/auth`.
23
+
24
+ ### Patch Changes
25
+
26
+ - 8742832: `blockAppliesTo` no longer matches `src/**/test.ts` against `src/mytest.ts`: `**/` now matches whole directories only.
27
+ - Updated dependencies [2aacc53]
28
+ - Updated dependencies [5d55198]
29
+ - @theokit/presenter@0.12.0
30
+
3
31
  ## 16.5.2
4
32
 
5
33
  ### Patch Changes
package/README.md CHANGED
@@ -34,16 +34,16 @@ Twenty-three entry points. Import the one you need — the barrel is not the API
34
34
  | Subpath | What lives there |
35
35
  |---|---|
36
36
  | `.` | `AgentBuilder.create()` — the authoring surface — plus the error hierarchy and shared types |
37
- | `./bridge` | The SDK seam — `createSdkAgentStream`, event translation, the agent builder internals |
37
+ | `./bridge` | The SDK seam — `createSdkAgentStream`, event translation, the agent builder internals, `ERROR_CODE_DATA_PART` |
38
38
  | `./testing` | Test seams: compiled-agent inspection, mock streams |
39
39
  | `./sandbox` | Sandbox backends, postures, `sandboxWritePolicy` |
40
40
  | `./persistence` | Transcript storage primitives forwarded from the SDK |
41
41
  | `./interactive` | The interactive-shell backend contract |
42
42
  | `./pty` | The node-pty implementation of that contract |
43
- | `./auth` | Credential store, OAuth/device flow, `resolveCredential`, `assertSecureModes` |
44
- | `./config` | Agent configuration, trust posture, and the instruction tree (`loadInstructionTree`) |
43
+ | `./auth` | Credential store, OAuth/device flow, `resolveCredential`, `assertSecureModes`, `RefreshFailure` |
44
+ | `./config` | Agent configuration, trust posture, and the instruction tree (`loadInstructionTree`); `defineAppBootstrap` runs one setup from every entry |
45
45
  | `./tools` | Built-in tool factories (read, list, grep, git, patch, edit, shell, …) |
46
- | `./client` | Transports for driving an agent from a client |
46
+ | `./client` | Transports for driving an agent from a client. `AgentClient.sendAndWait(input)` resolves when that turn settles (`done`/`error`/`aborted`, never rejects), and `asGoalLoopAgent(client)` adapts a client to the SDK `GoalLoopAgent` so `runGoalLoop` can drive it without polling |
47
47
  | `./client/react` | `useAgent` and the React bindings |
48
48
  | `./session` | Session lifecycle, listing, fork/rewind, transcript GC with a retention floor |
49
49
  | `./hooks` | The lifecycle-hook engine and its fingerprint gate |
@@ -51,12 +51,51 @@ Twenty-three entry points. Import the one you need — the barrel is not the API
51
51
  | `./tool-scope` | `bindToolScope` — bind `{projectRoot, writeRoot, sandbox}` once so an unconfined shell is unrepresentable |
52
52
  | `./a2a` | `createA2ATool` — call a remote agent over HTTP as a tool |
53
53
  | `./mcp-health` | MCP server health probing |
54
- | `./commands` | Command routing and the shutdown/cleanup contract |
54
+ | `./commands` | Command routing and the shutdown/cleanup contract. `Shutdown.register` returns a disposer (a no-op once `run()` started); `exitAfterDrain(code)` sets the exit code and forces the exit only if the loop has not drained within `capMs` |
55
55
  | `./doctor` | Environment diagnostics |
56
56
  | `./usage` | Token and cost accounting |
57
57
  | `./evals` | `runAgentEvals` — run cases against an agent and read pass, fail or error per case |
58
58
  | `./handoff` | `createHandoffConversation`: one agent hands the conversation to another, and the next turn is answered by the receiver |
59
59
 
60
+ A terminal command list, with aliases, hidden names and handlers, from `./commands`:
61
+
62
+ ```ts
63
+ import { createCommandRegistry, defineCommand } from '@theokit/agents/commands'
64
+
65
+ const registry = createCommandRegistry<{ exit(): void }>([
66
+ defineCommand({ name: 'quit', description: 'leave', aliases: ['exit'], arg: 'none', run: (_arg, ctx) => ctx.exit() }),
67
+ defineCommand({ name: 'debug', description: 'toggle debug', hidden: true }),
68
+ ])
69
+ registry.palette() // [{ name: 'quit', description: 'leave' }]
70
+ await registry.dispatch('/exit', { exit: () => process.exit(0) })
71
+ ```
72
+
73
+ `AuthProvider.ensureFresh` throws `RefreshFailure` (exported from `./auth`) when a token refresh fails. It is a `TheokitAgentError` with `code: 'oauth_refresh_failed'`, `isRetryable` equal to `.transient`, and the original error as `cause`, so the SDK's `isTransientError(err)` is `true` for a network reset and `false` for `invalid_grant`.
74
+
75
+ ## One bootstrap for every entry
76
+
77
+ An app with several entries (CLI, ACP server) declares its setup once. Each step runs once, in order,
78
+ before anything resolves an SDK path; a failing step throws `BootstrapStepError` and later steps do not run.
79
+
80
+ ```ts
81
+ // bootstrap.ts
82
+ import { defineAppBootstrap, projectEnvStep } from '@theokit/agents/config'
83
+
84
+ export const bootstrap = defineAppBootstrap([
85
+ projectEnvStep, // loads .env, refusing the SDK's sovereign keys
86
+ { name: 'home', run: (ctx) => void (ctx.env.THEOKIT_HOME ??= ctx.home) },
87
+ ])
88
+
89
+ // cli.ts and acp.ts both begin with the same call
90
+ import { homedir } from 'node:os'
91
+ import { bootstrap } from './bootstrap.js'
92
+ await bootstrap.run({ env: process.env, cwd: process.cwd(), home: homedir() })
93
+
94
+ // any module that resolves SDK paths
95
+ import { assertBootstrapped } from '@theokit/agents/config'
96
+ assertBootstrapped(bootstrap, 'openTranscriptStore')
97
+ ```
98
+
60
99
  ## The shapes worth knowing before you start
61
100
 
62
101
  **Tool scope is bound once, not per tool.** `bindToolScope({ projectRoot, writeRoot, sandbox })`
@@ -121,6 +160,25 @@ entry, that brings its own `transfer_to_agent` tool is refused with `reserved_to
121
160
  `@theokit/sdk-handoff` and `createDelegateTool` work differently. They are call-and-return: the
122
161
  agent you call answers the caller, and the caller keeps the turn.
123
162
 
163
+ ## Withholding SDK builtin tools
164
+
165
+ `AgentBuilder.withholdBuiltinTools(['shell'])` keeps the named SDK builtin tools (`shell`,
166
+ `memory_search`, `memory_get`) out of the model's tool list, on every run path: `createSdkAgentStream`,
167
+ `streamAgentTurnInProcess`, the client's `InProcessTransport` and `toAgentFactory`. An unknown name is
168
+ refused with a `ConfigurationError`. `toAgentFactory({ withholdBuiltinShell: true })` still works;
169
+ when both are set, the union is passed.
170
+
171
+ ## Hooks the host owns
172
+
173
+ `buildHookHandlers` wires hooks into one agent loop. Some events belong to the host instead:
174
+ `on_session_start` fires once per loop context, so an app that builds a fresh agent per turn would
175
+ run a session-start hook on every message. For those, call `runHostHooks(event, specs, options)` from
176
+ `@theokit/agents/hooks` at the moment the host starts the session. It applies the same trust and
177
+ fingerprint gate as `buildHookHandlers`, ignores specs of other events, and returns one
178
+ `HostHookOutcome` per spec (`ran`, `not-approved`, `failed`, `timed-out` or `could-not-start`)
179
+ without throwing. `options.env` is required and is the whole environment of the hook; `process.env`
180
+ is never inherited. Leave the event unwired in the loop handlers so it is not delivered twice.
181
+
124
182
  ## What changed recently
125
183
 
126
184
  See [`CHANGELOG.md`](./CHANGELOG.md) — shipped inside this package, so `node_modules` answers the
@@ -186,6 +244,8 @@ gap worth declaring and one worth closing — so it was closed. `loadPersonalMcp
186
244
  and only that key, and returns empty on a malformed file rather than throwing, because one stray comma
187
245
  in a shared home file must not break every project on the machine.
188
246
 
247
+ **MCP scopes.** `loadMcpScopes({ cwd, home, projectAllowed, onClash?, personalFiles?, onWarn? })` (from `@theokit/agents/bridge`) merges the personal servers (`~/.claude.json` by default) with `<cwd>/.mcp.json`. When `projectAllowed` is false the project's servers are withheld: the file is parsed only to list its names in `projectWithheld`. On a name clash the personal server wins by default, so a repository cannot replace a server the operator configured; pass `onClash: 'project-wins'` for the reference format. Clashes are returned as data in `shadowed`. A malformed project file throws `McpFileError`; a malformed personal file only warns.
248
+
189
249
  Both MCP readers are called by the host, not from inside this package — `loadMcpJson` has no internal
190
250
  caller either, and a library with no `main()` cannot have one. That is why both rows say **read**: the
191
251
  criterion is not who calls, it is whether the chain is intact. Nothing drops an MCP server.
@@ -231,6 +291,23 @@ A consumer that wants it passes it. Measured 2026-09-15 while auditing this tabl
231
291
  was listed as `read`. The word describes the mechanism existing; a reader takes it as the behaviour
232
292
  happening.
233
293
 
294
+ ### Reading settings under two roots
295
+
296
+ An app with its own root (`.myapp/`) that also honours `.claude/` uses `settingsCandidates` (per scope,
297
+ own root before foreign root; `foreignRoot: false` reads only the own root) and `firstSettingsFile` /
298
+ `readSettingsFile`. The first existing file in a scope wins.
299
+
300
+ ```ts
301
+ const c = settingsCandidates({ cwd, home, ownRoot: '.myapp' })
302
+ const read = firstSettingsFile(c.project, { ownKeys: ['model'], renames: { outputStyle: 'style' }, onWarn })
303
+ ```
304
+
305
+ In an own-root file an unknown key stays in `values`, so your strict schema rejects it by name. In a
306
+ foreign-root file it is listed in `unrecognised`. A Claude Code key you do not implement, `$schema` and
307
+ `_`-prefixed keys go to `ignored`. `permissions` becomes `permissionRules`, and entries that cannot be
308
+ rendered are in `unsupportedPermissions`. `hooks` is returned raw. A file that exists but cannot be
309
+ parsed is reported through `onWarn` and yields `undefined`.
310
+
234
311
  ### `settings.json` — `env`
235
312
 
236
313
  `outputStyle` is read AND applied: `loadSettings` returns it and `resolveOutputStyle` hands it to
@@ -388,3 +465,9 @@ Two consequences worth stating, because they are the cost:
388
465
  ## Licence
389
466
 
390
467
  See `LICENSE`.
468
+
469
+ ## Sessions
470
+
471
+ `@theokit/agents/session` forks a session before a user turn with `forkBeforeUserTurn(srcId, newId, nth, { cwd })`.
472
+ `listUserTurns(sessionId, { cwd })` lists the turns it can cut before as `{ nth, text }`. `nth` is 1-based and is
473
+ the number `forkBeforeUserTurn` takes, so a backtrack UI can show the list and fork at the chosen entry.
@@ -1,4 +1,4 @@
1
- import { InlineSkill, CustomTool, MemorySettings, TelemetrySettings, SystemPromptResolver, SessionStore, PermissionGate, SkillsSettings, ContextSettings } from '@theokit/sdk';
1
+ import { InlineSkill, CustomTool, BuiltinToolName, MemorySettings, TelemetrySettings, SystemPromptResolver, SessionStore, PermissionGate, SkillsSettings, ContextSettings } from '@theokit/sdk';
2
2
  import { AgentDefinition as AgentDefinition$1 } from '@theokit/sdk/subagents-loader';
3
3
  import { TheokitAgentError } from '@theokit/sdk/errors';
4
4
  import { R as ReasoningEffort, H as HumanInTheLoopOptions, a as McpServersMap, b as MemoryOptions, P as ProjectContextOptions, C as CheckpointOptions, T as ToolOptions, A as ApprovalOptions, B as BudgetOptions } from './types-D5cHmSLi.js';
@@ -359,6 +359,12 @@ interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
359
359
  * rather than forwarded, because a gate that silently does not gate is worse than none.
360
360
  */
361
361
  hookApproval?: HookApprovalGate;
362
+ /**
363
+ * #1912 — SDK builtin tools to withhold from the model (`Agent.create({ withheldBuiltinTools })`),
364
+ * so their schema is never declared, rather than refused at call time. Unknown names are refused
365
+ * at assembly with a `ConfigurationError`.
366
+ */
367
+ withheldBuiltinTools?: readonly BuiltinToolName[];
362
368
  /**
363
369
  * B-054 — `MEMORY.md` here is NOT the Claude Code CLI's auto-memory file. This is the durable
364
370
  * subsystem below: a SQLite+FTS5 store under `.theokit/memory/`, with `memory_search`/`memory_get`
@@ -555,6 +561,12 @@ interface CompiledAgentOptions {
555
561
  * a foreign dialect imported through `compatSources` — is spawned at all.
556
562
  */
557
563
  hookApproval?: HookApprovalGate;
564
+ /**
565
+ * #1912 — SDK builtin tools to withhold from the model (`Agent.create({ withheldBuiltinTools })`),
566
+ * so their schema is never declared, rather than refused at call time. Unknown names are refused
567
+ * at assembly with a `ConfigurationError`.
568
+ */
569
+ withheldBuiltinTools?: readonly BuiltinToolName[];
558
570
  /** Code `Plugin` objects forwarded to `Agent.create({ plugins })` (lifecycle-hook seam). */
559
571
  /**
560
572
  * Code plugins — `{ name, register }` objects registered with the SDK's lifecycle-hook seam.
@@ -298,6 +298,16 @@ interface AgentClientOptions {
298
298
  */
299
299
  readonly chatId?: string;
300
300
  }
301
+ /** How one turn ended, as `sendAndWait` reports it. */
302
+ interface TurnSettled {
303
+ readonly status: 'done' | 'error' | 'aborted';
304
+ /** Concatenated text parts of the turn's last assistant message. */
305
+ readonly text?: string;
306
+ readonly usage?: {
307
+ readonly totalTokens?: number;
308
+ };
309
+ readonly error?: Error;
310
+ }
301
311
  declare class AgentClient<TInput = unknown> {
302
312
  #private;
303
313
  constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined, options?: AgentClientOptions);
@@ -314,6 +324,11 @@ declare class AgentClient<TInput = unknown> {
314
324
  getSnapshot: () => AgentClientState;
315
325
  /** Send a typed input; opens a fresh stream (replaces prior messages). */
316
326
  send: (input: TInput) => void;
327
+ /**
328
+ * Same as `send`, and resolves when THIS turn settles — from the same place `#drive` sets the final
329
+ * status, never from a timer. Never rejects; a superseded or aborted turn resolves `'aborted'`.
330
+ */
331
+ sendAndWait: (input: TInput) => Promise<TurnSettled>;
317
332
  /** Resume an interrupted stream via the transport's `reconnectToStream` (no-op when unavailable). */
318
333
  reconnect: () => void;
319
334
  /** Abort an in-flight stream (not an error — leaves messages as-is). */
@@ -369,4 +384,4 @@ declare function agentHandle<TInput = unknown, TToolNames extends string = strin
369
384
  /** Narrow an unknown binding to an {@link AgentHandle} (has a string `path`, is not a transport). */
370
385
  declare function isAgentHandle(value: unknown): value is AgentHandle;
371
386
 
372
- export { type ApprovalDecision as A, type ChannelPushSource as C, type InProcessApprovalRequestLike as I, type PendingApproval as P, type RequestContext as R, type UseAgentStatus as U, type AgentHandle as a, type AgentTransport as b, AgentClient as c, type AgentClientOptions as d, type AgentClientState as e, AgentStreamInterruptedError as f, ApprovalAbortedError as g, ChannelTransport as h, type ChannelTransportOptions as i, type ChannelTurnHandlers as j, type InProcessAwaitApproval as k, type InProcessRunInput as l, type InProcessRunner as m, InProcessTransport as n, type InProcessTransportOptions as o, agentHandle as p, isAgentHandle as q };
387
+ export { type ApprovalDecision as A, type ChannelPushSource as C, type InProcessApprovalRequestLike as I, type PendingApproval as P, type RequestContext as R, type TurnSettled as T, type UseAgentStatus as U, type AgentHandle as a, type AgentTransport as b, AgentClient as c, type AgentClientOptions as d, type AgentClientState as e, AgentStreamInterruptedError as f, ApprovalAbortedError as g, ChannelTransport as h, type ChannelTransportOptions as i, type ChannelTurnHandlers as j, type InProcessAwaitApproval as k, type InProcessRunInput as l, type InProcessRunner as m, InProcessTransport as n, type InProcessTransportOptions as o, agentHandle as p, isAgentHandle as q };
@@ -1,10 +1,10 @@
1
1
  import { PluginsSettings, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
2
2
  import { RetryOptions } from '@theokit/sdk/retry';
3
- import { a as CompiledAgentOptions, C as CompiledTool } from './agent-compiler-C-4X_vKz.js';
3
+ import { a as CompiledAgentOptions, C as CompiledTool } from './agent-compiler-aubY9WIa.js';
4
4
  import { TheokitAgentError } from '@theokit/sdk/errors';
5
5
  import { z } from 'zod';
6
6
  import { M as MainLoopMeta } from './types-D5cHmSLi.js';
7
- import { S as StreamEvent } from './agent-sse-handler-BRp9vHrb.js';
7
+ import { S as StreamEvent } from './agent-sse-handler-BtIpJZxO.js';
8
8
  import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
9
9
 
10
10
  /**
@@ -1,8 +1,8 @@
1
1
  import { PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
2
2
  import { RetryOptions } from '@theokit/sdk/retry';
3
- import { C as CompiledTool, a as CompiledAgentOptions } from './agent-compiler-C-4X_vKz.js';
4
- import { S as StreamEvent } from './agent-sse-handler-BRp9vHrb.js';
5
- import { R as RoundStreamFactory, L as LoopStrategy, b as ReflectionStrategy, D as DelegationResult } from './agent-orchestrator-BHF1bS6k.js';
3
+ import { C as CompiledTool, a as CompiledAgentOptions } from './agent-compiler-aubY9WIa.js';
4
+ import { S as StreamEvent } from './agent-sse-handler-BtIpJZxO.js';
5
+ import { R as RoundStreamFactory, L as LoopStrategy, b as ReflectionStrategy, D as DelegationResult } from './agent-orchestrator-DQtfrPaq.js';
6
6
  import { B as BudgetOptions, R as ReasoningEffort, M as MainLoopMeta } from './types-D5cHmSLi.js';
7
7
  import { CompressibleMessage } from '@theokit/sdk/compaction';
8
8
  import { z } from 'zod';
@@ -273,6 +273,8 @@ declare function isDone(e: AgentStreamEvent): e is DoneEvent;
273
273
  declare function isError(e: AgentStreamEvent): e is ErrorEvent;
274
274
  declare function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredEvent;
275
275
 
276
+ /** The data-part name carrying the failure `code`. Public in effect: the consumer matches on it. */
277
+ declare const ERROR_CODE_DATA_PART = "data-error-code";
276
278
  /**
277
279
  * The failure, as chunks the protocol accepts — theokit#161 (B).
278
280
  *
@@ -345,4 +347,4 @@ declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>, op
345
347
  onError?: Parameters<typeof presentUIMessageStream>[1]['onError'];
346
348
  }): Response;
347
349
 
348
- export { type ApprovalRequiredEvent as A, type CheckpointSavedEvent as C, type DoneEvent as D, type ErrorEvent as E, type FileEditEvent as F, type IterationEvent as I, type MaskError as M, type PartialToolCallEvent as P, type RunStartedEvent as R, type StreamEvent as S, type TextDeltaEvent as T, type AgentStopReason as a, type AgentStreamEvent as b, type AgentTurnMetadata as c, type ArtifactChunkEvent as d, type ArtifactStartEvent as e, type StateUpdateEvent as f, type ThinkingEvent as g, type ToolCallEvent as h, type ToolResultEvent as i, isApprovalRequired as j, isDone as k, isError as l, isPartialToolCall as m, isTextDelta as n, isToolCall as o, isToolResult as p, presentUIMessageStream as q, streamAgentResponse as s };
350
+ export { type ApprovalRequiredEvent as A, type CheckpointSavedEvent as C, type DoneEvent as D, ERROR_CODE_DATA_PART as E, type FileEditEvent as F, type IterationEvent as I, type MaskError as M, type PartialToolCallEvent as P, type RunStartedEvent as R, type StreamEvent as S, type TextDeltaEvent as T, type AgentStopReason as a, type AgentStreamEvent as b, type AgentTurnMetadata as c, type ArtifactChunkEvent as d, type ArtifactStartEvent as e, type ErrorEvent as f, type StateUpdateEvent as g, type ThinkingEvent as h, type ToolCallEvent as i, type ToolResultEvent as j, isApprovalRequired as k, isDone as l, isError as m, isPartialToolCall as n, isTextDelta as o, isToolCall as p, isToolResult as q, presentUIMessageStream as r, streamAgentResponse as s };
package/dist/auth.d.ts CHANGED
@@ -24,6 +24,26 @@ type EnsureFreshHttpDeps = Parameters<typeof ensureFreshCredential>[2];
24
24
  /** The device-flow deps + prompt hook of `openaiDeviceLogin` — typed off the SDK. */
25
25
  type DeviceLoginDeps = Parameters<typeof openaiDeviceLogin>[1];
26
26
  type DeviceLoginHooks = Parameters<typeof openaiDeviceLogin>[2];
27
+ /**
28
+ * A classified refresh failure — because the decision to retry depends on the class, not the text.
29
+ *
30
+ * M74: repeating an `invalid_grant` is not resilience, it is noise. The refresh token was revoked and
31
+ * no attempt changes that; the user who revoked the login waits through three backoffs to read a
32
+ * message that was already known from the first response. Network and 5xx are the opposite: they
33
+ * almost always succeed on the second try.
34
+ *
35
+ * SECRET-SAFETY: the message never carries token material — only the class and the reason.
36
+ */
37
+ declare class RefreshFailure extends TheokitAgentError {
38
+ /** `true` ⇒ worth retrying with backoff. `false` ⇒ terminal, fails on the first attempt. */
39
+ readonly transient: boolean;
40
+ readonly name = "RefreshFailure";
41
+ constructor(message: string,
42
+ /** `true` ⇒ worth retrying with backoff. `false` ⇒ terminal, fails on the first attempt. */
43
+ transient: boolean, options?: {
44
+ cause?: unknown;
45
+ });
46
+ }
27
47
  /** How an {@link AuthProvider} decides when a token is stale. */
28
48
  interface AuthProviderOptions {
29
49
  /**
@@ -691,4 +711,4 @@ interface PlanOnlyGateOptions {
691
711
  */
692
712
  declare function createPlanOnlyGate(options: PlanOnlyGateOptions): (ctx: PlanOnlyContext) => Promise<undefined>;
693
713
 
694
- export { type AgentCredentialInput, type AuthMethod, AuthProvider, type AuthProviderOptions, CODEX_CLIENT_ID_ENV_VAR, CODEX_PROVIDER, type Classification, CredentialNotFoundError, type ProviderDescriptor as CredentialProviderDescriptor, type CredentialResolution, type CredentialSourcesInput, DEFAULT_PROVIDERS, DeclaredProviderError, type DeviceAuthProvider, type Governed, type Grant, type GrantGateContext, type GrantOptions, type NotGoverned, type PermissionQuery, PermissionStore, type PermissionStoreOptions, type PlanOnlyContext, type PlanOnlyGateOptions, PlanOnlyRefusalError, type PromptHooks, ProviderKeyMismatchError, ProviderPrefixMismatchError, type ResolveCredentialInput, type RunCredentialHelperOptions, type SourceOrigin, type Veto, createPlanOnlyGate, credentialSources, grantGate, loginWithDevice, requireCredential, resolveAgentCredential, resolveCredential, resolveOperatorApiKey };
714
+ export { type AgentCredentialInput, type AuthMethod, AuthProvider, type AuthProviderOptions, CODEX_CLIENT_ID_ENV_VAR, CODEX_PROVIDER, type Classification, CredentialNotFoundError, type ProviderDescriptor as CredentialProviderDescriptor, type CredentialResolution, type CredentialSourcesInput, DEFAULT_PROVIDERS, DeclaredProviderError, type DeviceAuthProvider, type Governed, type Grant, type GrantGateContext, type GrantOptions, type NotGoverned, type PermissionQuery, PermissionStore, type PermissionStoreOptions, type PlanOnlyContext, type PlanOnlyGateOptions, PlanOnlyRefusalError, type PromptHooks, ProviderKeyMismatchError, ProviderPrefixMismatchError, RefreshFailure, type ResolveCredentialInput, type RunCredentialHelperOptions, type SourceOrigin, type Veto, createPlanOnlyGate, credentialSources, grantGate, loginWithDevice, requireCredential, resolveAgentCredential, resolveCredential, resolveOperatorApiKey };
package/dist/auth.js CHANGED
@@ -17,15 +17,20 @@ import {
17
17
 
18
18
  // src/auth/auth-provider.ts
19
19
  import { authFilePath, ensureFreshCredential, openaiDeviceLogin, persistOAuthTokens, readStoredOAuth } from "@theokit/sdk/auth";
20
+ import { TheokitAgentError } from "@theokit/sdk/errors";
20
21
  import { withFileLock } from "@theokit/sdk/persistence";
21
- var RefreshFailure = class extends Error {
22
+ var RefreshFailure = class extends TheokitAgentError {
22
23
  static {
23
24
  __name(this, "RefreshFailure");
24
25
  }
25
26
  transient;
26
- constructor(message, transient) {
27
- super(message), this.transient = transient;
28
- this.name = "RefreshFailure";
27
+ name = "RefreshFailure";
28
+ constructor(message, transient, options) {
29
+ super(message, {
30
+ isRetryable: transient,
31
+ code: "oauth_refresh_failed",
32
+ cause: options?.cause
33
+ }), this.transient = transient;
29
34
  }
30
35
  };
31
36
  var TRANSIENT_REASONS = [
@@ -39,10 +44,14 @@ var TRANSIENT_REASONS = [
39
44
  function classifyRefreshFailure(err) {
40
45
  const text = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
41
46
  if (/invalid_grant|invalid_request|unauthorized_client/i.test(text)) {
42
- return new RefreshFailure("the refresh token is no longer valid \u2014 log in again. Retrying does not change the outcome.", false);
47
+ return new RefreshFailure("the refresh token is no longer valid \u2014 log in again. Retrying does not change the outcome.", false, {
48
+ cause: err
49
+ });
43
50
  }
44
51
  const transient = TRANSIENT_REASONS.some((m) => text.includes(m)) || /\b(5\d{2})\b|timeout|network/i.test(text);
45
- return new RefreshFailure(transient ? "transient failure refreshing the credential" : "failure refreshing the credential", transient);
52
+ return new RefreshFailure(transient ? "transient failure refreshing the credential" : "failure refreshing the credential", transient, {
53
+ cause: err
54
+ });
46
55
  }
47
56
  __name(classifyRefreshFailure, "classifyRefreshFailure");
48
57
  function waitWithJitter(attempt, baseMs = 200, random = Math.random) {
@@ -226,8 +235,8 @@ __name(loginWithDevice, "loginWithDevice");
226
235
  import { readFileSync } from "fs";
227
236
  import { join } from "path";
228
237
  import { providerFromApiKeyPrefix, readAuthFile } from "@theokit/sdk/auth";
229
- import { TheokitAgentError } from "@theokit/sdk/errors";
230
- var ProviderPrefixMismatchError = class extends TheokitAgentError {
238
+ import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
239
+ var ProviderPrefixMismatchError = class extends TheokitAgentError2 {
231
240
  static {
232
241
  __name(this, "ProviderPrefixMismatchError");
233
242
  }
@@ -236,7 +245,7 @@ var ProviderPrefixMismatchError = class extends TheokitAgentError {
236
245
  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.`);
237
246
  }
238
247
  };
239
- var ProviderKeyMismatchError = class extends TheokitAgentError {
248
+ var ProviderKeyMismatchError = class extends TheokitAgentError2 {
240
249
  static {
241
250
  __name(this, "ProviderKeyMismatchError");
242
251
  }
@@ -251,7 +260,7 @@ var ProviderKeyMismatchError = class extends TheokitAgentError {
251
260
  }), this.provider = provider, this.where = where, this.expectedPrefix = expectedPrefix;
252
261
  }
253
262
  };
254
- var DeclaredProviderError = class extends TheokitAgentError {
263
+ var DeclaredProviderError = class extends TheokitAgentError2 {
255
264
  static {
256
265
  __name(this, "DeclaredProviderError");
257
266
  }
@@ -263,7 +272,7 @@ var DeclaredProviderError = class extends TheokitAgentError {
263
272
  });
264
273
  }
265
274
  };
266
- var CredentialNotFoundError = class extends TheokitAgentError {
275
+ var CredentialNotFoundError = class extends TheokitAgentError2 {
267
276
  static {
268
277
  __name(this, "CredentialNotFoundError");
269
278
  }
@@ -675,8 +684,8 @@ function grantGate(store, classify) {
675
684
  __name(grantGate, "grantGate");
676
685
 
677
686
  // src/loop/plan-only.ts
678
- import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
679
- var PlanOnlyRefusalError = class extends TheokitAgentError2 {
687
+ import { TheokitAgentError as TheokitAgentError3 } from "@theokit/sdk/errors";
688
+ var PlanOnlyRefusalError = class extends TheokitAgentError3 {
680
689
  static {
681
690
  __name(this, "PlanOnlyRefusalError");
682
691
  }
@@ -710,6 +719,7 @@ export {
710
719
  PlanOnlyRefusalError,
711
720
  ProviderKeyMismatchError,
712
721
  ProviderPrefixMismatchError,
722
+ RefreshFailure,
713
723
  assertSecureModes,
714
724
  authFilePath2 as authFilePath,
715
725
  createPlanOnlyGate,
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/credential-helper.ts","../src/auth/permission-store.ts","../src/auth/permission-gate.ts","../src/loop/plan-only.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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Lock","RefreshFailure","Error","message","transient","name","TRANSIENT_REASONS","classifyRefreshFailure","err","text","String","test","some","m","includes","waitWithJitter","attempt","baseMs","random","Math","base","round","AuthProvider","refreshBeforeMs","config","store","options","Number","isFinite","RangeError","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","decidedOn","MAX_ATTEMPTS","fresh","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","providerFromApiKeyPrefix","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","providerFromApiKeyPrefix","readAuthFile","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","inferred","providerFromApiKeyPrefix","keyPrefix","pinnedProvider","byPriority","declaredProviderEnvVar","declared","env","find","d","resolveCredential","pinned","kind","source","originOf","home","available","flatMap","claimed","claimedProvider","found","candidate","storedOAuthResolution","diagnose","console","warn","filePathOf","stored","readAuthFile","cause","Error","p","type","api_key","access","modelPrefix","varName","dotenv","has","requireCredential","resolved","DEFAULT_PROVIDERS","resolveAgentCredential","execFile","DEFAULT_TIMEOUT_MS","runCredentialHelper","command","options","timeoutMs","printed","Promise","resolve","reject","execFile","shell","timeout","cwd","encoding","error","stdout","killed","ConfigurationError","code","credential","trim","length","resolveOperatorApiKey","warn","apiKeyHelper","currentOperatorPolicy","undefined","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","grantGate","store","classify","ctx","classification","governed","Promise","resolve","undefined","isGranted","query","because","lastReadError","debugLog","tool","name","scope","block","message","cause","why","Error","String","TheokitAgentError","PlanOnlyRefusalError","TheokitAgentError","name","tool","code","createPlanOnlyGate","options","ctx","permissionMode","undefined","isStateChanging"]}
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/credential-helper.ts","../src/auth/permission-store.ts","../src/auth/permission-gate.ts","../src/loop/plan-only.ts"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SACEA,cACAC,uBACAC,mBACAC,oBACAC,uBACK;AAQP,SAASC,yBAAyB;AAClC,SAASC,oBAAoB;AAkCtB,IAAMC,iBAAN,cAA6BC,kBAAAA;EAjDpC,OAiDoCA;;;;EAChBC,OAAO;EACzB,YACEC,SAESC,WACTC,SACA;AAEA,UAAMF,SAAS;MAAEG,aAAaF;MAAWG,MAAM;MAAwB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;EACd;AACF;AAwBO,SAASE,mBAAmBC,SAA4B;AAO7D,SAAO,OAAOC,QAAAA;AAGZ,QAAIA,IAAIC,mBAAmB,OAAQ,QAAOC;AAI1C,QAAI,CAACH,QAAQI,gBAAgBH,IAAIL,IAAI,EAAG,QAAOO;AAE/C,UAAM,IAAIT,qBAAqBO,IAAIL,IAAI;EACzC;AACF;AAlBgBG;","names":["authFilePath","ensureFreshCredential","openaiDeviceLogin","persistOAuthTokens","readStoredOAuth","TheokitAgentError","withFileLock","RefreshFailure","TheokitAgentError","name","message","transient","options","isRetryable","code","cause","TRANSIENT_REASONS","classifyRefreshFailure","err","text","Error","String","test","some","m","includes","waitWithJitter","attempt","baseMs","random","Math","base","round","AuthProvider","refreshBeforeMs","config","store","Number","isFinite","RangeError","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","decidedOn","MAX_ATTEMPTS","fresh","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","providerFromApiKeyPrefix","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","providerFromApiKeyPrefix","readAuthFile","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","inferred","providerFromApiKeyPrefix","keyPrefix","pinnedProvider","byPriority","declaredProviderEnvVar","declared","env","find","d","resolveCredential","pinned","kind","source","originOf","home","available","flatMap","claimed","claimedProvider","found","candidate","storedOAuthResolution","diagnose","console","warn","filePathOf","stored","readAuthFile","cause","Error","p","type","api_key","access","modelPrefix","varName","dotenv","has","requireCredential","resolved","DEFAULT_PROVIDERS","resolveAgentCredential","execFile","DEFAULT_TIMEOUT_MS","runCredentialHelper","command","options","timeoutMs","printed","Promise","resolve","reject","execFile","shell","timeout","cwd","encoding","error","stdout","killed","ConfigurationError","code","credential","trim","length","resolveOperatorApiKey","warn","apiKeyHelper","currentOperatorPolicy","undefined","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","grantGate","store","classify","ctx","classification","governed","Promise","resolve","undefined","isGranted","query","because","lastReadError","debugLog","tool","name","scope","block","message","cause","why","Error","String","TheokitAgentError","PlanOnlyRefusalError","TheokitAgentError","name","tool","code","createPlanOnlyGate","options","ctx","permissionMode","undefined","isStateChanging"]}