@theokit/agents 2.0.0 → 3.0.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.
@@ -1363,11 +1363,17 @@ interface LoopOutcome {
1363
1363
  }
1364
1364
  /** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */
1365
1365
  interface LoopStrategy {
1366
- /** The originating `@MainLoop` strategy name. */
1367
- readonly name: MainLoopMeta['strategy'];
1368
- /** Hard ceiling on rounds guarantees termination. */
1366
+ /**
1367
+ * The strategy name, surfaced in `finalize`/logs. M54 relaxes this from
1368
+ * `MainLoopMeta['strategy']` to `string` so a caller-injected `.loopStrategy(custom)` can name
1369
+ * itself freely — the three built-ins keep their names, but the seam is no longer union-locked.
1370
+ * The INTERNAL resolution (`loopStrategyConfigSchema`) still validates the three built-in names
1371
+ * via `z.enum`; a custom never passes through it (it enters by the seam, not by name).
1372
+ */
1373
+ readonly name: string;
1374
+ /** Hard ceiling on rounds — guarantees termination (enforced by the runner since M54). */
1369
1375
  readonly maxIterations: number;
1370
- /** True ⇒ re-enter for another round; false ⇒ terminate. Never true forever. */
1376
+ /** True ⇒ re-enter for another round; false ⇒ terminate. The runner caps it at `maxIterations`. */
1371
1377
  shouldContinue(outcome: LoopOutcome): boolean;
1372
1378
  }
1373
1379
  /** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */
@@ -1397,7 +1403,7 @@ type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>;
1397
1403
  *
1398
1404
  * Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.
1399
1405
  */
1400
- declare function resolveLoopStrategy(strategy: MainLoopMeta['strategy'], maxIterations?: number): LoopStrategy;
1406
+ declare function resolveLoopStrategy(strategy: string, maxIterations?: number): LoopStrategy;
1401
1407
 
