@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.
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-C9xkhNEF.cjs';
2
- export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, E as ErrorCode, m as ErrorMetadata, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-C9xkhNEF.cjs';
3
- import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as MemoryContext, m as ConversationStorageAdapter, n as StoredMessage, B as BudgetTracker, o as MemoryProvider, p as MemoryId, q as SDKProvider } from './cron-CSTqNZp9.cjs';
4
- export { r as ActiveMemoryPassArgs, s as ActiveMemoryPassResult, t as AgentMemory, u as BudgetCheck, v as BudgetTotal, w as BudgetUsageEvent, x as CloudEnv, y as CloudRepo, z as ContextBudget, D as ContextManagerKind, E as ContextSnapshot, F as ContextSource, H as ContextSourceStatus, I as Cron, J as CronCreateOptions, K as CronGetOptions, N as CronJob, O as CronJobStatus, Q as CronListOptions, R as CronOperationOptions, T as CronRunOptions, U as CronRuntime, V as CronSchedulerStatus, W as CronStartOptions, X as GoalEvent, Y as GoalOptions, Z as GoalResult, _ as InvalidateCacheOptions, $ as MemoryAdapter, a0 as MemoryAdapterCapabilities, a1 as MemoryFact, a2 as MemoryProviderHandle, a3 as MemoryProviderInitOptions, a4 as MemoryRevision, a5 as MemoryToolSchema, a6 as MemoryTurnMessage, a7 as PersonalityPreset, a8 as ProviderCapability, a9 as ProviderRoute, aa as RecordSessionSummaryArgs, ab as ResolvedProviderRoute, ac as RunUntilIterator, ad as SDKAgentPlugins, ae as SDKAgentSkills, af as SDKArtifact, ag as SDKContextManager, ah as SDKPluginMetadata, ai as SDKProvidersManager, aj as SettingSource, ak as SystemPromptContext, al as SystemPromptMemoryFact, am as SystemPromptSkillRef, an as TelemetrySettings } from './cron-CSTqNZp9.cjs';
5
- import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-DrwUpFxZ.cjs';
6
- export { A as AgentConversationTurn, c as AssistantMessage, d as ConversationStep, e as ConversationTurn, f as CostBreakdown, g as CostSource, h as CostStatus, I as InteractionUpdate, i as McpAuthConfig, j as McpHttpServerConfig, k as McpOAuthConfig, l as McpStdioServerConfig, m as ModelParameterValue, P as PartialToolCallUpdate, n as RunErrorDetail, o as RunGitInfo, p as RunOperation, q as RunStatus, r as SDKAssistantMessage, s as SDKImage, t as SDKImageDimension, u as SDKObjectDelta, v as SDKRequestMessage, w as SDKStatusMessage, x as SDKSystemMessage, y as SDKTaskMessage, z as SDKThinkingMessage, B as SDKToolUseMessage, D as SDKUserMessage, E as SDKUserMessageEvent, F as SendOptions, G as ShellCommand, H as ShellConversationTurn, J as ShellOutput, K as ShellOutputDeltaUpdate, L as StepCompletedUpdate, N as StepStartedUpdate, O as SummaryCompletedUpdate, Q as SummaryStartedUpdate, T as SummaryUpdate, U as TextBlock, V as TextDeltaUpdate, W as ThinkingCompletedUpdate, X as ThinkingDeltaUpdate, Y as ThinkingMessage, Z as TokenDeltaUpdate, _ as TokenUsage, $ as ToolCall, a0 as ToolCallCompletedUpdate, a1 as ToolCallStartedUpdate, a2 as ToolResult, a3 as ToolUseBlock, a4 as TurnEndedUpdate, a5 as UserMessage, a6 as UserMessageAppendedUpdate } from './run-DrwUpFxZ.cjs';
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-QDYUPABr.cjs';
2
+ export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, E as ErrorCode, m as ErrorMetadata, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-QDYUPABr.cjs';
3
+ import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as MemoryContext, m as ConversationStorageAdapter, n as StoredMessage, B as BudgetTracker, o as MemoryProvider, p as MemoryId, q as SDKProvider } from './cron-B_H8rn-j.cjs';
4
+ export { r as ActiveMemoryPassArgs, s as ActiveMemoryPassResult, t as AgentMemory, u as BudgetCheck, v as BudgetTotal, w as BudgetUsageEvent, x as CloudEnv, y as CloudRepo, z as ContextBudget, D as ContextManagerKind, E as ContextSnapshot, F as ContextSource, H as ContextSourceStatus, I as Cron, J as CronCreateOptions, K as CronGetOptions, N as CronJob, O as CronJobStatus, Q as CronListOptions, R as CronOperationOptions, T as CronRunOptions, U as CronRuntime, V as CronSchedulerStatus, W as CronStartOptions, X as GoalEvent, Y as GoalOptions, Z as GoalResult, _ as InvalidateCacheOptions, $ as MemoryAdapter, a0 as MemoryAdapterCapabilities, a1 as MemoryFact, a2 as MemoryProviderHandle, a3 as MemoryProviderInitOptions, a4 as MemoryRevision, a5 as MemoryToolSchema, a6 as MemoryTurnMessage, a7 as PersonalityPreset, a8 as ProviderCapability, a9 as ProviderRoute, aa as RecordSessionSummaryArgs, ab as ResolvedProviderRoute, ac as RunUntilIterator, ad as SDKAgentPlugins, ae as SDKAgentSkills, af as SDKArtifact, ag as SDKContextManager, ah as SDKPluginMetadata, ai as SDKProvidersManager, aj as SettingSource, ak as SystemPromptContext, al as SystemPromptMemoryFact, am as SystemPromptSkillRef, an as TelemetrySettings } from './cron-B_H8rn-j.cjs';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-BPRYG1Id.cjs';
6
+ export { A as AgentConversationTurn, c as AssistantMessage, d as ConversationStep, e as ConversationTurn, f as CostBreakdown, g as CostSource, h as CostStatus, I as InteractionUpdate, i as McpAuthConfig, j as McpHttpServerConfig, k as McpOAuthConfig, l as McpStdioServerConfig, m as ModelParameterValue, P as PartialToolCallUpdate, n as RunErrorDetail, o as RunGitInfo, p as RunOperation, q as RunStatus, r as RunToCompletionOptions, s as RunToCompletionResult, t as SDKAssistantMessage, u as SDKImage, v as SDKImageDimension, w as SDKObjectDelta, x as SDKRequestMessage, y as SDKStatusMessage, z as SDKSystemMessage, B as SDKTaskMessage, D as SDKThinkingMessage, E as SDKToolUseMessage, F as SDKUserMessage, G as SDKUserMessageEvent, H as SendOptions, J as ShellCommand, K as ShellConversationTurn, L as ShellOutput, N as ShellOutputDeltaUpdate, O as StepCompletedUpdate, Q as StepStartedUpdate, T as SummaryCompletedUpdate, U as SummaryStartedUpdate, V as SummaryUpdate, W as TextBlock, X as TextDeltaUpdate, Y as ThinkingCompletedUpdate, Z as ThinkingDeltaUpdate, _ as ThinkingMessage, $ as TokenDeltaUpdate, a0 as TokenUsage, a1 as ToolCall, a2 as ToolCallCompletedUpdate, a3 as ToolCallStartedUpdate, a4 as ToolResult, a5 as ToolUseBlock, a6 as TurnEndedUpdate, a7 as UserMessage, a8 as UserMessageAppendedUpdate } from './run-BPRYG1Id.cjs';
7
7
  import * as zod from 'zod';
