@theokit/sdk 2.1.0 → 2.3.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.
@@ -1,4 +1,4 @@
1
- import { C as CustomTool, M as ModelSelection, D as SDKUserMessage, F as SendOptions, b as Run, a as McpServerConfig } from './run-DrwUpFxZ.js';
1
+ import { C as CustomTool, M as ModelSelection, F as SDKUserMessage, H as SendOptions, b as Run, r as RunToCompletionOptions, s as RunToCompletionResult, a as McpServerConfig } from './run-BPRYG1Id.cjs';
2
2
 
3
3
  /**
4
4
  * Fork primitive public type contracts (T1.2, ADRs D110-D114).
@@ -559,6 +559,14 @@ interface BudgetTracker {
559
559
  check(): BudgetCheck;
560
560
  /** Snapshot of accumulated totals (for telemetry / final reporting). */
561
561
  getTotal(): BudgetTotal;
562
+ /**
563
+ * Advance the iteration counter by one. Called by the agent loop ONCE per
564
+ * completed turn (M1-1) so that trackers which gate on `maxIterations`
565
+ * (e.g. `createCounterBudgetTracker`) actually halt. OPTIONAL: trackers that
566
+ * only gate on tokens/USD omit it and the loop no-ops via optional chaining.
567
+ * MUST be synchronous and non-throwing.
568
+ */
569
+ nextIteration?(): void;
562
570
  }
563
571
 
564
572
  /**
@@ -583,7 +591,11 @@ interface BudgetTracker {
583
591
  * @public
584
592
  */
