@dudko.dev/agent-web 0.0.30 → 0.0.32

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
@@ -294,8 +294,17 @@ interface CompactionConfig {
294
294
  auto?: boolean;
295
295
  /** The model's context window, in tokens (default 128 000). */
296
296
  contextWindowTokens?: number;
297
- /** Compact once the estimated context exceeds this (default: half the window). */
297
+ /**
298
+ * Compact once the estimated context - the fixed prompt (system, tools, skills), the transcript
299
+ * and the run's step log together - exceeds this many tokens. Default: `thresholdRatio` of the
300
+ * window.
301
+ */
298
302
  thresholdTokens?: number;
303
+ /**
304
+ * The same threshold as a share of the window, 0 < ratio <= 1 (default 0.85). `thresholdTokens`
305
+ * wins when both are set; it follows the window if the model turns out to have a smaller one.
306
+ */
307
+ thresholdRatio?: number;
299
308
  /** Transcript messages kept verbatim (default 4). */
300
309
  keepRecentTurns?: number;
301
310
  /** Executed steps kept verbatim in the run's trace (default 3). */
@@ -317,6 +326,7 @@ interface ResolvedCompaction {
317
326
  auto: boolean;
318
327
  contextWindowTokens: number;
319
328
  thresholdTokens: number;
329
+ thresholdRatio: number;
320
330
  keepRecentTurns: number;
321
331
  keepRecentSteps: number;
322
332
  summaryMaxTokens: number;
@@ -324,8 +334,24 @@ interface ResolvedCompaction {
324
334
  clearToolResultsAfterTokens: number;
325
335
  keepToolResults: number;
326
336
  }
337
+ /**
338
+ * Compaction starts at this share of the window unless configured. The estimate leans high (see
339
+ * `estimateTokens`), so on a Claude model this is roughly 70-75% really used - the rest is room
340
+ * for the answer and for what one step adds before the next check.
341
+ */
342
+ declare const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85;
327
343
  declare const resolveCompaction: (c: CompactionConfig | undefined) => ResolvedCompaction;
328
- /** Cheap, provider-independent token estimate (~4 chars per token). */
344
+ /**
345
+ * Cheap, provider-independent token estimate, by kind of character - because text is not one
346
+ * thing: letters run ~2.5 to a token (prose is kinder; code, markdown and JSON are not), digits
347
+ * and punctuation about one each (JSON, tables, ids), a space a quarter, a newline one, other
348
+ * scripts (Russian...) two characters, CJK and emoji one. Calibrated against Claude's tokenizer,
349
+ * the most token-hungry in use, over prose, markdown, code, JSON, a table, Russian and a mix: it
350
+ * comes out 1.1-1.4x the real count and never below it (a flat "4 characters a token" was
351
+ * 0.4-0.7x for everything but Russian). It errs high ON PURPOSE: it decides when to compact, and
352
+ * compacting a little early is cheap while overflowing the window is a failed run. A tokenizer
353
+ * that packs tighter (OpenAI, Gemini) makes it higher still - then raise `thresholdRatio`.
354
+ */
329
355
  declare const estimateTokens: (text: string) => number;
330
356
  declare const messageTokens: (msgs: StoredMessage[]) => number;
331
357
  interface CompressOptions {
@@ -337,6 +363,12 @@ interface CompressOptions {
337
363
  keepRecent?: number;
338
364
  /** Output cap of the summary call. */
339
365
  summaryMaxTokens?: number;
366
+ /**
367
+ * The most the summariser is shown, in estimated tokens (the newest part is kept). Default: a
368
+ * fixed 48 000 characters. The agent passes a share of the window, so a long transcript is
369
+ * summarised whole instead of cut to its last few pages first.
370
+ */
371
+ maxInputTokens?: number;
340
372
  /** Compact even when below the threshold (manual "compact now"). */
341
373
  force?: boolean;
342
374
  /** Time-box the summarisation call so it can never hang the caller. */
@@ -1075,6 +1107,11 @@ interface ResolvedConfig {
1075
1107
  compaction: ResolvedCompaction;
1076
1108
  logLevel: LogLevel;
1077
1109
  }
1110
+ /**
1111
+ * The effective per-call output caps: what the host set (`limits.perCall`, then the legacy
1112
+ * `budgets`) wins; every other phase gets its share of the window.
1113
+ */
1114
+ declare const resolveBudgets: (c: BrowserAgentConfig, contextWindowTokens: number) => ResolvedConfig["budgets"];
1078
1115
  declare const resolveConfig: (c: BrowserAgentConfig) => ResolvedConfig;
1079
1116
 
1080
1117
  type ReplanMode = 'continue' | 'revise' | 'finish';
@@ -1610,6 +1647,15 @@ interface Agent {
1610
1647
  * count, or its definitions' share of the context window).
1611
1648
  */
1612
1649
  readonly toolStrategy: EffectiveToolStrategy;
1650
+ /**
1651
+ * Tokens this agent has spent - on every run and manual compaction, stopped or failed ones
1652
+ * included - since it was built or `resetUsage()` was called. A snapshot (a copy).
1653
+ */
1654
+ readonly usage: IUsage;
1655
+ /** The same for one memory session (default: the agent's `sessionId`). A snapshot. */
1656
+ sessionUsage(sessionId?: string): IUsage;
1657
+ /** Zero the counters (the whole agent and every session). */
1658
+ resetUsage(): void;
1613
1659
  /**
1614
1660
  * The context window the agent fits its runs into: the configured one, never
1615
1661
  * more than the model's own (read from local WebLLM models).
@@ -2380,7 +2426,6 @@ interface SdkUsageLike {
2380
2426
  reasoningTokens?: number;
2381
2427
  cachedInputTokens?: number;
2382
2428
  }
2383
- /** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */
2384
2429
  declare const normalizeUsage: (u?: SdkUsageLike) => IUsage;
2385
2430
 
2386
2431
  /**
@@ -2563,5 +2608,5 @@ declare class IndexedDBRunStore implements RunPersistence {
2563
2608
  clear(): Promise<void>;
2564
2609
  }
2565
2610
 
2566
- export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2611
+ export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, DEFAULT_COMPACTION_THRESHOLD_RATIO, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2567
2612
  export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, EffectiveToolStrategy, EgressErrorCode, EncryptedBlob, ExecutorPromptContext, ExecutorResult, FileToolsOptions, GenerateOptions, GuardedFetch, IEgressPolicy, IPlan, IPlanStep, IResolvedEgressPolicy, IStepResult, IToolCall, IUsage, IWebFetchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MessageEndpoint, ModelInput, ParentToWorker, Phase, PhaseBudgets, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunControl, RunFile, RunImage, RunOptions, RunPersistence, RunResult, RunSnapshot, RunStatus, RunStoreOptions, SaveSkillInput, SearchToolsOptions, ServeSubagentOptions, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StoredMessage, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };
package/dist/index.d.ts CHANGED
@@ -294,8 +294,17 @@ interface CompactionConfig {
294
294
  auto?: boolean;
295
295
  /** The model's context window, in tokens (default 128 000). */
296
296
  contextWindowTokens?: number;
297
- /** Compact once the estimated context exceeds this (default: half the window). */
297
+ /**
298
+ * Compact once the estimated context - the fixed prompt (system, tools, skills), the transcript
299
+ * and the run's step log together - exceeds this many tokens. Default: `thresholdRatio` of the
300
+ * window.
301
+ */
298
302
  thresholdTokens?: number;
303
+ /**
304
+ * The same threshold as a share of the window, 0 < ratio <= 1 (default 0.85). `thresholdTokens`
305
+ * wins when both are set; it follows the window if the model turns out to have a smaller one.
306
+ */
307
+ thresholdRatio?: number;
299
308
  /** Transcript messages kept verbatim (default 4). */
300
309
  keepRecentTurns?: number;
301
310
  /** Executed steps kept verbatim in the run's trace (default 3). */
@@ -317,6 +326,7 @@ interface ResolvedCompaction {
317
326
  auto: boolean;
318
327
  contextWindowTokens: number;
319
328
  thresholdTokens: number;
329
+ thresholdRatio: number;
320
330
  keepRecentTurns: number;
321
331
  keepRecentSteps: number;
322
332
  summaryMaxTokens: number;
@@ -324,8 +334,24 @@ interface ResolvedCompaction {
324
334
  clearToolResultsAfterTokens: number;
325
335
  keepToolResults: number;
326
336
  }
337
+ /**
338
+ * Compaction starts at this share of the window unless configured. The estimate leans high (see
339
+ * `estimateTokens`), so on a Claude model this is roughly 70-75% really used - the rest is room
340
+ * for the answer and for what one step adds before the next check.
341
+ */
342
+ declare const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85;
327
343
  declare const resolveCompaction: (c: CompactionConfig | undefined) => ResolvedCompaction;
328
- /** Cheap, provider-independent token estimate (~4 chars per token). */
344
+ /**
345
+ * Cheap, provider-independent token estimate, by kind of character - because text is not one
346
+ * thing: letters run ~2.5 to a token (prose is kinder; code, markdown and JSON are not), digits
347
+ * and punctuation about one each (JSON, tables, ids), a space a quarter, a newline one, other
348
+ * scripts (Russian...) two characters, CJK and emoji one. Calibrated against Claude's tokenizer,
349
+ * the most token-hungry in use, over prose, markdown, code, JSON, a table, Russian and a mix: it
350
+ * comes out 1.1-1.4x the real count and never below it (a flat "4 characters a token" was
351
+ * 0.4-0.7x for everything but Russian). It errs high ON PURPOSE: it decides when to compact, and
352
+ * compacting a little early is cheap while overflowing the window is a failed run. A tokenizer
353
+ * that packs tighter (OpenAI, Gemini) makes it higher still - then raise `thresholdRatio`.
354
+ */
329
355
  declare const estimateTokens: (text: string) => number;
330
356
  declare const messageTokens: (msgs: StoredMessage[]) => number;
331
357
  interface CompressOptions {
@@ -337,6 +363,12 @@ interface CompressOptions {
337
363
  keepRecent?: number;
338
364
  /** Output cap of the summary call. */
339
365
  summaryMaxTokens?: number;
366
+ /**
367
+ * The most the summariser is shown, in estimated tokens (the newest part is kept). Default: a
368
+ * fixed 48 000 characters. The agent passes a share of the window, so a long transcript is
369
+ * summarised whole instead of cut to its last few pages first.
370
+ */
371
+ maxInputTokens?: number;
340
372
  /** Compact even when below the threshold (manual "compact now"). */
341
373
  force?: boolean;
342
374
  /** Time-box the summarisation call so it can never hang the caller. */
@@ -1075,6 +1107,11 @@ interface ResolvedConfig {
1075
1107
  compaction: ResolvedCompaction;
1076
1108
  logLevel: LogLevel;
1077
1109
  }
1110
+ /**
1111
+ * The effective per-call output caps: what the host set (`limits.perCall`, then the legacy
1112
+ * `budgets`) wins; every other phase gets its share of the window.
1113
+ */
1114
+ declare const resolveBudgets: (c: BrowserAgentConfig, contextWindowTokens: number) => ResolvedConfig["budgets"];
1078
1115
  declare const resolveConfig: (c: BrowserAgentConfig) => ResolvedConfig;
1079
1116
 
1080
1117
  type ReplanMode = 'continue' | 'revise' | 'finish';
@@ -1610,6 +1647,15 @@ interface Agent {
1610
1647
  * count, or its definitions' share of the context window).
1611
1648
  */
1612
1649
  readonly toolStrategy: EffectiveToolStrategy;
1650
+ /**
1651
+ * Tokens this agent has spent - on every run and manual compaction, stopped or failed ones
1652
+ * included - since it was built or `resetUsage()` was called. A snapshot (a copy).
1653
+ */
1654
+ readonly usage: IUsage;
1655
+ /** The same for one memory session (default: the agent's `sessionId`). A snapshot. */
1656
+ sessionUsage(sessionId?: string): IUsage;
1657
+ /** Zero the counters (the whole agent and every session). */
1658
+ resetUsage(): void;
1613
1659
  /**
1614
1660
  * The context window the agent fits its runs into: the configured one, never
1615
1661
  * more than the model's own (read from local WebLLM models).
@@ -2380,7 +2426,6 @@ interface SdkUsageLike {
2380
2426
  reasoningTokens?: number;
2381
2427
  cachedInputTokens?: number;
2382
2428
  }
2383
- /** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */
2384
2429
  declare const normalizeUsage: (u?: SdkUsageLike) => IUsage;
2385
2430
 
2386
2431
  /**
@@ -2563,5 +2608,5 @@ declare class IndexedDBRunStore implements RunPersistence {
2563
2608
  clear(): Promise<void>;
2564
2609
  }
2565
2610
 
2566
- export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2611
+ export { AgentTool, AgentToolSet, AttachmentsNotSupportedError, ContextWindowExceededError, DEFAULT_COMPACTION_THRESHOLD_RATIO, EgressError, FILES_STORE, FIND_TOOLS_NAME, FORGET_SKILL_TOOL, ImagesNotSupportedError, IndexedDBRunStore, IndexedDBStore, KEYS_STORE, MemoryCredentialStore, MemoryRunStore, MemorySkillStore, MemoryStore, PlanSchema, PlanStepSchema, RUNS_STORE, ReplanSchema, SAVE_SKILL_TOOL, SECRETS_STORE, SESSIONS_STORE, SKILL_TOOL_NAMES, TOOL_APPROVAL_MODES, TOOL_SEARCH_WINDOW_SHARE, ToolBudgetError, ToolDeniedError, VaultCredentialStore, VaultOptions, VfsSkillStore, VirtualFileSystem, WEBLLM_DEFAULT_CONTEXT_WINDOW, WEB_FETCH_TOOL, attachmentKind, buildModelFromStage, bytesToBase64, checkEgressUrl, checkLimits, classifyAddress, compactHistory, compactSteps, compressHistory, contextOverflowOf, contextWindowOf, createAgent, createEgressTools, createFileTools, createFindToolsTool, createGuardedFetch, createLearning, createLogger, createPlan, createRunControl, createSkillTools, createSubagentTool, createToolResultClearer, createWebFetchTool, createWebLLMModel, decideReplan, decideToolPermission, decryptJSON, defaultPrompts, defineSkill, defineTool, directBrowserOk, dispatch, encryptJSON, messageTokens as estimateMessagesTokens, estimateTokens, executeStep, findSecret, fitCompactionToWindow, generate, generateStructured, getOrCreateVaultKey, hostMatches, htmlToText, isAttachmentRefusal, isDirectModel, isImageRefusal, isProviderSpec, isReadOnlyTool, isTextMime, isWebGPUAvailable, learnedPreamble, limitModelOutput, loadSkillFromUrl, looksLikeJson, markReadOnly, matchRule, mediaTypeOf, mergeProviderOptions, mimeFromPath, normalizePath, normalizeSkillName, normalizeSteps, normalizeUsage, openAgentWebDB, parseExecutorResponse, parsePlainText, parsePlannerResponse, parseReplannerResponse, parseSkillMarkdown, preloadWebLLMModel, renderActiveSkills, renderCatalog, renderSearchCatalog, renderSkillIndex, replanWanted, resolveBudgets, resolveCaching, resolveCompaction, resolveConfig, resolveEgressPolicy, resolveModel, resolveResume, resolveStage, resolveThinking, runToolLoop, schemaHintOf, searchTools, selectToolMode, serveSubagentWorker, shouldReplan, splitBlocker, stream, supportsImages, supportsNativeTools, supportsPdf, supportsStructuredOutput, synthesizeAnswer, thinkingFor, toFilePart, toImagePart, tokenize, toolCatalogOf, toolDefinitionTokens, toolRunContextOf, unloadWebLLMModel, webLLMContextWindow, withRollingBreakpoint, withSystem, withWebLLMContextWindow };
2567
2612
  export type { Agent, AgentContext, AgentEvent, AgentEventHandler, AgentLogger, AgentLoggerSink, AgentWebDBOptions, AttachmentKind, BrowserAgentConfig, ClearedInfo, CompactOptions, CompactResult, CompactionConfig, CompressOptions, ContextStore, CredentialStore, EffectiveToolStrategy, EgressErrorCode, EncryptedBlob, ExecutorPromptContext, ExecutorResult, FileToolsOptions, GenerateOptions, GuardedFetch, IEgressPolicy, IPlan, IPlanStep, IResolvedEgressPolicy, IStepResult, IToolCall, IUsage, IWebFetchOptions, IndexedDBRunStoreOptions, IndexedDBStoreOptions, Learning, LearningConfig, LimitBreach, LimitKind, LoadSkillOptions, LogLevel, MessageEndpoint, ModelInput, ParentToWorker, Phase, PhaseBudgets, PlanShape, PlannerPromptContext, PlannerResult, PromptCachingSetting, PromptParts, Prompts, ProviderModelSpec, ProviderOptionsMap, ProviderType, ProxiedToolSpec, RawAction, ReplanDecision, ReplanMode, ReplanShape, ReplanTrigger, ReplannerPromptContext, ReplannerResult, ResolvedCaching, ResolvedCompaction, ResolvedConfig, ResolvedStage, ResolvedThinking, RunControl, RunFile, RunImage, RunOptions, RunPersistence, RunResult, RunSnapshot, RunStatus, RunStoreOptions, SaveSkillInput, SearchToolsOptions, ServeSubagentOptions, Skill, SkillOrigin, SkillStore, StageInput, StageOverride, StoredMessage, SubagentInfo, SubagentProfile, SubagentToolOptions, SubagentWorkerConfig, SynthesizerPromptContext, ThinkingConfig, ThinkingLevel, ThinkingSetting, ThinkingStage, TokenLimits, ToolApprovalConfig, ToolApprovalDecision, ToolApprovalMode, ToolApprovalRequest, ToolCallMode, ToolCatalogEntry, ToolLoopCallbacks, ToolLoopOptions, ToolLoopResult, ToolMode, ToolPermission, ToolResultClearing, ToolRunContext, ToolSelectionStrategy, UsagePhase, VfsListener, VirtualFile, VirtualFileInfo, VirtualFileSystemOptions, WebLLMAppConfigLike, WebLLMModelOptions, WorkerLike, WorkerToParent };
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  import {
14
14
  AttachmentsNotSupportedError,
15
15
  ContextWindowExceededError,
16
+ DEFAULT_COMPACTION_THRESHOLD_RATIO,
16
17
  ImagesNotSupportedError,
17
18
  TOOL_SEARCH_WINDOW_SHARE,
18
19
  WEBLLM_DEFAULT_CONTEXT_WINDOW,
@@ -37,6 +38,7 @@ import {
37
38
  normalizeUsage,
38
39
  preloadWebLLMModel,
39
40
  promptOf,
41
+ promptOverheadTokens,
40
42
  resolveCompaction,
41
43
  stream,
42
44
  timeoutSignal,
@@ -45,9 +47,10 @@ import {
45
47
  toolDefinitionTokens,
46
48
  unloadWebLLMModel,
47
49
  unsupportedAttachment,
50
+ usageOfError,
48
51
  webLLMContextWindow,
49
52
  withWebLLMContextWindow
50
- } from "./chunk-YA6TQQ3Q.js";
53
+ } from "./chunk-Y7OGKYE5.js";
51
54
 
52
55
  // src/caching.ts
53
56
  var resolveCaching = (s) => {
@@ -93,6 +96,22 @@ var withRollingBreakpoint = (messages, caching) => {
93
96
  };
94
97
 
95
98
  // src/config.ts
99
+ var BUDGET_SHARES = {
100
+ planner: { num: 1, den: 160, min: 256, max: 2e3 },
101
+ executor: { num: 3, den: 320, min: 384, max: 8192 },
102
+ replanner: { num: 1, den: 320, min: 192, max: 1500 },
103
+ synthesizer: { num: 3, den: 128, min: 512, max: 8192 },
104
+ compaction: { num: 1, den: 125, min: 256, max: 4096 }
105
+ };
106
+ var share = (window, s) => Math.min(s.max, Math.max(s.min, Math.round(window * s.num / s.den)));
107
+ var resolveBudgets = (c, contextWindowTokens) => ({
108
+ planner: c.limits?.perCall?.planner ?? c.budgets?.planner ?? share(contextWindowTokens, BUDGET_SHARES.planner),
109
+ executor: c.limits?.perCall?.executor ?? c.budgets?.executor ?? share(contextWindowTokens, BUDGET_SHARES.executor),
110
+ replanner: c.limits?.perCall?.replanner ?? c.budgets?.replanner ?? share(contextWindowTokens, BUDGET_SHARES.replanner),
111
+ // The final answer is the one call whose text the user reads: 400 cut a normal answer short.
112
+ synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? share(contextWindowTokens, BUDGET_SHARES.synthesizer),
113
+ compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? share(contextWindowTokens, BUDGET_SHARES.compaction)
114
+ });
96
115
  var resolveConfig = (c) => ({
97
116
  clientName: c.clientName ?? "agent-web",
98
117
  sessionId: c.sessionId ?? "default",
@@ -105,13 +124,7 @@ var resolveConfig = (c) => ({
105
124
  maxToolCalls: c.maxToolCalls ?? 0,
106
125
  maxPlanSteps: c.maxPlanSteps ?? 8,
107
126
  chatTimeoutMs: c.chatTimeoutMs ?? 12e4,
108
- budgets: {
109
- planner: c.limits?.perCall?.planner ?? c.budgets?.planner ?? 800,
110
- executor: c.limits?.perCall?.executor ?? c.budgets?.executor ?? 1200,
111
- replanner: c.limits?.perCall?.replanner ?? c.budgets?.replanner ?? 400,
112
- synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? 400,
113
- compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? 1024
114
- },
127
+ budgets: resolveBudgets(c, resolveCompaction(c.compaction).contextWindowTokens),
115
128
  limits: c.limits ?? {},
116
129
  temperature: c.temperature,
117
130
  replan: c.replan ?? true,
@@ -255,7 +268,7 @@ var buildModelFromStage = async (resolved, credentials, clientName = "agent-web"
255
268
  const apiKey = await resolveApiKey(spec, credentials);
256
269
  switch (spec.providerType) {
257
270
  case "web-llm": {
258
- const { createWebLLMModel: createWebLLMModel2 } = await import("./webllm-QTJ3EGTG.js");
271
+ const { createWebLLMModel: createWebLLMModel2 } = await import("./webllm-PCPDLDQA.js");
259
272
  return createWebLLMModel2(spec.model, providerOptions);
260
273
  }
261
274
  case "gateway": {
@@ -2660,6 +2673,7 @@ ${nudge}` : goal;
2660
2673
  }
2661
2674
  return kept;
2662
2675
  };
2676
+ let wasted = normalizeUsage();
2663
2677
  if (ctx.plannerMode === "native") {
2664
2678
  try {
2665
2679
  const result2 = await generateStructured(ctx.plannerModel, PlanSchema, commonFor("native"));
@@ -2675,6 +2689,7 @@ ${nudge}` : goal;
2675
2689
  if (refused) throw refused;
2676
2690
  const overflow = contextOverflowOf(err, ctx.plannerModel);
2677
2691
  if (overflow) throw overflow;
2692
+ wasted = usageOfError(err);
2678
2693
  ctx.log.warn("planner: native structured output failed, salvaging:", asMessage(err));
2679
2694
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: asMessage(err) });
2680
2695
  }
@@ -2693,7 +2708,7 @@ ${nudge}` : goal;
2693
2708
  cap
2694
2709
  )
2695
2710
  },
2696
- usage: normalizeUsage(result.usage),
2711
+ usage: addUsage(wasted, normalizeUsage(result.usage)),
2697
2712
  skills: validSkills(parsed.skills)
2698
2713
  };
2699
2714
  };
@@ -2723,6 +2738,7 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2723
2738
  timeoutMs: ctx.config.chatTimeoutMs
2724
2739
  };
2725
2740
  };
2741
+ let wasted = normalizeUsage();
2726
2742
  if (ctx.plannerMode === "native") {
2727
2743
  try {
2728
2744
  const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
@@ -2732,7 +2748,8 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2732
2748
  plan: result.object.plan ?? [],
2733
2749
  usage: normalizeUsage(result.usage)
2734
2750
  };
2735
- } catch {
2751
+ } catch (err) {
2752
+ wasted = usageOfError(err);
2736
2753
  }
2737
2754
  }
2738
2755
  try {
@@ -2742,10 +2759,10 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2742
2759
  decision: parsed.decision,
2743
2760
  reason: parsed.reason,
2744
2761
  plan: parsed.plan,
2745
- usage: normalizeUsage(result.usage)
2762
+ usage: addUsage(wasted, normalizeUsage(result.usage))
2746
2763
  };
2747
2764
  } catch {
2748
- return { decision: "continue", reason: "replanner unavailable", plan: [], usage: emptyUsage() };
2765
+ return { decision: "continue", reason: "replanner unavailable", plan: [], usage: wasted };
2749
2766
  }
2750
2767
  };
2751
2768
 
@@ -2901,6 +2918,7 @@ var createAgent = async (config) => {
2901
2918
  const modelWindows = [executorModel, plannerModel, synthesizerModel].map(contextWindowOf).filter((w) => w !== void 0);
2902
2919
  const modelWindow = modelWindows.length ? Math.min(...modelWindows) : void 0;
2903
2920
  cfg.compaction = fitCompactionToWindow(cfg.compaction, config.compaction, modelWindow);
2921
+ cfg.budgets = resolveBudgets(config, cfg.compaction.contextWindowTokens);
2904
2922
  const byTokens = Boolean(config.compaction) || modelWindow !== void 0;
2905
2923
  const log = createLogger(cfg.logLevel, config.logger);
2906
2924
  const skills = (config.skills ?? []).map(defineSkill);
@@ -2923,7 +2941,8 @@ var createAgent = async (config) => {
2923
2941
  config.excludedTools
2924
2942
  );
2925
2943
  const catalog = toolCatalogOf(baseTools);
2926
- const toolTokens = cfg.toolSelectionStrategy === "auto" ? await toolDefinitionTokens(baseTools) : 0;
2944
+ const toolDefTokens = await toolDefinitionTokens(baseTools);
2945
+ const toolTokens = cfg.toolSelectionStrategy === "auto" ? toolDefTokens : 0;
2927
2946
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
2928
2947
  const reserved = [
2929
2948
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
@@ -2937,6 +2956,14 @@ var createAgent = async (config) => {
2937
2956
  }
2938
2957
  }
2939
2958
  const builtinTools = new Set(reserved);
2959
+ const fixedPromptTokens = (active) => promptOverheadTokens({
2960
+ systemPrompt: config.systemPrompt,
2961
+ toolTokens: toolDefTokens,
2962
+ searching: strategy === "search",
2963
+ skillsText: `${renderSkillIndex(skills)}
2964
+ ${renderActiveSkills(active)}`
2965
+ });
2966
+ const summaryInputTokens = Math.floor(cfg.compaction.contextWindowTokens * 0.6);
2940
2967
  const hints = /* @__PURE__ */ new Map();
2941
2968
  await Promise.all(
2942
2969
  Object.entries(baseTools).map(async ([name, t]) => {
@@ -2959,6 +2986,12 @@ var createAgent = async (config) => {
2959
2986
  log.info(
2960
2987
  `agent ready \u2014 ${catalog.length} tool(s) (${strategy}, ~${toolTokens || "?"} tokens), window ${cfg.compaction.contextWindowTokens}${modelWindow ? " (the model\u2019s)" : ""}, skills: [${skills.map((s) => s.name).join(", ") || "none"}], planner mode: ${plannerMode}, executor mode: ${executorMode}, approval: ${approval.mode}`
2961
2988
  );
2989
+ let spentAll = emptyUsage();
2990
+ const spentBySession = /* @__PURE__ */ new Map();
2991
+ const charge = (sessionId, u) => {
2992
+ spentAll = addUsage(spentAll, u);
2993
+ spentBySession.set(sessionId, addUsage(spentBySession.get(sessionId) ?? emptyUsage(), u));
2994
+ };
2962
2995
  const runCore = async (goal, opts, track, port) => {
2963
2996
  const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
2964
2997
  const emit = (event) => {
@@ -2989,6 +3022,7 @@ var createAgent = async (config) => {
2989
3022
  const isAborted = () => opts.signal?.aborted === true;
2990
3023
  const bumpUsage = (u, phase) => {
2991
3024
  usage = addUsage(usage, u);
3025
+ charge(sessionId, u);
2992
3026
  result.usage = usage;
2993
3027
  emit({ type: "usage", phase, usage: u });
2994
3028
  };
@@ -3104,11 +3138,13 @@ var createAgent = async (config) => {
3104
3138
  }
3105
3139
  if (config.memory && byTokens && cfg.compaction.auto && history.length > 0) {
3106
3140
  const before = messageTokens(history);
3107
- if (before > cfg.compaction.thresholdTokens) {
3141
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3142
+ if (before + fixed > cfg.compaction.thresholdTokens) {
3108
3143
  const compacted = await compressHistory(history, synthesizerModel, {
3109
- thresholdTokens: cfg.compaction.thresholdTokens,
3144
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3110
3145
  keepRecent: cfg.compaction.keepRecentTurns,
3111
3146
  summaryMaxTokens: cfg.budgets.compaction,
3147
+ maxInputTokens: summaryInputTokens,
3112
3148
  timeoutMs: cfg.chatTimeoutMs,
3113
3149
  abortSignal: opts.signal,
3114
3150
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3319,11 +3355,16 @@ var createAgent = async (config) => {
3319
3355
  while (findings.join("\n").length > FINDINGS_BUDGET && findings.length > 1) findings.shift();
3320
3356
  if (cfg.compaction.auto) {
3321
3357
  const before = estimateTokens(done.join("\n"));
3322
- if (before > cfg.compaction.thresholdTokens) {
3358
+ const room = Math.max(
3359
+ 1,
3360
+ cfg.compaction.thresholdTokens - fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name))) - messageTokens(history)
3361
+ );
3362
+ if (before > room) {
3323
3363
  const compacted = await compactSteps(done, synthesizerModel, {
3324
- thresholdTokens: cfg.compaction.thresholdTokens,
3364
+ thresholdTokens: room,
3325
3365
  keepRecent: cfg.compaction.keepRecentSteps,
3326
3366
  summaryMaxTokens: cfg.budgets.compaction,
3367
+ maxInputTokens: summaryInputTokens,
3327
3368
  timeoutMs: cfg.chatTimeoutMs,
3328
3369
  abortSignal: opts.signal,
3329
3370
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3406,11 +3447,13 @@ var createAgent = async (config) => {
3406
3447
  try {
3407
3448
  const transcript = await config.memory.load(sessionId);
3408
3449
  const before = messageTokens(transcript);
3450
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3409
3451
  const compacted = await compressHistory(transcript, synthesizerModel, {
3410
3452
  ...byTokens ? {
3411
- thresholdTokens: cfg.compaction.thresholdTokens,
3453
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3412
3454
  keepRecent: cfg.compaction.keepRecentTurns,
3413
- summaryMaxTokens: cfg.budgets.compaction
3455
+ summaryMaxTokens: cfg.budgets.compaction,
3456
+ maxInputTokens: summaryInputTokens
3414
3457
  } : { maxChars: cfg.compressAfterChars },
3415
3458
  timeoutMs: cfg.chatTimeoutMs,
3416
3459
  abortSignal: opts.signal,
@@ -3469,11 +3512,13 @@ var createAgent = async (config) => {
3469
3512
  thresholdTokens: cfg.compaction.thresholdTokens,
3470
3513
  keepRecent: cfg.compaction.keepRecentTurns,
3471
3514
  summaryMaxTokens: cfg.budgets.compaction,
3515
+ maxInputTokens: summaryInputTokens,
3472
3516
  force: o.force ?? true,
3473
3517
  timeoutMs: cfg.chatTimeoutMs,
3474
3518
  abortSignal: o.signal,
3475
3519
  onUsage: (u) => {
3476
3520
  usage = addUsage(usage, u);
3521
+ charge(sessionId, u);
3477
3522
  }
3478
3523
  });
3479
3524
  if (compacted === transcript)
@@ -3496,6 +3541,16 @@ var createAgent = async (config) => {
3496
3541
  },
3497
3542
  listTools: () => catalog.map((e) => ({ ...e })),
3498
3543
  toolStrategy: strategy,
3544
+ get usage() {
3545
+ return { ...spentAll };
3546
+ },
3547
+ sessionUsage: (sessionId) => ({
3548
+ ...spentBySession.get(sessionId ?? cfg.sessionId) ?? emptyUsage()
3549
+ }),
3550
+ resetUsage: () => {
3551
+ spentAll = emptyUsage();
3552
+ spentBySession.clear();
3553
+ },
3499
3554
  contextWindowTokens: cfg.compaction.contextWindowTokens,
3500
3555
  get skills() {
3501
3556
  return skills.map((s) => ({
@@ -4321,6 +4376,7 @@ var IndexedDBRunStore = class {
4321
4376
  export {
4322
4377
  AttachmentsNotSupportedError,
4323
4378
  ContextWindowExceededError,
4379
+ DEFAULT_COMPACTION_THRESHOLD_RATIO,
4324
4380
  EgressError,
4325
4381
  FILES_STORE,
4326
4382
  FIND_TOOLS_NAME,
@@ -4428,6 +4484,7 @@ export {
4428
4484
  renderSearchCatalog,
4429
4485
  renderSkillIndex,
4430
4486
  replanWanted,
4487
+ resolveBudgets,
4431
4488
  resolveCaching,
4432
4489
  resolveCompaction,
4433
4490
  resolveConfig,