8
8
  import { ZodType, z } from 'zod';
9
9
 
@@ -1136,6 +1136,49 @@ declare function createCounterBudgetTracker(options?: CounterBudgetTrackerOption
1136
1136
  nextIteration(): void;
1137
1137
  };
1138
1138
 
1139
+ /**
1140
+ * Stateless continuation-history rebuild (M1-3 — plan m1-continuation-history).
1141
+ *
1142
+ * `buildReplayHistory` serializes `SDKMessage[]` stream events into a bounded
1143
+ * `StoredMessage[]` replay history for the STATELESS continuation path: a server
1144
+ * (or serverless handler) that re-runs an agent on a fresh request reconstructs
1145
+ * the working memory from persisted events rather than a live session. The
1146
+ * replayed history is the ONLY working memory the continued model has, so it
1147
+ * MUST carry tool-result content and be bounded against the context window.
1148
+ *
1149
+ * Complements M1 Phase 3 `runToCompletion` (the STATEFUL path, where the session
1150
+ * preserves history). Pure, sync, dependency-free; reuses the SDK's own
1151
+ * `truncateWithMarker` for per-item caps (Rule 9). Design: blueprint
1152
+ * `m1-continuation-history` ADRs D1-D5; first-party baseline
1153
+ * `theocode/server/lib/continuation-history.ts`.
1154
+ *
1155
+ * @public
1156
+ */
1157
+
1158
+ /**
1159
+ * Options for {@link buildReplayHistory}.
1160
+ *
1161
+ * @public
1162
+ */
1163
+ interface ReplayHistoryOptions {
1164
+ /** The continued model's context window, in tokens. Drives the char budget. */
1165
+ contextWindowTokens: number;
1166
+ /** Tokens held back for system + continuation prompt + reply. Default 8000. */
1167
+ reserveTokens?: number;
1168
+ /**
1169
+ * Max characters for a single oversized turn before it is truncated (never
1170
+ * dropped). Default `floor(budgetChars / 2)`. Guarded to ≥ 0.
1171
+ */
1172
+ perItemCap?: number;
1173
+ }
1174
+ /**
1175
+ * Rebuild a bounded replay history from `base` (prior durable turns) plus the
1176
+ * `events` of the latest round. Returns a NEW array; never mutates inputs.
1177
+ *
1178
+ * @public
1179
+ */
1180
+ declare function buildReplayHistory(base: readonly StoredMessage[], events: readonly SDKMessage[], options: ReplayHistoryOptions): StoredMessage[];
1181
+
1139
1182
  /**
1140
1183
  * Reference `MemoryProvider` impl — no-op fallback (SDK 2.0 Phase 1 /
1141
1184
  * T1.2 reference implementation, mirrors `createCounterBudgetTracker`).
@@ -2108,4 +2151,4 @@ declare function toShareGptTrajectory(result: BatchResult, options?: {
2108
2151
  model?: string;
2109
2152
  }): ShareGptTrajectory | null;
2110
2153
 
2111
- export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, type HookName, InMemoryConversationStorage, JobQueue, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryContext, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, PermissionEngine, type Plugin, type PluginContext, PluginsSettings, type PostAssistantReplyContext, type PreToolCallContext, type PreToolCallDecision, type PreUserSendContext, type PreUserSendResult, type ProviderProfile, ProviderRoutingSettings, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
2154
+ export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, type HookName, InMemoryConversationStorage, JobQueue, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryContext, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, PermissionEngine, type Plugin, type PluginContext, PluginsSettings, type PostAssistantReplyContext, type PreToolCallContext, type PreToolCallDecision, type PreUserSendContext, type PreUserSendResult, type ProviderProfile, ProviderRoutingSettings, type ReplayHistoryOptions, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, buildReplayHistory, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors--VP2qrGc.js';
2
- export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, E as ErrorCode, m as ErrorMetadata, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors--VP2qrGc.js';
3
- import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as MemoryContext, m as ConversationStorageAdapter, n as StoredMessage, B as BudgetTracker, o as MemoryProvider, p as MemoryId, q as SDKProvider } from './cron-Da6vF_2y.js';
4
- export { r as ActiveMemoryPassArgs, s as ActiveMemoryPassResult, t as AgentMemory, u as BudgetCheck, v as BudgetTotal, w as BudgetUsageEvent, x as CloudEnv, y as CloudRepo, z as ContextBudget, D as ContextManagerKind, E as ContextSnapshot, F as ContextSource, H as ContextSourceStatus, I as Cron, J as CronCreateOptions, K as CronGetOptions, N as CronJob, O as CronJobStatus, Q as CronListOptions, R as CronOperationOptions, T as CronRunOptions, U as CronRuntime, V as CronSchedulerStatus, W as CronStartOptions, X as GoalEvent, Y as GoalOptions, Z as GoalResult, _ as InvalidateCacheOptions, $ as MemoryAdapter, a0 as MemoryAdapterCapabilities, a1 as MemoryFact, a2 as MemoryProviderHandle, a3 as MemoryProviderInitOptions, a4 as MemoryRevision, a5 as MemoryToolSchema, a6 as MemoryTurnMessage, a7 as PersonalityPreset, a8 as ProviderCapability, a9 as ProviderRoute, aa as RecordSessionSummaryArgs, ab as ResolvedProviderRoute, ac as RunUntilIterator, ad as SDKAgentPlugins, ae as SDKAgentSkills, af as SDKArtifact, ag as SDKContextManager, ah as SDKPluginMetadata, ai as SDKProvidersManager, aj as SettingSource, ak as SystemPromptContext, al as SystemPromptMemoryFact, am as SystemPromptSkillRef, an as TelemetrySettings } from './cron-Da6vF_2y.js';
5
- import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-DrwUpFxZ.js';
6
- export { A as AgentConversationTurn, c as AssistantMessage, d as ConversationStep, e as ConversationTurn, f as CostBreakdown, g as CostSource, h as CostStatus, I as InteractionUpdate, i as McpAuthConfig, j as McpHttpServerConfig, k as McpOAuthConfig, l as McpStdioServerConfig, m as ModelParameterValue, P as PartialToolCallUpdate, n as RunErrorDetail, o as RunGitInfo, p as RunOperation, q as RunStatus, r as SDKAssistantMessage, s as SDKImage, t as SDKImageDimension, u as SDKObjectDelta, v as SDKRequestMessage, w as SDKStatusMessage, x as SDKSystemMessage, y as SDKTaskMessage, z as SDKThinkingMessage, B as SDKToolUseMessage, D as SDKUserMessage, E as SDKUserMessageEvent, F as SendOptions, G as ShellCommand, H as ShellConversationTurn, J as ShellOutput, K as ShellOutputDeltaUpdate, L as StepCompletedUpdate, N as StepStartedUpdate, O as SummaryCompletedUpdate, Q as SummaryStartedUpdate, T as SummaryUpdate, U as TextBlock, V as TextDeltaUpdate, W as ThinkingCompletedUpdate, X as ThinkingDeltaUpdate, Y as ThinkingMessage, Z as TokenDeltaUpdate, _ as TokenUsage, $ as ToolCall, a0 as ToolCallCompletedUpdate, a1 as ToolCallStartedUpdate, a2 as ToolResult, a3 as ToolUseBlock, a4 as TurnEndedUpdate, a5 as UserMessage, a6 as UserMessageAppendedUpdate } from './run-DrwUpFxZ.js';
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-DG_7CAUg.js';
2
+ export { A as AgentDisposedError, c as AgentRunError, d as AgentRunErrorCode, e as AuthenticationError, f as BudgetExceedEvent, g as BudgetExceededError, h as BudgetLimit, i as BudgetMode, j as BudgetScope, k as BudgetThresholdEvent, l as BudgetWindow, C as ConfigurationError, E as ErrorCode, m as ErrorMetadata, I as IntegrationNotConnectedError, n as InvalidTaskIdError, M as MemoryAdapterError, o as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, p as TaskNotFoundError, U as UnknownAgentError, q as UnsupportedBudgetOperationError, r as UnsupportedRunOperationError, s as UnsupportedTaskOperationError, t as isTransientError } from './errors-DG_7CAUg.js';
3
+ import { A as AgentOptions, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, M as MemorySettings, a as AgentDefinition, b as ContextSettings, c as PluginsSettings, d as SkillsSettings, e as SDKAgent, f as ListAgentsOptions, g as ListResult, h as SDKAgentInfo, G as GetAgentOptions, i as ListRunsOptions, j as GetRunOptions, k as AgentOperationOptions, l as MemoryContext, m as ConversationStorageAdapter, n as StoredMessage, B as BudgetTracker, o as MemoryProvider, p as MemoryId, q as SDKProvider } from './cron-DX6HbHxd.js';
4
+ export { r as ActiveMemoryPassArgs, s as ActiveMemoryPassResult, t as AgentMemory, u as BudgetCheck, v as BudgetTotal, w as BudgetUsageEvent, x as CloudEnv, y as CloudRepo, z as ContextBudget, D as ContextManagerKind, E as ContextSnapshot, F as ContextSource, H as ContextSourceStatus, I as Cron, J as CronCreateOptions, K as CronGetOptions, N as CronJob, O as CronJobStatus, Q as CronListOptions, R as CronOperationOptions, T as CronRunOptions, U as CronRuntime, V as CronSchedulerStatus, W as CronStartOptions, X as GoalEvent, Y as GoalOptions, Z as GoalResult, _ as InvalidateCacheOptions, $ as MemoryAdapter, a0 as MemoryAdapterCapabilities, a1 as MemoryFact, a2 as MemoryProviderHandle, a3 as MemoryProviderInitOptions, a4 as MemoryRevision, a5 as MemoryToolSchema, a6 as MemoryTurnMessage, a7 as PersonalityPreset, a8 as ProviderCapability, a9 as ProviderRoute, aa as RecordSessionSummaryArgs, ab as ResolvedProviderRoute, ac as RunUntilIterator, ad as SDKAgentPlugins, ae as SDKAgentSkills, af as SDKArtifact, ag as SDKContextManager, ah as SDKPluginMetadata, ai as SDKProvidersManager, aj as SettingSource, ak as SystemPromptContext, al as SystemPromptMemoryFact, am as SystemPromptSkillRef, an as TelemetrySettings } from './cron-DX6HbHxd.js';
5
+ import { R as RunResult, M as ModelSelection, C as CustomTool, a as McpServerConfig, b as Run, S as SDKMessage } from './run-BPRYG1Id.js';
6
+ export { A as AgentConversationTurn, c as AssistantMessage, d as ConversationStep, e as ConversationTurn, f as CostBreakdown, g as CostSource, h as CostStatus, I as InteractionUpdate, i as McpAuthConfig, j as McpHttpServerConfig, k as McpOAuthConfig, l as McpStdioServerConfig, m as ModelParameterValue, P as PartialToolCallUpdate, n as RunErrorDetail, o as RunGitInfo, p as RunOperation, q as RunStatus, r as RunToCompletionOptions, s as RunToCompletionResult, t as SDKAssistantMessage, u as SDKImage, v as SDKImageDimension, w as SDKObjectDelta, x as SDKRequestMessage, y as SDKStatusMessage, z as SDKSystemMessage, B as SDKTaskMessage, D as SDKThinkingMessage, E as SDKToolUseMessage, F as SDKUserMessage, G as SDKUserMessageEvent, H as SendOptions, J as ShellCommand, K as ShellConversationTurn, L as ShellOutput, N as ShellOutputDeltaUpdate, O as StepCompletedUpdate, Q as StepStartedUpdate, T as SummaryCompletedUpdate, U as SummaryStartedUpdate, V as SummaryUpdate, W as TextBlock, X as TextDeltaUpdate, Y as ThinkingCompletedUpdate, Z as ThinkingDeltaUpdate, _ as ThinkingMessage, $ as TokenDeltaUpdate, a0 as TokenUsage, a1 as ToolCall, a2 as ToolCallCompletedUpdate, a3 as ToolCallStartedUpdate, a4 as ToolResult, a5 as ToolUseBlock, a6 as TurnEndedUpdate, a7 as UserMessage, a8 as UserMessageAppendedUpdate } from './run-BPRYG1Id.js';
7
7
  import * as zod from 'zod';
8
8
  import { ZodType, z } from 'zod';
9
9
 
@@ -1136,6 +1136,49 @@ declare function createCounterBudgetTracker(options?: CounterBudgetTrackerOption
1136
1136
  nextIteration(): void;
1137
1137
  };
1138
1138
 
1139
+ /**
1140
+ * Stateless continuation-history rebuild (M1-3 — plan m1-continuation-history).
1141
+ *
1142
+ * `buildReplayHistory` serializes `SDKMessage[]` stream events into a bounded
1143
+ * `StoredMessage[]` replay history for the STATELESS continuation path: a server
1144
+ * (or serverless handler) that re-runs an agent on a fresh request reconstructs
1145
+ * the working memory from persisted events rather than a live session. The
1146
+ * replayed history is the ONLY working memory the continued model has, so it
1147
+ * MUST carry tool-result content and be bounded against the context window.
1148
+ *
1149
+ * Complements M1 Phase 3 `runToCompletion` (the STATEFUL path, where the session
1150
+ * preserves history). Pure, sync, dependency-free; reuses the SDK's own
1151
+ * `truncateWithMarker` for per-item caps (Rule 9). Design: blueprint
1152
+ * `m1-continuation-history` ADRs D1-D5; first-party baseline
1153
+ * `theocode/server/lib/continuation-history.ts`.
1154
+ *
1155
+ * @public
1156
+ */
1157
+
1158
+ /**
1159
+ * Options for {@link buildReplayHistory}.
1160
+ *
1161
+ * @public
1162
+ */
1163
+ interface ReplayHistoryOptions {
1164
+ /** The continued model's context window, in tokens. Drives the char budget. */
1165
+ contextWindowTokens: number;
1166
+ /** Tokens held back for system + continuation prompt + reply. Default 8000. */
1167
+ reserveTokens?: number;
1168
+ /**
1169
+ * Max characters for a single oversized turn before it is truncated (never
1170
+ * dropped). Default `floor(budgetChars / 2)`. Guarded to ≥ 0.
1171
+ */
1172
+ perItemCap?: number;
1173
+ }
1174
+ /**
1175
+ * Rebuild a bounded replay history from `base` (prior durable turns) plus the
1176
+ * `events` of the latest round. Returns a NEW array; never mutates inputs.
1177
+ *
1178
+ * @public
1179
+ */
1180
+ declare function buildReplayHistory(base: readonly StoredMessage[], events: readonly SDKMessage[], options: ReplayHistoryOptions): StoredMessage[];
1181
+
1139
1182
  /**
1140
1183
  * Reference `MemoryProvider` impl — no-op fallback (SDK 2.0 Phase 1 /
1141
1184
  * T1.2 reference implementation, mirrors `createCounterBudgetTracker`).
@@ -2108,4 +2151,4 @@ declare function toShareGptTrajectory(result: BatchResult, options?: {
2108
2151
  model?: string;
2109
2152
  }): ShareGptTrajectory | null;
2110
2153
 
2111
- export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, type HookName, InMemoryConversationStorage, JobQueue, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryContext, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, PermissionEngine, type Plugin, type PluginContext, PluginsSettings, type PostAssistantReplyContext, type PreToolCallContext, type PreToolCallDecision, type PreUserSendContext, type PreUserSendResult, type ProviderProfile, ProviderRoutingSettings, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
2154
+ export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, BudgetTracker, CloudOptions, ContextSettings, ConversationStorageAdapter, type CounterBudgetTrackerOptions, CustomTool, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, EventBus, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, type HookName, InMemoryConversationStorage, JobQueue, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryContext, MemoryId, MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, PermissionEngine, type Plugin, type PluginContext, PluginsSettings, type PostAssistantReplyContext, type PreToolCallContext, type PreToolCallDecision, type PreUserSendContext, type PreUserSendResult, type ProviderProfile, ProviderRoutingSettings, type ReplayHistoryOptions, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, type Squad, type SquadOptions, type SquadRun, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, buildReplayHistory, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
package/dist/index.js CHANGED
@@ -2796,6 +2796,71 @@ var init_agent_factory_registry = __esm({
2796
2796
  }
2797
2797
  });
2798
2798
 
2799
+ // src/internal/runtime/lifecycle/run-to-completion.ts
2800
+ var run_to_completion_exports = {};
2801
+ __export(run_to_completion_exports, {
2802
+ classifyRound: () => classifyRound,
2803
+ runToCompletionImpl: () => runToCompletionImpl
2804
+ });
2805
+ function isEmptyRound(result) {
2806
+ return (result.result ?? "").trim() === "";
2807
+ }
2808
+ function classifyRound(result, round, maxRounds, emptyStreak) {
2809
+ if (result.stoppedAtIterationLimit !== true) return "done";
2810
+ if (isEmptyRound(result) && emptyStreak >= 1) return "no_progress";
2811
+ if (round >= maxRounds) return "step_limit";
2812
+ return "continue";
2813
+ }
2814
+ function addUsage(acc, u) {
2815
+ if (u === void 0) return acc;
2816
+ const inputTokens = (acc?.inputTokens ?? 0) + u.inputTokens;
2817
+ const outputTokens = (acc?.outputTokens ?? 0) + u.outputTokens;
2818
+ const sumOpt = (a, b) => a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
2819
+ return {
2820
+ inputTokens,
2821
+ outputTokens,
2822
+ totalTokens: inputTokens + outputTokens,
2823
+ cacheReadTokens: sumOpt(acc?.cacheReadTokens, u.cacheReadTokens),
2824
+ cacheWriteTokens: sumOpt(acc?.cacheWriteTokens, u.cacheWriteTokens),
2825
+ reasoningTokens: sumOpt(acc?.reasoningTokens, u.reasoningTokens)
2826
+ };
2827
+ }
2828
+ function buildResult(terminal, rounds, lastResult, usage) {
2829
+ return { terminal, rounds, lastResult, ...usage !== void 0 ? { usage } : {} };
2830
+ }
2831
+ async function stepRound(agent, prompt, sendOptions, round, maxRounds, state4) {
2832
+ const run = await agent.send(prompt, sendOptions);
2833
+ const result = await run.wait();
2834
+ const usage = addUsage(state4.usage, result.usage);
2835
+ const decision = classifyRound(result, round, maxRounds, state4.emptyStreak);
2836
+ if (decision !== "continue") return { terminal: buildResult(decision, round, result, usage) };
2837
+ const emptyStreak = isEmptyRound(result) ? state4.emptyStreak + 1 : 0;
2838
+ return { next: { usage, emptyStreak }, lastResult: result };
2839
+ }
2840
+ async function runToCompletionImpl(agent, message, options) {
2841
+ const maxRounds = options?.maxRounds ?? DEFAULT_MAX_ROUNDS;
2842
+ const continuationPrompt = options?.continuationPrompt ?? DEFAULT_CONTINUATION_PROMPT;
2843
+ const { onTruncated, signal, sendOptions } = options ?? {};
2844
+ let state4 = { usage: void 0, emptyStreak: 0 };
2845
+ for (let round = 0; ; round += 1) {
2846
+ const prompt = round === 0 ? message : continuationPrompt;
2847
+ const outcome = await stepRound(agent, prompt, sendOptions, round, maxRounds, state4);
2848
+ if ("terminal" in outcome) return outcome.terminal;
2849
+ state4 = outcome.next;
2850
+ await onTruncated?.({ round });
2851
+ if (signal?.aborted === true) {
2852
+ return buildResult("step_limit", round, outcome.lastResult, state4.usage);
2853
+ }
2854
+ }
2855
+ }
2856
+ var DEFAULT_MAX_ROUNDS, DEFAULT_CONTINUATION_PROMPT;
2857
+ var init_run_to_completion = __esm({
2858
+ "src/internal/runtime/lifecycle/run-to-completion.ts"() {
2859
+ DEFAULT_MAX_ROUNDS = 5;
2860
+ DEFAULT_CONTINUATION_PROMPT = "Continue from where you left off and finish the task. If it is already complete, give the final answer.";
2861
+ }
2862
+ });
2863
+
2799
2864
  // src/internal/runtime/lifecycle/fork-agent.ts
2800
2865
  var fork_agent_exports = {};
2801
2866
  __export(fork_agent_exports, {
@@ -2884,10 +2949,10 @@ var RingBuffer;
2884
2949
  var init_ring_buffer = __esm({
2885
2950
  "src/internal/task/ring-buffer.ts"() {
2886
2951
  RingBuffer = class {
2887
- constructor(cap) {
2888
- this.cap = cap;
2889
- if (!Number.isInteger(cap) || cap < 1) {
2890
- throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);
2952
+ constructor(cap2) {
2953
+ this.cap = cap2;
2954
+ if (!Number.isInteger(cap2) || cap2 < 1) {
2955
+ throw new Error(`RingBuffer capacity must be a positive integer, got ${cap2}`);
2891
2956
  }
2892
2957
  }
2893
2958
  cap;
@@ -6804,8 +6869,7 @@ var FixtureRunBase = class {
6804
6869
  if (status === "error" && this.script.errorDetail !== void 0) {
6805
6870
  base.error = this.script.errorDetail;
6806
6871
  }
6807
- if (this.script.usage !== void 0) base.usage = this.script.usage;
6808
- if (this.script.cost !== void 0) base.cost = this.script.cost;
6872
+ applyScriptMetrics(base, this.script);
6809
6873
  return this.extendRunResult(applyExtraRunFields(base, this.script));
6810
6874
  }
6811
6875
  /** Subclasses override to attach runtime-specific fields (e.g. cloud git info). */