1402
1408
  /**
1403
1409
  * Shared delegation value types + typed errors.
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { j as AGENT_BRAND, k as AfterToolCallContext, l as AgentBuilder, m as AgentDefinition, n as AgentDefinitionError, o as AgentExecutionContext, p as AgentManifest, i as AgentManifestEntry, q as AgentManifestSource, r as AgentManifestTool, t as AgentRoute, u as AgentRouteContext, v as AgentRunInfo, w as AgentStreamEvent, x as AgentTurnMetadata, y as AgentsPluginOptions, z as ApiErrorContext, B as ApiErrorDecision, E as ApiErrorPolicy, F as ApprovalRequiredEvent, I as ArtifactChunkEvent, J as ArtifactStartEvent, K as BackgroundDelegation, N as BeforeToolCallContext, O as BudgetExceededError, U as CheckpointSavedEvent, C as CompiledAgentOptions, V as CompiledContextWindow, a as CompiledTool, W as ContextualTool, Z as DefineAgentConfig, _ as DelegateFn, $ as DelegateOptions, a0 as DelegationError, D as DelegationResult, a1 as DoneEvent, a2 as ErrorEvent, a3 as FileEditEvent, a9 as InferAgentInput, aa as InferAgentToolNames, ab as IterationEvent, ac as LLMCallContext, ah as McpApprovalSpec, ai as McpRegistryConfig, aj as McpRequestContext, ak as McpSelection, al as PartialToolCallEvent, an as ProcessInputContext, ar as RunStartedEvent, as as ScoreVerdict, at as ScoredDelegation, au as Scorer, av as SdkAgentHandle, aw as SdkMessage, ax as Segment, az as StateUpdateEvent, S as StreamEvent, aA as TextDeltaEvent, aB as ThinkingEvent, aD as ToolCallEvent, aE as ToolCallVeto, aF as ToolHooks, aG as ToolHooksPlugin, aH as ToolResultEvent, aI as ToolWalkResult, aK as ToolboxWalkResult, aL as agent, aM as agentsPlugin, aN as buildModelSelection, aO as compileAgentDefinition, aP as compileAgentModule, aQ as compileContextWindow, aR as compileProjectContext, aS as compileSkills, aT as compileTools, aU as contextualTool, aV as createAgentExecutionContext, aW as createApiErrorHandler, aX as createSdkAgentStream, aY as createThinkTagExtractor, aZ as createToolHooksPlugin, a_ as delegate, a$ as delegateBackground, b0 as delegateWithScoring, b1 as extractThinkTagStream, b2 as generateAgentManifest, b3 as generateAgentRoutes, b4 as isAgentContext, b5 as isAgentDefinition, b6 as isApprovalRequired, b7 as isDone, b8 as isError, b9 as isPartialToolCall, ba as isTextDelta, bb as isToolCall, bc as isToolResult, bf as mcpRegistry, bg as mcpToolApprovals, bi as presentUIMessageStream, bj as projectContextMetadataOnlyKnobs, bn as resolveMcpServers, bo as runWithApiErrorHandling, bp as streamAgentResponse, bq as streamAgentUIMessages, br as toAgentFactory, bs as translateSdkEvent } from './bridge-entry-F9kHGaIn.js';
1
+ export { j as AGENT_BRAND, k as AfterToolCallContext, l as AgentBuilder, m as AgentDefinition, n as AgentDefinitionError, o as AgentExecutionContext, p as AgentManifest, i as AgentManifestEntry, q as AgentManifestSource, r as AgentManifestTool, t as AgentRoute, u as AgentRouteContext, v as AgentRunInfo, w as AgentStreamEvent, x as AgentTurnMetadata, y as AgentsPluginOptions, z as ApiErrorContext, B as ApiErrorDecision, E as ApiErrorPolicy, F as ApprovalRequiredEvent, I as ArtifactChunkEvent, J as ArtifactStartEvent, K as BackgroundDelegation, N as BeforeToolCallContext, O as BudgetExceededError, U as CheckpointSavedEvent, C as CompiledAgentOptions, V as CompiledContextWindow, a as CompiledTool, W as ContextualTool, Z as DefineAgentConfig, _ as DelegateFn, $ as DelegateOptions, a0 as DelegationError, D as DelegationResult, a1 as DoneEvent, a2 as ErrorEvent, a3 as FileEditEvent, a9 as InferAgentInput, aa as InferAgentToolNames, ab as IterationEvent, ac as LLMCallContext, ah as McpApprovalSpec, ai as McpRegistryConfig, aj as McpRequestContext, ak as McpSelection, al as PartialToolCallEvent, an as ProcessInputContext, ar as RunStartedEvent, as as ScoreVerdict, at as ScoredDelegation, au as Scorer, av as SdkAgentHandle, aw as SdkMessage, ax as Segment, az as StateUpdateEvent, S as StreamEvent, aA as TextDeltaEvent, aB as ThinkingEvent, aD as ToolCallEvent, aE as ToolCallVeto, aF as ToolHooks, aG as ToolHooksPlugin, aH as ToolResultEvent, aI as ToolWalkResult, aK as ToolboxWalkResult, aL as agent, aM as agentsPlugin, aN as buildModelSelection, aO as compileAgentDefinition, aP as compileAgentModule, aQ as compileContextWindow, aR as compileProjectContext, aS as compileSkills, aT as compileTools, aU as contextualTool, aV as createAgentExecutionContext, aW as createApiErrorHandler, aX as createSdkAgentStream, aY as createThinkTagExtractor, aZ as createToolHooksPlugin, a_ as delegate, a$ as delegateBackground, b0 as delegateWithScoring, b1 as extractThinkTagStream, b2 as generateAgentManifest, b3 as generateAgentRoutes, b4 as isAgentContext, b5 as isAgentDefinition, b6 as isApprovalRequired, b7 as isDone, b8 as isError, b9 as isPartialToolCall, ba as isTextDelta, bb as isToolCall, bc as isToolResult, bf as mcpRegistry, bg as mcpToolApprovals, bi as presentUIMessageStream, bj as projectContextMetadataOnlyKnobs, bn as resolveMcpServers, bo as runWithApiErrorHandling, bp as streamAgentResponse, bq as streamAgentUIMessages, br as toAgentFactory, bs as translateSdkEvent } from './bridge-entry-8gsH0kVZ.js';
2
2
  import '@theokit/http';
3
3
  import '@theokit/sdk';
4
4
  import 'zod';
package/dist/bridge.js CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  streamAgentUIMessages,
44
44
  toAgentFactory,
45
45
  translateSdkEvent
46
- } from "./chunk-K3VX4S65.js";
46
+ } from "./chunk-C2DALG62.js";
47
47
  import "./chunk-7QVYU63E.js";
48
48
  export {
49
49
  AGENT_BRAND,
@@ -2470,14 +2470,22 @@ var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
2470
2470
  // src/loop/loop-strategy.ts
2471
2471
  import { z as z2 } from "zod";
2472
2472
  var DEFAULT_MAX_ITERATIONS = 8;
2473
+ var maxIterationsSchema = z2.number().int().min(1);
2473
2474
  var loopStrategyConfigSchema = z2.object({
2474
2475
  name: z2.enum([
2475
2476
  "simple-chat",
2476
2477
  "plan-act-reflect",
2477
2478
  "react"
2478
2479
  ]),
2479
- maxIterations: z2.number().int().min(1)
2480
+ maxIterations: maxIterationsSchema
2480
2481
  });
2482
+ function assertValidCustomLoopStrategy(strategy) {
2483
+ const result = maxIterationsSchema.safeParse(strategy.maxIterations);
2484
+ if (!result.success) {
2485
+ throw new Error(`loopStrategy: maxIterations inv\xE1lido (${String(strategy.maxIterations)}) \u2014 deve ser um inteiro finito \u2265 1 (sen\xE3o o teto round < maxIterations nunca termina)`);
2486
+ }
2487
+ }
2488
+ __name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
2481
2489
  function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
2482
2490
  const cfg = loopStrategyConfigSchema.parse({
2483
2491
  name: strategy,
@@ -2795,7 +2803,7 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2795
2803
  responseText: r.responseText
2796
2804
  };
2797
2805
  const reflectionResult = reflection.reflect(outcome, reflectionContext);
2798
- if (!(reflectionResult.continue && loop.shouldContinue(outcome))) {
2806
+ if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
2799
2807
  const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
2800
2808
  return finalize(acc, round, reason, loop.name);
2801
2809
  }
@@ -2823,6 +2831,8 @@ var AgentRunner = class {
2823
2831
  agentName;
2824
2832
  /** The resolved terminal-decision strategy (parity with `delegate()`). */
