@dudko.dev/agent-web 0.0.31 → 0.0.33

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';
@@ -1268,7 +1305,6 @@ type AgentEvent =
1268
1305
  error: string;
1269
1306
  stopped?: boolean;
1270
1307
  }
1271
- /** A message sent with `RunControl.send` is waiting for the next boundary. */
1272
1308
  /**
1273
1309
  * A request of the `web_fetch` tool, allowed or refused by the egress policy. `url` is origin and
1274
1310
  * path only (a query string can carry a secret).
@@ -1279,7 +1315,9 @@ type AgentEvent =
1279
1315
  allowed: boolean;
1280
1316
  status?: number;
1281
1317
  reason?: string;
1282
- } | {
1318
+ }
1319
+ /** A message sent with `RunControl.send` is waiting for the next boundary. */
1320
+ | {
1283
1321
  type: 'message.queued';
1284
1322
  id: string;
1285
1323
  text: string;
@@ -1610,6 +1648,15 @@ interface Agent {
1610
1648
  * count, or its definitions' share of the context window).
1611
1649
  */
1612
1650
  readonly toolStrategy: EffectiveToolStrategy;
1651
+ /**
1652
+ * Tokens this agent has spent - on every run and manual compaction, stopped or failed ones
1653
+ * included - since it was built or `resetUsage()` was called. A snapshot (a copy).
1654
+ */
1655
+ readonly usage: IUsage;
1656
+ /** The same for one memory session (default: the agent's `sessionId`). A snapshot. */
1657
+ sessionUsage(sessionId?: string): IUsage;
1658
+ /** Zero the counters (the whole agent and every session). */
1659
+ resetUsage(): void;
1613
1660
  /**
1614
1661
  * The context window the agent fits its runs into: the configured one, never
1615
1662
  * more than the model's own (read from local WebLLM models).
@@ -2380,7 +2427,6 @@ interface SdkUsageLike {
2380
2427
  reasoningTokens?: number;
2381
2428
  cachedInputTokens?: number;
2382
2429
  }
2383
- /** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */
2384
2430
  declare const normalizeUsage: (u?: SdkUsageLike) => IUsage;
2385
2431
 
2386
2432
  /**
@@ -2563,5 +2609,5 @@ declare class IndexedDBRunStore implements RunPersistence {
2563
2609
  clear(): Promise<void>;
2564
2610
  }
2565
2611
 
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 };
2612
+ 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
2613
  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';
@@ -1268,7 +1305,6 @@ type AgentEvent =
1268
1305
  error: string;
1269
1306
  stopped?: boolean;
1270
1307
  }
1271
- /** A message sent with `RunControl.send` is waiting for the next boundary. */
1272
1308
  /**
1273
1309
  * A request of the `web_fetch` tool, allowed or refused by the egress policy. `url` is origin and
1274
1310
  * path only (a query string can carry a secret).
@@ -1279,7 +1315,9 @@ type AgentEvent =
1279
1315
  allowed: boolean;
1280
1316
  status?: number;
1281
1317
  reason?: string;
1282
- } | {
1318
+ }
1319
+ /** A message sent with `RunControl.send` is waiting for the next boundary. */
1320
+ | {
1283
1321
  type: 'message.queued';
1284
1322
  id: string;
1285
1323
  text: string;
@@ -1610,6 +1648,15 @@ interface Agent {
1610
1648
  * count, or its definitions' share of the context window).
1611
1649
  */
1612
1650
  readonly toolStrategy: EffectiveToolStrategy;
1651
+ /**
1652
+ * Tokens this agent has spent - on every run and manual compaction, stopped or failed ones
1653
+ * included - since it was built or `resetUsage()` was called. A snapshot (a copy).
1654
+ */
1655
+ readonly usage: IUsage;
1656
+ /** The same for one memory session (default: the agent's `sessionId`). A snapshot. */
1657
+ sessionUsage(sessionId?: string): IUsage;
1658
+ /** Zero the counters (the whole agent and every session). */
1659
+ resetUsage(): void;
1613
1660
  /**
1614
1661
  * The context window the agent fits its runs into: the configured one, never
1615
1662
  * more than the model's own (read from local WebLLM models).
@@ -2380,7 +2427,6 @@ interface SdkUsageLike {
2380
2427
  reasoningTokens?: number;
2381
2428
  cachedInputTokens?: number;
2382
2429
  }
2383
- /** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */
2384
2430
  declare const normalizeUsage: (u?: SdkUsageLike) => IUsage;
2385
2431
 
2386
2432
  /**
@@ -2563,5 +2609,5 @@ declare class IndexedDBRunStore implements RunPersistence {
2563
2609
  clear(): Promise<void>;
2564
2610
  }
2565
2611
 
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 };
2612
+ 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
2613
  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,14 +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
- // The final answer is the one call whose text the user reads: 400 cut a normal answer short.
113
- synthesizer: c.limits?.perCall?.synthesizer ?? c.budgets?.synthesizer ?? 3e3,
114
- compaction: c.limits?.perCall?.compaction ?? c.compaction?.summaryMaxTokens ?? 1024
115
- },
127
+ budgets: resolveBudgets(c, resolveCompaction(c.compaction).contextWindowTokens),
116
128
  limits: c.limits ?? {},
117
129
  temperature: c.temperature,
118
130
  replan: c.replan ?? true,
@@ -256,7 +268,7 @@ var buildModelFromStage = async (resolved, credentials, clientName = "agent-web"
256
268
  const apiKey = await resolveApiKey(spec, credentials);
257
269
  switch (spec.providerType) {
258
270
  case "web-llm": {
259
- const { createWebLLMModel: createWebLLMModel2 } = await import("./webllm-QTJ3EGTG.js");
271
+ const { createWebLLMModel: createWebLLMModel2 } = await import("./webllm-PCPDLDQA.js");
260
272
  return createWebLLMModel2(spec.model, providerOptions);
261
273
  }
262
274
  case "gateway": {
@@ -2661,6 +2673,7 @@ ${nudge}` : goal;
2661
2673
  }
2662
2674
  return kept;
2663
2675
  };
2676
+ let wasted = normalizeUsage();
2664
2677
  if (ctx.plannerMode === "native") {
2665
2678
  try {
2666
2679
  const result2 = await generateStructured(ctx.plannerModel, PlanSchema, commonFor("native"));
@@ -2676,6 +2689,7 @@ ${nudge}` : goal;
2676
2689
  if (refused) throw refused;
2677
2690
  const overflow = contextOverflowOf(err, ctx.plannerModel);
2678
2691
  if (overflow) throw overflow;
2692
+ wasted = usageOfError(err);
2679
2693
  ctx.log.warn("planner: native structured output failed, salvaging:", asMessage(err));
2680
2694
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: asMessage(err) });
2681
2695
  }
@@ -2694,7 +2708,7 @@ ${nudge}` : goal;
2694
2708
  cap
2695
2709
  )
2696
2710
  },
2697
- usage: normalizeUsage(result.usage),
2711
+ usage: addUsage(wasted, normalizeUsage(result.usage)),
2698
2712
  skills: validSkills(parsed.skills)
2699
2713
  };
2700
2714
  };
@@ -2724,6 +2738,7 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2724
2738
  timeoutMs: ctx.config.chatTimeoutMs
2725
2739
  };
2726
2740
  };
2741
+ let wasted = normalizeUsage();
2727
2742
  if (ctx.plannerMode === "native") {
2728
2743
  try {
2729
2744
  const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
@@ -2733,7 +2748,8 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2733
2748
  plan: result.object.plan ?? [],
2734
2749
  usage: normalizeUsage(result.usage)
2735
2750
  };
2736
- } catch {
2751
+ } catch (err) {
2752
+ wasted = usageOfError(err);
2737
2753
  }
2738
2754
  }
2739
2755
  try {
@@ -2743,10 +2759,10 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
2743
2759
  decision: parsed.decision,
2744
2760
  reason: parsed.reason,
2745
2761
  plan: parsed.plan,
2746
- usage: normalizeUsage(result.usage)
2762
+ usage: addUsage(wasted, normalizeUsage(result.usage))
2747
2763
  };
2748
2764
  } catch {
2749
- return { decision: "continue", reason: "replanner unavailable", plan: [], usage: emptyUsage() };
2765
+ return { decision: "continue", reason: "replanner unavailable", plan: [], usage: wasted };
2750
2766
  }
2751
2767
  };
2752
2768
 
@@ -2902,6 +2918,7 @@ var createAgent = async (config) => {
2902
2918
  const modelWindows = [executorModel, plannerModel, synthesizerModel].map(contextWindowOf).filter((w) => w !== void 0);
2903
2919
  const modelWindow = modelWindows.length ? Math.min(...modelWindows) : void 0;
2904
2920
  cfg.compaction = fitCompactionToWindow(cfg.compaction, config.compaction, modelWindow);
2921
+ cfg.budgets = resolveBudgets(config, cfg.compaction.contextWindowTokens);
2905
2922
  const byTokens = Boolean(config.compaction) || modelWindow !== void 0;
2906
2923
  const log = createLogger(cfg.logLevel, config.logger);
2907
2924
  const skills = (config.skills ?? []).map(defineSkill);
@@ -2924,7 +2941,8 @@ var createAgent = async (config) => {
2924
2941
  config.excludedTools
2925
2942
  );
2926
2943
  const catalog = toolCatalogOf(baseTools);
2927
- const toolTokens = cfg.toolSelectionStrategy === "auto" ? await toolDefinitionTokens(baseTools) : 0;
2944
+ const toolDefTokens = await toolDefinitionTokens(baseTools);
2945
+ const toolTokens = cfg.toolSelectionStrategy === "auto" ? toolDefTokens : 0;
2928
2946
  const strategy = cfg.toolSelectionStrategy === "auto" ? catalog.length > cfg.toolSearchThreshold || toolTokens > cfg.compaction.contextWindowTokens * TOOL_SEARCH_WINDOW_SHARE ? "search" : "all" : cfg.toolSelectionStrategy;
2929
2947
  const reserved = [
2930
2948
  ...skills.length || learning ? SKILL_TOOL_NAMES : [],
@@ -2938,6 +2956,14 @@ var createAgent = async (config) => {
2938
2956
  }
2939
2957
  }
2940
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);
2941
2967
  const hints = /* @__PURE__ */ new Map();
2942
2968
  await Promise.all(
2943
2969
  Object.entries(baseTools).map(async ([name, t]) => {
@@ -2960,6 +2986,12 @@ var createAgent = async (config) => {
2960
2986
  log.info(
2961
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}`
2962
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
+ };
2963
2995
  const runCore = async (goal, opts, track, port) => {
2964
2996
  const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
2965
2997
  const emit = (event) => {
@@ -2990,6 +3022,7 @@ var createAgent = async (config) => {
2990
3022
  const isAborted = () => opts.signal?.aborted === true;
2991
3023
  const bumpUsage = (u, phase) => {
2992
3024
  usage = addUsage(usage, u);
3025
+ charge(sessionId, u);
2993
3026
  result.usage = usage;
2994
3027
  emit({ type: "usage", phase, usage: u });
2995
3028
  };
@@ -3105,11 +3138,13 @@ var createAgent = async (config) => {
3105
3138
  }
3106
3139
  if (config.memory && byTokens && cfg.compaction.auto && history.length > 0) {
3107
3140
  const before = messageTokens(history);
3108
- if (before > cfg.compaction.thresholdTokens) {
3141
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3142
+ if (before + fixed > cfg.compaction.thresholdTokens) {
3109
3143
  const compacted = await compressHistory(history, synthesizerModel, {
3110
- thresholdTokens: cfg.compaction.thresholdTokens,
3144
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3111
3145
  keepRecent: cfg.compaction.keepRecentTurns,
3112
3146
  summaryMaxTokens: cfg.budgets.compaction,
3147
+ maxInputTokens: summaryInputTokens,
3113
3148
  timeoutMs: cfg.chatTimeoutMs,
3114
3149
  abortSignal: opts.signal,
3115
3150
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3320,11 +3355,16 @@ var createAgent = async (config) => {
3320
3355
  while (findings.join("\n").length > FINDINGS_BUDGET && findings.length > 1) findings.shift();
3321
3356
  if (cfg.compaction.auto) {
3322
3357
  const before = estimateTokens(done.join("\n"));
3323
- 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) {
3324
3363
  const compacted = await compactSteps(done, synthesizerModel, {
3325
- thresholdTokens: cfg.compaction.thresholdTokens,
3364
+ thresholdTokens: room,
3326
3365
  keepRecent: cfg.compaction.keepRecentSteps,
3327
3366
  summaryMaxTokens: cfg.budgets.compaction,
3367
+ maxInputTokens: summaryInputTokens,
3328
3368
  timeoutMs: cfg.chatTimeoutMs,
3329
3369
  abortSignal: opts.signal,
3330
3370
  onUsage: (u) => bumpUsage(u, "compact")
@@ -3407,11 +3447,13 @@ var createAgent = async (config) => {
3407
3447
  try {
3408
3448
  const transcript = await config.memory.load(sessionId);
3409
3449
  const before = messageTokens(transcript);
3450
+ const fixed = fixedPromptTokens(skills.filter((s) => activeSkillNames.has(s.name)));
3410
3451
  const compacted = await compressHistory(transcript, synthesizerModel, {
3411
3452
  ...byTokens ? {
3412
- thresholdTokens: cfg.compaction.thresholdTokens,
3453
+ thresholdTokens: Math.max(1, cfg.compaction.thresholdTokens - fixed),
3413
3454
  keepRecent: cfg.compaction.keepRecentTurns,
3414
- summaryMaxTokens: cfg.budgets.compaction
3455
+ summaryMaxTokens: cfg.budgets.compaction,
3456
+ maxInputTokens: summaryInputTokens
3415
3457
  } : { maxChars: cfg.compressAfterChars },
3416
3458
  timeoutMs: cfg.chatTimeoutMs,
3417
3459
  abortSignal: opts.signal,
@@ -3470,11 +3512,13 @@ var createAgent = async (config) => {
3470
3512
  thresholdTokens: cfg.compaction.thresholdTokens,
3471
3513
  keepRecent: cfg.compaction.keepRecentTurns,
3472
3514
  summaryMaxTokens: cfg.budgets.compaction,
3515
+ maxInputTokens: summaryInputTokens,
3473
3516
  force: o.force ?? true,
3474
3517
  timeoutMs: cfg.chatTimeoutMs,
3475
3518
  abortSignal: o.signal,
3476
3519
  onUsage: (u) => {
3477
3520
  usage = addUsage(usage, u);
3521
+ charge(sessionId, u);
3478
3522
  }
3479
3523
  });
3480
3524
  if (compacted === transcript)
@@ -3497,6 +3541,16 @@ var createAgent = async (config) => {
3497
3541
  },
3498
3542
  listTools: () => catalog.map((e) => ({ ...e })),
3499
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
+ },
3500
3554
  contextWindowTokens: cfg.compaction.contextWindowTokens,
3501
3555
  get skills() {
3502
3556
  return skills.map((s) => ({
@@ -4322,6 +4376,7 @@ var IndexedDBRunStore = class {
4322
4376
  export {
4323
4377
  AttachmentsNotSupportedError,
4324
4378
  ContextWindowExceededError,
4379
+ DEFAULT_COMPACTION_THRESHOLD_RATIO,
4325
4380
  EgressError,
4326
4381
  FILES_STORE,
4327
4382
  FIND_TOOLS_NAME,
@@ -4429,6 +4484,7 @@ export {
4429
4484
  renderSearchCatalog,
4430
4485
  renderSkillIndex,
4431
4486
  replanWanted,
4487
+ resolveBudgets,
4432
4488
  resolveCaching,
4433
4489
  resolveCompaction,
4434
4490
  resolveConfig,