@@ -6839,6 +6903,11 @@ function makeNotifier() {
6839
6903
  });
6840
6904
  return { promise, resolve: resolve3 };
6841
6905
  }
6906
+ function applyScriptMetrics(base, script) {
6907
+ if (script.usage !== void 0) base.usage = script.usage;
6908
+ if (script.cost !== void 0) base.cost = script.cost;
6909
+ if (script.stoppedAtIterationLimit === true) base.stoppedAtIterationLimit = true;
6910
+ }
6842
6911
 
6843
6912
  // src/internal/runtime/cloud/cloud-run.ts
6844
6913
  function createCloudRun(options) {
@@ -7347,6 +7416,18 @@ var CloudAgent = class {
7347
7416
  "fork"
7348
7417
  );
7349
7418
  }
7419
+ /**
7420
+ * The continuation driver re-sends against a stateful local session; the
7421
+ * cloud runtime manages its own continuation policy server-side (M1 Phase 3).
7422
+ *
7423
+ * @public
7424
+ */
7425
+ runToCompletion() {
7426
+ throw new UnsupportedRunOperationError(
7427
+ "Agent.runToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.",
7428
+ "runToCompletion"
7429
+ );
7430
+ }
7350
7431
  /**
7351
7432
  * Personality presets require consistent server-side enforcement that
7352
7433
  * the cloud runtime (pre-release) does not yet provide. Reject explicitly
@@ -10118,7 +10199,7 @@ async function loadPluginManifestFromJson(manifestPath, folderName) {
10118
10199
  const record = parsed;
10119
10200
  const name = typeof record.name === "string" ? record.name : folderName;
10120
10201
  const version = typeof record.version === "string" ? record.version : "0.0.0";
10121
- const capabilities = Array.isArray(record.capabilities) ? record.capabilities.filter((cap) => typeof cap === "string") : [];
10202
+ const capabilities = Array.isArray(record.capabilities) ? record.capabilities.filter((cap2) => typeof cap2 === "string") : [];
10122
10203
  const source = manifestPath.slice(manifestPath.indexOf(".theokit/"));
10123
10204
  const metadata = { name, version, capabilities, source };
10124
10205
  if (typeof record.entry === "string") metadata.entry = record.entry;
@@ -10441,6 +10522,9 @@ var LocalRun = class extends FixtureRunBase {
10441
10522
  }
10442
10523
  };
10443
10524
 
10525
+ // src/internal/runtime/local-agent/real-local-run.ts
10526
+ init_errors();
10527
+
10444
10528
  // src/internal/runtime/budget/budget.ts
10445
10529
  var IterationBudget = class {
10446
10530
  #remaining;
@@ -11665,6 +11749,7 @@ async function runAgentLoop(inputs) {
11665
11749
  const ctx = await initLoopContext(inputs);
11666
11750
  ctxRef = ctx;
11667
11751
  const budget = inputs.budget ?? new IterationBudget({ maxIterations: inputs.maxIterations ?? 8 });
11752
+ let lastTurnDecision;
11668
11753
  while (budget.shouldContinue()) {
11669
11754
  if (inputs.budgetTracker !== void 0) {
11670
11755
  const decision2 = evaluateBudgetGate(inputs.budgetTracker);
@@ -11673,18 +11758,26 @@ async function runAgentLoop(inputs) {
11673
11758
  if (decision2.detail !== void 0) {
11674
11759
  ctx.error = { message: decision2.detail, code: decision2.reason ?? "budget" };
11675
11760
  }
11761
+ if (decision2.reason === "iteration_limit") {
11762
+ ctx.stoppedAtIterationLimit = true;
11763
+ }
11676
11764
  break;
11677
11765
  }
11678
11766
  }
11679
11767
  const usingGrace = budget.remaining <= 0 && !budget.graceCallUsed;
11680
11768
  if (usingGrace) budget.useGraceCall();
11681
11769
  const decision = await runIteration(inputs, ctx);
11770
+ lastTurnDecision = decision;
11682
11771
  if (decision === "done") break;
11683
11772
  if (decision === "error") {
11684
11773
  ctx.finalStatus = "error";
11685
11774
  break;
11686
11775
  }
11687
11776
  budget.consume();
11777
+ inputs.budgetTracker?.nextIteration?.();
11778
+ }
11779
+ if (lastTurnDecision === "continue" && budget.shouldContinue() === false) {
11780
+ ctx.stoppedAtIterationLimit = true;
11688
11781
  }
11689
11782
  if (budget.shouldContinue() === false && ctx.finalStatus === "finished" && ctx.finalText === "") {
11690
11783
  ctx.finalStatus = "error";
@@ -11715,7 +11808,8 @@ async function runAgentLoop(inputs) {
11715
11808
  conversation: ctx.conversation,
11716
11809
  ...usage !== void 0 ? { usage } : {},
11717
11810
  ...cost !== void 0 ? { cost } : {},
11718
- ...ctx.error !== void 0 ? { error: ctx.error } : {}
11811
+ ...ctx.error !== void 0 ? { error: ctx.error } : {},
11812
+ ...ctx.stoppedAtIterationLimit === true ? { stoppedAtIterationLimit: true } : {}
11719
11813
  };
11720
11814
  } finally {
11721
11815
  if (ctxRef !== void 0 && ctxRef.memoryProviderHandle !== void 0 && inputs.memoryProvider !== void 0) {
@@ -11772,8 +11866,8 @@ function handleToolErrorContinuation(inputs, ctx, toolResults) {
11772
11866
  const hasError = toolResults.some((part) => part.type === "tool_result" && part.isError === true);
11773
11867
  if (hasError) {
11774
11868
  ctx._consecutiveToolErrors = (ctx._consecutiveToolErrors ?? 0) + 1;
11775
- const cap = inputs.maxConsecutiveToolErrors ?? 3;
11776
- if (ctx._consecutiveToolErrors >= cap) return "error";
11869
+ const cap2 = inputs.maxConsecutiveToolErrors ?? 3;
11870
+ if (ctx._consecutiveToolErrors >= cap2) return "error";
11777
11871
  return "continue";
11778
11872
  }
11779
11873
  ctx._consecutiveToolErrors = 0;
@@ -14150,6 +14244,13 @@ function resolveRunProvider(options) {
14150
14244
  return { primary, effectiveModelId };
14151
14245
  }
14152
14246
  function buildLoopInputs(options, runId, userText) {
14247
+ const maxIterations = options.sendOptions.maxIterations;
14248
+ if (maxIterations !== void 0 && (!Number.isInteger(maxIterations) || maxIterations < 1)) {
14249
+ throw new ConfigurationError(
14250
+ `SendOptions.maxIterations must be a positive integer, got ${maxIterations}`,
14251
+ { code: "invalid_max_iterations" }
14252
+ );
14253
+ }
14153
14254
  const { primary, effectiveModelId } = resolveRunProvider(options);
14154
14255
  const fallback = options.agentOptions.providers?.fallback;
14155
14256
  const apiKeys = options.agentOptions.providers?.apiKeys;
@@ -14188,6 +14289,9 @@ function buildLoopInputs(options, runId, userText) {
14188
14289
  // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn
14189
14290
  // can attach it to the LLM `fetch({ signal })` call.
14190
14291
  ...options.sendOptions.signal !== void 0 ? { signal: options.sendOptions.signal } : {},
14292
+ // M1-2: per-send iteration ceiling (validated above). The loop reads
14293
+ // inputs.maxIterations (default 8 when unset).
14294
+ ...maxIterations !== void 0 ? { maxIterations } : {},
14191
14295
  // D315-D317 — tool lifecycle hooks (cost tracking + audit + retry/alert)
14192
14296
  ...options.agentOptions.onToolStart !== void 0 ? { onToolStart: options.agentOptions.onToolStart } : {},
14193
14297
  ...options.agentOptions.onToolEnd !== void 0 ? { onToolEnd: options.agentOptions.onToolEnd } : {},
@@ -14319,6 +14423,7 @@ var RealLocalRun = class extends FixtureRunBase {
14319
14423
  if (output.result.length > 0) this.script.result = output.result;
14320
14424
  if (output.usage !== void 0) this.script.usage = output.usage;
14321
14425
  if (output.cost !== void 0) this.script.cost = output.cost;
14426
+ if (output.stoppedAtIterationLimit === true) this.script.stoppedAtIterationLimit = true;
14322
14427
  if (output.error !== void 0 && this.script.errorDetail === void 0) {
14323
14428
  this.script.errorDetail = {
14324
14429
  message: output.error.message,
@@ -15256,7 +15361,7 @@ var MEMORY_GET_SCHEMA = {
15256
15361
  };
15257
15362
  var DEFAULT_MAX_TOTAL_CHARS = 16384;
15258
15363
  function createMemorySearchTool(opts) {
15259
- const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;
15364
+ const cap2 = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;
15260
15365
  return {
15261
15366
  name: "memory_search",
15262
15367
  description: SEARCH_DESCRIPTION,
@@ -15273,7 +15378,7 @@ function createMemorySearchTool(opts) {
15273
15378
  ...sources !== void 0 ? { sources } : {}
15274
15379
  };
15275
15380
  const hits = await opts.index.search(query, searchOptions);
15276
- return JSON.stringify(capByTotalChars(hits, cap));
15381
+ return JSON.stringify(capByTotalChars(hits, cap2));
15277
15382
  }
15278
15383
  };
15279
15384
  }
@@ -15841,6 +15946,13 @@ function localAgentRunUntil(agent, goal, options) {
15841
15946
  }
15842
15947
  return wrap();
15843
15948
  }
15949
+ function localAgentRunToCompletion(agent, message, options) {
15950
+ async function run() {
15951
+ const { runToCompletionImpl: runToCompletionImpl2 } = await Promise.resolve().then(() => (init_run_to_completion(), run_to_completion_exports));
15952
+ return runToCompletionImpl2({ send: (m, o) => agent.send(m, o) }, message, options);
15953
+ }
15954
+ return run();
15955
+ }
15844
15956
  async function localAgentFork(parent, options) {
15845
15957
  const { forkAgentImpl: forkAgentImpl2 } = await Promise.resolve().then(() => (init_fork_agent(), fork_agent_exports));
15846
15958
  const { getAgentFacade: getAgentFacade2 } = await Promise.resolve().then(() => (init_agent_factory_registry(), agent_factory_registry_exports));
@@ -15904,8 +16016,8 @@ async function applyPreUserSendHook(args) {
15904
16016
  ...args.options.memoryContext !== void 0 ? { memoryContext: args.options.memoryContext } : {},
15905
16017
  ...args.sendOptions.signal !== void 0 ? { signal: args.sendOptions.signal } : {}
15906
16018
  };
15907
- const cap = args.options.maxRecallContextBytes ?? DEFAULT_MAX_RECALL_BYTES;
15908
- const recalled = await args.pluginManager.runPreUserSendHooks(ctx, cap);
16019
+ const cap2 = args.options.maxRecallContextBytes ?? DEFAULT_MAX_RECALL_BYTES;
16020
+ const recalled = await args.pluginManager.runPreUserSendHooks(ctx, cap2);
15909
16021
  if (recalled === void 0 || recalled.length === 0) return args.original;
15910
16022
  const wrapped = `<memory-context>
15911
16023
  ${recalled}
@@ -16381,6 +16493,10 @@ var LocalAgent = class {
16381
16493
  fork(options) {
16382
16494
  return localAgentFork({ agentId: this.agentId, options: this.options, personalitySlugSnapshot: this.personalityStore.active(this.agentId) }, options);
16383
16495
  }
16496
+ // biome-ignore format: G8 budget — see runUntil comment above.
16497
+ runToCompletion(message, options) {
16498
+ return localAgentRunToCompletion(this, message, options);
16499
+ }
16384
16500
  };
16385
16501
  function resolveCwd(cwd) {
16386
16502
  return (Array.isArray(cwd) ? cwd[0] : cwd) ?? process.cwd();
@@ -17896,6 +18012,77 @@ function createCounterBudgetTracker(options = {}) {
17896
18012
  };
17897
18013
  }
17898
18014
 
18015
+ // src/internal/runtime/context/replay-history.ts
18016
+ var CHARS_PER_TOKEN = 4;
18017
+ var DEFAULT_RESERVE_TOKENS = 8e3;
18018
+ function finiteOr(value, fallback) {
18019
+ return Number.isFinite(value) ? value : fallback;
18020
+ }
18021
+ function charBudget(options) {
18022
+ const window = finiteOr(options.contextWindowTokens, 0);
18023
+ const reserve = finiteOr(options.reserveTokens ?? DEFAULT_RESERVE_TOKENS, DEFAULT_RESERVE_TOKENS);
18024
+ return Math.max(0, window - reserve) * CHARS_PER_TOKEN;
18025
+ }
18026
+ function assistantText2(event) {
18027
+ return event.message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
18028
+ }
18029
+ function stringifyPayload(value) {
18030
+ if (value === void 0) return "";
18031
+ return typeof value === "string" ? value : JSON.stringify(value) ?? "";
18032
+ }
18033
+ function cap(content, perItemCap) {
18034
+ return truncateWithMarker(content, Math.max(0, perItemCap)).finalContent;
18035
+ }
18036
+ function mapEvent(event, perItemCap) {
18037
+ if (event.type === "assistant") {
18038
+ const text = assistantText2(event);
18039
+ return text.length > 0 ? { message: { role: "assistant", content: cap(text, perItemCap) } } : null;
18040
+ }
18041
+ if (event.type === "tool_call") {
18042
+ if (event.status === "running") {
18043
+ const content2 = cap(`[tool_call ${event.name}] ${stringifyPayload(event.args)}`, perItemCap);
18044
+ return { message: { role: "tool_call", content: content2 }, pairId: event.call_id };
18045
+ }
18046
+ const content = cap(
18047
+ `[tool_result ${event.name}] ${stringifyPayload(event.result)}`,
18048
+ perItemCap
18049
+ );
18050
+ return { message: { role: "tool_result", content }, pairId: event.call_id };
18051
+ }
18052
+ return null;
18053
+ }
18054
+ function evictionIndices(turns) {
18055
+ const head = turns[0];
18056
+ if (head?.pairId === void 0) return [0];
18057
+ const indices = [];
18058
+ for (let i = 0; i < turns.length; i += 1) {
18059
+ if (turns[i]?.pairId === head.pairId) indices.push(i);
18060
+ }
18061
+ return indices;
18062
+ }
18063
+ function totalChars(turns) {
18064
+ return turns.reduce((n, t) => n + t.message.content.length, 0);
18065
+ }
18066
+ function trimToBudget(turns, budgetChars) {
18067
+ const kept = [...turns];
18068
+ while (kept.length > 1 && totalChars(kept) > budgetChars) {
18069
+ const evict = evictionIndices(kept);
18070
+ if (kept.length - evict.length < 1) break;
18071
+ for (const idx of evict.sort((a, b) => b - a)) kept.splice(idx, 1);
18072
+ }
18073
+ return kept;
18074
+ }
18075
+ function buildReplayHistory(base, events, options) {
18076
+ const budgetChars = charBudget(options);
18077
+ const perItemCap = Math.max(0, options.perItemCap ?? Math.floor(budgetChars / 2));
18078
+ const turns = base.map((message) => ({ message }));
18079
+ for (const event of events) {
18080
+ const turn = mapEvent(event, perItemCap);
18081
+ if (turn !== null) turns.push(turn);
18082
+ }
18083
+ return trimToBudget(turns, budgetChars).map((t) => t.message);
18084
+ }
18085
+
17899
18086
  // src/internal/runtime/memory/memory-provider-noop.ts
17900
18087
  var NOOP_ADAPTER_ID = "noop";
17901
18088
  var NOOP_CAPABILITIES = {
@@ -19266,6 +19453,6 @@ function safeStringify2(v) {
19266
19453
  }
19267
19454
  }
19268
19455
 
19269
- export { Agent, AgentBuilder, AgentDisposedError, AgentRunError, AuthenticationError, Budget, BudgetExceededError, ConfigurationError, Cron, EventBus, FileSystemConversationStorage, GenerateObjectError, InMemoryConversationStorage, IntegrationNotConnectedError, InvalidTaskIdError, JobQueue, Memory, MemoryAdapterError, NetworkError, PermissionEngine, RateLimitError, Security, StreamObjectError, Task, TaskNotFoundError, Theokit, TheokitAgentError, UnknownAgentError, UnsupportedBudgetOperationError, UnsupportedRunOperationError, UnsupportedTaskOperationError, UsageAccumulator, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isTransientError, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
19456
+ export { Agent, AgentBuilder, AgentDisposedError, AgentRunError, AuthenticationError, Budget, BudgetExceededError, ConfigurationError, Cron, EventBus, FileSystemConversationStorage, GenerateObjectError, InMemoryConversationStorage, IntegrationNotConnectedError, InvalidTaskIdError, JobQueue, Memory, MemoryAdapterError, NetworkError, PermissionEngine, RateLimitError, Security, StreamObjectError, Task, TaskNotFoundError, Theokit, TheokitAgentError, UnknownAgentError, UnsupportedBudgetOperationError, UnsupportedRunOperationError, UnsupportedTaskOperationError, UsageAccumulator, buildReplayHistory, chargeAndCheckThresholds, computeCost, createAgentFactory, createCounterBudgetTracker, createNoopMemoryProvider, createSquad, definePlugin, defineProvider, defineTool, extractRawId, getPricingEntry, inferApiMode, isTransientError, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory, withCwdMutex };
19270
19457
  //# sourceMappingURL=index.js.map
19271
19458
  //# sourceMappingURL=index.js.map