2825
2833
  loopStrategy;
2834
+ /** M54 — whether {@link loopStrategy} is a caller-injected custom (see {@link AgentRunnerState}). */
2835
+ loopStrategyIsCustom;
2826
2836
  /** The resolved between-round reflection (default or `.reflection(custom)` override). */
2827
2837
  reflectionStrategy;
2828
2838
  /**
@@ -2843,6 +2853,7 @@ var AgentRunner = class {
2843
2853
  this.compiled = state.compiled;
2844
2854
  this.agentName = state.agentName;
2845
2855
  this.loopStrategy = state.loopStrategy;
2856
+ this.loopStrategyIsCustom = state.loopStrategyIsCustom ?? false;
2846
2857
  this.reflectionStrategy = state.reflectionStrategy;
2847
2858
  this.streamEnabled = state.streamEnabled;
2848
2859
  this.compaction = state.compaction;
@@ -2874,7 +2885,7 @@ var AgentRunner = class {
2874
2885
  const tools = opts.tools ? [
2875
2886
  ...opts.tools
2876
2887
  ] : this.compiled.tools;
2877
- const loop = opts.maxIterations != null ? resolveLoopStrategy(this.loopStrategy.name, opts.maxIterations) : this.loopStrategy;
2888
+ const loop = this.resolvePerRunLoop(opts.maxIterations);
2878
2889
  const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
2879
2890
  model: opts.model,
2880
2891
  reasoningEffort: opts.reasoningEffort,
@@ -2900,6 +2911,23 @@ var AgentRunner = class {
2900
2911
  });
2901
2912
  }
2902
2913
  /** Run the agent to a terminal result via the shared reflective loop (collect mode). */