585
593
  interface StoredMessage {
586
- /** Origin of the message. `tool_call` / `tool_result` reserved for forward compat. */
594
+ /**
595
+ * Origin of the message. `tool_call` / `tool_result` are produced by
596
+ * `buildReplayHistory` (M1-3) for stateless replay; a consumer feeding a
597
+ * `user`/`assistant`-only wire-mapper must map those two roles itself.
598
+ */
587
599
  role: "user" | "assistant" | "system" | "tool_call" | "tool_result";
588
600
  /** UTF-8 payload. May be empty string (e.g., a tool with no return value). */
589
601
  content: string;
@@ -1439,6 +1451,20 @@ interface SDKAgent {
1439
1451
  * @public
1440
1452
  */
1441
1453
  fork?(options: ForkOptions): Promise<ForkResult>;
1454
+ /**
1455
+ * Drive `send` to completion across iteration-ceiling truncations (M1 Phase 3).
1456
+ * When a `send` stops at the loop's iteration cap (`RunResult.stoppedAtIterationLimit`),
1457
+ * this re-sends a short continuation prompt — the agent's stateful session
1458
+ * preserves the conversation — until a genuine terminal: `done` (finished),
1459
+ * `step_limit` (`maxRounds` exhausted), or `no_progress` (two empty rounds).
1460
+ *
1461
+ * Local agents only. Cloud agents throw
1462
+ * {@link import("../errors.js").UnsupportedRunOperationError} (the cloud
1463
+ * runtime manages its own continuation policy server-side).
1464
+ *
1465
+ * @public
1466
+ */
1467
+ runToCompletion?(message: string, options?: RunToCompletionOptions): Promise<RunToCompletionResult>;
1442
1468
  /**
1443
1469
  * Direct API to third-party memory adapter(s) registered via
1444
1470
  * `plugins: [...]` (ADR D141 / D142). Returns `null` when no adapter
@@ -1,4 +1,4 @@
1
- import { C as CustomTool, M as ModelSelection, D as SDKUserMessage, F as SendOptions, b as Run, a as McpServerConfig } from './run-DrwUpFxZ.cjs';
1
+ import { C as CustomTool, M as ModelSelection, F as SDKUserMessage, H as SendOptions, b as Run, r as RunToCompletionOptions, s as RunToCompletionResult, a as McpServerConfig } from './run-BPRYG1Id.js';
2
2
 
3
3
  /**
4
4
  * Fork primitive public type contracts (T1.2, ADRs D110-D114).
@@ -559,6 +559,14 @@ interface BudgetTracker {
559
559
  check(): BudgetCheck;
560
560
  /** Snapshot of accumulated totals (for telemetry / final reporting). */
561
561
  getTotal(): BudgetTotal;
562
+ /**
563
+ * Advance the iteration counter by one. Called by the agent loop ONCE per
564
+ * completed turn (M1-1) so that trackers which gate on `maxIterations`
565
+ * (e.g. `createCounterBudgetTracker`) actually halt. OPTIONAL: trackers that
566
+ * only gate on tokens/USD omit it and the loop no-ops via optional chaining.
567
+ * MUST be synchronous and non-throwing.
568
+ */
569
+ nextIteration?(): void;
562
570
  }
563
571
 
564
572
  /**
@@ -583,7 +591,11 @@ interface BudgetTracker {
583
591
  * @public
584
592
  */
585
593
  interface StoredMessage {
586
- /** Origin of the message. `tool_call` / `tool_result` reserved for forward compat. */
594
+ /**
595
+ * Origin of the message. `tool_call` / `tool_result` are produced by
596
+ * `buildReplayHistory` (M1-3) for stateless replay; a consumer feeding a
597
+ * `user`/`assistant`-only wire-mapper must map those two roles itself.
598
+ */
587
599
  role: "user" | "assistant" | "system" | "tool_call" | "tool_result";
588
600
  /** UTF-8 payload. May be empty string (e.g., a tool with no return value). */
589
601
  content: string;
@@ -1439,6 +1451,20 @@ interface SDKAgent {
1439
1451
  * @public
1440
1452
  */
1441
1453
  fork?(options: ForkOptions): Promise<ForkResult>;
1454
+ /**
1455
+ * Drive `send` to completion across iteration-ceiling truncations (M1 Phase 3).
1456
+ * When a `send` stops at the loop's iteration cap (`RunResult.stoppedAtIterationLimit`),
1457
+ * this re-sends a short continuation prompt — the agent's stateful session
1458
+ * preserves the conversation — until a genuine terminal: `done` (finished),
1459
+ * `step_limit` (`maxRounds` exhausted), or `no_progress` (two empty rounds).
1460
+ *
1461
+ * Local agents only. Cloud agents throw
1462
+ * {@link import("../errors.js").UnsupportedRunOperationError} (the cloud
1463
+ * runtime manages its own continuation policy server-side).
1464
+ *
1465
+ * @public
1466
+ */
1467
+ runToCompletion?(message: string, options?: RunToCompletionOptions): Promise<RunToCompletionResult>;
1442
1468
  /**
1443
1469
  * Direct API to third-party memory adapter(s) registered via
1444
1470
  * `plugins: [...]` (ADR D141 / D142). Returns `null` when no adapter
package/dist/cron.cjs CHANGED
@@ -1440,6 +1440,71 @@ var init_agent_factory_registry = __esm({
1440
1440
  }
1441
1441
  });
1442
1442
 
1443
+ // src/internal/runtime/lifecycle/run-to-completion.ts
1444
+ var run_to_completion_exports = {};
1445
+ __export(run_to_completion_exports, {
1446
+ classifyRound: () => classifyRound,
1447
+ runToCompletionImpl: () => runToCompletionImpl
1448
+ });
1449
+ function isEmptyRound(result) {
1450
+ return (result.result ?? "").trim() === "";
1451
+ }
1452
+ function classifyRound(result, round, maxRounds, emptyStreak) {
1453
+ if (result.stoppedAtIterationLimit !== true) return "done";
1454
+ if (isEmptyRound(result) && emptyStreak >= 1) return "no_progress";
1455
+ if (round >= maxRounds) return "step_limit";
1456
+ return "continue";
1457
+ }
1458
+ function addUsage(acc, u) {
1459
+ if (u === void 0) return acc;
1460
+ const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;
1461
+ const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;
1462
+ const sumOpt = (a, b) => a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
1463
+ return {
1464
+ inputTokens,
1465
+ outputTokens,
1466
+ totalTokens: inputTokens + outputTokens,
1467
+ cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),
1468
+ cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),
1469
+ reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens)
1470
+ };
1471
+ }
1472
+ function buildResult(terminal, rounds, lastResult, usage) {
1473
+ return { terminal, rounds, lastResult, ...usage !== void 0 ? { usage } : {} };
1474
+ }
1475
+ async function stepRound(agent, prompt, sendOptions, round, maxRounds, state3) {
1476
+ const run = await agent.send(prompt, sendOptions);
1477
+ const result = await run.wait();
1478
+ const usage = addUsage(state3.usage, result.usage);
1479
+ const decision = classifyRound(result, round, maxRounds, state3.emptyStreak);
1480
+ if (decision !== "continue") return { terminal: buildResult(decision, round, result, usage) };
1481
+ const emptyStreak = isEmptyRound(result) ? state3.emptyStreak + 1 : 0;
1482
+ return { next: { usage, emptyStreak }, lastResult: result };
1483
+ }
1484
+ async function runToCompletionImpl(agent, message, options) {
1485
+ const maxRounds = options?.maxRounds ?? DEFAULT_MAX_ROUNDS;
1486
+ const continuationPrompt = options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT;
1487
+ const { onTruncated, signal, sendOptions } = options ?? {};
1488
+ let state3 = { usage: void 0, emptyStreak: 0 };
1489
+ for (let round = 0; ; round += 1) {
1490
+ const prompt = round === 0 ? message : continuationPrompt;
1491
+ const outcome = await stepRound(agent, prompt, sendOptions, round, maxRounds, state3);
1492
+ if ("terminal" in outcome) return outcome.terminal;
1493
+ state3 = outcome.next;
1494
+ await onTruncated?.({ round });
1495
+ if (signal?.aborted === true) {
1496
+ return buildResult("step_limit", round, outcome.lastResult, state3.usage);
1497
+ }
1498
+ }
1499
+ }
1500
+ var DEFAULT_MAX_ROUNDS, DEFAULT_CONTINUATION_PROMPT;
1501
+ var init_run_to_completion = __esm({
1502
+ "src/internal/runtime/lifecycle/run-to-completion.ts"() {
1503
+ DEFAULT_MAX_ROUNDS = 5;
1504
+ DEFAULT_CONTINUATION_PROMPT = "Continue from where you left off and finish the task. If it is already complete, give the final answer.";
1505
+ }
1506
+ });
1507
+
1443
1508
  // src/internal/runtime/lifecycle/fork-agent.ts
1444
1509
  var fork_agent_exports = {};
1445
1510
  __export(fork_agent_exports, {
@@ -4320,8 +4385,7 @@ var FixtureRunBase = class {
4320
4385
  if (status === "error" && this.script.errorDetail !== void 0) {
4321
4386
  base.error = this.script.errorDetail;
4322
4387
  }
4323
- if (this.script.usage !== void 0) base.usage = this.script.usage;
4324
- if (this.script.cost !== void 0) base.cost = this.script.cost;
4388
+ applyScriptMetrics(base, this.script);
4325
4389
  return this.extendRunResult(applyExtraRunFields(base, this.script));
4326
4390
  }
4327
4391
  /** Subclasses override to attach runtime-specific fields (e.g. cloud git info). */
@@ -4355,6 +4419,11 @@ function makeNotifier() {
4355
4419
  });
4356
4420
  return { promise, resolve: resolve3 };
4357
4421
  }
4422
+ function applyScriptMetrics(base, script) {
4423
+ if (script.usage !== void 0) base.usage = script.usage;
4424
+ if (script.cost !== void 0) base.cost = script.cost;
4425
+ if (script.stoppedAtIterationLimit === true) base.stoppedAtIterationLimit = true;
4426
+ }
4358
4427
 
4359
4428
  // src/internal/runtime/cloud/cloud-run.ts
4360
4429
  function createCloudRun(options) {
@@ -4863,6 +4932,18 @@ var CloudAgent = class {
4863
4932
  "fork"
4864
4933
  );
4865
4934
  }
4935
+ /**
4936
+ * The continuation driver re-sends against a stateful local session; the
4937
+ * cloud runtime manages its own continuation policy server-side (M1 Phase 3).
4938
+ *
4939
+ * @public
4940
+ */
4941
+ runToCompletion() {
4942
+ throw new UnsupportedRunOperationError(
4943
+ "Agent.runToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.",
4944
+ "runToCompletion"
4945
+ );
4946
+ }
4866
4947
  /**
4867
4948
  * Personality presets require consistent server-side enforcement that
4868
4949
  * the cloud runtime (pre-release) does not yet provide. Reject explicitly
@@ -7987,6 +8068,9 @@ var LocalRun = class extends FixtureRunBase {
7987
8068
  }
7988
8069
  };
7989
8070
 
8071
+ // src/internal/runtime/local-agent/real-local-run.ts
8072
+ init_errors();
8073
+
7990
8074
  // src/internal/runtime/budget/budget.ts
7991
8075
  var IterationBudget = class {
7992
8076
  #remaining;
@@ -9211,6 +9295,7 @@ async function runAgentLoop(inputs) {
9211
9295
  const ctx = await initLoopContext(inputs);
9212
9296
  ctxRef = ctx;
9213
9297
  const budget = inputs.budget ?? new IterationBudget({ maxIterations: inputs.maxIterations ?? 8 });
9298
+ let lastTurnDecision;
9214
9299
  while (budget.shouldContinue()) {
9215
9300
  if (inputs.budgetTracker !== void 0) {
9216
9301
  const decision2 = evaluateBudgetGate(inputs.budgetTracker);
@@ -9219,18 +9304,26 @@ async function runAgentLoop(inputs) {
9219
9304
  if (decision2.detail !== void 0) {
9220
9305
  ctx.error = { message: decision2.detail, code: decision2.reason ?? "budget" };
9221
9306
  }
9307
+ if (decision2.reason === "iteration_limit") {
9308
+ ctx.stoppedAtIterationLimit = true;
9309
+ }
9222
9310
  break;
9223
9311
  }
9224
9312
  }
9225
9313
  const usingGrace = budget.remaining <= 0 && !budget.graceCallUsed;
9226
9314
  if (usingGrace) budget.useGraceCall();
9227
9315
  const decision = await runIteration(inputs, ctx);
9316
+ lastTurnDecision = decision;
9228
9317
  if (decision === "done") break;
9229
9318
  if (decision === "error") {
9230
9319
  ctx.finalStatus = "error";
9231
9320
  break;
9232
9321
  }
9233
9322
  budget.consume();
9323
+ inputs.budgetTracker?.nextIteration?.();
9324
+ }
9325
+ if (lastTurnDecision === "continue" && budget.shouldContinue() === false) {
9326
+ ctx.stoppedAtIterationLimit = true;
9234
9327
  }
9235
9328
  if (budget.shouldContinue() === false && ctx.finalStatus === "finished" && ctx.finalText === "") {
9236
9329
  ctx.finalStatus = "error";
@@ -9261,7 +9354,8 @@ async function runAgentLoop(inputs) {
9261
9354
  conversation: ctx.conversation,
9262
9355
  ...usage !== void 0 ? { usage } : {},
9263
9356
  ...cost !== void 0 ? { cost } : {},
9264
- ...ctx.error !== void 0 ? { error: ctx.error } : {}
9357
+ ...ctx.error !== void 0 ? { error: ctx.error } : {},
9358
+ ...ctx.stoppedAtIterationLimit === true ? { stoppedAtIterationLimit: true } : {}
9265
9359
  };
9266
9360
  } finally {
9267
9361
  if (ctxRef !== void 0 && ctxRef.memoryProviderHandle !== void 0 && inputs.memoryProvider !== void 0) {
@@ -11680,6 +11774,13 @@ function resolveRunProvider(options) {
11680
11774
  return { primary, effectiveModelId };
11681
11775
  }
11682
11776
  function buildLoopInputs(options, runId, userText) {
11777
+ const maxIterations = options.sendOptions.maxIterations;
11778
+ if (maxIterations !== void 0 && (!Number.isInteger(maxIterations) || maxIterations < 1)) {
11779
+ throw new ConfigurationError(
11780
+ `SendOptions.maxIterations must be a positive integer, got ${maxIterations}`,
11781
+ { code: "invalid_max_iterations" }
11782
+ );
11783
+ }
11683
11784
  const { primary, effectiveModelId } = resolveRunProvider(options);
11684
11785
  const fallback = options.agentOptions.providers?.fallback;
11685
11786
  const apiKeys = options.agentOptions.providers?.apiKeys;
@@ -11718,6 +11819,9 @@ function buildLoopInputs(options, runId, userText) {
11718
11819
  // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn
11719
11820
  // can attach it to the LLM `fetch({ signal })` call.
11720
11821
  ...options.sendOptions.signal !== void 0 ? { signal: options.sendOptions.signal } : {},
11822
+ // M1-2: per-send iteration ceiling (validated above). The loop reads
11823
+ // inputs.maxIterations (default 8 when unset).
11824
+ ...maxIterations !== void 0 ? { maxIterations } : {},
11721
11825
  // D315-D317 — tool lifecycle hooks (cost tracking + audit + retry/alert)
11722
11826
  ...options.agentOptions.onToolStart !== void 0 ? { onToolStart: options.agentOptions.onToolStart } : {},
11723
11827
  ...options.agentOptions.onToolEnd !== void 0 ? { onToolEnd: options.agentOptions.onToolEnd } : {},
@@ -11849,6 +11953,7 @@ var RealLocalRun = class extends FixtureRunBase {
11849
11953
  if (output.result.length > 0) this.script.result = output.result;
11850
11954
  if (output.usage !== void 0) this.script.usage = output.usage;
11851
11955
  if (output.cost !== void 0) this.script.cost = output.cost;
11956
+ if (output.stoppedAtIterationLimit === true) this.script.stoppedAtIterationLimit = true;
11852
11957
  if (output.error !== void 0 && this.script.errorDetail === void 0) {
11853
11958
  this.script.errorDetail = {
11854
11959
  message: output.error.message,
@@ -14319,6 +14424,13 @@ function localAgentRunUntil(agent, goal, options) {
14319
14424
  }
14320
14425
  return wrap();
14321
14426
  }
14427
+ function localAgentRunToCompletion(agent, message, options) {
14428
+ async function run() {
14429
+ const { runToCompletionImpl: runToCompletionImpl2 } = await Promise.resolve().then(() => (init_run_to_completion(), run_to_completion_exports));
14430
+ return runToCompletionImpl2({ send: (m, o) => agent.send(m, o) }, message, options);
14431
+ }
14432
+ return run();
14433
+ }
14322
14434
  async function localAgentFork(parent, options) {
14323
14435
  const { forkAgentImpl: forkAgentImpl2 } = await Promise.resolve().then(() => (init_fork_agent(), fork_agent_exports));
14324
14436
  const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
@@ -14859,6 +14971,10 @@ var LocalAgent = class {
14859
14971
  fork(options) {
14860
14972
  return localAgentFork({ agentId: this.agentId, options: this.options, personalitySlugSnapshot: this.personalityStore.active(this.agentId) }, options);
14861
14973
  }
14974
+ // biome-ignore format: G8 budget — see runUntil comment above.
14975
+ runToCompletion(message, options) {
14976
+ return localAgentRunToCompletion(this, message, options);
14977
+ }
14862
14978
  };
14863
14979
  function resolveCwd(cwd) {
14864
14980
  return (Array.isArray(cwd) ? cwd[0] : cwd) ?? process.cwd();