@caupulican/pi-adaptative 0.93.15 → 0.93.16
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/CHANGELOG.md +7 -0
- package/dist/core/agent-session-contracts.d.ts +2 -2
- package/dist/core/agent-session-contracts.d.ts.map +1 -1
- package/dist/core/agent-session-contracts.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +4 -1
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +46 -16
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +1 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +13 -1
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/modes/json-event-projection.d.ts +4 -0
- package/dist/modes/json-event-projection.d.ts.map +1 -0
- package/dist/modes/json-event-projection.js +44 -0
- package/dist/modes/json-event-projection.js.map +1 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +2 -1
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +2 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/docs/json.md +5 -3
- package/docs/rpc.md +7 -7
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
## [0.93.16] - 2026-08-20
|
|
2
|
+
|
|
3
|
+
### Fixed
|
|
4
|
+
|
|
5
|
+
- Recovered repeated xAI retained-history token-generation failures after one unchanged retry by performing one bounded provider-recovery compaction and continuing the same foreground run.
|
|
6
|
+
- Prevented print/RPC JSON streams from repeating the complete accumulated assistant prefix on every delta, which could turn one long response into gigabytes of output; streaming records now stay below 50 KiB and the terminal event remains authoritative.
|
|
7
|
+
|
|
1
8
|
## [0.93.15] - 2026-08-20
|
|
2
9
|
|
|
3
10
|
## [0.93.14] - 2026-08-20
|
|
@@ -30,7 +30,7 @@ export type AgentSessionEvent = Exclude<AgentEvent, {
|
|
|
30
30
|
commands: readonly string[];
|
|
31
31
|
} | {
|
|
32
32
|
type: "compaction_start";
|
|
33
|
-
reason: "manual" | "threshold" | "overflow";
|
|
33
|
+
reason: "manual" | "threshold" | "overflow" | "provider_recovery";
|
|
34
34
|
} | {
|
|
35
35
|
type: "session_info_changed";
|
|
36
36
|
name: string | undefined;
|
|
@@ -45,7 +45,7 @@ export type AgentSessionEvent = Exclude<AgentEvent, {
|
|
|
45
45
|
tasks: readonly BackgroundToolTaskLiveView[];
|
|
46
46
|
} | {
|
|
47
47
|
type: "compaction_end";
|
|
48
|
-
reason: "manual" | "threshold" | "overflow";
|
|
48
|
+
reason: "manual" | "threshold" | "overflow" | "provider_recovery";
|
|
49
49
|
result: CompactionResult | undefined;
|
|
50
50
|
aborted: boolean;
|
|
51
51
|
willRetry: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-contracts.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-contracts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,KAAK,EACL,UAAU,EACV,eAAe,EACf,YAAY,EACZ,kBAAkB,EAClB,SAAS,EACT,iBAAiB,EACjB,aAAa,EACb,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACvF,OAAO,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,YA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AG,eAAe,CAAC;AACzD,MAAM,CAAC,MAAM,wBAAwB,GAAG,cAAc,CAAC;AACvD,MAAM,CAAC,MAAM,sCAAsC,GAAG,4BAA4B,CAAC;AA0EnF,MAAM,CAAC,MAAM,0BAA0B,GAAG,UAAU,CAAC;AAErD,MAAM,UAAU,sBAAsB,CAAC,QAAgB,EAAE,KAA6B,EAAE,YAAoB;IAC3G,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;IAC3E,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC;SACjC,MAAM,CAAC,CAAC,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAChF,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACf,OAAO,QAAQ,QAAQ,IAAI,MAAM,EAAE,CAAC;AACrC,CAAC;AAuCD,oGAAoG;AACpG,MAAM,UAAU,gCAAgC,CAAC,UAAkC;IAClF,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,OAAO,CAAC;AAC3D,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentMessageOrigin,\n\tAgentTool,\n\tStreamIdleOptions,\n\tThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { CompactionResult, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, CacheRetention, ImageContent, Message, Model, StopReason, Usage } from \"@caupulican/pi-ai\";\nimport type { LaneRecord, LaneTerminalStatus } from \"./autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskLiveView } from \"./background-tool-task-controller.ts\";\nimport type { WorkerRunOutcome } from \"./delegation/worker-runner.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionErrorListener,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tInputSource,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { GoalContinuationPrompt } from \"./goals/goal-continuation-prompt.ts\";\nimport type { GoalRuntimeSnapshot } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { LocalRuntimeDeps } from \"./models/local-runtime.ts\";\nimport type { OrchestrationProfile } from \"./orchestration/contracts.ts\";\nimport type { ResearchRunResult } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { ResourceProfileFilterSettings, SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolArgumentValidationStats } from \"./tool-recovery-stats.ts\";\n\nexport { type ParsedSkillBlock, parseSkillBlock } from \"./skill-block.mjs\";\n\n/** Session-specific events that extend the core AgentEvent. */\nexport type AgentSessionEvent =\n\t| Exclude<AgentEvent, { type: \"agent_end\" }>\n\t| { type: \"agent_end\"; messages: AgentMessage[]; willRetry: boolean }\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t\t\tcommands: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\" }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"warning\"; message: string }\n\t| { type: \"background_tools\"; tasks: readonly BackgroundToolTaskLiveView[] }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t\t\t/** Benign no-op explanation when compaction did not produce a result. */\n\t\t\tskipReason?: string;\n\t }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t/** UI-only bracket around foreground routing/preparation. Always paired with `routing_end`. */\n\t| { type: \"routing_start\" }\n\t| { type: \"routing_end\" }\n\t| {\n\t\t\ttype: \"delegate_workers\";\n\t\t\tactive: number;\n\t\t\tqueued: number;\n\t\t\trunning: number;\n\t\t\tcompletedSinceFlush: number;\n\t\t\tfailedSinceFlush: number;\n\t\t\t/** partial, blocked, and canceled terminals — needs parent review, not a harness failure. */\n\t\t\tattentionSinceFlush: number;\n\t\t\tterminalSinceFlush: Array<{ laneId: string; status: LaneTerminalStatus; reasonCode?: string }>;\n\t };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\t/** User-level agent state directory for generated runtime artifacts. */\n\tagentDir?: string;\n\t/** Models available to the interactive model-cycle action. */\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tresourceLoader: ResourceLoader;\n\t/** SDK tools registered outside extensions. */\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\t/** Initial active tool names before profile and UAC filtering. */\n\tinitialActiveToolNames?: string[];\n\t/** Optional tool allowlist. */\n\tallowedToolNames?: string[];\n\t/** Optional tool denylist. */\n\texcludedToolNames?: string[];\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Preserve an explicit launch-time model across profile reloads. */\n\tisExplicitModel?: boolean;\n\t/** Preserve an explicit launch-time thinking level across profile reloads. */\n\tisExplicitThinking?: boolean;\n\t/** Child sessions receive the worker UAC and write ceilings. */\n\tisChildSession?: boolean;\n\t/** Alternate base tool instances for embedded/custom runtimes. */\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\t/** Mutable bridge used by the agent loop to reach the current extension generation. */\n\textensionRunnerRef?: { current?: ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Injectable pointer-first workspace collector; tests use this to avoid process execution. */\n\tcollectWorkspaceSources?: typeof collectWorkspaceSources;\n\t/** Immutable owner-authored orchestration policy. */\n\torchestrationProfile?: OrchestrationProfile;\n\t/** Injectable local-runtime I/O dependencies. */\n\tlocalRuntimeDeps?: LocalRuntimeDeps;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionContext[\"mode\"];\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tabortHandler?: () => void;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface PromptOptions {\n\t/** Expand file prompt templates and skills. Defaults to true. */\n\texpandPromptTemplates?: boolean;\n\t/** Process slash commands before model submission. Defaults to `expandPromptTemplates`. */\n\tprocessSlashCommands?: boolean;\n\timages?: ImageContent[];\n\t/** Required queue behavior when a foreground turn is already streaming. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\t/** Observe whether prompt preflight accepted the request. */\n\tpreflightResult?: (success: boolean) => void;\n\t/** Permit idle goal continuation after this prompt settles. Defaults to true. */\n\tautoContinueGoal?: boolean;\n\t/** Hidden internal turn persisted as a typed context marker. */\n\tinternalContextType?: string;\n\t/** Active goal whose autonomous foreground execution owns this internal turn's provider usage. */\n\tgoalExecutionId?: string;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\t/** Whether cycling was constrained to launch-scoped models. */\n\tisScoped: boolean;\n}\n\nexport interface CompactionGateCheckStats {\n\tfailures: number;\n\tminScore?: number;\n\tmaxScore?: number;\n\tthreshold?: number;\n\tcomparator?: \"minimum\" | \"maximum\";\n}\n\nexport interface CompactionGateStats {\n\tgateFailures: number;\n\tdeterministicGapFills: number;\n\tcompactionsWithGateFailures: number;\n\tchecks: Record<string, CompactionGateCheckStats>;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n\ttoolArgumentValidation: ToolArgumentValidationStats;\n\tcompactionGates: CompactionGateStats;\n}\n\nexport const SPAWNED_USAGE_CUSTOM_TYPE = \"spawned_usage\";\nexport const RUNAWAY_STOP_CUSTOM_TYPE = \"runaway_stop\";\nexport const TOOL_VALIDATION_ESCALATION_CUSTOM_TYPE = \"tool_validation_escalation\";\n\nexport interface RunawayStopRecord {\n\treason: \"repeated_tool_call\" | \"provider_turn_limit\";\n\tsignature: string;\n\trepeats: number;\n\tmodel?: string;\n\tprovider?: string;\n\tat: string;\n}\n\nexport interface ToolValidationEscalationRecord {\n\ttool: string;\n\tsignature: string;\n\trepeats: number;\n\tmodel: string;\n\tprovider: string;\n\tat: string;\n}\n\nexport interface SpawnedUsageReport {\n\t/** Cumulative child usage, including that child's already-rolled-up descendants. */\n\tusage: Usage;\n\tlabel?: string;\n\tsourceSessionId?: string;\n\t/** Stable idempotency identity for retry-safe ingestion. */\n\treportId?: string;\n}\n\nexport interface SpawnedUsageTotals {\n\tcost: number;\n\treports: number;\n}\n\nexport interface IsolatedCompletionOptions {\n\tsystemPrompt: string;\n\t/** New child-owned prompt messages for this call; foreground session history is never inherited. */\n\tmessages: Message[];\n\t/** Previously persisted child history. Omission preserves fresh one-shot behavior. */\n\thistory?: Message[];\n\tmodel?: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tmaxTokens?: number;\n\t/** Fresh child-owned tool instances. Omission preserves one-shot behavior. */\n\ttools?: AgentTool[];\n\t/** Explicit child-loop turn cap. */\n\tmaxTurns?: number;\n\t/** Optional tool-free finalization prompt after the bounded tool loop. */\n\tfinalTextPrompt?: string;\n\t/** Child-only capability/path gate. */\n\tbeforeToolCall?: AgentLoopConfig[\"beforeToolCall\"];\n\t/** Child-only result observer. */\n\tafterToolCall?: AgentLoopConfig[\"afterToolCall\"];\n\t/**\n\t * Durable child transcript sink. Message-end ordering means an assistant tool request is recorded\n\t * before execution starts and each tool result is recorded before the next provider request.\n\t * Throwing aborts the child loop; continuing without durable history would make replay unsafe.\n\t */\n\tonMessage?: (message: Message, origin?: AgentMessageOrigin) => Promise<void> | void;\n\t/** Durable mid-run steering inbox owned by the child conversation. */\n\tgetSteeringMessages?: AgentLoopConfig[\"getSteeringMessages\"];\n\t/** Durable post-turn follow-up inbox owned by the child conversation. */\n\tgetFollowUpMessages?: AgentLoopConfig[\"getFollowUpMessages\"];\n\t/** Child-owned provider projection, invoked before every request without mutating raw history. */\n\ttransformContext?: AgentLoopConfig[\"transformContext\"];\n\t/** Request-local budget/authority check, invoked immediately before every child provider transport. */\n\trequestPreflight?: AgentLoopConfig[\"requestPreflight\"];\n\tsignal?: AbortSignal;\n\t/** Required cache policy; isolated calls never inherit a provider default implicitly. */\n\tcacheRetention: CacheRetention;\n\t/** Stable namespace used to derive provider cache affinity. */\n\tlaneKind?: string;\n}\n\nexport const DEFAULT_ISOLATED_LANE_KIND = \"isolated\";\n\nexport function computeLaneAffinityKey(laneKind: string, model: Model<Api> | undefined, systemPrompt: string): string {\n\tconst modelKey = model ? `${model.provider}/${model.id}` : \"unknown-model\";\n\tconst digest = createHash(\"sha256\")\n\t\t.update([\"pi-lane-affinity-v1\", laneKind, modelKey, systemPrompt].join(\"\\u0000\"))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `lane:${laneKind}:${digest}`;\n}\n\nexport interface IsolatedCompletionResult {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: StopReason;\n\t/** Provider diagnostic for an error stop; lane owners classify it without parsing transcript history. */\n\terrorMessage?: string;\n\t/** Complete child-owned conversation; isolated calls never expose foreground history. */\n\tmessages?: Message[];\n}\n\nexport interface ResearchLaneRunOutcome {\n\tstarted: boolean;\n\tskipReason?: string;\n\trecord?: LaneRecord;\n\tresult?: ResearchRunResult;\n}\n\nexport interface WorkerDelegationRunOutcome {\n\tstarted: boolean;\n\tskipReason?: string;\n\trecord?: LaneRecord;\n\toutcome?: WorkerRunOutcome;\n}\n\nexport interface GoalContinuationOnceOptions {\n\t/** Consecutive non-progress passes allowed before deterministic escalation; 0 disables the gate. */\n\tmaxStallTurns: number;\n}\n\nexport interface GoalContinuationOnceResult {\n\tsubmitted: boolean;\n\tsnapshot: GoalRuntimeSnapshot;\n\tprompt?: GoalContinuationPrompt;\n\t/** Terminal outcome of the submitted provider turn; absent when no prompt was submitted. */\n\tturnOutcome?: \"completed\" | \"interrupted\";\n}\n\n/** Provider aborts and terminal errors must never drive another autonomous continuation request. */\nexport function isInterruptedAssistantStopReason(stopReason: StopReason | undefined): boolean {\n\treturn stopReason === \"aborted\" || stopReason === \"error\";\n}\n\nexport type GoalContinuationLoopStopReason =\n\t| \"continuation_not_allowed\"\n\t| \"max_turns_reached\"\n\t| \"wall_clock_budget_reached\"\n\t| \"goal_budget_exhausted\"\n\t| \"already_continuing\"\n\t| \"session_disposed\"\n\t| \"goal_tool_unavailable\"\n\t| \"worker_in_flight\"\n\t| \"turn_interrupted\";\n\nexport interface GoalContinuationLoopOptions extends GoalContinuationOnceOptions {\n\t/** Explicit per-invocation turn limit; 0 means unbounded. */\n\tmaxTurns: number;\n\t/** Explicit per-invocation active-time limit; 0/undefined means unbounded. */\n\tmaxWallClockMinutes?: number;\n\t/** Injectable monotonic-enough clock for deterministic tests. */\n\tnow?: () => number;\n}\n\nexport interface GoalContinuationLoopResult {\n\tturnsSubmitted: number;\n\tstopReason: GoalContinuationLoopStopReason;\n\tfinalSnapshot: GoalRuntimeSnapshot;\n}\n\n/** Test-only stream watchdog override contract retained in the public session module. */\nexport type StreamIdleOptionsOverride = Partial<StreamIdleOptions> | undefined;\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-contracts.js","sourceRoot":"","sources":["../../src/core/agent-session-contracts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAuCzC,OAAO,EAAyB,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAsJ3E,MAAM,CAAC,MAAM,yBAAyB,GAAG,eAAe,CAAC;AACzD,MAAM,CAAC,MAAM,wBAAwB,GAAG,cAAc,CAAC;AACvD,MAAM,CAAC,MAAM,sCAAsC,GAAG,4BAA4B,CAAC;AA0EnF,MAAM,CAAC,MAAM,0BAA0B,GAAG,UAAU,CAAC;AAErD,MAAM,UAAU,sBAAsB,CAAC,QAAgB,EAAE,KAA6B,EAAE,YAAoB;IAC3G,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;IAC3E,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC;SACjC,MAAM,CAAC,CAAC,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAChF,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACf,OAAO,QAAQ,QAAQ,IAAI,MAAM,EAAE,CAAC;AACrC,CAAC;AAuCD,oGAAoG;AACpG,MAAM,UAAU,gCAAgC,CAAC,UAAkC;IAClF,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,OAAO,CAAC;AAC3D,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentMessageOrigin,\n\tAgentTool,\n\tStreamIdleOptions,\n\tThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { CompactionResult, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, CacheRetention, ImageContent, Message, Model, StopReason, Usage } from \"@caupulican/pi-ai\";\nimport type { LaneRecord, LaneTerminalStatus } from \"./autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskLiveView } from \"./background-tool-task-controller.ts\";\nimport type { WorkerRunOutcome } from \"./delegation/worker-runner.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionErrorListener,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tInputSource,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { GoalContinuationPrompt } from \"./goals/goal-continuation-prompt.ts\";\nimport type { GoalRuntimeSnapshot } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { LocalRuntimeDeps } from \"./models/local-runtime.ts\";\nimport type { OrchestrationProfile } from \"./orchestration/contracts.ts\";\nimport type { ResearchRunResult } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { ResourceProfileFilterSettings, SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolArgumentValidationStats } from \"./tool-recovery-stats.ts\";\n\nexport { type ParsedSkillBlock, parseSkillBlock } from \"./skill-block.mjs\";\n\n/** Session-specific events that extend the core AgentEvent. */\nexport type AgentSessionEvent =\n\t| Exclude<AgentEvent, { type: \"agent_end\" }>\n\t| { type: \"agent_end\"; messages: AgentMessage[]; willRetry: boolean }\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t\t\tcommands: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\" | \"provider_recovery\" }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"warning\"; message: string }\n\t| { type: \"background_tools\"; tasks: readonly BackgroundToolTaskLiveView[] }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\" | \"provider_recovery\";\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t\t\t/** Benign no-op explanation when compaction did not produce a result. */\n\t\t\tskipReason?: string;\n\t }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t/** UI-only bracket around foreground routing/preparation. Always paired with `routing_end`. */\n\t| { type: \"routing_start\" }\n\t| { type: \"routing_end\" }\n\t| {\n\t\t\ttype: \"delegate_workers\";\n\t\t\tactive: number;\n\t\t\tqueued: number;\n\t\t\trunning: number;\n\t\t\tcompletedSinceFlush: number;\n\t\t\tfailedSinceFlush: number;\n\t\t\t/** partial, blocked, and canceled terminals — needs parent review, not a harness failure. */\n\t\t\tattentionSinceFlush: number;\n\t\t\tterminalSinceFlush: Array<{ laneId: string; status: LaneTerminalStatus; reasonCode?: string }>;\n\t };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\t/** User-level agent state directory for generated runtime artifacts. */\n\tagentDir?: string;\n\t/** Models available to the interactive model-cycle action. */\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tresourceLoader: ResourceLoader;\n\t/** SDK tools registered outside extensions. */\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\t/** Initial active tool names before profile and UAC filtering. */\n\tinitialActiveToolNames?: string[];\n\t/** Optional tool allowlist. */\n\tallowedToolNames?: string[];\n\t/** Optional tool denylist. */\n\texcludedToolNames?: string[];\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Preserve an explicit launch-time model across profile reloads. */\n\tisExplicitModel?: boolean;\n\t/** Preserve an explicit launch-time thinking level across profile reloads. */\n\tisExplicitThinking?: boolean;\n\t/** Child sessions receive the worker UAC and write ceilings. */\n\tisChildSession?: boolean;\n\t/** Alternate base tool instances for embedded/custom runtimes. */\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\t/** Mutable bridge used by the agent loop to reach the current extension generation. */\n\textensionRunnerRef?: { current?: ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Injectable pointer-first workspace collector; tests use this to avoid process execution. */\n\tcollectWorkspaceSources?: typeof collectWorkspaceSources;\n\t/** Immutable owner-authored orchestration policy. */\n\torchestrationProfile?: OrchestrationProfile;\n\t/** Injectable local-runtime I/O dependencies. */\n\tlocalRuntimeDeps?: LocalRuntimeDeps;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionContext[\"mode\"];\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tabortHandler?: () => void;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface PromptOptions {\n\t/** Expand file prompt templates and skills. Defaults to true. */\n\texpandPromptTemplates?: boolean;\n\t/** Process slash commands before model submission. Defaults to `expandPromptTemplates`. */\n\tprocessSlashCommands?: boolean;\n\timages?: ImageContent[];\n\t/** Required queue behavior when a foreground turn is already streaming. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\t/** Observe whether prompt preflight accepted the request. */\n\tpreflightResult?: (success: boolean) => void;\n\t/** Permit idle goal continuation after this prompt settles. Defaults to true. */\n\tautoContinueGoal?: boolean;\n\t/** Hidden internal turn persisted as a typed context marker. */\n\tinternalContextType?: string;\n\t/** Active goal whose autonomous foreground execution owns this internal turn's provider usage. */\n\tgoalExecutionId?: string;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\t/** Whether cycling was constrained to launch-scoped models. */\n\tisScoped: boolean;\n}\n\nexport interface CompactionGateCheckStats {\n\tfailures: number;\n\tminScore?: number;\n\tmaxScore?: number;\n\tthreshold?: number;\n\tcomparator?: \"minimum\" | \"maximum\";\n}\n\nexport interface CompactionGateStats {\n\tgateFailures: number;\n\tdeterministicGapFills: number;\n\tcompactionsWithGateFailures: number;\n\tchecks: Record<string, CompactionGateCheckStats>;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n\ttoolArgumentValidation: ToolArgumentValidationStats;\n\tcompactionGates: CompactionGateStats;\n}\n\nexport const SPAWNED_USAGE_CUSTOM_TYPE = \"spawned_usage\";\nexport const RUNAWAY_STOP_CUSTOM_TYPE = \"runaway_stop\";\nexport const TOOL_VALIDATION_ESCALATION_CUSTOM_TYPE = \"tool_validation_escalation\";\n\nexport interface RunawayStopRecord {\n\treason: \"repeated_tool_call\" | \"provider_turn_limit\";\n\tsignature: string;\n\trepeats: number;\n\tmodel?: string;\n\tprovider?: string;\n\tat: string;\n}\n\nexport interface ToolValidationEscalationRecord {\n\ttool: string;\n\tsignature: string;\n\trepeats: number;\n\tmodel: string;\n\tprovider: string;\n\tat: string;\n}\n\nexport interface SpawnedUsageReport {\n\t/** Cumulative child usage, including that child's already-rolled-up descendants. */\n\tusage: Usage;\n\tlabel?: string;\n\tsourceSessionId?: string;\n\t/** Stable idempotency identity for retry-safe ingestion. */\n\treportId?: string;\n}\n\nexport interface SpawnedUsageTotals {\n\tcost: number;\n\treports: number;\n}\n\nexport interface IsolatedCompletionOptions {\n\tsystemPrompt: string;\n\t/** New child-owned prompt messages for this call; foreground session history is never inherited. */\n\tmessages: Message[];\n\t/** Previously persisted child history. Omission preserves fresh one-shot behavior. */\n\thistory?: Message[];\n\tmodel?: Model<Api>;\n\tthinkingLevel?: ThinkingLevel;\n\tmaxTokens?: number;\n\t/** Fresh child-owned tool instances. Omission preserves one-shot behavior. */\n\ttools?: AgentTool[];\n\t/** Explicit child-loop turn cap. */\n\tmaxTurns?: number;\n\t/** Optional tool-free finalization prompt after the bounded tool loop. */\n\tfinalTextPrompt?: string;\n\t/** Child-only capability/path gate. */\n\tbeforeToolCall?: AgentLoopConfig[\"beforeToolCall\"];\n\t/** Child-only result observer. */\n\tafterToolCall?: AgentLoopConfig[\"afterToolCall\"];\n\t/**\n\t * Durable child transcript sink. Message-end ordering means an assistant tool request is recorded\n\t * before execution starts and each tool result is recorded before the next provider request.\n\t * Throwing aborts the child loop; continuing without durable history would make replay unsafe.\n\t */\n\tonMessage?: (message: Message, origin?: AgentMessageOrigin) => Promise<void> | void;\n\t/** Durable mid-run steering inbox owned by the child conversation. */\n\tgetSteeringMessages?: AgentLoopConfig[\"getSteeringMessages\"];\n\t/** Durable post-turn follow-up inbox owned by the child conversation. */\n\tgetFollowUpMessages?: AgentLoopConfig[\"getFollowUpMessages\"];\n\t/** Child-owned provider projection, invoked before every request without mutating raw history. */\n\ttransformContext?: AgentLoopConfig[\"transformContext\"];\n\t/** Request-local budget/authority check, invoked immediately before every child provider transport. */\n\trequestPreflight?: AgentLoopConfig[\"requestPreflight\"];\n\tsignal?: AbortSignal;\n\t/** Required cache policy; isolated calls never inherit a provider default implicitly. */\n\tcacheRetention: CacheRetention;\n\t/** Stable namespace used to derive provider cache affinity. */\n\tlaneKind?: string;\n}\n\nexport const DEFAULT_ISOLATED_LANE_KIND = \"isolated\";\n\nexport function computeLaneAffinityKey(laneKind: string, model: Model<Api> | undefined, systemPrompt: string): string {\n\tconst modelKey = model ? `${model.provider}/${model.id}` : \"unknown-model\";\n\tconst digest = createHash(\"sha256\")\n\t\t.update([\"pi-lane-affinity-v1\", laneKind, modelKey, systemPrompt].join(\"\\u0000\"))\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `lane:${laneKind}:${digest}`;\n}\n\nexport interface IsolatedCompletionResult {\n\ttext: string;\n\tusage: Usage;\n\tstopReason: StopReason;\n\t/** Provider diagnostic for an error stop; lane owners classify it without parsing transcript history. */\n\terrorMessage?: string;\n\t/** Complete child-owned conversation; isolated calls never expose foreground history. */\n\tmessages?: Message[];\n}\n\nexport interface ResearchLaneRunOutcome {\n\tstarted: boolean;\n\tskipReason?: string;\n\trecord?: LaneRecord;\n\tresult?: ResearchRunResult;\n}\n\nexport interface WorkerDelegationRunOutcome {\n\tstarted: boolean;\n\tskipReason?: string;\n\trecord?: LaneRecord;\n\toutcome?: WorkerRunOutcome;\n}\n\nexport interface GoalContinuationOnceOptions {\n\t/** Consecutive non-progress passes allowed before deterministic escalation; 0 disables the gate. */\n\tmaxStallTurns: number;\n}\n\nexport interface GoalContinuationOnceResult {\n\tsubmitted: boolean;\n\tsnapshot: GoalRuntimeSnapshot;\n\tprompt?: GoalContinuationPrompt;\n\t/** Terminal outcome of the submitted provider turn; absent when no prompt was submitted. */\n\tturnOutcome?: \"completed\" | \"interrupted\";\n}\n\n/** Provider aborts and terminal errors must never drive another autonomous continuation request. */\nexport function isInterruptedAssistantStopReason(stopReason: StopReason | undefined): boolean {\n\treturn stopReason === \"aborted\" || stopReason === \"error\";\n}\n\nexport type GoalContinuationLoopStopReason =\n\t| \"continuation_not_allowed\"\n\t| \"max_turns_reached\"\n\t| \"wall_clock_budget_reached\"\n\t| \"goal_budget_exhausted\"\n\t| \"already_continuing\"\n\t| \"session_disposed\"\n\t| \"goal_tool_unavailable\"\n\t| \"worker_in_flight\"\n\t| \"turn_interrupted\";\n\nexport interface GoalContinuationLoopOptions extends GoalContinuationOnceOptions {\n\t/** Explicit per-invocation turn limit; 0 means unbounded. */\n\tmaxTurns: number;\n\t/** Explicit per-invocation active-time limit; 0/undefined means unbounded. */\n\tmaxWallClockMinutes?: number;\n\t/** Injectable monotonic-enough clock for deterministic tests. */\n\tnow?: () => number;\n}\n\nexport interface GoalContinuationLoopResult {\n\tturnsSubmitted: number;\n\tstopReason: GoalContinuationLoopStopReason;\n\tfinalSnapshot: GoalRuntimeSnapshot;\n}\n\n/** Test-only stream watchdog override contract retained in the public session module. */\nexport type StreamIdleOptionsOverride = Partial<StreamIdleOptions> | undefined;\n"]}
|
|
@@ -6,7 +6,7 @@ import type { Api, AssistantMessage, Model } from "@caupulican/pi-ai";
|
|
|
6
6
|
import type { ExtensionRunner } from "./extensions/index.ts";
|
|
7
7
|
import type { FailureCorpusRecorder } from "./failure-corpus.ts";
|
|
8
8
|
import type { SettingsManager } from "./settings-manager.ts";
|
|
9
|
-
export type AutoCompactionReason = "overflow" | "threshold";
|
|
9
|
+
export type AutoCompactionReason = "overflow" | "provider_recovery" | "threshold";
|
|
10
10
|
export interface ProviderRequestCompactionInput {
|
|
11
11
|
requestTokens: number;
|
|
12
12
|
nonCompactableTokens: number;
|
|
@@ -95,6 +95,7 @@ export declare class CompactionController {
|
|
|
95
95
|
private autoAbortController;
|
|
96
96
|
private autoRunPromise;
|
|
97
97
|
private overflowRecoveryAttempted;
|
|
98
|
+
private providerRecoveryAttempted;
|
|
98
99
|
private ineffectiveThresholdFrontier;
|
|
99
100
|
private readonly deps;
|
|
100
101
|
constructor(deps: CompactionControllerDeps);
|
|
@@ -116,6 +117,8 @@ export declare class CompactionController {
|
|
|
116
117
|
private emitIneffectiveThresholdSkip;
|
|
117
118
|
compactWithRetry(run: () => Promise<CompactionResult>, signal: AbortSignal, provider?: string): Promise<CompactionResult>;
|
|
118
119
|
private findLastAssistantMessage;
|
|
120
|
+
private dropTrailingAssistantErrors;
|
|
121
|
+
private appendProviderRecoveryContinuation;
|
|
119
122
|
private getExtensionCompaction;
|
|
120
123
|
private applyResult;
|
|
121
124
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAOvB,MAAM,iDAAiD,CAAC;
|
|
1
|
+
{"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAOvB,MAAM,iDAAiD,CAAC;AAYzD,OAAO,EAAkD,KAAK,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAItE,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,uBAAuB,CAAC;AACzF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,mBAAmB,GAAG,WAAW,CAAC;AAElF,MAAM,WAAW,8BAA8B;IAC9C,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,iCAAiC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,QAAQ,CAAA;CAAE,CAAC;AAE1F,UAAU,wBAAwB;IACjC,aAAa,CAAC,EAAE,MAAM,CA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mB;IA2H3B,KAAK,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CA4EzF;IAED,wBAAwB,IAAI,MAAM,CAWjC;IAED,IAAI,YAAY,IAAI,OAAO,CAE1B;IAED,OAAO,CAAC,MAAM,EAAE,oBAAoB,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,OAAO,CAAC,CAgBlH;YAEa,WAAW;IAsKzB,OAAO,CAAC,yBAAyB;IAmBjC,OAAO,CAAC,uBAAuB;IA2B/B,OAAO,CAAC,4BAA4B;IAY9B,gBAAgB,CACrB,GAAG,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACpC,MAAM,EAAE,WAAW,EACnB,QAAQ,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC,CAQ3B;IAED,OAAO,CAAC,wBAAwB;IAQhC,OAAO,CAAC,2BAA2B;IAWnC,OAAO,CAAC,kCAAkC;YAY5B,sBAAsB;YAkBtB,WAAW;CAuBzB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assessCompactionNeed, calculateContextTokens, compact, createDeterministicCompaction, estimateContextTokens, prepareCompaction, shouldCompact, } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
2
2
|
import { runCompactionLoop } from "@caupulican/pi-agent-core/compaction/loop";
|
|
3
|
+
import { createCustomMessage } from "@caupulican/pi-agent-core/messages";
|
|
3
4
|
import { estimateProviderRequestTokens } from "@caupulican/pi-agent-core/provider-request-estimator";
|
|
4
5
|
import { projectToolsForProvider } from "@caupulican/pi-agent-core/provider-tool-projection";
|
|
5
6
|
import { classifyFailure, computeRetryDelayMs, DEFAULT_RETRY_POLICY, sleepAbortable, } from "@caupulican/pi-agent-core/reliability";
|
|
@@ -16,6 +17,8 @@ export class ProviderRequestEnvelopeOverflowError extends Error {
|
|
|
16
17
|
}
|
|
17
18
|
const COMPACTION_RETRY_PREPARATION_OPTIONS = { allowTrailingCompactionAsPrevious: true };
|
|
18
19
|
const INEFFECTIVE_THRESHOLD_SKIP_REASON = "previous auto-compaction did not restore headroom; waiting for materially new compactable history";
|
|
20
|
+
const PROVIDER_RECOVERY_CONTINUATION_CUSTOM_TYPE = "provider_recovery_continuation";
|
|
21
|
+
const PROVIDER_RECOVERY_CONTINUATION = "Continue the latest owner request from the compacted checkpoint.";
|
|
19
22
|
function formatRequestTokenBreakdown(input) {
|
|
20
23
|
const total = Math.max(0, Math.ceil(input.requestTokens));
|
|
21
24
|
const nonCompactable = Math.max(0, Math.min(total, Math.ceil(input.nonCompactableTokens)));
|
|
@@ -51,6 +54,7 @@ export async function runCompactionWithRetry(options) {
|
|
|
51
54
|
export class CompactionController {
|
|
52
55
|
constructor(deps) {
|
|
53
56
|
this.overflowRecoveryAttempted = false;
|
|
57
|
+
this.providerRecoveryAttempted = false;
|
|
54
58
|
this.deps = deps;
|
|
55
59
|
}
|
|
56
60
|
async buildCompactionInstructions(customInstructions) {
|
|
@@ -70,6 +74,7 @@ export class CompactionController {
|
|
|
70
74
|
}
|
|
71
75
|
resetOverflowRecovery() {
|
|
72
76
|
this.overflowRecoveryAttempted = false;
|
|
77
|
+
this.providerRecoveryAttempted = false;
|
|
73
78
|
}
|
|
74
79
|
async admitProviderRequest(input) {
|
|
75
80
|
const model = this.deps.getModel();
|
|
@@ -325,12 +330,19 @@ export class CompactionController {
|
|
|
325
330
|
return false;
|
|
326
331
|
}
|
|
327
332
|
this.overflowRecoveryAttempted = true;
|
|
328
|
-
|
|
329
|
-
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
330
|
-
this.deps.agent.state.messages = messages.slice(0, -1);
|
|
331
|
-
}
|
|
333
|
+
this.dropTrailingAssistantErrors();
|
|
332
334
|
return this.deps.runAutoCompaction("overflow", true);
|
|
333
335
|
}
|
|
336
|
+
const classified = assistantMessage.stopReason === "error" && assistantMessage.errorMessage
|
|
337
|
+
? classifyFailure({ message: assistantMessage.errorMessage, provider: assistantMessage.provider })
|
|
338
|
+
: undefined;
|
|
339
|
+
if (sameModel && classified?.shouldCompact) {
|
|
340
|
+
if (this.providerRecoveryAttempted)
|
|
341
|
+
return false;
|
|
342
|
+
this.providerRecoveryAttempted = true;
|
|
343
|
+
this.dropTrailingAssistantErrors();
|
|
344
|
+
return this.deps.runAutoCompaction("provider_recovery", true);
|
|
345
|
+
}
|
|
334
346
|
let contextTokens;
|
|
335
347
|
if (assistantMessage.stopReason === "error") {
|
|
336
348
|
const messages = this.deps.agent.state.messages;
|
|
@@ -428,9 +440,9 @@ export class CompactionController {
|
|
|
428
440
|
const outcome = await runCompactionLoop({
|
|
429
441
|
getBranch: () => this.deps.sessionManager.getBranch(),
|
|
430
442
|
measureLiveTokens: () => options.initialTokens ?? this.deps.measureLiveContextTokens(),
|
|
431
|
-
shouldCompact: reason === "
|
|
432
|
-
? () =>
|
|
433
|
-
: (
|
|
443
|
+
shouldCompact: reason === "threshold"
|
|
444
|
+
? (tokens) => shouldCompact(tokens, contextWindow, settings, model.autoCompactionTriggerTokens)
|
|
445
|
+
: () => true,
|
|
434
446
|
getPostApplyMargin: () => margin,
|
|
435
447
|
getBaseKeepRecentTokens: () => settings.keepRecentTokens,
|
|
436
448
|
resolveModelAndAuth: async (modelTier) => this.deps.resolveModelAndAuth(modelTier === "session" ? model : this.deps.resolveModel(model), model),
|
|
@@ -466,7 +478,7 @@ export class CompactionController {
|
|
|
466
478
|
lastCompaction = result;
|
|
467
479
|
await this.applyResult(result, fromExtension);
|
|
468
480
|
},
|
|
469
|
-
verifyPostApplyEffect: reason
|
|
481
|
+
verifyPostApplyEffect: reason !== "threshold" || options.singlePass ? () => false : undefined,
|
|
470
482
|
allowTrailingCompactionAsPrevious: options.allowTrailingCompactionAsPrevious,
|
|
471
483
|
forceDeterministic: options.forceDeterministic,
|
|
472
484
|
onTransition: ({ cycle, cause, detail }) => {
|
|
@@ -507,15 +519,14 @@ export class CompactionController {
|
|
|
507
519
|
}
|
|
508
520
|
else
|
|
509
521
|
this.ineffectiveThresholdFrontier = undefined;
|
|
510
|
-
this.deps.emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
511
522
|
if (willRetry) {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
this.deps.agent.state.messages = messages.slice(0, -1);
|
|
516
|
-
}
|
|
517
|
-
return true;
|
|
523
|
+
this.dropTrailingAssistantErrors();
|
|
524
|
+
if (reason === "provider_recovery")
|
|
525
|
+
this.appendProviderRecoveryContinuation();
|
|
518
526
|
}
|
|
527
|
+
this.deps.emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
528
|
+
if (willRetry)
|
|
529
|
+
return true;
|
|
519
530
|
return hadQueuedMessages || this.deps.agent.hasQueuedMessages();
|
|
520
531
|
}
|
|
521
532
|
catch (error) {
|
|
@@ -528,7 +539,9 @@ export class CompactionController {
|
|
|
528
539
|
willRetry: false,
|
|
529
540
|
errorMessage: reason === "overflow"
|
|
530
541
|
? `Context overflow recovery failed: ${errorMessage}`
|
|
531
|
-
:
|
|
542
|
+
: reason === "provider_recovery"
|
|
543
|
+
? `Provider failure recovery failed: ${errorMessage}`
|
|
544
|
+
: `Auto-compaction failed: ${errorMessage}`,
|
|
532
545
|
});
|
|
533
546
|
return hadQueuedMessages || this.deps.agent.hasQueuedMessages();
|
|
534
547
|
}
|
|
@@ -603,6 +616,23 @@ export class CompactionController {
|
|
|
603
616
|
}
|
|
604
617
|
return undefined;
|
|
605
618
|
}
|
|
619
|
+
dropTrailingAssistantErrors() {
|
|
620
|
+
const messages = this.deps.agent.state.messages;
|
|
621
|
+
let keepLength = messages.length;
|
|
622
|
+
while (keepLength > 0) {
|
|
623
|
+
const message = messages[keepLength - 1];
|
|
624
|
+
if (message?.role !== "assistant" || message.stopReason !== "error")
|
|
625
|
+
break;
|
|
626
|
+
keepLength--;
|
|
627
|
+
}
|
|
628
|
+
if (keepLength < messages.length)
|
|
629
|
+
this.deps.agent.state.messages = messages.slice(0, keepLength);
|
|
630
|
+
}
|
|
631
|
+
appendProviderRecoveryContinuation() {
|
|
632
|
+
const message = createCustomMessage(PROVIDER_RECOVERY_CONTINUATION_CUSTOM_TYPE, PROVIDER_RECOVERY_CONTINUATION, false, undefined, new Date().toISOString());
|
|
633
|
+
this.deps.sessionManager.appendMessage(message);
|
|
634
|
+
this.deps.agent.state.messages = [...this.deps.agent.state.messages, message];
|
|
635
|
+
}
|
|
606
636
|
async getExtensionCompaction(preparation, branchEntries, customInstructions, signal) {
|
|
607
637
|
const extensionRunner = this.deps.getExtensionRunner();
|
|
608
638
|
if (!extensionRunner.hasHandlers("session_before_compact"))
|