2914
+ /**
2915
+ * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
2916
+ * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
2917
+ * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
2918
+ * overriding just that field bounds a custom without touching its logic. A built-in keeps the
2919
+ * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
2920
+ */
2921
+ resolvePerRunLoop(maxIterations) {
2922
+ if (maxIterations == null) return this.loopStrategy;
2923
+ if (this.loopStrategyIsCustom) {
2924
+ const base = this.loopStrategy;
2925
+ return Object.assign(Object.create(Object.getPrototypeOf(base)), base, {
2926
+ maxIterations
2927
+ });
2928
+ }
2929
+ return resolveLoopStrategy(this.loopStrategy.name, maxIterations);
2930
+ }
2903
2931
  async run(message, opts) {
2904
2932
  const gen = this.stream(message, opts);
2905
2933
  let res = await gen.next();
@@ -2915,6 +2943,7 @@ var AgentRunnerBuilder = class {
2915
2943
  reflectionOverride;
2916
2944
  streamEnabled = true;
2917
2945
  compactionOverride;
2946
+ loopStrategyOverride;
2918
2947
  constructor(spec) {
2919
2948
  this.spec = spec;
2920
2949
  }
@@ -2923,6 +2952,29 @@ var AgentRunnerBuilder = class {
2923
2952
  if (strategy) this.reflectionOverride = strategy;
2924
2953
  return this;
2925
2954
  }
2955
+ /**
2956
+ * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
2957
+ * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
2958
+ * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
2959
+ * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
2960
+ * infinite loop.
2961
+ *
2962
+ * @example
2963
+ * ```ts
2964
+ * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
2965
+ * const stopWhenConfident: LoopStrategy = {
2966
+ * name: 'confident',
2967
+ * maxIterations: 8,
2968
+ * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
2969
+ * }
2970
+ * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
2971
+ * ```
2972
+ */
2973
+ loopStrategy(custom) {
2974
+ assertValidCustomLoopStrategy(custom);
2975
+ this.loopStrategyOverride = custom;
2976
+ return this;
2977
+ }
2926
2978
  /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */
2927
2979
  stream(enabled = true) {
2928
2980
  this.streamEnabled = enabled;
@@ -2944,7 +2996,8 @@ var AgentRunnerBuilder = class {
2944
2996
  build() {
2945
2997
  const { spec } = this;
2946
2998
  const strategy = spec.strategy ?? "simple-chat";
2947
- const loopStrategy = resolveLoopStrategy(strategy, spec.maxIterations);
2999
+ const loopStrategyIsCustom = this.loopStrategyOverride !== void 0;
3000
+ const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
2948
3001
  const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2949
3002
  const compactionDecl = this.compactionOverride ?? spec.compaction;
2950
3003
  const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
@@ -2954,6 +3007,7 @@ var AgentRunnerBuilder = class {
2954
3007
  compiled: spec.compiled,
2955
3008
  agentName: spec.name,
2956
3009
  loopStrategy,
3010
+ loopStrategyIsCustom,
2957
3011
  reflectionStrategy,
2958
3012
  streamEnabled: this.streamEnabled,
2959
3013
  compaction
@@ -3424,4 +3478,4 @@ export {
3424
3478
  generateAgentManifest,
3425
3479
  agentsPlugin
3426
3480
  };
3427
- //# sourceMappingURL=chunk-K3VX4S65.js.map
3481
+ //# sourceMappingURL=chunk-C2DALG62.js.map