You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/16 04:53:40 UTC
(maka) branch rust-preview updated: feat(agent): add configurable context compaction
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/rust-preview by this push:
new 7baabab2f7 feat(agent): add configurable context compaction
7baabab2f7 is described below
commit 7baabab2f7307fd703459eb4d1810cd17d70cbef
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Oct 16 12:53:25 2026 +0800
feat(agent): add configurable context compaction
Add manual compaction with editable one-shot and global prompts, durable progress and completion display, and preserved Recall history. Reuse the Main request prefix, reserve at least 4% of context capacity for summary output with a 200k fallback, and remove summary-content and tool-archive byte gates.
Generated-by: Codex
---
packages/plugin-sdk/src/contracts.ts | 233 +++++++++++-
packages/plugin-sdk/src/generated/runtime.ts | 16 +-
.../migrations/0020_compaction_history.sql | 20 +-
platform/event-log/src/archive/candidates.rs | 13 +-
platform/event-log/src/archive/target.rs | 6 +-
platform/event-log/src/composition.rs | 32 ++
platform/event-log/src/context/proof.rs | 3 +-
platform/event-log/src/observation.rs | 4 +
platform/event-log/src/observation/delivery.rs | 16 +-
platform/event-log/src/observation/streams.rs | 25 ++
platform/event-log/src/sessions/execution.rs | 8 +-
platform/event-log/src/transcript.rs | 18 +-
platform/event-log/src/transcript/compaction.rs | 125 +++++++
platform/event-log/src/transcript/history.rs | 12 +-
platform/event-log/tests/archive.rs | 56 ++-
platform/event-log/tests/archive/fixtures.rs | 2 +-
platform/event-log/tests/auxiliary_usage.rs | 1 +
platform/event-log/tests/compact_presentation.rs | 46 ++-
.../tests/compact_presentation/automatic.rs | 16 +-
platform/event-log/tests/context_compaction.rs | 2 +-
.../event-log/tests/context_compaction/active.rs | 2 +-
.../event-log/tests/context_compaction/fixtures.rs | 268 +++++++++++++-
.../event-log/tests/context_compaction/latest.rs | 2 +-
.../event-log/tests/context_compaction/lineage.rs | 2 +-
platform/event-log/tests/continuation/fixtures.rs | 1 +
platform/event-log/tests/executor.rs | 1 +
platform/event-log/tests/tool_payloads.rs | 35 +-
.../event-log/tests/transcript_tools/payloads.rs | 76 +++-
platform/presentation/src/compact.rs | 358 ++++++++++++++++---
platform/presentation/src/lib.rs | 15 +-
platform/presentation/src/message.rs | 3 +
plugins/agent/agent-screen/actions.ts | 16 +-
plugins/agent/agent-screen/compact.ts | 282 +++++++++++++++
plugins/agent/agent-screen/component-events.ts | 12 +
plugins/agent/agent-screen/conversation-view.ts | 2 +
plugins/agent/agent-screen/events.ts | 1 +
plugins/agent/agent-screen/frame.ts | 86 ++---
plugins/agent/agent-screen/index.ts | 2 +
plugins/agent/agent-screen/messages.ts | 3 +-
plugins/agent/agent-screen/raw-events.ts | 9 +
plugins/agent/agent-screen/results.ts | 16 +
plugins/agent/agent-screen/state.ts | 8 +
plugins/agent/api/src/contract.rs | 15 +
plugins/agent/api/src/contract_compaction.rs | 58 +++
plugins/agent/assistant-preferences/index.ts | 108 +++++-
plugins/agent/assistant-preferences/locale.ts | 12 +-
plugins/agent/composer-footer/index.ts | 39 +-
plugins/agent/composer-footer/locale.ts | 5 +-
plugins/agent/composer/component.ts | 17 +-
plugins/agent/engine/src/compact.rs | 138 ++++---
plugins/agent/engine/src/context_input.rs | 42 ++-
plugins/agent/engine/src/continuation.rs | 11 +-
plugins/agent/engine/src/model_attempt.rs | 121 +++----
plugins/agent/engine/src/request_composition.rs | 18 +
plugins/agent/engine/src/steps.rs | 5 -
.../engine/tests/integration/context_compaction.rs | 397 +++++++++++++++++++--
.../engine/tests/integration/context_overflow.rs | 6 +-
.../engine/tests/integration/dynamic_tools.rs | 6 +-
.../tests/integration/dynamic_tools/session.rs | 8 +-
.../engine/tests/integration/frozen_projection.rs | 12 +-
.../integration/model_interruption/websocket.rs | 2 +-
plugins/agent/engine/tests/integration/pruning.rs | 14 +-
.../engine/tests/integration/session_import.rs | 6 +-
.../agent/engine/tests/integration/support/http.rs | 2 +-
.../engine/tests/integration/support/invocation.rs | 1 +
plugins/agent/facts/src/archive.rs | 32 +-
plugins/agent/facts/src/archive/encoding.rs | 17 +-
plugins/agent/facts/src/configuration/policy.rs | 3 +
plugins/agent/facts/src/context.rs | 79 ++--
plugins/agent/facts/src/context/summary.rs | 148 +-------
plugins/agent/facts/src/execution.rs | 3 +
plugins/agent/facts/src/tool_output/durable.rs | 20 +-
plugins/agent/native/src/owner.rs | 5 +
plugins/agent/native/src/owner/compaction.rs | 212 +++++++++++
plugins/agent/native/src/owner/execution.rs | 7 +-
plugins/agent/native/src/owner/notifications.rs | 1 +
plugins/agent/native/src/owner/queue.rs | 2 +
plugins/agent/native/src/owner/queue/controls.rs | 8 +-
.../agent/native/src/owner/scheduler/dispatch.rs | 1 +
plugins/agent/native/src/owner/tests.rs | 3 +
plugins/agent/native/src/owner/tests/compaction.rs | 88 +++++
plugins/agent/native/src/owner/tests/recall.rs | 23 ++
plugins/agent/native/src/owner/tests/settings.rs | 22 ++
plugins/agent/native/src/service.rs | 10 +-
plugins/agent/ports/src/session/history.rs | 12 +
plugins/agent/session-recap/src/recap.rs | 1 +
plugins/settings/native/src/preferences.rs | 15 +
plugins/settings/store/src/policy.rs | 11 +
plugins/shared/components.ts | 37 +-
plugins/shared/contracts.ts | 6 +-
plugins/shared/locale-catalogs/components.ts | 9 +-
.../bundle/tests/assistant-preferences.test.mjs | 105 ++++++
products/maka/bundle/tests/compact.test.mjs | 222 ++++++++++++
.../maka/bundle/tests/compaction-display.test.mjs | 131 +++++++
products/maka/bundle/tests/composer.test.mjs | 22 ++
products/maka/cli/notices.json | 41 +--
products/maka/cli/src/code.rs | 1 +
.../integration/terminal/bundled_product/chat.rs | 1 +
.../terminal/bundled_product/chat/compaction.rs | 241 +++++++++++++
99 files changed, 3768 insertions(+), 668 deletions(-)
diff --git a/packages/plugin-sdk/src/contracts.ts b/packages/plugin-sdk/src/contracts.ts
index 7cce3ee115..eb4bb51758 100644
--- a/packages/plugin-sdk/src/contracts.ts
+++ b/packages/plugin-sdk/src/contracts.ts
@@ -8491,6 +8491,187 @@ export const contracts = {
},
resources: {},
},
+ compact: {
+ mode: 'mutation',
+ input: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'AgentCompact',
+ type: 'object',
+ properties: {
+ sessionId: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 128,
+ },
+ model: {
+ $ref: '#/$defs/ModelSelection',
+ },
+ thinkingLevel: {
+ anyOf: [
+ {
+ $ref: '#/$defs/ThinkingLevel',
+ },
+ {
+ type: 'null',
+ },
+ ],
+ },
+ prompt: {
+ description: 'One invocation only; omission uses the global preference.',
+ type: ['string', 'null'],
+ },
+ },
+ additionalProperties: false,
+ required: ['sessionId', 'model'],
+ $defs: {
+ ModelSelection: {
+ description:
+ 'Exact public selection observed by a caller, checked once at run admission.',
+ type: 'object',
+ properties: {
+ connectionId: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 128,
+ },
+ revision: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 1,
+ maximum: 9007199254740991,
+ },
+ modelId: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 512,
+ },
+ },
+ additionalProperties: false,
+ required: ['connectionId', 'revision', 'modelId'],
+ },
+ ThinkingLevel: {
+ type: 'string',
+ enum: ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
+ },
+ },
+ },
+ output: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'AgentCompactResult',
+ oneOf: [
+ {
+ type: 'object',
+ properties: {
+ execution: {
+ $ref: '#/$defs/AgentExecution',
+ },
+ kind: {
+ type: 'string',
+ const: 'started',
+ },
+ },
+ additionalProperties: false,
+ required: ['kind', 'execution'],
+ },
+ {
+ type: 'object',
+ properties: {
+ reason: {
+ $ref: '#/$defs/AgentCompactRejection',
+ },
+ kind: {
+ type: 'string',
+ const: 'rejected',
+ },
+ },
+ additionalProperties: false,
+ required: ['kind', 'reason'],
+ },
+ ],
+ $defs: {
+ AgentExecution: {
+ description:
+ 'Canonical physical execution receipt, independent of the current Session tip.',
+ type: 'object',
+ properties: {
+ sessionId: {
+ type: 'string',
+ },
+ turnId: {
+ type: 'string',
+ },
+ runId: {
+ type: 'string',
+ },
+ invocationId: {
+ type: 'string',
+ },
+ highWater: {
+ description: 'Run-local event count, not the root-global transcript cursor.',
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ },
+ state: {
+ $ref: '#/$defs/AgentExecutionState',
+ },
+ },
+ additionalProperties: false,
+ required: ['sessionId', 'turnId', 'runId', 'invocationId', 'highWater', 'state'],
+ },
+ AgentExecutionState: {
+ type: 'string',
+ enum: [
+ 'admitted',
+ 'running',
+ 'waiting',
+ 'paused',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ ],
+ },
+ AgentCompactRejection: {
+ type: 'string',
+ enum: ['busy', 'closed', 'archived', 'backend_unavailable', 'workspace_changed'],
+ },
+ },
+ },
+ resources: {},
+ },
+ compactionPrompt: {
+ mode: 'query',
+ input: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'AgentSessionRead',
+ type: 'object',
+ properties: {
+ sessionId: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 128,
+ },
+ },
+ additionalProperties: false,
+ required: ['sessionId'],
+ },
+ output: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'AgentCompactionPrompt',
+ type: 'object',
+ properties: {
+ compactionPrompt: {
+ type: 'string',
+ },
+ defaultCompactionPrompt: {
+ type: 'string',
+ },
+ },
+ additionalProperties: false,
+ required: ['compactionPrompt', 'defaultCompactionPrompt'],
+ },
+ resources: {},
+ },
create: {
mode: 'mutation',
input: {
@@ -10656,6 +10837,16 @@ export const contracts = {
AgentHistoryChunk: {
type: 'object',
properties: {
+ compaction: {
+ anyOf: [
+ {
+ $ref: '#/$defs/HistoryCompaction',
+ },
+ {
+ type: 'null',
+ },
+ ],
+ },
attachments: {
description:
'Display metadata only, on the first user-message fragment; no storage capability.',
@@ -10735,6 +10926,21 @@ export const contracts = {
'tool',
],
},
+ HistoryCompaction: {
+ description:
+ 'Duration of a successfully adopted context checkpoint, in recorded milliseconds.',
+ type: 'object',
+ properties: {
+ durationMs: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ additionalProperties: false,
+ required: ['durationMs'],
+ },
AgentHistoryAttachment: {
type: 'object',
properties: {
@@ -10814,7 +11020,7 @@ export const contracts = {
description:
'Canonical message author/kind; the field identifies body versus thinking.\nTool body JSON contributes string values, never its keys.',
type: 'string',
- enum: ['user', 'assistant', 'tool_call', 'tool_result'],
+ enum: ['compaction', 'user', 'assistant', 'tool_call', 'tool_result'],
},
HistoryTool: {
description:
@@ -14894,6 +15100,9 @@ export const contracts = {
session: {
$ref: '#/$defs/AgentSession',
},
+ compacting: {
+ type: 'boolean',
+ },
rememberedBackend: {
anyOf: [
{
@@ -36688,6 +36897,12 @@ export const contracts = {
title: 'SettingsAssistantPreferences',
type: 'object',
properties: {
+ compactionPrompt: {
+ type: 'string',
+ },
+ defaultCompactionPrompt: {
+ type: 'string',
+ },
revision: {
type: 'integer',
format: 'uint64',
@@ -36713,6 +36928,8 @@ export const contracts = {
},
additionalProperties: false,
required: [
+ 'compactionPrompt',
+ 'defaultCompactionPrompt',
'revision',
'displayName',
'assistantTone',
@@ -39976,6 +40193,20 @@ export const contracts = {
$defs: {
SettingsPreferencesMutation: {
oneOf: [
+ {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: ['string', 'null'],
+ },
+ kind: {
+ type: 'string',
+ const: 'compaction_prompt',
+ },
+ },
+ additionalProperties: false,
+ required: ['kind'],
+ },
{
type: 'object',
properties: {
diff --git a/packages/plugin-sdk/src/generated/runtime.ts b/packages/plugin-sdk/src/generated/runtime.ts
index a0743e6b0b..b453da6a2e 100644
--- a/packages/plugin-sdk/src/generated/runtime.ts
+++ b/packages/plugin-sdk/src/generated/runtime.ts
@@ -2357,6 +2357,10 @@ export type NetworkProxyUpdateResult =
kind: 'credential_stale';
};
export type SettingsPreferencesMutation =
+ | {
+ prompt?: string | null;
+ kind: 'compaction_prompt';
+ }
| {
displayName: string;
assistantTone: string;
@@ -4567,7 +4571,7 @@ export type HistoryTurnOutcome = 'completed' | 'failed' | 'aborted';
* Canonical message author/kind; the field identifies body versus thinking.
* Tool body JSON contributes string values, never its keys.
*/
-export type Role = 'user' | 'assistant' | 'tool_call' | 'tool_result';
+export type Role = 'compaction' | 'user' | 'assistant' | 'tool_call' | 'tool_result';
/**
* Recorded Host settlement for presentation; returned is not business success.
* Foreign/provider results do not establish this Host evidence.
@@ -8196,6 +8200,8 @@ export interface PricingUpdate {
mutation: PricingMutation;
}
export interface SettingsAssistantPreferences {
+ compactionPrompt: string;
+ defaultCompactionPrompt: string;
revision: number;
displayName: string;
assistantTone: string;
@@ -9827,6 +9833,7 @@ export interface AgentDelivery {
}
export interface AgentObservation {
session: AgentSession;
+ compacting?: boolean;
rememberedBackend?: AgentBackendPreference | null;
metrics?: AgentSessionMetrics | null;
through: number;
@@ -9913,6 +9920,7 @@ export interface AgentQueueMutation {
edit: AgentQueueAction;
}
export interface AgentHistoryChunk {
+ compaction?: HistoryCompaction | null;
/**
* Display metadata only, on the first user-message fragment; no storage capability.
*
@@ -9975,6 +9983,12 @@ export interface AgentHistoryChunk {
text: string;
tool: HistoryTool | null;
}
+/**
+ * Duration of a successfully adopted context checkpoint, in recorded milliseconds.
+ */
+export interface HistoryCompaction {
+ durationMs: number;
+}
export interface AgentHistoryAttachment {
name: string;
mimeType: string;
diff --git a/plugins/agent/composer-footer/locale.ts b/platform/event-log/migrations/0020_compaction_history.sql
similarity index 60%
copy from plugins/agent/composer-footer/locale.ts
copy to platform/event-log/migrations/0020_compaction_history.sql
index 834c3ecaf6..2818393c87 100644
--- a/plugins/agent/composer-footer/locale.ts
+++ b/platform/event-log/migrations/0020_compaction_history.sql
@@ -17,19 +17,7 @@
* under the License.
*/
-import { translate } from '../../shared/tui-locale.js';
-import { tui_chat_context, tui_chat_metrics_hint } from '../../shared/tui-messages.js';
-
-// This feature owns this explicit message catalog; shared messages remain tree-shakeable.
-
-const terminalMessages = {
- 'chat-context': tui_chat_context,
- 'chat-metrics-hint': tui_chat_metrics_hint,
-};
-export function tuiText(
- locale: string,
- key: string,
- values: Record<string, string | number> = {},
-): string {
- return translate(locale, terminalMessages, key, values);
-}
+-- Rebuild disposable history so existing successful checkpoints gain markers.
+DELETE FROM transcript_text;
+DELETE FROM transcript_rows;
+DELETE FROM transcript_progress;
diff --git a/platform/event-log/src/archive/candidates.rs b/platform/event-log/src/archive/candidates.rs
index b2423c4dc0..22042cd339 100644
--- a/platform/event-log/src/archive/candidates.rs
+++ b/platform/event-log/src/archive/candidates.rs
@@ -100,7 +100,6 @@ async fn scan(
WHERE t.kind='tool_settled' AND t.sequence>?1 AND t.sequence<=?3 AND t.owner_session_id=?2
AND {filter} AND json_extract(d.event_json,'$.fact.call.origin.kind')='provider'
AND NOT EXISTS(SELECT 1 FROM runtime_events a WHERE a.kind='tool_result_archived' AND json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id')=t.event_id AND {archive_filter})
- AND (json_extract(t.event_json,'$.fact.outcome.kind')='succeeded' OR length(CAST(json_extract(t.event_json,'$.fact.outcome.message') AS BLOB))<=262144)
ORDER BY t.sequence LIMIT 1"
);
let mut after = cursor.after_sequence as i64;
@@ -116,11 +115,8 @@ async fn scan(
let Some((sequence, id, bytes)) = row else {
break;
};
- if bytes as usize > max_bytes && output.candidates.is_empty() {
- return Err(StoreError::PrefixTooLarge);
- }
if output.candidates.len() >= max_candidates
- || bytes as usize > max_bytes.saturating_sub(used)
+ || (!output.candidates.is_empty() && bytes as usize > max_bytes.saturating_sub(used))
{
output.next = Some(PruneCursor {
through: cursor.through,
@@ -145,10 +141,9 @@ async fn scan(
))?
.len()
+ 128;
- if measured > max_bytes && output.candidates.is_empty() {
- return Err(StoreError::PrefixTooLarge);
- }
- if measured > max_bytes.saturating_sub(used) {
+ // A batch budget must not prevent an individual large result from ever
+ // being archived. Admit it alone and resume the scan on the next call.
+ if !output.candidates.is_empty() && measured > max_bytes.saturating_sub(used) {
output.next = Some(PruneCursor {
through: cursor.through,
after_sequence: after as u64,
diff --git a/platform/event-log/src/archive/target.rs b/platform/event-log/src/archive/target.rs
index 3c3d4d259b..101512cc3e 100644
--- a/platform/event-log/src/archive/target.rs
+++ b/platform/event-log/src/archive/target.rs
@@ -45,10 +45,8 @@ pub(super) async fn read(
json_extract(d.event_json, '$.invocation') AS di, json_extract(d.event_json, '$.fact.call') AS call,
json_extract(d.event_json, '$.fact.name') AS name,
json_extract(t.event_json, '$.fact.outcome.kind') AS outcome,
- CASE WHEN length(CAST(json_extract(t.event_json, '$.fact.outcome.model_projection') AS BLOB)) <= 2097152
- THEN json_extract(t.event_json, '$.fact.outcome.model_projection') END AS projection,
- CASE WHEN length(CAST(json_extract(t.event_json, '$.fact.outcome.message') AS BLOB)) <= 262144
- THEN json_extract(t.event_json, '$.fact.outcome.message') END AS message,
+ json_extract(t.event_json, '$.fact.outcome.model_projection') AS projection,
+ json_extract(t.event_json, '$.fact.outcome.message') AS message,
c.sequence AS completed,
(json_extract(t.event_json,'$.id')=t.event_id
AND json_extract(t.event_json,'$.invocation.invocation_id')=t.invocation_id
diff --git a/platform/event-log/src/composition.rs b/platform/event-log/src/composition.rs
index 86100b19f8..91bdb5ea24 100644
--- a/platform/event-log/src/composition.rs
+++ b/platform/event-log/src/composition.rs
@@ -130,6 +130,38 @@ pub(crate) async fn verify_replay(
}
impl EventLog {
+ /// Resolve the frozen request behind a previously validated Main completion.
+ pub async fn completed_request_composition(
+ &self,
+ session: &str,
+ sequence: u64,
+ ) -> Result<Option<RequestComposition>, StoreError> {
+ self.validate_root()?;
+ crate::sessions::validate_id(session)?;
+ let owned_session = session.to_owned();
+ let event_id: Option<String> = self
+ .connection
+ .run(move |connection| {
+ Box::pin(async move {
+ Ok(sqlx::query_scalar(
+ "SELECT r.event_id FROM runtime_events c JOIN runtime_events r
+ ON r.invocation_id=c.invocation_id AND r.operation_id=c.operation_id
+ WHERE c.sequence=?1 AND c.kind='model_completed' AND r.kind='model_requested'
+ AND json_extract(c.event_json,'$.invocation.session_id')=?2",
+ )
+ .bind(sequence as i64)
+ .bind(owned_session)
+ .fetch_optional(connection)
+ .await?)
+ })
+ })
+ .await?;
+ match event_id {
+ Some(id) => self.request_composition(session, &id).await,
+ None => Ok(None),
+ }
+ }
+
pub async fn request_composition(
&self,
session: &str,
diff --git a/platform/event-log/src/context/proof.rs b/platform/event-log/src/context/proof.rs
index bd5bb25a73..2c77e76c3e 100644
--- a/platform/event-log/src/context/proof.rs
+++ b/platform/event-log/src/context/proof.rs
@@ -190,8 +190,7 @@ pub(super) async fn validate(
};
if completion.invocation != event.invocation
|| !(opened < requested && requested < completed && completed < sequence)
- || TextSummary::from_model_step(output, checkpoint.previous_checkpoint_id.is_none())
- .map_err(|_| invalid("invalid completed summary"))?
+ || TextSummary::from_model_step(output).map_err(|_| invalid("invalid completed summary"))?
!= checkpoint.summary
{
return Err(invalid("summary does not match its completed model step"));
diff --git a/platform/event-log/src/observation.rs b/platform/event-log/src/observation.rs
index 584596e3f1..5e66987a87 100644
--- a/platform/event-log/src/observation.rs
+++ b/platform/event-log/src/observation.rs
@@ -38,6 +38,7 @@ pub struct SessionObservation<T> {
pub root_turn: Option<turns::TurnBoundary>,
pub through_sequence: u64,
pub active_streams: Vec<AssistantStreamSeed>,
+ pub compacting: bool,
pub pending_interactions: Vec<InteractionRecord>,
pub message_queue: crate::message_queue::MessageQueue,
}
@@ -167,12 +168,15 @@ impl EventLog {
};
let active_streams =
streams::read(&mut transaction, root_turn.as_ref()).await?;
+ let compacting =
+ streams::compacting(&mut transaction, root_turn.as_ref()).await?;
transaction.commit().await?;
Ok(Some(SessionObservation {
session,
root_turn,
through_sequence,
active_streams,
+ compacting,
pending_interactions,
message_queue,
}))
diff --git a/platform/event-log/src/observation/delivery.rs b/platform/event-log/src/observation/delivery.rs
index 9e7798abee..708d78aa78 100644
--- a/platform/event-log/src/observation/delivery.rs
+++ b/platform/event-log/src/observation/delivery.rs
@@ -39,6 +39,7 @@ pub struct StoreStreamEvent {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StreamFact {
+ ContextChanged,
ExecutorStarted,
ExecutorDelta {
text_kind: TextKind,
@@ -237,6 +238,12 @@ SELECT json_object(
'run_id', json_extract(event_json, '$.invocation.run_id'),
'invocation_id', invocation_id),
'fact', json(CASE
+ WHEN kind IN ('model_requested', 'context_checkpoint_recorded') OR
+ (kind IN ('model_completed', 'model_interrupted') AND EXISTS (
+ SELECT 1 FROM runtime_events request WHERE request.invocation_id = runtime_events.invocation_id
+ AND request.kind = 'model_requested' AND request.operation_id = runtime_events.operation_id
+ AND json_extract(request.event_json, '$.fact.purpose') = 'summary'))
+ THEN json_object('kind', 'context_changed')
WHEN kind IN ('executor_started', 'executor_completed') THEN json_object('kind', kind)
WHEN kind = 'executor_observed' AND json_extract(event_json, '$.fact.output.type') IN ('output_delta','thinking_delta') THEN
json_object('kind', 'executor_delta',
@@ -262,6 +269,8 @@ SELECT json_object(
WHEN kind IN ('invocation_opened', 'message_steered') THEN json_object('kind', kind)
WHEN kind = 'invocation_ended' THEN json_object('kind', kind,
'failed', json(CASE WHEN json_extract(event_json, '$.fact.outcome.kind') = 'failed'
+ OR (json_extract(event_json, '$.fact.outcome.kind') = 'context_compact_finished'
+ AND json_extract(event_json, '$.fact.outcome.outcome.kind') = 'failed')
OR (json_extract(event_json, '$.fact.outcome.kind') = 'cancelled' AND EXISTS (
SELECT 1 FROM runtime_events started WHERE started.invocation_id = runtime_events.invocation_id AND started.kind = 'executor_started'))
THEN 'true' ELSE 'false' END))
@@ -286,12 +295,12 @@ SELECT json_object(
FROM runtime_events
WHERE sequence > ?2 AND sequence <= ?3
AND json_extract(event_json, '$.invocation.session_id') = ?1
-AND (kind = 'invocation_ended' OR NOT EXISTS (
+AND (kind IN ('invocation_ended', 'model_requested', 'model_completed', 'model_interrupted', 'context_checkpoint_recorded') OR NOT EXISTS (
SELECT 1 FROM runtime_events opening
WHERE opening.invocation_id = runtime_events.invocation_id
AND opening.kind = 'invocation_opened'
AND json_extract(opening.event_json, '$.fact.input.kind') = 'context_compact'))
-AND (kind NOT IN ('model_observed', 'model_completed', 'model_interrupted') OR
+AND (kind != 'model_observed' OR
EXISTS (SELECT 1 FROM runtime_events request
JOIN runtime_events opening ON opening.invocation_id = request.invocation_id
AND opening.kind = 'invocation_opened'
@@ -300,7 +309,8 @@ AND (kind NOT IN ('model_observed', 'model_completed', 'model_interrupted') OR
AND json_extract(opening.event_json, '$.fact.input.kind') IN ('message', 'continuation', 'handoff')
AND json_extract(request.event_json, '$.fact.purpose') = 'main'))
AND (kind IN ('invocation_opened', 'message_steered', 'invocation_ended', 'model_completed', 'model_interrupted',
- 'tool_dispatched', 'tool_rejected', 'tool_settled', 'executor_started', 'executor_observed', 'executor_completed')
+ 'tool_dispatched', 'tool_rejected', 'tool_settled', 'executor_started', 'executor_observed', 'executor_completed', 'context_checkpoint_recorded')
+ OR (kind = 'model_requested' AND json_extract(event_json, '$.fact.purpose') = 'summary')
OR (kind = 'model_observed'
AND json_extract(event_json, '$.fact.event.kind') IN
('part_started', 'part_delta', 'part_finished')))
diff --git a/platform/event-log/src/observation/streams.rs b/platform/event-log/src/observation/streams.rs
index 1bfb07f6e7..d4059d4f92 100644
--- a/platform/event-log/src/observation/streams.rs
+++ b/platform/event-log/src/observation/streams.rs
@@ -138,3 +138,28 @@ pub(super) async fn read(
}
Ok(result)
}
+
+/// Display status from the same committed snapshot as the session observation.
+pub(super) async fn compacting(
+ connection: &mut sqlx::SqliteConnection,
+ root: Option<&TurnBoundary>,
+) -> Result<bool, StoreError> {
+ let Some(root) = root else {
+ return Ok(false);
+ };
+ if matches!(root.state, InvocationState::Ended { .. }) {
+ return Ok(false);
+ }
+ Ok(sqlx::query_scalar::<_, bool>(
+ "SELECT EXISTS(SELECT 1 FROM runtime_events request
+ WHERE request.invocation_id = ?1 AND request.kind = 'model_requested'
+ AND json_extract(request.event_json, '$.fact.purpose') = 'summary'
+ AND NOT EXISTS(SELECT 1 FROM runtime_events done
+ WHERE done.invocation_id = request.invocation_id
+ AND done.operation_id = request.operation_id
+ AND done.kind IN ('model_completed', 'model_interrupted')))",
+ )
+ .bind(&root.invocation.invocation_id)
+ .fetch_one(connection)
+ .await?)
+}
diff --git a/platform/event-log/src/sessions/execution.rs b/platform/event-log/src/sessions/execution.rs
index 3e5935da61..19c8287299 100644
--- a/platform/event-log/src/sessions/execution.rs
+++ b/platform/event-log/src/sessions/execution.rs
@@ -69,7 +69,8 @@ pub(super) async fn read(
let opened_at = number(&opening, 2)?;
let terminal = sqlx::query(
"SELECT json_extract(event_json, '$.fact.outcome.kind'),
- catalog_time(json_extract(event_json, '$.recorded_at')) FROM event_log
+ catalog_time(json_extract(event_json, '$.recorded_at')),
+ json_extract(event_json, '$.fact.outcome.outcome.kind') FROM event_log
INDEXED BY invocation_boundary
WHERE invocation_id = ? AND kind IN ('invocation_opened', 'invocation_ended')
AND kind = 'invocation_ended' ORDER BY sequence DESC LIMIT 1",
@@ -84,6 +85,11 @@ pub(super) async fn read(
Ok(SessionExecutionState::Ended {
recorded_at,
status: match kind.as_str() {
+ "context_compact_finished"
+ if row.try_get::<Option<String>, _>(2)?.as_deref() == Some("failed") =>
+ {
+ Ok(TerminalStatus::Failed)
+ }
"completed" | "context_compact_finished" => Ok(TerminalStatus::Completed),
"failed" => Ok(TerminalStatus::Failed),
"cancelled" => Ok(TerminalStatus::Cancelled),
diff --git a/platform/event-log/src/transcript.rs b/platform/event-log/src/transcript.rs
index 6f707ed71b..09d5aae3a0 100644
--- a/platform/event-log/src/transcript.rs
+++ b/platform/event-log/src/transcript.rs
@@ -19,6 +19,7 @@
//! Disposable message index; authority stays in the owner-typed canonical ledger.
mod active;
+mod compaction;
pub(crate) use active::interrupted_messages;
mod evidence;
mod history;
@@ -81,13 +82,13 @@ impl EventLog {
// and budget-checked separately, one boundary at a time.
let boundaries = {
let records = sqlx::query(
- "SELECT sequence, invocation_id, operation_id FROM session_history_events runtime_events
+ "SELECT sequence, invocation_id, operation_id, kind FROM session_history_events runtime_events
WHERE owner_session_id = ?1
AND sequence > ?2 AND sequence <= ?3
- AND NOT EXISTS (SELECT 1 FROM runtime_events opening
+ AND (kind = 'context_checkpoint_recorded' OR NOT EXISTS (SELECT 1 FROM runtime_events opening
WHERE opening.invocation_id = runtime_events.invocation_id
AND opening.kind = 'invocation_opened'
- AND json_extract(opening.event_json, '$.fact.input.kind') = 'context_compact')
+ AND json_extract(opening.event_json, '$.fact.input.kind') = 'context_compact'))
AND (kind NOT IN ('model_completed', 'model_interrupted') OR
EXISTS (SELECT 1 FROM runtime_events request
JOIN runtime_events opening ON opening.invocation_id = request.invocation_id
@@ -97,7 +98,7 @@ impl EventLog {
AND json_extract(opening.event_json, '$.fact.input.kind') IN ('message', 'continuation', 'handoff')
AND json_extract(request.event_json, '$.fact.purpose') = 'main'))
AND (kind IN ('message_imported', 'invocation_opened', 'message_steered', 'model_completed',
- 'model_interrupted', 'invocation_ended',
+ 'model_interrupted', 'invocation_ended', 'context_checkpoint_recorded',
'tool_dispatched', 'tool_rejected', 'tool_settled', 'executor_completed')
OR (kind = 'executor_observed' AND json_extract(event_json, '$.fact.output.type') IN ('tool_start','tool_result')))
ORDER BY sequence LIMIT ?4",
@@ -115,13 +116,20 @@ impl EventLog {
row.try_get::<i64, _>(0)?,
row.try_get::<String, _>(1)?,
row.try_get::<Option<String>, _>(2)?,
+ row.try_get::<String, _>(3)?,
))
})
.collect::<Result<Vec<_>, sqlx::Error>>()?
};
let ready = boundaries.len() <= max_boundaries;
let mut processed = progress;
- for (sequence, invocation, step) in boundaries.iter().take(max_boundaries) {
+ for (sequence, invocation, step, kind) in boundaries.iter().take(max_boundaries) {
+ if kind == "context_checkpoint_recorded" {
+ let row = compaction::project(&mut tx, *sequence).await?;
+ persist(&mut tx, &session, row).await?;
+ processed = *sequence;
+ continue;
+ }
let facts = evidence::selected(
&mut tx,
invocation,
diff --git a/platform/event-log/src/transcript/compaction.rs b/platform/event-log/src/transcript/compaction.rs
new file mode 100644
index 0000000000..46c639deec
--- /dev/null
+++ b/platform/event-log/src/transcript/compaction.rs
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::{StoreError, sequence_number};
+use maka_presentation::{Content, Message, Row, watermark};
+use sqlx::{Row as SqlRow, SqliteConnection};
+
+/// Project only adoption metadata, without hydrating the private summary body.
+pub(super) async fn project(tx: &mut SqliteConnection, sequence: i64) -> Result<Row, StoreError> {
+ let row = sqlx::query(
+ "SELECT c.event_id, json_extract(c.event_json, '$.invocation.turn_id') AS turn_id,
+ catalog_time(json_extract(c.event_json, '$.recorded_at')) AS adopted_at,
+ (SELECT catalog_time(json_extract(r.event_json, '$.recorded_at'))
+ FROM runtime_events r
+ WHERE r.invocation_id = c.invocation_id AND r.kind = 'model_requested'
+ AND json_extract(r.event_json, '$.fact.purpose') = 'summary'
+ AND r.sequence <= adopted.sequence
+ AND json_extract(r.event_json, '$.fact.source_high_water') = json_extract(adopted.event_json, '$.fact.source_high_water')
+ AND json_extract(r.event_json, '$.fact.source_digest') = json_extract(adopted.event_json, '$.fact.source_digest')
+ AND NOT EXISTS (SELECT 1 FROM runtime_events boundary
+ WHERE boundary.invocation_id = c.invocation_id AND boundary.sequence > r.sequence AND boundary.sequence < c.sequence
+ AND boundary.kind = 'context_checkpoint_recorded')
+ ORDER BY r.sequence LIMIT 1) AS started_at
+ FROM runtime_events c JOIN runtime_events adopted
+ ON adopted.invocation_id = c.invocation_id AND adopted.kind = 'model_requested'
+ AND adopted.operation_id = json_extract(c.event_json, '$.fact.checkpoint.summary_step_id')
+ WHERE c.sequence = ? AND c.kind = 'context_checkpoint_recorded'"
+ ).bind(sequence).fetch_one(tx).await?;
+ let ts = sequence_number(row.try_get("adopted_at")?)?;
+ let started = sequence_number(row.try_get("started_at")?)?;
+ Ok(Row {
+ sequence: watermark(sequence_number(sequence)?)? - 255,
+ message: Message {
+ id: row.try_get("event_id")?,
+ turn_id: row.try_get("turn_id")?,
+ ts,
+ content: Content::ContextCompacted {
+ duration_ms: ts.saturating_sub(started),
+ },
+ },
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use sqlx::Connection;
+ use std::time::{Duration, UNIX_EPOCH};
+
+ #[tokio::test]
+ async fn concurrent_main_does_not_end_summary_timing_but_new_source_does() {
+ for new_source in [false, true] {
+ let mut db = SqliteConnection::connect(":memory:").await.unwrap();
+ crate::sqlite_functions::register(&mut db).await.unwrap();
+ sqlx::query("CREATE TABLE runtime_events(sequence INTEGER, invocation_id TEXT, kind TEXT, operation_id TEXT, event_id TEXT, event_json TEXT)").execute(&mut db).await.unwrap();
+ for (sequence, at, kind, step, fact) in [
+ (
+ 1,
+ 1000,
+ "model_requested",
+ "summary",
+ json!({"purpose":"summary","source_high_water":1,"source_digest":"source"}),
+ ),
+ (
+ 2,
+ 1500,
+ "model_requested",
+ "main",
+ json!({"purpose":"main","source_high_water":2,"source_digest":"main"}),
+ ),
+ (
+ 3,
+ 3000,
+ "model_requested",
+ "retry",
+ json!({"purpose":"summary","source_high_water":if new_source {2} else {1},"source_digest":if new_source {"new-source"} else {"source"}}),
+ ),
+ (
+ 4,
+ 5500,
+ "context_checkpoint_recorded",
+ "",
+ json!({"checkpoint":{"summary_step_id":"retry"}}),
+ ),
+ ] {
+ let value = json!({"invocation":{"turn_id":"turn"}, "recorded_at":UNIX_EPOCH + Duration::from_millis(at), "fact":fact});
+ sqlx::query("INSERT INTO runtime_events VALUES (?, 'invocation', ?, ?, ?, ?)")
+ .bind(sequence)
+ .bind(kind)
+ .bind(step)
+ .bind(format!("event-{sequence}"))
+ .bind(value.to_string())
+ .execute(&mut db)
+ .await
+ .unwrap();
+ }
+ let row = project(&mut db, 4).await.unwrap();
+ assert_eq!(row.message.id, "event-4");
+ assert_eq!(row.message.ts, 5500);
+ assert_eq!(
+ row.message.content,
+ Content::ContextCompacted {
+ duration_ms: if new_source { 2500 } else { 4500 }
+ }
+ );
+ }
+ }
+}
diff --git a/platform/event-log/src/transcript/history.rs b/platform/event-log/src/transcript/history.rs
index 6edf93155e..22aa204ae9 100644
--- a/platform/event-log/src/transcript/history.rs
+++ b/platform/event-log/src/transcript/history.rs
@@ -219,11 +219,13 @@ impl EventLog {
let ending = (Cursor { field, sequence, offset: end }, row.total);
let candidate_left = if reverse { Some(beginning) } else { left.or(Some(beginning)) };
let candidate_right = if reverse { right.or(Some(ending)) } else { Some(ending) };
- let emit = row.total != 0 || matches!(row.role.as_str(), "tool_call" | "tool_result");
+ let emit = row.total != 0 || matches!(row.role.as_str(), "tool_call" | "tool_result")
+ || (view == HistoryView::Conversation && row.role == "context_compacted");
if emit {
let role = match row.role.as_str() {
"user" => Role::User, "assistant" => Role::Assistant,
"tool_call" => Role::ToolCall, "tool_result" => Role::ToolResult,
+ "context_compacted" => Role::Compaction,
_ => return Err(invalid("invalid history text role")),
};
let attachments = if start == 0 && role == Role::User {
@@ -240,7 +242,13 @@ impl EventLog {
Some(tool)
} else { None };
let timing = super::timing::read(&mut tx, &session, &row.turn, through_sql).await?;
- chunks.push(Chunk { field, timing,
+ let compaction = if role == Role::Compaction {
+ let duration: i64 = sqlx::query_scalar(
+ "SELECT json_extract(payload, '$.durationMs') FROM transcript_rows WHERE session_id = ?1 AND sequence = ?2"
+ ).bind(&session).bind(sql_number(sequence)?).fetch_one(&mut *tx).await?;
+ Some(maka_agent_ports::session::history::Compaction { duration_ms: sequence_number(duration)? })
+ } else { None };
+ chunks.push(Chunk { field, timing, compaction,
message_id: row.message, turn_id: row.turn, timestamp: row.timestamp, role,
sequence, offset: start, total_bytes: row.total, text: text.to_owned(), attachments, tool,
});
diff --git a/platform/event-log/tests/archive.rs b/platform/event-log/tests/archive.rs
index 9b0ab16655..9ec9f4c432 100644
--- a/platform/event-log/tests/archive.rs
+++ b/platform/event-log/tests/archive.rs
@@ -764,7 +764,7 @@ async fn inherited_results_prune_and_compact_without_changing_siblings_or_frozen
covered_through: source.source_evidence.high_water,
source_digest: source.source_evidence.digest,
previous_checkpoint_id: None,
- summary: TextSummary::from_model_step(&output, false).unwrap(),
+ summary: TextSummary::from_model_step(&output).unwrap(),
summary_step_id: "summary".into(),
},
},
@@ -1022,3 +1022,57 @@ async fn read_prefixes_keep_literal_archive_ids_and_session_scope() {
}
log.close().await.unwrap();
}
+
+#[tokio::test]
+async fn oversized_tool_result_archives_alone_and_remains_readable() {
+ let directory = tempfile::tempdir().unwrap();
+ let log = EventLog::open(&directory.path().join("large.sqlite"))
+ .await
+ .unwrap();
+ open(&log, "writer", false).await;
+ let text = "x".repeat(5 * 1024 * 1024);
+ let large = tool(&log, "writer", "large", text.clone()).await;
+ let small = tool(&log, "writer", "small", "next".into()).await;
+ let batch = log
+ .prepare_prune_candidates("session", Some("writer"), 10, 1024 * 1024, None)
+ .await
+ .unwrap();
+ assert_eq!(batch.candidates.len(), 1);
+ assert_eq!(batch.candidates[0].event_id, large.event().id);
+ assert_eq!(
+ batch.candidates[0].projection,
+ maka_agent_facts::tool_output::DurableToolProjection::Text { text: text.clone() }
+ );
+ let next = log
+ .prepare_prune_candidates(
+ "session",
+ Some("writer"),
+ 10,
+ 1024 * 1024,
+ batch.next.as_ref(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(next.candidates.len(), 1);
+ assert_eq!(next.candidates[0].event_id, small.event().id);
+ let archived = archive("writer", &large);
+ log.append(&archived).await.unwrap();
+ let Fact::ToolResultArchived { placeholder } = &archived.event().fact else {
+ panic!()
+ };
+ let body = log
+ .read_archive("session", &placeholder.identity)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(serde_json::from_slice::<String>(&body).unwrap(), text);
+ assert_eq!(placeholder.identity.original_bytes, 5 * 1024 * 1024 + 2);
+ assert!(placeholder.page.next.is_some());
+ let resource = log
+ .read_tool_result("session", &large.event().id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(resource.serialized_result.as_bytes(), body);
+ log.close().await.unwrap();
+}
diff --git a/platform/event-log/tests/archive/fixtures.rs b/platform/event-log/tests/archive/fixtures.rs
index 581a0b302d..30a83fb974 100644
--- a/platform/event-log/tests/archive/fixtures.rs
+++ b/platform/event-log/tests/archive/fixtures.rs
@@ -188,7 +188,7 @@ pub(super) async fn summary_pair(
covered_through: source.source_evidence.high_water,
source_digest: source.source_evidence.digest.clone(),
previous_checkpoint_id: source.baseline.as_ref().map(|b| b.event_id.clone()),
- summary: TextSummary::from_model_step(&output, false).unwrap(),
+ summary: TextSummary::from_model_step(&output).unwrap(),
summary_step_id: summary_step,
},
},
diff --git a/platform/event-log/tests/auxiliary_usage.rs b/platform/event-log/tests/auxiliary_usage.rs
index e4b5c416de..dd6f60dd8e 100644
--- a/platform/event-log/tests/auxiliary_usage.rs
+++ b/platform/event-log/tests/auxiliary_usage.rs
@@ -217,6 +217,7 @@ async fn title_accounting_uses_first_opening_after_stop_and_never_replays_after_
.is_err()
);
let configuration = InvocationConfiguration {
+ compaction_prompt: None,
workspace_origin: WorkspaceOrigin::Selected,
approval_policy: ApprovalPolicy::OnRequest,
boundary_revision: 0,
diff --git a/platform/event-log/tests/compact_presentation.rs b/platform/event-log/tests/compact_presentation.rs
index 9b157e8262..ea05c8a1c7 100644
--- a/platform/event-log/tests/compact_presentation.rs
+++ b/platform/event-log/tests/compact_presentation.rs
@@ -49,7 +49,7 @@ mod automatic;
#[tokio::test]
async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
- for mode in ["accepted", "interrupted", "failed"] {
+ for mode in ["accepted", "rejected", "interrupted", "failed"] {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("events.sqlite");
let log = EventLog::open(&path).await.unwrap();
@@ -160,6 +160,7 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
.await
.unwrap()
.unwrap();
+ assert!(running.compacting);
let root = running.root_turn.unwrap();
assert_eq!(root.invocation, compact);
assert!(matches!(root.input, InvocationInput::ContextCompact { .. }));
@@ -174,10 +175,14 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
.is_empty()
);
let delivery = log
- .session_stream_events("session", old_end.sequence, delta.sequence, 1, 1)
+ .session_stream_events("session", old_end.sequence, delta.sequence, 1, 4096)
.await
.unwrap();
- assert!(delivery.events.is_empty());
+ assert_eq!(delivery.events.len(), 1);
+ assert!(matches!(
+ delivery.events[0].fact,
+ StreamFact::ContextChanged
+ ));
assert!(delivery.next_after.is_none());
assert_eq!(delivery.through_sequence, delta.sequence);
assert!(
@@ -187,7 +192,7 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
);
assert_eq!(transcript(&db), old_rows);
let outcome = match mode {
- "accepted" => {
+ "accepted" | "rejected" => {
hidden(
&log,
&mut view,
@@ -200,8 +205,14 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
.await;
hidden(&log, &mut view, &compact, accepted(&secret)).await;
InvocationOutcome::ContextCompactFinished {
- outcome: CompactOutcome::Unchanged {
- reason: "fixture".into(),
+ outcome: if mode == "rejected" {
+ CompactOutcome::Failed {
+ reason: "output_length".into(),
+ }
+ } else {
+ CompactOutcome::Unchanged {
+ reason: "fixture".into(),
+ }
},
}
}
@@ -226,7 +237,11 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
message: None,
},
};
- let status = outcome.status();
+ let status = if mode == "rejected" {
+ maka_agent_facts::event::TerminalStatus::Failed
+ } else {
+ outcome.status()
+ };
let terminal = hidden(
&log,
&mut view,
@@ -242,6 +257,7 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
.unwrap()
.unwrap();
assert!(ended.active_streams.is_empty());
+ assert!(!ended.compacting);
assert!(
matches!(ended.root_turn.unwrap().state, InvocationState::Ended {
event_id, outcome: actual
@@ -255,15 +271,21 @@ async fn compact_attempts_preserve_visible_history_read_markers_and_rebuild() {
);
assert_eq!(ended.session.last_message, previous.last_message);
let page = log
- .session_stream_events("session", old_end.sequence, terminal.sequence, 1, 4096)
+ .session_stream_events("session", old_end.sequence, terminal.sequence, 32, 4096)
.await
.unwrap();
- assert_eq!(page.events.len(), 1);
+ assert_eq!(page.events.len(), if mode == "failed" { 2 } else { 3 });
+ let (terminal_event, changes) = page.events.split_last().unwrap();
+ assert!(
+ changes
+ .iter()
+ .all(|event| matches!(event.fact, StreamFact::ContextChanged))
+ );
assert!(matches!(
- page.events[0].fact,
- StreamFact::InvocationEnded { .. }
+ terminal_event.fact,
+ StreamFact::InvocationEnded { failed, .. } if failed == matches!(mode, "failed" | "rejected")
));
- assert_eq!(page.events[0].id, terminal.event.id);
+ assert_eq!(terminal_event.id, terminal.event.id);
assert!(page.next_after.is_none());
assert_eq!(page.through_sequence, terminal.sequence);
assert!(
diff --git a/platform/event-log/tests/compact_presentation/automatic.rs b/platform/event-log/tests/compact_presentation/automatic.rs
index 23bc385e6b..4cfa68377e 100644
--- a/platform/event-log/tests/compact_presentation/automatic.rs
+++ b/platform/event-log/tests/compact_presentation/automatic.rs
@@ -90,6 +90,7 @@ async fn automatic_summary_is_hidden_without_interrupting_main_delivery_or_read_
InvocationState::Running
));
assert!(during.active_streams.is_empty());
+ assert!(during.compacting);
assert!(
log.active_transcript(&inv, summary_fence)
.await
@@ -98,8 +99,8 @@ async fn automatic_summary_is_hidden_without_interrupting_main_delivery_or_read_
);
assert_eq!(during.session.last_message, read.last_message);
assert_eq!(during.session.read_state, read.read_state);
- // Existing subscribers still receive the main closer at a fence which
- // includes a later summary. No summary event consumes delivery budget.
+ // Subscribers receive the main closer and a status invalidation,
+ // while private summary content remains hidden.
let mut cursor = main_fence;
let mut facts = Vec::new();
loop {
@@ -115,7 +116,8 @@ async fn automatic_summary_is_hidden_without_interrupting_main_delivery_or_read_
break;
}
}
- assert_eq!(facts.len(), 2);
+ assert_eq!(facts.len(), 3);
+ assert!(matches!(&facts[2], StreamFact::ContextChanged));
assert!(
matches!(&facts[0], StreamFact::PartFinished { step_id, .. } if step_id == "main-a")
);
@@ -165,6 +167,7 @@ async fn automatic_summary_is_hidden_without_interrupting_main_delivery_or_read_
.unwrap()
.unwrap();
assert_eq!(active.active_streams.len(), 1);
+ assert!(!active.compacting);
assert_eq!(active.active_streams[0].message_id, later_id);
assert_eq!(
log.active_transcript(&inv, later).await.unwrap()[0].id,
@@ -187,6 +190,13 @@ async fn automatic_summary_is_hidden_without_interrupting_main_delivery_or_read_
)
.await;
expected.extend(view.push(&end).unwrap());
+ assert!(
+ !log.observe_session::<Value>("session")
+ .await
+ .unwrap()
+ .unwrap()
+ .compacting
+ );
assert!(
log.get_session::<Value>("session")
.await
diff --git a/platform/event-log/tests/context_compaction.rs b/platform/event-log/tests/context_compaction.rs
index aa9654db0f..75aead6133 100644
--- a/platform/event-log/tests/context_compaction.rs
+++ b/platform/event-log/tests/context_compaction.rs
@@ -221,7 +221,7 @@ async fn forged_summary_source_and_hidden_old_unknowns_never_become_a_baseline()
};
match mutation {
0 => checkpoint.source_digest = format!("sha256:{}", "0".repeat(64)),
- 1 => checkpoint.summary.text = SUMMARY.replace("first", "second"),
+ 1 => checkpoint.summary.text = "forged summary text".into(),
_ => checkpoint.previous_checkpoint_id = Some(forged.id.clone()),
}
assert!(
diff --git a/platform/event-log/tests/context_compaction/active.rs b/platform/event-log/tests/context_compaction/active.rs
index dfcba08d12..a5d0a9fc8c 100644
--- a/platform/event-log/tests/context_compaction/active.rs
+++ b/platform/event-log/tests/context_compaction/active.rs
@@ -92,7 +92,7 @@ async fn checkpoint(log: &EventLog, id: &str, mode: CheckpointMode) -> EventWrit
covered_through: source.source_evidence.high_water,
source_digest: source.source_evidence.digest,
previous_checkpoint_id: source.baseline.map(|b| b.event_id),
- summary: TextSummary::from_model_step(output, false).unwrap(),
+ summary: TextSummary::from_model_step(output).unwrap(),
summary_step_id: step,
},
},
diff --git a/platform/event-log/tests/context_compaction/fixtures.rs b/platform/event-log/tests/context_compaction/fixtures.rs
index 19f3d48258..edfea322b5 100644
--- a/platform/event-log/tests/context_compaction/fixtures.rs
+++ b/platform/event-log/tests/context_compaction/fixtures.rs
@@ -19,7 +19,8 @@
use super::*;
-pub(super) const SUMMARY: &str = "## Goal\nContinue the work.\n## Progress\nCompleted the first stage.\n## Next Steps\nVerify the remaining behavior.\n## Critical Context\nPreserve the durable execution facts.";
+pub(super) const SUMMARY: &str =
+ "Custom summary without required sections. Continue with these details:...";
fn identity(id: &str) -> Invocation {
Invocation {
@@ -164,7 +165,7 @@ pub(super) async fn prepare_trace(
.await
.unwrap();
let output = step(SUMMARY);
- let summary = TextSummary::from_model_step(&output, source.baseline.is_none()).unwrap();
+ let summary = TextSummary::from_model_step(&output).unwrap();
log.append(&request(id, &source)).await.unwrap();
let trace: Vec<_> = (0..observations)
.map(|_| {
@@ -240,3 +241,266 @@ pub(super) async fn prepare_trace(
);
vec![checkpoint, terminal]
}
+
+#[tokio::test]
+async fn adoption_markers_are_durable_timed_and_hidden_from_recall() {
+ use maka_agent_facts::context::CheckpointMode;
+ use maka_agent_ports::session::history::{HistoryView, Page, Position, Role};
+ use std::time::{Duration, UNIX_EPOCH};
+
+ for standalone in [false, true] {
+ for adopt in [false, true] {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("markers.sqlite");
+ let log = EventLog::open(&path).await.unwrap();
+ log.create_session("session", "create", &json!({}), 1)
+ .await
+ .unwrap();
+ log.append_batch(&[
+ event(
+ "prior",
+ Fact::InvocationOpened {
+ configuration: None,
+ input: InvocationInput::Message {
+ source_messages: Vec::new(),
+ content: "prior question".into(),
+ request_fingerprint: None,
+ },
+ },
+ ),
+ event(
+ "prior",
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Completed,
+ },
+ ),
+ ])
+ .await
+ .unwrap();
+ let id = "compacting";
+ log.append(&event(
+ id,
+ Fact::InvocationOpened {
+ configuration: None,
+ input: if standalone {
+ InvocationInput::ContextCompact {
+ request_fingerprint: "compact".into(),
+ }
+ } else {
+ InvocationInput::Message {
+ source_messages: Vec::new(),
+ content: "continue".into(),
+ request_fingerprint: None,
+ }
+ },
+ },
+ ))
+ .await
+ .unwrap();
+ let mode = if standalone {
+ CheckpointMode::Standalone
+ } else {
+ CheckpointMode::PreTurn
+ };
+ let source = log
+ .prepare_context_compaction("session", Some(id), &mode)
+ .await
+ .unwrap();
+ let timed = |write: EventWrite, at| {
+ let mut value = write.event().clone();
+ value.recorded_at = UNIX_EPOCH + Duration::from_millis(at);
+ EventWrite::plain(value).unwrap()
+ };
+ log.append(&timed(request(id, &source), 1000))
+ .await
+ .unwrap();
+ let output = step("custom summary");
+ log.append(&timed(
+ event(
+ id,
+ Fact::ModelCompleted {
+ step_id: format!("{id}-summary"),
+ output: output.clone(),
+ },
+ ),
+ 2000,
+ ))
+ .await
+ .unwrap();
+ let mut retry = request(id, &source).event().clone();
+ if let Fact::ModelRequested { step_id, .. } = &mut retry.fact {
+ *step_id = "retry".into();
+ }
+ log.append(&timed(EventWrite::plain(retry).unwrap(), 3000))
+ .await
+ .unwrap();
+ if !standalone {
+ let main_source = log.read_model_context("session", Some(id)).await.unwrap();
+ let mut main = request(id, &main_source).event().clone();
+ if let Fact::ModelRequested {
+ step_id,
+ purpose,
+ effective_source_digest,
+ ..
+ } = &mut main.fact
+ {
+ *step_id = "concurrent-main".into();
+ *purpose = maka_agent_facts::context::ModelPurpose::Main;
+ *effective_source_digest = None;
+ }
+ log.append(&timed(EventWrite::plain(main).unwrap(), 3500))
+ .await
+ .unwrap();
+ }
+
+ log.append(&timed(
+ event(
+ id,
+ Fact::ModelCompleted {
+ step_id: "retry".into(),
+ output: output.clone(),
+ },
+ ),
+ 4000,
+ ))
+ .await
+ .unwrap();
+ if !standalone {
+ log.append(&timed(
+ event(
+ id,
+ Fact::ModelCompleted {
+ step_id: "concurrent-main".into(),
+ output: serde_json::from_value(
+ json!({"parts":[], "finish_reason":"stop", "usage":{}}),
+ )
+ .unwrap(),
+ },
+ ),
+ 4500,
+ ))
+ .await
+ .unwrap();
+ }
+ let checkpoint = timed(
+ event(
+ id,
+ Fact::ContextCheckpointRecorded {
+ checkpoint: ContextCheckpoint {
+ mode,
+ covered_through: source.source_evidence.high_water,
+ source_digest: source.source_evidence.digest.clone(),
+ previous_checkpoint_id: source
+ .baseline
+ .as_ref()
+ .map(|b| b.event_id.clone()),
+ summary: TextSummary::from_model_step(&output).unwrap(),
+ summary_step_id: "retry".into(),
+ },
+ },
+ ),
+ 5500,
+ );
+ let terminal = timed(
+ event(
+ id,
+ Fact::InvocationEnded {
+ outcome: if !adopt {
+ InvocationOutcome::Failed {
+ class: "summary_failed".into(),
+ message: None,
+ }
+ } else if standalone {
+ InvocationOutcome::ContextCompactFinished {
+ outcome: CompactOutcome::Compacted {
+ checkpoint_id: checkpoint.event().id.clone(),
+ },
+ }
+ } else {
+ InvocationOutcome::Completed
+ },
+ },
+ ),
+ 6000,
+ );
+ let through = if adopt {
+ *log.append_batch(&[checkpoint.clone(), terminal])
+ .await
+ .unwrap()
+ .last()
+ .unwrap()
+ } else {
+ log.append(&terminal).await.unwrap()
+ };
+ while !log
+ .prepare_transcript("session", through, 32)
+ .await
+ .unwrap()
+ {}
+ for view in [HistoryView::Conversation, HistoryView::Text] {
+ let Page::Ready { chunks, .. } = log
+ .history_view(
+ "session",
+ through,
+ Position::Start,
+ false,
+ view,
+ 128 * 1024,
+ None,
+ 1024 * 1024,
+ )
+ .await
+ .unwrap()
+ else {
+ panic!()
+ };
+ let markers: Vec<_> = chunks
+ .iter()
+ .filter(|chunk| chunk.role == Role::Compaction)
+ .collect();
+ if adopt && view == HistoryView::Conversation {
+ assert_eq!(markers.len(), 1);
+ assert_eq!(markers[0].message_id, checkpoint.event().id);
+ assert_eq!(markers[0].timestamp, 5500);
+ assert_eq!(markers[0].compaction.as_ref().unwrap().duration_ms, 4500);
+ assert_eq!(markers[0].text, "");
+ } else {
+ assert!(markers.is_empty());
+ }
+ }
+ log.close().await.unwrap();
+ let log = EventLog::open(&path).await.unwrap();
+ while !log
+ .prepare_transcript("session", through, 32)
+ .await
+ .unwrap()
+ {}
+ let Page::Ready { chunks, .. } = log
+ .history_view(
+ "session",
+ through,
+ Position::Start,
+ false,
+ HistoryView::Conversation,
+ 128 * 1024,
+ None,
+ 1024 * 1024,
+ )
+ .await
+ .unwrap()
+ else {
+ panic!()
+ };
+ let markers: Vec<_> = chunks
+ .iter()
+ .filter(|chunk| chunk.compaction.is_some())
+ .collect();
+ assert_eq!(markers.len(), usize::from(adopt));
+ if adopt {
+ assert_eq!(markers[0].message_id, checkpoint.event().id);
+ assert_eq!(markers[0].compaction.as_ref().unwrap().duration_ms, 4500);
+ }
+ log.close().await.unwrap();
+ }
+ }
+}
diff --git a/platform/event-log/tests/context_compaction/latest.rs b/platform/event-log/tests/context_compaction/latest.rs
index ad7870845e..d90b5c4590 100644
--- a/platform/event-log/tests/context_compaction/latest.rs
+++ b/platform/event-log/tests/context_compaction/latest.rs
@@ -59,7 +59,7 @@ async fn preturn_keeps_anchor_and_latest_main_never_falls_back_a_broken_newer_tr
covered_through: source.source_evidence.high_water,
source_digest: source.source_evidence.digest,
previous_checkpoint_id: None,
- summary: TextSummary::from_model_step(output, false).unwrap(),
+ summary: TextSummary::from_model_step(output).unwrap(),
summary_step_id: "summary".into(),
},
},
diff --git a/platform/event-log/tests/context_compaction/lineage.rs b/platform/event-log/tests/context_compaction/lineage.rs
index ff40a9b19f..45cabc0354 100644
--- a/platform/event-log/tests/context_compaction/lineage.rs
+++ b/platform/event-log/tests/context_compaction/lineage.rs
@@ -180,7 +180,7 @@ async fn continuation_requests_and_checkpoints_prove_selected_source_across_repa
covered_through: source.source_evidence.high_water,
source_digest: source.source_evidence.digest.clone(),
previous_checkpoint_id: source.baseline.as_ref().map(|b| b.event_id.clone()),
- summary: TextSummary::from_model_step(output, false).unwrap(),
+ summary: TextSummary::from_model_step(output).unwrap(),
summary_step_id: "repair".into(),
},
},
diff --git a/platform/event-log/tests/continuation/fixtures.rs b/platform/event-log/tests/continuation/fixtures.rs
index 1a766638e9..177b64951c 100644
--- a/platform/event-log/tests/continuation/fixtures.rs
+++ b/platform/event-log/tests/continuation/fixtures.rs
@@ -29,6 +29,7 @@ pub(super) fn opening(id: &str, claim: Option<ContinuationClaim>) -> RuntimeEven
},
Fact::InvocationOpened {
configuration: Some(Box::new(InvocationConfiguration {
+ compaction_prompt: None,
workspace_origin: maka_agent_facts::execution::WorkspaceOrigin::Selected,
approval_policy: maka_agent_facts::execution::ApprovalPolicy::OnRequest,
boundary_revision: 0,
diff --git a/platform/event-log/tests/executor.rs b/platform/event-log/tests/executor.rs
index 144ec3c491..3b6481f1d9 100644
--- a/platform/event-log/tests/executor.rs
+++ b/platform/event-log/tests/executor.rs
@@ -56,6 +56,7 @@ async fn external_output_is_durable_observation_not_native_dispatch_and_rebuilds
request_fingerprint: None,
},
configuration: Some(Box::new(InvocationConfiguration {
+ compaction_prompt: None,
workspace_origin: maka_agent_facts::execution::WorkspaceOrigin::Selected,
approval_policy: maka_agent_facts::execution::ApprovalPolicy::OnRequest,
boundary_revision: 0,
diff --git a/platform/event-log/tests/tool_payloads.rs b/platform/event-log/tests/tool_payloads.rs
index d49630d9ea..d62c67e1f2 100644
--- a/platform/event-log/tests/tool_payloads.rs
+++ b/platform/event-log/tests/tool_payloads.rs
@@ -87,27 +87,35 @@ async fn open(path: &std::path::Path) -> EventLog {
}
#[tokio::test]
-async fn large_raw_reopens_exactly_without_entering_the_compact_prefix() {
+async fn large_raw_and_model_projection_reopen_exactly() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("events.sqlite");
let log = open(&path).await;
let output = ToolOutput::Text("🦊\u{0001}".repeat(1024 * 1024 / 5));
let operation = "large";
let outcome = success(operation, &output);
- assert!(matches!(
- &outcome.event().fact,
- Fact::ToolSettled {
- outcome: ToolOutcome::Succeeded {
- model_projection: DurableToolProjection::Failure,
- ..
- },
- ..
+ let Fact::ToolSettled {
+ outcome: ToolOutcome::Succeeded {
+ model_projection, ..
+ },
+ ..
+ } = &outcome.event().fact
+ else {
+ panic!()
+ };
+ let ToolOutput::Text(text) = &output else {
+ panic!()
+ };
+ assert_eq!(
+ model_projection,
+ &DurableToolProjection::Json {
+ value: json!({"kind":"text", "text":text})
}
- ));
+ );
log.append_batch(&[dispatch(operation), outcome.clone()])
.await
.unwrap();
- let prefix = log.prefix(100, 8192).await.unwrap();
+ let prefix = log.prefix(100, 4 * 1024 * 1024).await.unwrap();
log.close().await.unwrap();
let log = EventLog::open(&path).await.unwrap();
assert_eq!(
@@ -116,7 +124,10 @@ async fn large_raw_reopens_exactly_without_entering_the_compact_prefix() {
.unwrap(),
output
);
- assert_eq!(log.prefix(100, 8192).await.unwrap().digest, prefix.digest);
+ assert_eq!(
+ log.prefix(100, 4 * 1024 * 1024).await.unwrap().digest,
+ prefix.digest
+ );
let commits = log.subscribe_commits();
log.append(&outcome).await.unwrap();
assert!(!commits.has_changed().unwrap());
diff --git a/platform/event-log/tests/transcript_tools/payloads.rs b/platform/event-log/tests/transcript_tools/payloads.rs
index e0ba18d8a1..53ea082c90 100644
--- a/platform/event-log/tests/transcript_tools/payloads.rs
+++ b/platform/event-log/tests/transcript_tools/payloads.rs
@@ -49,7 +49,7 @@ async fn open(log: &EventLog) {
}
#[tokio::test]
-async fn ten_mib_raw_fragments_rebuild_after_restart_from_compact_facts() {
+async fn ten_mib_raw_fragments_rebuild_after_restart_from_durable_facts() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("events.sqlite");
let log = EventLog::open(&path).await.unwrap();
@@ -61,7 +61,7 @@ async fn ten_mib_raw_fragments_rebuild_after_restart_from_compact_facts() {
let id = write.event().id.clone();
drop(write);
prepare(&log, through).await;
- assert!(log.prefix(100, 8 * 1024 * 1024).await.is_ok());
+ assert!(log.prefix(100, 16 * 1024 * 1024).await.is_ok());
let db = Connection::open(&path).unwrap();
let original: Vec<u8> = db
.query_row(
@@ -161,9 +161,7 @@ async fn escaped_raw_remains_durable_when_full_ui_row_exceeds_client_capacity()
let through = log.append(&write).await.unwrap();
assert!(matches!(
log.prepare_transcript("session", through, 32).await,
- Err(maka_event_log::StoreError::Projection(
- maka_presentation::ProjectionError::TooLarge
- ))
+ Err(maka_event_log::StoreError::PrefixTooLarge)
));
log.close().await.unwrap();
let log = EventLog::open(&path).await.unwrap();
@@ -174,10 +172,10 @@ async fn escaped_raw_remains_durable_when_full_ui_row_exceeds_client_capacity()
.to_json(),
raw
);
- assert!(log.prefix(100, 8 * 1024 * 1024).await.is_ok());
- // A known-oversize UI row is rejected from compact evidence alone. Even
- // absent bytes must not trigger hydration; the raw resolver still detects
- // that damage, so this capacity decision does not certify payload integrity.
+ assert!(log.prefix(100, 32 * 1024 * 1024).await.is_ok());
+ // The preserved projection exceeds the transcript evidence budget before
+ // raw payload hydration. Missing raw bytes still fail the raw resolver;
+ // the transcript capacity refusal does not certify payload integrity.
let db = Connection::open(&path).unwrap();
db.execute(
"DELETE FROM tool_result_payloads WHERE event_id = ?",
@@ -186,9 +184,7 @@ async fn escaped_raw_remains_durable_when_full_ui_row_exceeds_client_capacity()
.unwrap();
assert!(matches!(
log.prepare_transcript("session", through, 32).await,
- Err(maka_event_log::StoreError::Projection(
- maka_presentation::ProjectionError::TooLarge
- ))
+ Err(maka_event_log::StoreError::PrefixTooLarge)
));
assert!(
log.resolve_tool_result("session", &write.event().id)
@@ -196,3 +192,59 @@ async fn escaped_raw_remains_durable_when_full_ui_row_exceeds_client_capacity()
.is_err()
);
}
+
+#[tokio::test]
+async fn multiple_large_results_keep_conversation_metadata_readable() {
+ use maka_agent_ports::session::history::{HistoryView, Page, Position, Role};
+ let directory = tempfile::tempdir().unwrap();
+ let log = EventLog::open(&directory.path().join("large-history.sqlite"))
+ .await
+ .unwrap();
+ log.create_session("session", "create", &json!({}), 1)
+ .await
+ .unwrap();
+ open(&log).await;
+ let mut ids = Vec::new();
+ let mut through = 0;
+ for index in 0..4 {
+ let operation = dispatch(&log, &format!("read-{index}")).await;
+ let result = success(&operation, json!({"text":"x".repeat(5 * 1024 * 1024)}));
+ through = log.append(&result).await.unwrap();
+ ids.push(result.event().id.clone());
+ }
+ prepare(&log, through).await;
+ let Page::Ready { chunks, .. } = log
+ .history_view(
+ "session",
+ through,
+ Position::Start,
+ false,
+ HistoryView::Conversation,
+ 128 * 1024,
+ None,
+ 1024 * 1024,
+ )
+ .await
+ .unwrap()
+ else {
+ panic!()
+ };
+ let results: Vec<_> = chunks
+ .iter()
+ .filter(|chunk| chunk.role == Role::ToolResult)
+ .collect();
+ assert_eq!(results.len(), 4);
+ assert_eq!(
+ results
+ .iter()
+ .map(|chunk| chunk.message_id.clone())
+ .collect::<Vec<_>>(),
+ ids
+ );
+ assert!(
+ results
+ .iter()
+ .all(|chunk| chunk.tool.as_ref().unwrap().result.is_some() && chunk.text.is_empty())
+ );
+ log.close().await.unwrap();
+}
diff --git a/platform/presentation/src/compact.rs b/platform/presentation/src/compact.rs
index b651d71f12..dff0d34997 100644
--- a/platform/presentation/src/compact.rs
+++ b/platform/presentation/src/compact.rs
@@ -17,55 +17,23 @@
* under the License.
*/
-use crate::{InvocationView, ProjectionError, State};
+use crate::{Content, InvocationView, Message, ProjectionError, State};
use maka_agent_facts::context::ModelPurpose;
-use maka_agent_facts::event::Fact;
-use maka_agent_facts::event::InvocationInput;
-use maka_agent_facts::event::RuntimeEvent;
+use maka_agent_facts::event::{Fact, InvocationInput, RuntimeEvent};
+
+pub(super) struct SummaryStart {
+ source_high_water: u64,
+ source_digest: String,
+ at: u64,
+}
impl InvocationView {
- // Summary attempts produce no transcript rows, whether standalone or inside
- // a Message Turn. Every request records its explicit purpose.
- pub(super) fn compact(&mut self, event: &RuntimeEvent) -> Result<bool, ProjectionError> {
- if let State::Active { invocation, .. } = &self.state {
- if *invocation != event.invocation {
- return Err(ProjectionError::Invalid("invocation identity changed"));
- }
- if let Fact::ModelRequested {
- step_id,
- purpose: ModelPurpose::Summary,
- ..
- } = &event.fact
- {
- if self.summary_step.is_some() {
- return Err(ProjectionError::Invalid("overlapping model steps"));
- }
- self.summary_step = Some(step_id.clone());
- return Ok(true);
- }
- if let Some(summary) = &self.summary_step {
- match &event.fact {
- Fact::ModelObserved { step_id, .. } if step_id == summary => return Ok(true),
- Fact::ModelCompleted { step_id, .. }
- | Fact::ModelInterrupted { step_id, .. }
- if step_id == summary =>
- {
- self.summary_step = None;
- return Ok(true);
- }
- Fact::InvocationEnded { outcome }
- if outcome.status()
- != maka_agent_facts::event::TerminalStatus::Completed =>
- {
- self.summary_step = None;
- }
- Fact::InvocationEnded { .. } => {
- return Err(ProjectionError::Invalid("unfinished summary at completion"));
- }
- _ => {} // Main and tool facts retain their ordinary identity checks.
- }
- }
- }
+ // Summary attempts stay private. Only the durable adoption emits a marker.
+ pub(super) fn compact(
+ &mut self,
+ event: &RuntimeEvent,
+ ts: u64,
+ ) -> Result<Option<Vec<Message>>, ProjectionError> {
if matches!(
event.fact,
Fact::InvocationOpened {
@@ -77,14 +45,80 @@ impl InvocationView {
return Err(ProjectionError::Invalid("duplicate invocation opening"));
}
self.state = State::Compact(event.invocation.clone());
- return Ok(true);
+ return Ok(Some(Vec::new()));
}
- let State::Compact(invocation) = &self.state else {
- return Ok(false);
+ let invocation = match &self.state {
+ State::Active { invocation, .. } | State::Compact(invocation) => invocation,
+ _ => return Ok(None),
};
if *invocation != event.invocation {
return Err(ProjectionError::Invalid("invocation identity changed"));
}
+ match &event.fact {
+ Fact::ModelRequested {
+ step_id,
+ purpose: ModelPurpose::Summary,
+ source_high_water,
+ source_digest,
+ ..
+ } => {
+ if self.summary_step.is_some() {
+ return Err(ProjectionError::Invalid("overlapping model steps"));
+ }
+ if self.summary_start.as_ref().is_none_or(|start| {
+ start.source_high_water != *source_high_water
+ || start.source_digest != *source_digest
+ }) {
+ self.summary_start = Some(SummaryStart {
+ source_high_water: *source_high_water,
+ source_digest: source_digest.clone(),
+ at: ts,
+ });
+ }
+ self.summary_step = Some(step_id.clone());
+ return Ok(Some(Vec::new()));
+ }
+ Fact::ContextCheckpointRecorded { .. } => {
+ let started = self.summary_start.take().ok_or(ProjectionError::Invalid(
+ "checkpoint without summary request",
+ ))?;
+ self.summary_step = None;
+ return Ok(Some(vec![Message {
+ id: event.id.clone(),
+ turn_id: event.invocation.turn_id.clone(),
+ ts,
+ content: Content::ContextCompacted {
+ duration_ms: ts.saturating_sub(started.at),
+ },
+ }]));
+ }
+ _ => {}
+ }
+ if let Some(summary) = &self.summary_step {
+ match &event.fact {
+ Fact::ModelObserved { step_id, .. } if step_id == summary => {
+ return Ok(Some(Vec::new()));
+ }
+ Fact::ModelCompleted { step_id, .. } | Fact::ModelInterrupted { step_id, .. }
+ if step_id == summary =>
+ {
+ self.summary_step = None;
+ return Ok(Some(Vec::new()));
+ }
+ Fact::InvocationEnded { outcome }
+ if outcome.status() != maka_agent_facts::event::TerminalStatus::Completed =>
+ {
+ self.summary_step = None;
+ }
+ Fact::InvocationEnded { .. } => {
+ return Err(ProjectionError::Invalid("unfinished summary at completion"));
+ }
+ _ => {}
+ }
+ }
+ if !matches!(self.state, State::Compact(_)) {
+ return Ok(None);
+ }
match event.fact {
Fact::ModelRequested {
purpose: ModelPurpose::Main,
@@ -94,15 +128,233 @@ impl InvocationView {
"main request in compact invocation",
));
}
- Fact::ModelRequested { .. }
- | Fact::ModelObserved { .. }
+ Fact::ModelObserved { .. }
| Fact::ModelCompleted { .. }
| Fact::ModelInterrupted { .. }
- | Fact::ContextCheckpointRecorded { .. }
| Fact::ToolResultArchived { .. } => {}
Fact::InvocationEnded { .. } => self.state = State::Ended,
_ => return Err(ProjectionError::Invalid("unexpected compaction fact")),
}
- Ok(true)
+ Ok(Some(Vec::new()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use maka_agent_facts::context::{
+ CheckpointMode, ContextCheckpoint, SummaryFormat, TextSummary,
+ };
+ use maka_agent_facts::event::{Invocation, InvocationOutcome, StoredEvent};
+ use maka_agent_facts::model::ModelStep;
+ use serde_json::json;
+ use std::time::{Duration, UNIX_EPOCH};
+
+ fn request(id: &str) -> Fact {
+ serde_json::from_value(json!({
+ "kind":"model_requested", "step_id":id, "purpose":"summary", "model_id":"model",
+ "item_acceptance":false, "source_scope":{"kind":"session","id":"session"},
+ "source_high_water":1, "source_digest":"source", "input_digest":"input", "route_identity":"route"
+ })).unwrap()
+ }
+
+ fn push(view: &mut InvocationView, sequence: u64, at: u64, fact: Fact) -> Vec<crate::Row> {
+ let mut event = RuntimeEvent::new(
+ Invocation {
+ session_id: "session".into(),
+ turn_id: "turn".into(),
+ run_id: "run".into(),
+ invocation_id: "invocation".into(),
+ },
+ fact,
+ );
+ event.id = format!("event-{sequence}");
+ event.recorded_at = UNIX_EPOCH + Duration::from_millis(at);
+ view.push(&StoredEvent { sequence, event }).unwrap()
+ }
+
+ #[test]
+ fn marker_appears_only_on_adoption_and_includes_retry_time() {
+ for standalone in [false, true] {
+ for adopted in [false, true] {
+ let mut view = InvocationView::new(1).unwrap();
+ push(
+ &mut view,
+ 1,
+ 0,
+ Fact::InvocationOpened {
+ configuration: None,
+ input: if standalone {
+ InvocationInput::ContextCompact {
+ request_fingerprint: "compact".into(),
+ }
+ } else {
+ InvocationInput::Message {
+ source_messages: Vec::new(),
+ content: "x".into(),
+ request_fingerprint: None,
+ }
+ },
+ },
+ );
+ let output: ModelStep = serde_json::from_value(json!({
+ "parts":[{"kind":"text","text_kind":"text","text":"private summary beyond presentation budget"}],
+ "finish_reason":"stop","usage":{}
+ })).unwrap();
+ assert!(push(&mut view, 2, 1000, request("summary")).is_empty());
+ assert!(
+ push(
+ &mut view,
+ 3,
+ 2000,
+ Fact::ModelCompleted {
+ step_id: "summary".into(),
+ output: output.clone()
+ }
+ )
+ .is_empty()
+ );
+ assert!(push(&mut view, 4, 3000, request("retry")).is_empty());
+ assert!(
+ push(
+ &mut view,
+ 5,
+ 4000,
+ Fact::ModelCompleted {
+ step_id: "retry".into(),
+ output
+ }
+ )
+ .is_empty()
+ );
+ if adopted {
+ let rows = push(
+ &mut view,
+ 6,
+ 5500,
+ Fact::ContextCheckpointRecorded {
+ checkpoint: ContextCheckpoint {
+ mode: CheckpointMode::Standalone,
+ covered_through: 1,
+ source_digest: "source".into(),
+ previous_checkpoint_id: None,
+ summary_step_id: "retry".into(),
+ summary: TextSummary {
+ format: SummaryFormat::SectionsV1,
+ text: "private summary".into(),
+ },
+ },
+ },
+ );
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].sequence, 6 * 256);
+ assert_eq!(
+ serde_json::to_value(&rows[0].message).unwrap(),
+ json!({
+ "id":"event-6", "turnId":"turn", "ts":5500,
+ "type":"context_compacted", "durationMs":4500
+ })
+ );
+ } else {
+ let rows = push(
+ &mut view,
+ 6,
+ 5500,
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Failed {
+ class: "summary_failed".into(),
+ message: None,
+ },
+ },
+ );
+ assert!(rows.iter().all(|row| !matches!(
+ row.message.content,
+ Content::ContextCompacted { .. }
+ )));
+ }
+ }
+ }
+ }
+ #[test]
+ fn concurrent_main_preserves_summary_timing_and_new_source_restarts_it() {
+ for new_source in [false, true] {
+ let mut view = InvocationView::new(1024).unwrap();
+ push(
+ &mut view,
+ 1,
+ 0,
+ Fact::InvocationOpened {
+ configuration: None,
+ input: InvocationInput::Message {
+ source_messages: Vec::new(),
+ content: "question".into(),
+ request_fingerprint: None,
+ },
+ },
+ );
+ push(&mut view, 2, 1000, request("summary"));
+ let mut main = request("main");
+ if let Fact::ModelRequested { purpose, .. } = &mut main {
+ *purpose = ModelPurpose::Main;
+ }
+ push(&mut view, 3, 1500, main);
+ let output: ModelStep =
+ serde_json::from_value(json!({"parts":[],"finish_reason":"stop","usage":{}}))
+ .unwrap();
+ push(
+ &mut view,
+ 4,
+ 2000,
+ Fact::ModelCompleted {
+ step_id: "summary".into(),
+ output: output.clone(),
+ },
+ );
+ let mut retry = request("retry");
+ if new_source
+ && let Fact::ModelRequested {
+ source_high_water,
+ source_digest,
+ ..
+ } = &mut retry
+ {
+ *source_high_water = 2;
+ *source_digest = "new-source".into();
+ }
+ push(&mut view, 5, 3000, retry);
+ push(
+ &mut view,
+ 6,
+ 4000,
+ Fact::ModelCompleted {
+ step_id: "retry".into(),
+ output,
+ },
+ );
+ let rows = push(
+ &mut view,
+ 7,
+ 5500,
+ Fact::ContextCheckpointRecorded {
+ checkpoint: ContextCheckpoint {
+ mode: CheckpointMode::PreTurn,
+ covered_through: if new_source { 2 } else { 1 },
+ source_digest: if new_source { "new-source" } else { "source" }.into(),
+ previous_checkpoint_id: None,
+ summary_step_id: "retry".into(),
+ summary: TextSummary {
+ format: SummaryFormat::SectionsV1,
+ text: "summary".into(),
+ },
+ },
+ },
+ );
+ assert_eq!(
+ rows[0].message.content,
+ Content::ContextCompacted {
+ duration_ms: if new_source { 2500 } else { 4500 }
+ }
+ );
+ }
}
}
diff --git a/platform/presentation/src/lib.rs b/platform/presentation/src/lib.rs
index 5053399169..f75dfcb868 100644
--- a/platform/presentation/src/lib.rs
+++ b/platform/presentation/src/lib.rs
@@ -80,6 +80,7 @@ pub struct InvocationView {
max_text_bytes: usize,
tools: tools::Tools,
summary_step: Option<String>,
+ summary_start: Option<compact::SummaryStart>,
}
impl InvocationView {
@@ -94,6 +95,7 @@ impl InvocationView {
max_text_bytes,
tools: tools::Tools::new(max_text_bytes),
summary_step: None,
+ summary_start: None,
})
}
@@ -139,11 +141,18 @@ impl InvocationView {
}
let event = &stored.event;
let ts = timestamp(event)?;
- if self.compact(event)? {
+ let base = watermark(stored.sequence)? - 255;
+ if let Some(messages) = self.compact(event, ts)? {
self.last_sequence = stored.sequence;
- return Ok(Vec::new());
+ return Ok(messages
+ .into_iter()
+ .enumerate()
+ .map(|(index, message)| Row {
+ sequence: base + index as u64,
+ message,
+ })
+ .collect());
}
- let base = watermark(stored.sequence)? - 255;
let mut messages = Vec::new();
match &event.fact {
Fact::MessageImported { record, .. } => {
diff --git a/platform/presentation/src/message.rs b/platform/presentation/src/message.rs
index ad62d061bf..d93628d4ba 100644
--- a/platform/presentation/src/message.rs
+++ b/platform/presentation/src/message.rs
@@ -99,6 +99,9 @@ pub struct Message {
rename_all_fields = "camelCase"
)]
pub enum Content {
+ ContextCompacted {
+ duration_ms: u64,
+ },
ModelInterruption {
message: String,
},
diff --git a/plugins/agent/agent-screen/actions.ts b/plugins/agent/agent-screen/actions.ts
index 668130e7d8..c62984d0ec 100644
--- a/plugins/agent/agent-screen/actions.ts
+++ b/plugins/agent/agent-screen/actions.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { canCompact, openCompact, compactCopy } from './compact.js';
import { tuiText, copy } from './locale.js';
import type {
Action,
@@ -459,6 +460,8 @@ export function select(state: State, actions: Action[], session: AgentSession |
state.navigation++;
state.parts = [];
state.run = null;
+ state.compacting = false;
+ state.compact = null;
state.metrics = null;
state.queue = null;
state.interactions = null;
@@ -544,6 +547,8 @@ export function mutationPending(state: State) {
state.uncertain !== null ||
Object.values(state.pending).some((request) =>
[
+ 'compact',
+ 'compactField',
'queueRead',
'questionRead',
'respond',
@@ -715,6 +720,13 @@ export function rootCommands(
? copied
: null;
const commands: (PaletteCommand & { kind: RootCommand })[] = [
+ {
+ kind: 'compact-open',
+ id: 'compact-open',
+ label: compactCopy(locale).title,
+ hint: '/compact',
+ disabled: !route || !canCompact(state),
+ },
...(target === 'tui'
? [
{
@@ -1057,7 +1069,8 @@ export function rootCommand(
)
)
return false;
- if (kind === 'outputs-open') {
+ if (kind === 'compact-open') openCompact(state, actions);
+ else if (kind === 'outputs-open') {
state.inspector = 'outputs';
const visit = state.visits.find((entry) => entry.id === state.selected?.id);
if (visit) {
@@ -1389,6 +1402,7 @@ export function changeSession(
}
export function closeDialog(state: State) {
+ if (state.dialog === 'compact') state.compact = null;
if (state.dialog === 'session-change') state.sessionChange = null;
// Cancel follows the original queue sheet: discard this edit, not an accepted operation.
if (state.dialog === 'queue') state.queueEdit = null;
diff --git a/plugins/agent/agent-screen/compact.ts b/plugins/agent/agent-screen/compact.ts
new file mode 100644
index 0000000000..7c40349a3f
--- /dev/null
+++ b/plugins/agent/agent-screen/compact.ts
@@ -0,0 +1,282 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type {
+ Action,
+ ComponentInput,
+ EditorCommand,
+ EditorObservation,
+ TextChunk,
+ TextareaProps,
+} from '../../../packages/plugin-sdk/src/index.js';
+import type { Theme } from '../../shared/contracts.js';
+import { createCopy } from '../../shared/locale.js';
+import { sameValue } from '../../shared/value.js';
+import { fill, type Node, type Presentation } from '../../shared/view.js';
+import { intent, mutationPending, observe } from './actions.js';
+import type { State } from './state.js';
+
+export const compactCopy = createCopy({
+ title: ['Compact context', '压缩上下文', '壓縮上下文'],
+ help: [
+ 'Summarize earlier context to make room. Edit the prompt for this compression only; your conversation history stays available.',
+ '总结较早的上下文以腾出空间。此处修改仅用于本次压缩,聊天历史仍可查看。',
+ '總結較早的上下文以騰出空間。此處修改僅用於本次壓縮,聊天歷史仍可查看。',
+ ],
+ prompt: ['Compression prompt', '压缩提示词', '壓縮提示詞'],
+ confirm: ['Compact', '开始压缩', '開始壓縮'],
+ cancel: ['Cancel', '取消', '取消'],
+ check: ['Check operation', '检查操作结果', '檢查操作結果'],
+ unknown: [
+ 'The operation outcome is unknown. Check it before retrying.',
+ '操作结果尚未确认,请先检查结果。',
+ '操作結果尚未確認,請先檢查結果。',
+ ],
+ loading: ['Loading prompt…', '正在加载提示词…', '正在載入提示詞…'],
+ failed: [
+ 'Could not compact. Check that the conversation is idle and a model is selected, then retry.',
+ '无法压缩。请确认会话空闲且已选择模型,然后重试。',
+ '無法壓縮。請確認會話閒置且已選擇模型,然後重試。',
+ ],
+});
+export interface CompactState {
+ sessionId: string;
+ attempt: number;
+ prompt: string | null;
+ observation: EditorObservation | null;
+ command: EditorCommand | null;
+ ready: boolean;
+ failed: boolean;
+}
+export type CompactRequest =
+ | { kind: 'compactPrompt'; sessionId: string; attempt: number }
+ | { kind: 'compactField'; sessionId: string; attempt: number; draft: EditorObservation }
+ | { kind: 'compact'; sessionId: string };
+export function canCompact(state: State) {
+ return (
+ !!state.selected &&
+ !state.selected.archived &&
+ state.selected.activity === 'idle' &&
+ !!state.model &&
+ !state.executor &&
+ !state.run &&
+ !state.compacting &&
+ !mutationPending(state)
+ );
+}
+export function openCompact(state: State, actions: Action[]) {
+ if (!canCompact(state)) {
+ state.notice = 'unavailable';
+ return;
+ }
+ const sessionId = state.selected!.id,
+ attempt = ++state.serial;
+ state.compact = {
+ sessionId,
+ attempt,
+ prompt: null,
+ observation: null,
+ command: null,
+ ready: false,
+ failed: false,
+ };
+ state.dialog = 'compact';
+ intent(
+ state,
+ actions,
+ { kind: 'compactPrompt', sessionId, attempt },
+ 'agent',
+ 'compactionPrompt',
+ { sessionId },
+ );
+}
+function initialize(state: State) {
+ const edit = state.compact;
+ if (edit?.prompt !== null && edit?.observation && !edit.command && !edit.ready)
+ edit.command = {
+ owner: edit.observation.snapshot.text.owner,
+ sequence: ++state.serial,
+ basedOn: edit.observation.revision,
+ edit: { kind: 'reset', text: edit.prompt },
+ };
+}
+export function compactComponent(
+ state: State,
+ input: Extract<ComponentInput, { kind: 'component' }>,
+) {
+ const edit = state.compact;
+ if (input.child !== 'compact-prompt' || input.name !== 'changed' || !edit) return false;
+ const observed = input.event as EditorObservation;
+ if (edit.observation && edit.observation.snapshot.text.owner !== observed.snapshot.text.owner) {
+ edit.command = null;
+ edit.ready = false;
+ }
+ edit.observation = observed;
+ if (
+ edit.command &&
+ observed.receipt?.owner === edit.command.owner &&
+ observed.receipt.sequence === edit.command.sequence
+ ) {
+ edit.ready = observed.receipt.outcome.status === 'applied';
+ edit.command = null;
+ edit.failed = !edit.ready;
+ } else initialize(state);
+ return true;
+}
+export function compactConfirm(state: State, actions: Action[]) {
+ const edit = state.compact,
+ draft = edit?.observation;
+ if (
+ !edit ||
+ state.dialog !== 'compact' ||
+ state.selected?.id !== edit.sessionId ||
+ !canCompact(state) ||
+ !edit.ready ||
+ edit.command ||
+ !draft ||
+ draft.snapshot.marked
+ )
+ return;
+ edit.failed = false;
+ intent(
+ state,
+ actions,
+ { kind: 'compactField', sessionId: edit.sessionId, attempt: edit.attempt, draft },
+ 'reader',
+ 'read',
+ { start: 0, end: draft.snapshot.text.bytes },
+ {
+ text: {
+ child: 'compact-prompt',
+ method: 'snapshot',
+ input: {
+ kind: 'at_revision',
+ owner: draft.snapshot.text.owner,
+ revision: draft.snapshot.text.revision,
+ },
+ },
+ },
+ );
+}
+export function compactQuery(
+ state: State,
+ actions: Action[],
+ request: CompactRequest,
+ value: unknown,
+) {
+ const edit = state.compact;
+ if (
+ !edit ||
+ request.kind === 'compact' ||
+ edit.attempt !== request.attempt ||
+ edit.sessionId !== request.sessionId ||
+ state.selected?.id !== request.sessionId
+ )
+ return;
+ if (request.kind === 'compactPrompt') {
+ edit.prompt = (value as { compactionPrompt: string }).compactionPrompt;
+ initialize(state);
+ } else {
+ const chunk = value as TextChunk;
+ if (
+ !sameValue(chunk.metadata, request.draft.snapshot.text) ||
+ !sameValue(edit.observation?.snapshot.text, request.draft.snapshot.text) ||
+ !chunk.text.trim() ||
+ new TextEncoder().encode(chunk.text).length !== request.draft.snapshot.text.bytes ||
+ !canCompact(state)
+ ) {
+ edit.failed = true;
+ return;
+ }
+ intent(state, actions, { kind: 'compact', sessionId: edit.sessionId }, 'agent', 'compact', {
+ sessionId: edit.sessionId,
+ prompt: chunk.text,
+ model: state.model!.choice.selection,
+ thinkingLevel: state.model!.thinkingLevel,
+ });
+ }
+}
+export function compactSettled(state: State, actions: Action[], sessionId: string, value: unknown) {
+ if (state.selected?.id !== sessionId) return;
+ if ((value as { kind: string }).kind === 'started') {
+ state.compact = null;
+ if (state.dialog === 'compact') state.dialog = null;
+ state.notice = null;
+ } else if (state.compact) state.compact.failed = true;
+ observe(state, actions);
+}
+export function compactView<N extends Node>(
+ presentation: Presentation<N>,
+ state: State,
+ theme: Theme,
+ locale: string,
+): N {
+ const ui = presentation.paint(theme),
+ text = compactCopy(locale),
+ edit = state.compact;
+ const busy = mutationPending(state);
+ return ui.box(
+ 'compact-content',
+ [
+ ui.text('compact-help', text.help, 14, theme.muted),
+ ...(edit?.prompt === null ? [ui.text('compact-loading', text.loading)] : []),
+ presentation.slot(
+ 'compact-prompt',
+ 'editor',
+ {
+ accessibilityLabel: text.prompt,
+ placeholder: '',
+ autoFocus: true,
+ tabIndex: 1,
+ readOnly: false,
+ disabled: busy || !edit?.ready || !!edit.command,
+ command: edit?.command ?? null,
+ appearance: theme.textarea,
+ softWrap: true,
+ terminalRows: { min: 6, max: 12 },
+ } satisfies TextareaProps,
+ { changed: 'changed' },
+ ),
+ ...(edit?.failed ? [ui.text('compact-error', text.failed, 13, theme.warning)] : []),
+ ...(state.uncertain?.reference.method === 'compact'
+ ? [
+ ui.text('compact-unknown', text.unknown, 13, theme.warning),
+ ui.button(
+ 'compact-check',
+ text.check,
+ Object.values(state.pending).some((request) => request.kind === 'receipt'),
+ ),
+ ]
+ : []),
+ ui.box(
+ 'compact-controls',
+ [
+ ui.button(
+ 'compact-confirm',
+ text.confirm,
+ busy || !edit?.ready || !!edit.command || !canCompact(state),
+ ),
+ ui.button('compact-cancel', text.cancel, busy),
+ ],
+ { row: true, gap: 1 },
+ ),
+ ],
+ { gap: 1, style: { width: fill } },
+ );
+}
diff --git a/plugins/agent/agent-screen/component-events.ts b/plugins/agent/agent-screen/component-events.ts
index c4a266e0f5..f0abc1bd44 100644
--- a/plugins/agent/agent-screen/component-events.ts
+++ b/plugins/agent/agent-screen/component-events.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { compactComponent, openCompact } from './compact.js';
import type {
Action,
AgentDirectorySelection,
@@ -104,6 +105,17 @@ export function handleComponent<N extends Node>(
locale: string,
) {
const target = presentation.target;
+ if (input.child === 'composer' && input.name === 'compact') {
+ const command = input.event as Pick<ComposerSent, 'context' | 'dataSource'>;
+ if (
+ command.context === state.selected?.id &&
+ sameValue(command.dataSource, state.selected.dataSource)
+ )
+ openCompact(state, actions);
+ return frame(presentation, configuredLocale, state, values, actions);
+ }
+ if (compactComponent(state, input))
+ return frame(presentation, configuredLocale, state, values, actions);
if (goalComponent(state, input))
return frame(presentation, configuredLocale, state, values, actions);
if (input.name === 'chrome' && state.openedPages.includes(input.child as Page)) {
diff --git a/plugins/agent/agent-screen/conversation-view.ts b/plugins/agent/agent-screen/conversation-view.ts
index e18bbb21cc..25c0648d1b 100644
--- a/plugins/agent/agent-screen/conversation-view.ts
+++ b/plugins/agent/agent-screen/conversation-view.ts
@@ -307,6 +307,7 @@ export function conversationView<N extends Node>(
autoFocus: !state.searchOpen && state.browse === null,
},
{
+ compact: 'compact',
sent: 'sent',
submission: 'submission',
setup: 'setup',
@@ -467,6 +468,7 @@ export function conversationView<N extends Node>(
sessionId: state.selected?.id ?? null,
dataSource: state.selected?.dataSource ?? null,
running: !!state.run,
+ compacting: state.compacting,
metrics,
theme,
locale,
diff --git a/plugins/agent/agent-screen/events.ts b/plugins/agent/agent-screen/events.ts
index 42a1923309..f13120328c 100644
--- a/plugins/agent/agent-screen/events.ts
+++ b/plugins/agent/agent-screen/events.ts
@@ -272,6 +272,7 @@ export function handleEvent<N extends Node>(
request.kind === 'respond' ||
request.kind === 'markRead' ||
request.kind === 'uploadAttachment' ||
+ request.kind === 'compact' ||
request.kind === 'recapGenerate' ||
request.kind === 'goalChange' ||
request.kind === 'graphChange' ||
diff --git a/plugins/agent/agent-screen/frame.ts b/plugins/agent/agent-screen/frame.ts
index e0e0cd7a43..159a82c493 100644
--- a/plugins/agent/agent-screen/frame.ts
+++ b/plugins/agent/agent-screen/frame.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { compactView, compactCopy } from './compact.js';
import type {
Action,
ComponentValues,
@@ -481,51 +482,54 @@ export function frame<N extends Node>(
state,
ui.dialog(
'agent-screen-dialog',
- state.dialog === 'sandbox'
- ? text.sandboxTitle
- : state.dialog === 'session-change'
- ? text.deleteSessionTitle
- : state.dialog === 'attachments'
- ? target === 'tui' && state.attachments.selection?.browse
- ? tuiText(locale, 'attachments-local-files')
- : text.attachmentTitle
- : state.dialog === 'skills'
- ? text.skillsTitle
- : state.dialog === 'terminal'
- ? text.terminalTitle
- : state.dialog === 'question'
- ? state.interaction?.record?.request.kind === 'form'
- ? text.formTitle
- : text.questionsTitle
- : state.dialog === 'approval'
- ? state.interaction?.record?.request.kind === 'permissions'
- ? text.permissionApprovalTitle
- : state.interaction?.record?.request.kind === 'client_capability'
- ? text.computerApprovalTitle
- : text.approvalTitle
- : state.dialog === 'directories'
- ? text.directoryTitle
- : state.dialog === 'graph'
- ? text.graphTitle
- : state.dialog === 'plan'
- ? text.planTitle
- : state.dialog === 'goal'
- ? text.goalTitle
- : state.dialog === 'recap'
- ? text.recapTitle
- : state.dialog === 'checklist'
- ? text.checklistTitle
- : state.dialog === 'details'
- ? text.detailsTitle
- : state.dialog === 'queue'
- ? text.queueEdit
- : state.dialog === 'help'
- ? text.helpTitle
- : text.paletteTitle,
+ state.dialog === 'compact'
+ ? compactCopy(locale).title
+ : state.dialog === 'sandbox'
+ ? text.sandboxTitle
+ : state.dialog === 'session-change'
+ ? text.deleteSessionTitle
+ : state.dialog === 'attachments'
+ ? target === 'tui' && state.attachments.selection?.browse
+ ? tuiText(locale, 'attachments-local-files')
+ : text.attachmentTitle
+ : state.dialog === 'skills'
+ ? text.skillsTitle
+ : state.dialog === 'terminal'
+ ? text.terminalTitle
+ : state.dialog === 'question'
+ ? state.interaction?.record?.request.kind === 'form'
+ ? text.formTitle
+ : text.questionsTitle
+ : state.dialog === 'approval'
+ ? state.interaction?.record?.request.kind === 'permissions'
+ ? text.permissionApprovalTitle
+ : state.interaction?.record?.request.kind === 'client_capability'
+ ? text.computerApprovalTitle
+ : text.approvalTitle
+ : state.dialog === 'directories'
+ ? text.directoryTitle
+ : state.dialog === 'graph'
+ ? text.graphTitle
+ : state.dialog === 'plan'
+ ? text.planTitle
+ : state.dialog === 'goal'
+ ? text.goalTitle
+ : state.dialog === 'recap'
+ ? text.recapTitle
+ : state.dialog === 'checklist'
+ ? text.checklistTitle
+ : state.dialog === 'details'
+ ? text.detailsTitle
+ : state.dialog === 'queue'
+ ? text.queueEdit
+ : state.dialog === 'help'
+ ? text.helpTitle
+ : text.paletteTitle,
background,
ui.box(
'dialog-content',
[
+ ...(state.dialog === 'compact' ? [compactView(presentation, state, theme, locale)] : []),
...(state.dialog === 'sandbox' ? [sandboxView(presentation, state, theme, locale)] : []),
...(state.dialog === 'session-change' && state.sessionChange
? [
diff --git a/plugins/agent/agent-screen/index.ts b/plugins/agent/agent-screen/index.ts
index 49ab77130c..0813c76fa0 100644
--- a/plugins/agent/agent-screen/index.ts
+++ b/plugins/agent/agent-screen/index.ts
@@ -112,6 +112,8 @@ export function agentScreen<N extends Node>(
navigation: 0,
landing: { sequence: 0, edge: 'end' },
tailReceipt: null,
+ compact: null,
+ compacting: false,
fileContext: null,
copyRequest: null,
messageCopy: null,
diff --git a/plugins/agent/agent-screen/messages.ts b/plugins/agent/agent-screen/messages.ts
index 979cd655d6..ff86702186 100644
--- a/plugins/agent/agent-screen/messages.ts
+++ b/plugins/agent/agent-screen/messages.ts
@@ -141,13 +141,14 @@ function chunkId(chunk: NonNullable<State['window']>['page']['chunks'][number])
function historyMessage(chunk: NonNullable<State['window']>['page']['chunks'][number]): Message {
return {
id: chunkId(chunk),
+ ...(chunk.compaction ? { compaction: chunk.compaction } : {}),
contentKey: 'body-' + chunkId(chunk),
role: chunk.field === 'thinking' ? 'thinking' : chunk.role,
timestamp: chunk.timestamp,
text: chunk.text,
tool: chunk.tool,
continued: chunk.offset !== 0 || utf8Bytes(chunk.text) !== chunk.totalBytes,
- source: chunk.sequence,
+ source: chunk.role === 'compaction' ? null : chunk.sequence,
image: chunk.tool?.result?.image ?? false,
};
}
diff --git a/plugins/agent/agent-screen/raw-events.ts b/plugins/agent/agent-screen/raw-events.ts
index 932e2eff47..282078fd19 100644
--- a/plugins/agent/agent-screen/raw-events.ts
+++ b/plugins/agent/agent-screen/raw-events.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { compactConfirm } from './compact.js';
import type {
Action,
ComponentInput,
@@ -74,6 +75,14 @@ export function handleRaw<N extends Node>(
locale: string,
) {
const target = presentation.target;
+ if (input.key === 'compact-confirm') compactConfirm(state, actions);
+ if (
+ input.key === 'compact-check' &&
+ state.uncertain?.reference.method === 'compact' &&
+ !Object.values(state.pending).some((request) => request.kind === 'receipt')
+ )
+ intent(state, actions, { kind: 'receipt' }, 'receipts', 'read', state.uncertain.reference);
+ if (input.key === 'compact-cancel' && !mutationPending(state)) closeDialog(state);
if (
input.key === 'schedule-reminder' &&
!state.dialog &&
diff --git a/plugins/agent/agent-screen/results.ts b/plugins/agent/agent-screen/results.ts
index c6431c3060..f951340b39 100644
--- a/plugins/agent/agent-screen/results.ts
+++ b/plugins/agent/agent-screen/results.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { compactQuery, compactSettled } from './compact.js';
import type {
Action,
AgentRecapReceipt,
@@ -80,6 +81,8 @@ function settled(state: State, actions: Action[], request: Mutation, value: unkn
limit: 1,
});
catalog(state);
+ } else if (request.kind === 'compact') {
+ compactSettled(state, actions, request.sessionId, value);
} else if (request.kind === 'create') {
const created = value as AgentCreated;
if (created.kind === 'rejected') {
@@ -302,6 +305,14 @@ export function receipt(state: State, actions: Action[], request: Mutation, repl
}
export function queryFailed(state: State, request: Request) {
+ if (
+ request.kind === 'compactPrompt' ||
+ request.kind === 'compactField' ||
+ request.kind === 'compact'
+ ) {
+ if (state.compact?.sessionId === request.sessionId) state.compact.failed = true;
+ return;
+ }
// A failed background checkpoint can be retried on the next confirmed result.
if ((request.kind === 'restorePage' || request.kind === 'restoreReceipt') && !state.restoring) {
state.restoreAfter = state.restoreThrough;
@@ -425,6 +436,10 @@ export function queryFailed(state: State, request: Request) {
export function querySucceeded(state: State, actions: Action[], request: Request, value: unknown) {
switch (request.kind) {
+ case 'compactPrompt':
+ case 'compactField':
+ compactQuery(state, actions, request, value);
+ break;
case 'goalField':
goalFieldResult(state, actions, request, value);
break;
@@ -540,6 +555,7 @@ export function querySucceeded(state: State, actions: Action[], request: Request
observation.session.revision >= state.selected!.revision
) {
state.run = observation.run ?? null;
+ state.compacting = observation.compacting ?? false;
state.metrics = observation.metrics ?? null;
state.runThrough = observation.through;
if (!state.run && state.notice === 'stopping') state.notice = null;
diff --git a/plugins/agent/agent-screen/state.ts b/plugins/agent/agent-screen/state.ts
index 57313fb62c..d9093a1c87 100644
--- a/plugins/agent/agent-screen/state.ts
+++ b/plugins/agent/agent-screen/state.ts
@@ -65,6 +65,8 @@ import { type AttachmentDrafts } from '../../shared/attachments.js';
import { type ComposerReadiness } from '../../shared/drafts.js';
+import type { CompactState, CompactRequest } from './compact.js';
+
import type { GoalState, GoalRequest } from './goal.js';
import type { PlanState, PlanRequest } from './plan.js';
import type { GraphState, GraphRequest } from './graph.js';
@@ -74,6 +76,7 @@ type BackendPreference = import('../../../packages/plugin-sdk/src/index.js').Age
type Notice = keyof Copy | null;
export type Request =
+ | CompactRequest
| { kind: 'sandboxChange'; epoch: number; sessionId: string }
| GoalRequest
| PlanRequest
@@ -144,6 +147,7 @@ export type Mutation =
| 'respond'
| 'markRead'
| 'uploadAttachment'
+ | 'compact'
| 'recapGenerate'
| 'goalChange'
| 'planChange'
@@ -309,7 +313,10 @@ export interface State {
skills: boolean;
place: string;
sessionChange: AgentSession | null;
+ compact: CompactState | null;
+ compacting: boolean;
dialog:
+ | 'compact'
| 'sandbox'
| 'session-change'
| 'attachments'
@@ -413,6 +420,7 @@ export type RootCommand =
| 'appearance-open'
| 'model-setup'
| 'terminal-open'
+ | 'compact-open'
| 'skills-open'
| 'checklist-open'
| 'recap-open'
diff --git a/plugins/agent/api/src/contract.rs b/plugins/agent/api/src/contract.rs
index bcec5b63a7..c5dfd86635 100644
--- a/plugins/agent/api/src/contract.rs
+++ b/plugins/agent/api/src/contract.rs
@@ -55,6 +55,9 @@ pub use projects::*;
#[path = "contract_execution.rs"]
mod execution;
pub use execution::*;
+#[path = "contract_compaction.rs"]
+mod compaction;
+pub use compaction::*;
#[path = "contract_interactions.rs"]
mod interaction;
@@ -740,6 +743,8 @@ pub struct SessionRead {
#[schemars(rename = "AgentObservation")]
pub struct Observation {
pub session: Session,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub compacting: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remembered_backend: Option<BackendPreference>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -938,6 +943,8 @@ pub struct HistoryAttachment {
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[schemars(rename = "AgentHistoryChunk")]
pub struct HistoryChunk {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub compaction: Option<maka_agent_ports::session::history::Compaction>,
/// Display metadata only, on the first user-message fragment; no storage capability.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[schemars(length(max = 8))]
@@ -1383,6 +1390,14 @@ pub fn contract() -> Contract {
method::<ExecutionRead, ExecutionResult>(MethodMode::Query),
),
("work".into(), method::<WorkRead, Work>(MethodMode::Query)),
+ (
+ "compactionPrompt".into(),
+ method::<SessionRead, CompactionPrompt>(MethodMode::Query),
+ ),
+ (
+ "compact".into(),
+ method::<Compact, CompactResult>(MethodMode::Mutation),
+ ),
(
"resume".into(),
method::<Resume, ResumeResult>(MethodMode::Mutation),
diff --git a/plugins/agent/api/src/contract_compaction.rs b/plugins/agent/api/src/contract_compaction.rs
new file mode 100644
index 0000000000..bba9bc8e38
--- /dev/null
+++ b/plugins/agent/api/src/contract_compaction.rs
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::{Execution, ModelSelection};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[derive(Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(rename = "AgentCompactionPrompt")]
+pub struct CompactionPrompt {
+ pub compaction_prompt: String,
+ pub default_compaction_prompt: String,
+}
+#[derive(Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(rename = "AgentCompact")]
+pub struct Compact {
+ #[schemars(length(min = 1, max = 128))]
+ pub session_id: String,
+ pub model: ModelSelection,
+ pub thinking_level: Option<maka_agent_facts::execution::ThinkingLevel>,
+ /// One invocation only; omission uses the global preference.
+ pub prompt: Option<String>,
+}
+#[derive(Serialize, Deserialize, JsonSchema)]
+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
+#[schemars(rename = "AgentCompactResult")]
+pub enum CompactResult {
+ Started { execution: Execution },
+ Rejected { reason: CompactRejection },
+}
+#[derive(Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+#[schemars(rename = "AgentCompactRejection")]
+pub enum CompactRejection {
+ Busy,
+ Closed,
+ Archived,
+ BackendUnavailable,
+ WorkspaceChanged,
+}
diff --git a/plugins/agent/assistant-preferences/index.ts b/plugins/agent/assistant-preferences/index.ts
index da20a081a7..834b341ba1 100644
--- a/plugins/agent/assistant-preferences/index.ts
+++ b/plugins/agent/assistant-preferences/index.ts
@@ -40,7 +40,7 @@ import { sameValue } from '../../shared/value.js';
import { copy, tuiText } from './locale.js';
import { fill, output, type Node, type Presentation } from '../../shared/view.js';
-type Name = 'name' | 'tone';
+type Name = 'name' | 'tone' | 'compaction';
interface Field {
observation: EditorObservation | null;
command: EditorCommand | null;
@@ -49,7 +49,7 @@ interface Field {
ready: boolean;
}
type Request =
- | { kind: 'preferences'; reset: boolean }
+ | { kind: 'preferences'; reset: boolean | 'compaction' | 'personalization' }
| { kind: 'mutate' | 'receipt' }
| { kind: 'history'; after: number }
| { kind: 'field'; name: Name; captured: EditorObservation };
@@ -61,6 +61,7 @@ interface State extends PageState {
pending: { key: string; request: Request } | null;
current: { input: SettingsPreferencesUpdate; reference: RecoveryRef | null } | null;
capture: { name: EditorObservation; tone: EditorObservation; displayName: string | null } | null;
+ compactionCapture: EditorObservation | null;
restoring: boolean;
notice: string | null;
}
@@ -94,7 +95,11 @@ function request(
state.pending = { key, request };
actions.push({ key, binding, member: 0, method, input, resources });
}
-function read(state: State, actions: Action[], reset = true) {
+function read(
+ state: State,
+ actions: Action[],
+ reset: boolean | 'compaction' | 'personalization' = true,
+) {
request(state, actions, { kind: 'preferences', reset }, 'settings', 'assistantPreferences', {});
}
function history(state: State, actions: Action[], after = 0) {
@@ -109,6 +114,7 @@ function disabled(state: State, props: ProjectsProps) {
!!state.pending ||
!!state.current ||
!!state.capture ||
+ !!state.compactionCapture ||
state.restoring
);
}
@@ -130,7 +136,12 @@ function settle(state: State, reply: OperationReply, actions: Action[]) {
return;
}
const result = reply.receipt.outcome.value as SettingsPreferencesUpdated;
- const reset = state.current.input.mutation.kind === 'personalization' || !state.saved;
+ const reset =
+ state.current.input.mutation.kind === 'compaction_prompt'
+ ? 'compaction'
+ : state.current.input.mutation.kind === 'personalization'
+ ? 'personalization'
+ : !state.saved;
state.current = null;
state.notice =
result.kind === 'committed'
@@ -141,7 +152,7 @@ function settle(state: State, reply: OperationReply, actions: Action[]) {
if (result.kind === 'committed' || !state.saved) read(state, actions, reset);
}
function capture(state: State, actions: Action[], name: Name) {
- const captured = state.capture![name];
+ const captured = name === 'compaction' ? state.compactionCapture! : state.capture![name];
request(
state,
actions,
@@ -175,12 +186,12 @@ export function assistantPreferences<N extends Node>(
t = (key: string) => tuiText(props.locale, key);
const busy = disabled(state, props),
text = copy(props.locale);
- const fields = (['name', 'tone'] as const).map((name) => {
+ const fields = (['name', 'tone', 'compaction'] as const).map((name) => {
const common = {
accessibilityLabel: t('assistant-' + name),
placeholder: '',
autoFocus: name === 'name',
- tabIndex: name === 'name' ? 1 : 2,
+ tabIndex: name === 'name' ? 1 : name === 'tone' ? 2 : 3,
readOnly: false,
disabled: busy || !state.fields[name].ready || !!state.fields[name].command,
command: state.fields[name].command,
@@ -213,7 +224,7 @@ export function assistantPreferences<N extends Node>(
const content = ui.box(
'assistant-preferences-content',
[
- ...fields,
+ ...fields.slice(0, 2),
ui.text(
'assistant-notice',
state.notice && !state.pending ? t(state.notice) : ' ',
@@ -228,6 +239,21 @@ export function assistantPreferences<N extends Node>(
(name) => !state.fields[name].ready || !!state.fields[name].command,
),
),
+ fields[2]!,
+ ui.button(
+ 'save-compaction',
+ t('assistant-compaction-save'),
+ busy || !state.fields.compaction.ready || !!state.fields.compaction.command,
+ ),
+ ui.button(
+ 'reset-compaction',
+ t('assistant-compaction-reset'),
+ busy ||
+ !state.saved ||
+ !state.fields.compaction.ready ||
+ !!state.fields.compaction.command,
+ ),
+ ui.text('assistant-compaction-help', t('assistant-compaction-help'), 13, props.theme.muted),
ui.text('assistant-help', t('assistant-instructions-help'), 13, props.theme.muted),
ui.button(
'instructions',
@@ -303,10 +329,11 @@ export function assistantPreferences<N extends Node>(
revision: 0,
serial: 0,
saved: null,
- fields: { name: field(), tone: field() },
+ fields: { name: field(), tone: field(), compaction: field() },
pending: null,
current: null,
capture: null,
+ compactionCapture: null,
restoring: true,
notice: null,
};
@@ -323,7 +350,7 @@ export function assistantPreferences<N extends Node>(
const actions: Action[] = [],
events: Emission[] = [];
if (input.kind === 'component') {
- const name = (['name', 'tone'] as const).find(
+ const name = (['name', 'tone', 'compaction'] as const).find(
(name) => input.kind === 'component' && input.child === 'assistant-' + name,
);
if (name && input.name === 'changed') {
@@ -338,7 +365,9 @@ export function assistantPreferences<N extends Node>(
field.reset =
name === 'name'
? (state.saved?.displayName ?? '')
- : (state.saved?.assistantTone ?? '');
+ : name === 'tone'
+ ? (state.saved?.assistantTone ?? '')
+ : (state.saved?.compactionPrompt ?? '');
}
field.observation = observed;
const receipt = observed.receipt;
@@ -396,10 +425,18 @@ export function assistantPreferences<N extends Node>(
else {
state.saved = result.value as SettingsAssistantPreferences;
if (r.reset)
- for (const name of ['name', 'tone'] as const) {
+ for (const name of (r.reset === 'compaction'
+ ? ['compaction']
+ : r.reset === 'personalization'
+ ? ['name', 'tone']
+ : ['name', 'tone', 'compaction']) as Name[]) {
state.fields[name].ready = false;
state.fields[name].reset =
- name === 'name' ? state.saved.displayName : state.saved.assistantTone;
+ name === 'name'
+ ? state.saved.displayName
+ : name === 'tone'
+ ? state.saved.assistantTone
+ : state.saved.compactionPrompt;
initialize(state.fields[name]);
}
}
@@ -415,7 +452,27 @@ export function assistantPreferences<N extends Node>(
else state.notice = 'assistant-unknown';
} else if (r.kind === 'field') {
const chunk = result.status === 'succeeded' ? (result.value as TextChunk) : null;
- if (
+ if (r.name === 'compaction') {
+ const captured = state.compactionCapture;
+ state.compactionCapture = null;
+ if (
+ captured &&
+ chunk &&
+ state.saved &&
+ sameValue(chunk.metadata, captured.snapshot.text) &&
+ sameValue(
+ state.fields.compaction.observation?.snapshot.text,
+ captured.snapshot.text,
+ ) &&
+ new TextEncoder().encode(chunk.text).length === captured.snapshot.text.bytes &&
+ chunk.text.trim()
+ )
+ mutate(state, actions, {
+ expectedRevision: state.saved.revision,
+ mutation: { kind: 'compaction_prompt', prompt: chunk.text },
+ });
+ else state.notice = 'assistant-invalid';
+ } else if (
!state.capture ||
!chunk ||
!sameValue(chunk.metadata, r.captured.snapshot.text) ||
@@ -468,7 +525,28 @@ export function assistantPreferences<N extends Node>(
);
else if (!disabled(state, props)) {
if (input.key === 'reload') read(state, actions);
- else if (input.key === 'instructions' && state.saved)
+ else if (
+ input.key === 'reset-compaction' &&
+ state.saved &&
+ state.fields.compaction.ready &&
+ !state.fields.compaction.command
+ )
+ mutate(state, actions, {
+ expectedRevision: state.saved.revision,
+ mutation: { kind: 'compaction_prompt', prompt: null },
+ });
+ else if (input.key === 'save-compaction' && state.saved) {
+ const draft = state.fields.compaction.observation;
+ if (
+ draft &&
+ !draft.snapshot.marked &&
+ state.fields.compaction.ready &&
+ !state.fields.compaction.command
+ ) {
+ state.compactionCapture = draft;
+ capture(state, actions, 'compaction');
+ }
+ } else if (input.key === 'instructions' && state.saved)
mutate(state, actions, {
expectedRevision: state.saved.revision,
mutation: {
diff --git a/plugins/agent/assistant-preferences/locale.ts b/plugins/agent/assistant-preferences/locale.ts
index 639139c42d..19122867dd 100644
--- a/plugins/agent/assistant-preferences/locale.ts
+++ b/plugins/agent/assistant-preferences/locale.ts
@@ -17,7 +17,7 @@
* under the License.
*/
-import { createCopy } from '../../shared/locale.js';
+import { type Catalog, createCopy } from '../../shared/locale.js';
import {
msg_back,
msg_executionReceipt,
@@ -60,6 +60,14 @@ export const copy = /* @__PURE__ */ createCopy(messages);
export type Copy = ReturnType<typeof copy>;
const terminalMessages = {
+ 'assistant-compaction': ['Compression prompt', '压缩提示词', '壓縮提示詞'],
+ 'assistant-compaction-save': ['Save compression prompt', '保存压缩提示词', '儲存壓縮提示詞'],
+ 'assistant-compaction-reset': ['Restore default prompt', '恢复默认提示词', '還原預設提示詞'],
+ 'assistant-compaction-help': [
+ 'Used for automatic and manual compression. You can override it for one compression in /compact.',
+ '用于自动和手动压缩,可在 /compact 中为单次压缩修改。',
+ '用於自動和手動壓縮,可在 /compact 中為單次壓縮修改。',
+ ],
'assistant-conflict': tui_assistant_conflict,
'assistant-instructions': tui_assistant_instructions,
'assistant-instructions-help': tui_assistant_instructions_help,
@@ -76,7 +84,7 @@ const terminalMessages = {
'assistant-unavailable': tui_assistant_unavailable,
'assistant-unknown': tui_assistant_unknown,
'settings-assistant': tui_settings_assistant,
-};
+} satisfies Catalog;
export function tuiText(
locale: string,
key: string,
diff --git a/plugins/agent/composer-footer/index.ts b/plugins/agent/composer-footer/index.ts
index 2b425628bb..1e419388b1 100644
--- a/plugins/agent/composer-footer/index.ts
+++ b/plugins/agent/composer-footer/index.ts
@@ -33,6 +33,7 @@ interface Props {
sessionId: string | null;
dataSource: AgentDataSource | null;
running: boolean;
+ compacting: boolean;
metrics: AgentSessionMetrics | null;
}
interface State {
@@ -47,24 +48,33 @@ const tokens = (value: number) =>
export function footer<N extends Node>(presentation: Presentation<N>): Component<State, Props, N> {
const frame = (state: State, props: Props) => {
const { metrics, theme, locale } = props;
- const parts: string[] = [];
+ let context = '';
const used = metrics?.contextTokens;
const capacity = metrics?.contextWindow;
if (used !== null && used !== undefined) {
const amount = `${metrics?.approximate ? '≈' : ''}${tokens(used)}`;
- parts.push(
- `${tuiText(locale, 'chat-context')} ${amount}${capacity ? ` / ${tokens(capacity)} · ${Math.round((100 * used) / capacity)}%` : ''}`,
- );
+ context = `${tuiText(locale, 'chat-context')} ${amount}${capacity ? ` / ${tokens(capacity)} · ${Math.round((100 * used) / capacity)}%` : ''}`;
}
+ if (props.compacting && !context) context = tuiText(locale, 'chat-compacting');
const rate = metrics?.outputTokensPerSecond;
- if (rate !== null && rate !== undefined && Number.isFinite(rate))
- parts.push(`${rate.toFixed(1)} tok/s`);
+ const speed = rate != null && Number.isFinite(rate) ? `${rate.toFixed(1)} tok/s` : '';
const ui = presentation.paint(theme);
const hint = tuiText(locale, 'chat-metrics-hint');
- const line = (key: string, text: string) =>
- ui.text(key, text, 12, theme.muted, 400, { truncate: true }, hint);
- if (presentation.target === 'desktop')
- return output(state, line('session-metrics-text', parts.join(' · ')));
+ const contextColor = props.compacting ? theme.accent : theme.muted;
+ const line = (key: string, text: string, color = contextColor) =>
+ ui.text(key, text, 12, color, 400, { truncate: true }, hint);
+ const full = () =>
+ ui.box(
+ 'session-metrics-text',
+ [
+ ...(context ? [line('session-context-text', context)] : []),
+ ...(speed
+ ? [line('session-rate-text', `${context ? ' · ' : ''}${speed}`, theme.muted)]
+ : []),
+ ],
+ { row: true, gap: 0 },
+ );
+ if (presentation.target === 'desktop') return output(state, full());
const layout = (basis: number) => ({
basis,
grow: 0,
@@ -79,8 +89,9 @@ export function footer<N extends Node>(presentation: Presentation<N>): Component
? capacity
? `${metrics?.approximate ? '≈' : ''}${Math.round((100 * used) / capacity)}%`
: `${metrics?.approximate ? '≈' : ''}${tokens(used)}`
- : '';
- const context = parts[0] && used != null ? parts[0] : '';
+ : props.compacting
+ ? tuiText(locale, 'chat-compacting')
+ : '';
const reduced = ui.box(
'metrics-reduced',
[
@@ -108,7 +119,7 @@ export function footer<N extends Node>(presentation: Presentation<N>): Component
'metrics-responsive',
[
reduced,
- ui.box('metrics-full', [line('session-metrics-text', parts.join(' · '))], {
+ ui.box('metrics-full', [full()], {
terminal: layout(0),
}),
],
@@ -119,7 +130,7 @@ export function footer<N extends Node>(presentation: Presentation<N>): Component
direction: 'column',
children: {
'metrics-reduced': layout(0),
- 'metrics-full': layout(parts.length ? 1 : 0),
+ 'metrics-full': layout(context || speed ? 1 : 0),
},
},
},
diff --git a/plugins/agent/composer-footer/locale.ts b/plugins/agent/composer-footer/locale.ts
index 834c3ecaf6..8c923d427d 100644
--- a/plugins/agent/composer-footer/locale.ts
+++ b/plugins/agent/composer-footer/locale.ts
@@ -22,10 +22,13 @@ import { tui_chat_context, tui_chat_metrics_hint } from '../../shared/tui-messag
// This feature owns this explicit message catalog; shared messages remain tree-shakeable.
+import type { Catalog } from '../../shared/locale.js';
+
const terminalMessages = {
'chat-context': tui_chat_context,
+ 'chat-compacting': ['Compressing context', '正在压缩上下文', '正在壓縮上下文'],
'chat-metrics-hint': tui_chat_metrics_hint,
-};
+} satisfies Catalog;
export function tuiText(
locale: string,
key: string,
diff --git a/plugins/agent/composer/component.ts b/plugins/agent/composer/component.ts
index 778693222f..74a81fafac 100644
--- a/plugins/agent/composer/component.ts
+++ b/plugins/agent/composer/component.ts
@@ -573,7 +573,22 @@ export function composer<N extends Node>(
new TextEncoder().encode(chunk.text).length === submission.draft.snapshot.text.bytes
) {
if (!chunk.text.trim() && !submission.attachments.length) entry.notice = 'empty';
- else {
+ else if (chunk.text.trim() === '/compact' && !submission.attachments.length) {
+ events.push({
+ name: 'compact',
+ value: { context: submission.context, dataSource: submission.dataSource },
+ });
+ entry.delivery = {
+ kind: 'clear',
+ caller: null,
+ command: {
+ owner: submission.draft.snapshot.text.owner,
+ sequence: ++state.serial,
+ basedOn: submission.draft.revision,
+ edit: { kind: 'reset', text: '' },
+ },
+ };
+ } else {
const key = `send-${++state.serial}`,
backend = submission.backend;
submission.preview = {
diff --git a/plugins/agent/engine/src/compact.rs b/plugins/agent/engine/src/compact.rs
index 8c900732bf..c5d0b1e120 100644
--- a/plugins/agent/engine/src/compact.rs
+++ b/plugins/agent/engine/src/compact.rs
@@ -21,13 +21,10 @@ use crate::{Inner, RunContext, RunError, context_input, model_attempt};
use maka_agent_facts::context::CheckpointMode;
use maka_agent_facts::context::CompactOutcome;
use maka_agent_facts::context::ContextCheckpoint;
-use maka_agent_facts::context::ModelPurpose;
-use maka_agent_facts::context::SUMMARY_FORMAT_TEMPLATE;
-use maka_agent_facts::context::SummaryDefect;
+use maka_agent_facts::context::DEFAULT_COMPACTION_PROMPT;
use maka_agent_facts::context::TextSummary;
use maka_agent_facts::event::Fact;
use maka_agent_facts::event::RuntimeEvent;
-use maka_agent_facts::model::ModelFinishReason;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
@@ -38,7 +35,8 @@ pub(super) struct Job {
source: model_attempt::RequestSource,
mode: CheckpointMode,
prompt: Vec<maka_model::prompt::Message>,
- adapter: maka_agent_ports::model::Binding,
+ surface: Arc<crate::request_composition::Surface>,
+ definitions: Vec<maka_model::ToolDefinition>,
}
pub(super) async fn run(
@@ -94,7 +92,6 @@ pub(super) async fn capture(
inner,
input,
&source,
- ModelPurpose::Summary,
cancellation,
continuation_base,
&input.invocation.invocation_id,
@@ -107,12 +104,74 @@ pub(super) async fn capture(
return Ok(None);
}
let adapter = inner.model.binding(&input.provider)?;
+ let prior = match &source.latest_main {
+ maka_event_log::context::LatestMainContext::Selected(latest)
+ if latest.model_id == input.provider.model
+ && latest.route_identity == model_attempt::route_identity(input)?
+ && latest.connection_id.as_deref()
+ == input
+ .configuration
+ .model
+ .as_ref()
+ .map(|model| model.connection_id.as_str()) =>
+ {
+ inner
+ .log
+ .completed_request_composition(&input.invocation.session_id, latest.sequence)
+ .await?
+ }
+ _ => None,
+ };
+ let mut composition =
+ prior.unwrap_or_else(|| maka_agent_facts::composition::RequestComposition {
+ system_prompt: input
+ .configuration
+ .system_prompt
+ .as_ref()
+ .map(|prompt| prompt.text.clone()),
+ dynamic_context: vec![],
+ tool_catalog_digest: maka_agent_facts::artifact::content_digest(b"[]"),
+ tools: vec![],
+ provider_options: Some(input.provider_options.clone()),
+ max_output_tokens: None,
+ sources: input
+ .configuration
+ .system_prompt
+ .as_ref()
+ .map(|prompt| prompt.sources.clone())
+ .unwrap_or_default(),
+ });
+ // The prompt/tool surface can be reused, while execution binds the currently
+ // captured adapter and model revision on this admitted route.
+ composition.sources.retain(|source| {
+ !matches!(
+ source.kind,
+ maka_agent_facts::composition::SourceKind::ModelAdapter
+ | maka_agent_facts::composition::SourceKind::ModelProvider
+ )
+ });
+ composition.sources.push(adapter.source().clone());
+ composition
+ .sources
+ .extend(input.model_revision.iter().cloned());
+ let definitions = composition.tools.clone();
+ let mut captured = input.clone();
+ if let Some(options) = &composition.provider_options {
+ captured.provider_options = options.clone();
+ }
+ let surface = Arc::new(crate::request_composition::Surface::summary(
+ adapter,
+ composition,
+ context_input::summary_output_budget(input),
+ )?);
+ let prompt = surface.apply(prompt);
Ok(Some(Job {
- input: input.clone(),
+ input: captured,
source: model_attempt::RequestSource::from(&source),
mode: mode.clone(),
prompt,
- adapter,
+ surface,
+ definitions,
}))
}
@@ -127,26 +186,35 @@ impl Job {
source,
mode,
prompt,
- adapter,
+ surface,
+ definitions,
} = self;
- let base = format!(
- "You are a context summarization assistant.\nRead the conversation between a user and an AI assistant, then produce a structured summary another LLM will use to continue the same task.\nDo NOT continue the conversation. Do NOT answer questions in it. ONLY output the structured summary.\n\nUse this exact format:\n\n{SUMMARY_FORMAT_TEMPLATE}\n\nKeep each section concise. Preserve exact file paths, function names, commands, and error messages."
+ let instruction = maka_model::prompt::Message::user(
+ input
+ .configuration
+ .compaction_prompt
+ .clone()
+ .unwrap_or_else(|| DEFAULT_COMPACTION_PROMPT.into()),
);
- let mut instruction = base.clone();
- let mut input_budget = context_input::summary_budget(&input);
- let mut shortened = false;
- let mut repair = None;
+ let mut input_budget = context_input::summary_budget(&input)
+ .saturating_sub(context_input::estimate(std::slice::from_ref(&instruction)))
+ .saturating_sub(context_input::json_tokens(&definitions));
+ let mut overflowed = false;
loop {
- let mut request = context_input::fit_summary(&prompt, input_budget);
- request.push(maka_model::prompt::Message::user(format!("{instruction}\n\nNow write the structured summary of the conversation above. Output only the summary.")));
+ let mut request = if overflowed {
+ context_input::fit_summary(&prompt, input_budget)
+ } else {
+ prompt.clone()
+ };
+ request.push(instruction.clone());
let result = model_attempt::execute_once(
inner,
&input,
&source,
request,
- Vec::new(),
+ definitions.clone(),
model_attempt::Attempt::Summary {
- adapter: adapter.clone(),
+ surface: surface.clone(),
},
cancellation,
&mut false,
@@ -159,40 +227,14 @@ impl Job {
observed_output: false,
})) if input_budget > 256 => {
input_budget = input_budget.min(context_input::estimate(&prompt)).max(1) / 2;
+ overflowed = true;
continue;
}
Err(error) => return Err(error),
};
- if output.finish_reason == ModelFinishReason::Length {
- if shortened || repair.is_some() {
- return Ok(failed("output_length"));
- }
- shortened = true;
- instruction = format!(
- "{base}\n\nYour previous attempt was cut off at the output limit. Produce the same summary in well under half the length: keep every section, drop detail rather than sections."
- );
- continue;
- }
- let summary = match TextSummary::from_model_step(&output, source.checkpoint.is_none()) {
+ let summary = match TextSummary::from_model_step(&output) {
Ok(summary) => summary,
- Err(defect) => {
- if let Some(original) = repair {
- return Ok(failed(&SummaryDefect::to_string(&original)));
- }
- if !matches!(
- defect,
- SummaryDefect::MissingSection
- | SummaryDefect::Truncated
- | SummaryDefect::TooSmallForFold
- ) {
- return Ok(failed(&defect.to_string()));
- }
- repair = Some(defect);
- instruction = format!(
- "{base}\n\nA prior attempt was rejected as {defect}.\nProduce one complete replacement summary from the source conversation.\nEvery required section must appear in order with substantive content. Do not discuss the repair."
- );
- continue;
- }
+ Err(defect) => return Ok(failed(&defect.to_string())),
};
let checkpoint = RuntimeEvent::new(
input.invocation.clone(),
diff --git a/plugins/agent/engine/src/context_input.rs b/plugins/agent/engine/src/context_input.rs
index 0ae0e1aa62..6030f893d7 100644
--- a/plugins/agent/engine/src/context_input.rs
+++ b/plugins/agent/engine/src/context_input.rs
@@ -67,7 +67,7 @@ fn output_tokens(output: &ToolOutput) -> u64 {
ToolOutput::Content(parts) => parts.iter().map(content_tokens).sum(),
}
}
-fn json_tokens(value: &(impl serde::Serialize + ?Sized)) -> u64 {
+pub(super) fn json_tokens(value: &(impl serde::Serialize + ?Sized)) -> u64 {
struct Count(u64);
impl std::io::Write for Count {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
@@ -83,18 +83,29 @@ fn json_tokens(value: &(impl serde::Serialize + ?Sized)) -> u64 {
count.0.div_ceil(3)
}
+/// Reserve at least 4% of total context capacity (200k if unknown), retaining
+/// any larger configured output budget. This is not a minimum summary length.
+pub(super) fn summary_output_budget<W>(input: &RunInput<W>) -> u64 {
+ input
+ .context
+ .as_ref()
+ .and_then(|context| context.model_context_window)
+ .unwrap_or(200_000)
+ .saturating_mul(4)
+ .div_ceil(100)
+ .max(input.main_output_limit.unwrap_or(8000))
+ .max(1)
+}
+
pub(super) fn summary_budget<W>(input: &RunInput<W>) -> u64 {
let context = input.context.as_ref();
- let window = context
- .and_then(|context| context.context_window)
- .unwrap_or(64_000);
- let requested = input.main_output_limit.unwrap_or(8000).min(8000);
let total = context
.and_then(|context| context.model_context_window)
- .unwrap_or(window);
- let output = requested.min(total / 4);
- // Input-only limits and total context capacity are different model facts.
- window.min(total.saturating_sub(output)).saturating_mul(3) / 4
+ .unwrap_or(200_000);
+ let window = context
+ .and_then(|context| context.context_window)
+ .unwrap_or(total);
+ window.min(total.saturating_sub(summary_output_budget(input)))
}
pub(super) fn needs_compaction<W>(input: &RunInput<W>, prompt: &[Message]) -> bool {
@@ -108,6 +119,15 @@ pub(super) fn fit_summary(prompt: &[Message], tokens: u64) -> Vec<Message> {
if estimate(prompt) <= tokens {
return prompt.to_vec();
}
+ // Preserve instruction roles and keep the conversational anchor independent
+ // of the System prefix. If the System alone cannot fit, provider overflow
+ // will fail safely rather than silently truncating its instructions.
+ let system_end = prompt
+ .iter()
+ .take_while(|message| matches!(message, Message::System { .. }))
+ .count();
+ let (system, prompt) = prompt.split_at(system_end);
+ let tokens = tokens.saturating_sub(estimate(system));
let bytes = usize::try_from(tokens.saturating_mul(3)).unwrap_or(usize::MAX);
const NOTICE: &str = "Conversation excerpts for summarization: some older text is omitted to fit this model. The complete original history remains stored locally. Preserve known goals and recent progress; do not infer facts from omitted text.\n\n";
let available = bytes.saturating_sub(NOTICE.len() + 100);
@@ -143,7 +163,9 @@ pub(super) fn fit_summary(prompt: &[Message], tokens: u64) -> Vec<Message> {
"{NOTICE}Earlier task or summary:\n{head}\n\nRecent conversation:\n{}",
excerpt(&tail, remaining)
);
- vec![Message::user(text)]
+ let mut fitted = system.to_vec();
+ fitted.push(Message::user(text));
+ fitted
}
fn excerpt(text: &str, bytes: usize) -> String {
diff --git a/plugins/agent/engine/src/continuation.rs b/plugins/agent/engine/src/continuation.rs
index 53c3e27f66..a5dd6c1a32 100644
--- a/plugins/agent/engine/src/continuation.rs
+++ b/plugins/agent/engine/src/continuation.rs
@@ -18,7 +18,6 @@
*/
use crate::{Inner, RunError, RunInput, model_attempt};
-use maka_agent_facts::context::ModelPurpose;
use maka_agent_facts::continuation::ContinuationClaim;
use maka_agent_facts::continuation::MAX_SOURCE_BYTES;
use maka_agent_facts::continuation::MAX_SOURCE_EVENTS;
@@ -160,7 +159,6 @@ pub(super) async fn inspect(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
match &input.work {
crate::RunWork::Handoff { pause, .. } => pause.execution.replay_base,
@@ -243,8 +241,13 @@ pub(super) fn replay<W>(
"continuation requires stable user/tool replay boundaries",
));
}
- let request =
- model_attempt::prepare_request(input, prompt, definitions, input.main_output_limit)?;
+ let request = model_attempt::prepare_request(
+ input,
+ prompt,
+ definitions,
+ input.main_output_limit,
+ maka_agent_facts::context::ModelPurpose::Main,
+ )?;
if cancellation.is_cancelled() {
return Err(RunError::Cancelled);
}
diff --git a/plugins/agent/engine/src/model_attempt.rs b/plugins/agent/engine/src/model_attempt.rs
index fc99145ad4..95f82739f2 100644
--- a/plugins/agent/engine/src/model_attempt.rs
+++ b/plugins/agent/engine/src/model_attempt.rs
@@ -44,7 +44,7 @@ pub(super) struct Main<'a> {
pub(super) enum Attempt<'a> {
Main(Main<'a>),
Summary {
- adapter: maka_agent_ports::model::Binding,
+ surface: Arc<crate::request_composition::Surface>,
},
}
@@ -67,7 +67,6 @@ pub(super) async fn prompt<W>(
inner: &Inner,
input: &RunInput<W>,
source: &ModelContextSource,
- purpose: ModelPurpose,
cancellation: &CancellationToken,
continuation_base: Option<u64>,
current: &str,
@@ -92,34 +91,26 @@ pub(super) async fn prompt<W>(
)
.await?;
if let Some(baseline) = &source.baseline {
- let text = match purpose {
- ModelPurpose::Summary => format!(
- "Previous continuation summary:\n{}\n\nUpdate it using the newer conversation events that follow.",
- baseline.checkpoint.summary.text
- ),
- ModelPurpose::Main => format!(
- "Continuation summary:\n{}",
- baseline.checkpoint.summary.text
- ),
- };
+ let text = format!(
+ "Continuation summary:\n{}",
+ baseline.checkpoint.summary.text
+ );
prompt.insert(0, Message::user(text));
}
- if purpose == ModelPurpose::Main {
- let system_text = input
- .configuration
- .system_prompt
- .as_ref()
- .map(|system| system.text.clone())
- .unwrap_or_default();
- if !system_text.is_empty() {
- prompt.insert(
- 0,
- Message::System {
- content: system_text,
- provider_options: None,
- },
- );
- }
+ let system_text = input
+ .configuration
+ .system_prompt
+ .as_ref()
+ .map(|system| system.text.clone())
+ .unwrap_or_default();
+ if !system_text.is_empty() {
+ prompt.insert(
+ 0,
+ Message::System {
+ content: system_text,
+ provider_options: None,
+ },
+ );
}
Ok(prompt)
}
@@ -323,7 +314,6 @@ pub(super) async fn execute_main(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
continuation_base,
&input.invocation.invocation_id,
@@ -359,59 +349,27 @@ pub(super) async fn execute_once(
progressed: &mut bool,
retry: &mut Option<Vec<Message>>,
) -> Result<(String, ModelStep), RunError> {
- let (purpose, lane, surface, summary_adapter, tools) = match attempt {
+ let (purpose, lane, surface, tools) = match attempt {
Attempt::Main(Main {
lane,
surface,
tools,
..
- }) => (
- ModelPurpose::Main,
- Some(lane),
- Some(surface),
- None,
- Some(tools),
- ),
- Attempt::Summary { adapter } => (ModelPurpose::Summary, None, None, Some(adapter), None),
+ }) => (ModelPurpose::Main, Some(lane), surface, Some(tools)),
+ Attempt::Summary { surface } => (ModelPurpose::Summary, None, surface, None),
};
if cancellation.is_cancelled() {
return Err(RunError::Cancelled);
}
- let max_output_tokens = surface.as_ref().map_or(
- Some(input.main_output_limit.unwrap_or(8000).min(8000)),
- |surface| surface.max_output_tokens,
- );
- let prepared = prepare_request(input, prompt, definitions, max_output_tokens)?;
- let (binding, composition) = match surface {
- Some(surface) => (surface.adapter.clone(), surface.evidence.clone()),
- None => {
- let request = &prepared.request;
- let binding = summary_adapter.expect("summary adapter frozen at capture");
- let evidence = maka_agent_facts::composition::RequestComposition {
- system_prompt: request.prompt.iter().find_map(|message| match message {
- Message::System { content, .. } => Some(content.clone()),
- _ => None,
- }),
- dynamic_context: vec![],
- tool_catalog_digest: maka_agent_facts::artifact::content_digest(
- &serde_json::to_vec(&request.tools)
- .map_err(|error| RunError::Internal(error.to_string()))?,
- ),
- tools: request.tools.clone(),
- provider_options: Some(request.provider_options.clone()),
- max_output_tokens: request.max_output_tokens,
- sources: input
- .model_revision
- .iter()
- .cloned()
- .chain(std::iter::once(binding.source().clone()))
- .collect(),
- }
- .freeze()
- .map_err(|error| RunError::Internal(error.into()))?;
- (binding, Arc::new(evidence))
- }
- };
+ let prepared = prepare_request(
+ input,
+ prompt,
+ definitions,
+ surface.max_output_tokens,
+ purpose,
+ )?;
+ let binding = surface.adapter.clone();
+ let composition = surface.evidence.clone();
let item_acceptance = purpose == ModelPurpose::Main && binding.supports_item_acceptance();
let step_id = Uuid::new_v4().to_string();
let event = maka_agent_facts::event::RuntimeEvent::new(
@@ -512,6 +470,7 @@ pub(super) fn prepare_request<W>(
prompt: Vec<Message>,
definitions: Vec<ToolDefinition>,
max_output_tokens: Option<u64>,
+ purpose: ModelPurpose,
) -> Result<PreparedRequest, RunError> {
let prompt = if input.supports_vision
&& matches!(
@@ -525,12 +484,16 @@ pub(super) fn prepare_request<W>(
};
let prompt = history::project_compatible(prompt, &input.provider.kind);
let prompt = maka_model::reasoning::project(prompt, &input.provider.kind);
- let max_output_tokens = Some(crate::context_input::output_limit(
- input,
- &prompt,
- &definitions,
- max_output_tokens.unwrap_or(8000),
- ));
+ let max_output_tokens = if purpose == ModelPurpose::Summary {
+ max_output_tokens
+ } else {
+ Some(crate::context_input::output_limit(
+ input,
+ &prompt,
+ &definitions,
+ max_output_tokens.unwrap_or(8000),
+ ))
+ };
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct Evidence<'a> {
diff --git a/plugins/agent/engine/src/request_composition.rs b/plugins/agent/engine/src/request_composition.rs
index cdd38233e4..e6fec83850 100644
--- a/plugins/agent/engine/src/request_composition.rs
+++ b/plugins/agent/engine/src/request_composition.rs
@@ -82,6 +82,24 @@ impl Surface {
})
}
+ pub fn summary(
+ adapter: maka_agent_ports::model::Binding,
+ mut composition: RequestComposition,
+ output_budget: u64,
+ ) -> Result<Self, RunError> {
+ composition.max_output_tokens = Some(output_budget);
+ Ok(Self {
+ adapter,
+ max_output_tokens: Some(output_budget),
+ system: composition.system_prompt.clone(),
+ evidence: Arc::new(
+ composition
+ .freeze()
+ .map_err(|error| RunError::Internal(error.into()))?,
+ ),
+ })
+ }
+
pub fn apply(&self, mut history: Vec<Message>) -> Vec<Message> {
if matches!(history.first(), Some(Message::System { .. })) {
history.remove(0);
diff --git a/plugins/agent/engine/src/steps.rs b/plugins/agent/engine/src/steps.rs
index a50b7e003d..4c04217b5b 100644
--- a/plugins/agent/engine/src/steps.rs
+++ b/plugins/agent/engine/src/steps.rs
@@ -19,7 +19,6 @@
use crate::{Inner, RunContext, RunError, auto_context, model_attempt, prune};
use futures_util::FutureExt;
-use maka_agent_facts::context::ModelPurpose;
use maka_tools::RunTools;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
@@ -88,7 +87,6 @@ pub(super) async fn run(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
continuation_base,
&intent.successor_invocation_id,
@@ -151,7 +149,6 @@ pub(super) async fn run(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
continuation_base,
&input.invocation.invocation_id,
@@ -192,7 +189,6 @@ pub(super) async fn run(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
continuation_base,
&input.invocation.invocation_id,
@@ -320,7 +316,6 @@ pub(super) async fn run(
inner,
input,
&context,
- ModelPurpose::Main,
cancellation,
continuation_base,
&input.invocation.invocation_id,
diff --git a/plugins/agent/engine/tests/integration/context_compaction.rs b/plugins/agent/engine/tests/integration/context_compaction.rs
index 07823d45d6..1051dc2e0c 100644
--- a/plugins/agent/engine/tests/integration/context_compaction.rs
+++ b/plugins/agent/engine/tests/integration/context_compaction.rs
@@ -98,17 +98,14 @@ async fn compact_next_main_and_reopen_use_durable_baseline_with_complete_tail()
"MAIN_SYSTEM_PROMPT_EVIDENCE"
);
}
- assert!(
- !requests[1]
- .to_string()
- .contains("MAIN_SYSTEM_PROMPT_EVIDENCE")
- );
+ assert_eq!(requests[1]["messages"][0], requests[0]["messages"][0]);
+ assert_eq!(requests[1]["messages"][1], requests[0]["messages"][1]);
assert!(
requests[1]["messages"]
.to_string()
.contains("old-answer-private")
);
- assert_eq!(requests[1]["messages"][0]["role"], "user");
+ assert_eq!(requests[1]["messages"][0]["role"], "system");
assert!(
requests[1]["messages"].as_array().unwrap().last().unwrap()["content"]
.as_str()
@@ -156,7 +153,10 @@ async fn compact_next_main_and_reopen_use_durable_baseline_with_complete_tail()
.unwrap()
.unwrap();
assert_eq!(composition.max_output_tokens, Some(8000));
- assert!(composition.system_prompt.is_none());
+ assert_eq!(
+ composition.system_prompt.as_deref(),
+ Some("MAIN_SYSTEM_PROMPT_EVIDENCE")
+ );
let first_request = prefix
.events
.iter()
@@ -198,7 +198,7 @@ async fn compact_next_main_and_reopen_use_durable_baseline_with_complete_tail()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn malformed_summary_repairs_once_then_keeps_previous_context() {
+async fn arbitrary_completed_summary_is_accepted_without_format_repair() {
let directory = tempfile::tempdir().unwrap();
let log = Arc::new(
EventLog::open(&directory.path().join("events.sqlite"))
@@ -209,12 +209,7 @@ async fn malformed_summary_repairs_once_then_keeps_previous_context() {
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let mut requests = Vec::new();
- for text in [
- "old-answer",
- "invalid-summary",
- "still-invalid",
- "next-answer",
- ] {
+ for text in ["old-answer", "invalid-summary", "next-answer"] {
let (mut socket, _) = listener.accept().await.unwrap();
requests.push(read_request(&mut socket).await);
respond(&mut socket, text, "stop").await;
@@ -229,30 +224,21 @@ async fn malformed_summary_repairs_once_then_keeps_previous_context() {
.unwrap();
}
let prefix = log.prefix(100, 256 * 1024).await.unwrap();
- assert!(
- !prefix
- .events
- .iter()
- .any(|event| matches!(event.event.fact, Fact::ContextCheckpointRecorded { .. }))
- );
- assert!(prefix.events.iter().any(|event|matches!(&event.event.fact,Fact::InvocationEnded {outcome:InvocationOutcome::ContextCompactFinished {outcome:CompactOutcome::Failed {reason}}} if reason=="malformed_summary_missing_section")));
+ assert!(prefix.events.iter().any(|event| matches!(&event.event.fact,
+ Fact::ContextCheckpointRecorded { checkpoint } if checkpoint.summary.text == "invalid-summary")));
let requests = server.await.unwrap();
+ assert_eq!(requests.len(), 3);
assert!(
requests[2]["messages"]
- .to_string()
- .contains("A prior attempt was rejected")
- );
- assert!(requests[3]["messages"].to_string().contains("old-answer"));
- assert!(
- !requests[3]["messages"]
.to_string()
.contains("invalid-summary")
);
+ assert!(!requests[2]["messages"].to_string().contains("old-answer"));
worker.drain().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn length_repairs_summary_but_retains_incomplete_main_without_success() {
+async fn incomplete_summary_fails_without_repair_and_main_retains_incomplete_text() {
use crate::support::agent_loop;
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -270,7 +256,6 @@ async fn length_repairs_summary_but_retains_incomplete_main_without_success() {
for (text, reason) in [
("old", "stop"),
("cut", "length"),
- (SUMMARY, "stop"),
("truncated-main", "length"),
("after-failure", "stop"),
] {
@@ -322,23 +307,26 @@ async fn length_repairs_summary_but_retains_incomplete_main_without_success() {
.unwrap();
let requests = server.await.unwrap();
assert!(
- requests[4]["messages"]
+ requests[3]["messages"]
.to_string()
.contains("truncated-main"),
"valid incomplete text remains available to a new user message"
);
- assert!(
- requests[2]["messages"]
- .to_string()
- .contains("well under half the length")
- );
let prefix = log.prefix(100, 256 * 1024).await.unwrap();
assert!(
- prefix
+ !prefix
.events
.iter()
.any(|event| matches!(event.event.fact, Fact::ContextCheckpointRecorded { .. }))
);
+ assert!(prefix.events.iter().any(|event| matches!(
+ &event.event.fact,
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::ContextCompactFinished {
+ outcome: CompactOutcome::Failed { .. }
+ }
+ }
+ )));
let truncated: Vec<_> = prefix
.events
.iter()
@@ -370,3 +358,340 @@ async fn length_repairs_summary_but_retains_incomplete_main_without_success() {
);
worker.drain().await;
}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn summary_preserves_main_prefix_tools_and_custom_instruction_with_independent_budget() {
+ use crate::support::agent_loop;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ for (window, main_budget, expected_budget) in [
+ (None, Some(128), 8000),
+ (Some(1_000_000), Some(128), 40_000),
+ (Some(1_000_000), Some(64_000), 64_000),
+ (Some(128_000), None, 8000),
+ (Some(128_000), Some(128), 5120),
+ ] {
+ let directory = tempfile::tempdir().unwrap();
+ let log = Arc::new(
+ EventLog::open(&directory.path().join("events.sqlite"))
+ .await
+ .unwrap(),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ let mut requests = vec![];
+ for text in ["original answer", "自由格式摘要", "next answer", ""] {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ requests.push(read_request(&mut socket).await);
+ respond(&mut socket, text, "stop").await;
+ }
+ requests
+ });
+ let effects = Arc::new(AtomicUsize::new(0));
+ let worker = engine(log.clone());
+ for (id, compact) in [
+ ("first", false),
+ ("compact", true),
+ ("next", false),
+ ("again", true),
+ ] {
+ let mut run = input(&base, id, compact);
+ run.main_output_limit = main_budget;
+ run.context = Some(maka_agent_facts::context::ModelRequestContext {
+ provider_id: "fixture".into(),
+ context_window: window,
+ model_context_window: window,
+ declared_window: None,
+ });
+ run.configuration.system_prompt = Some(maka_agent_facts::execution::SystemPrompt {
+ text: if compact {
+ "different compact invocation system"
+ } else {
+ "frozen ordinary main system"
+ }
+ .into(),
+ sources: vec![],
+ policy_revision: 1,
+ });
+ if compact {
+ run.configuration.compaction_prompt = Some("只保留下一步;可使用任意格式。".into());
+ } else {
+ run.work = agent_loop::input(
+ &base,
+ id,
+ Arc::new(agent_loop::Effect {
+ log: log.clone(),
+ count: effects.clone(),
+ }),
+ )
+ .work;
+ }
+ worker.run(run, CancellationToken::new()).await.unwrap();
+ }
+ worker.drain().await;
+ let requests = server.await.unwrap();
+ for (main, summary) in [(0, 1), (2, 3)] {
+ let prefix = requests[main]["messages"].as_array().unwrap();
+ let compact = requests[summary]["messages"].as_array().unwrap();
+ assert_eq!(&compact[..prefix.len()], prefix);
+ assert_eq!(
+ compact.len(),
+ prefix.len() + 2,
+ "one completed assistant message and one compaction instruction"
+ );
+ assert_eq!(compact.last().unwrap()["role"], "user");
+ assert_eq!(
+ compact.last().unwrap()["content"],
+ "只保留下一步;可使用任意格式。"
+ );
+ assert_eq!(requests[summary]["tools"], requests[main]["tools"]);
+ assert!(!requests[main]["tools"].as_array().unwrap().is_empty());
+ assert_eq!(requests[summary]["max_tokens"], expected_budget);
+ assert_eq!(requests[main]["max_tokens"], main_budget.unwrap_or(8000));
+ }
+ assert_eq!(effects.load(Ordering::SeqCst), 0);
+ let context = log.read_model_context("session", None).await.unwrap();
+ assert_eq!(context.baseline.unwrap().checkpoint.summary.text, "");
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn summary_only_excerpts_after_provider_overflow_with_frozen_composition() {
+ use tokio::io::AsyncWriteExt;
+ let directory = tempfile::tempdir().unwrap();
+ let log = Arc::new(
+ EventLog::open(&directory.path().join("events.sqlite"))
+ .await
+ .unwrap(),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let original = "history-marker ".repeat(3000);
+ let expected = original.clone();
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ read_request(&mut socket).await;
+ respond(&mut socket, &original, "stop").await;
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let full = read_request(&mut socket).await;
+ let body = r#"{"error":{"message":"request exceeds context","type":"invalid_request_error","code":"context_length_exceeded"}}"#;
+ socket.write_all(format!("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let fitted = read_request(&mut socket).await;
+ respond(&mut socket, "brief arbitrary summary", "stop").await;
+ (full, fitted)
+ });
+ let worker = engine(log.clone());
+ worker
+ .run(input(&base, "old", false), CancellationToken::new())
+ .await
+ .unwrap();
+ let mut compact = input(&base, "compact", true);
+ compact.main_output_limit = Some(128);
+ compact.context = Some(maka_agent_facts::context::ModelRequestContext {
+ provider_id: "fixture".into(),
+ context_window: Some(10_000),
+ model_context_window: Some(10_000),
+ declared_window: None,
+ });
+ worker.run(compact, CancellationToken::new()).await.unwrap();
+ worker.drain().await;
+ let (full, fitted) = server.await.unwrap();
+ assert!(full["messages"].to_string().contains(&expected));
+ assert!(
+ !full["messages"]
+ .to_string()
+ .contains("Conversation excerpts")
+ );
+ assert!(
+ fitted["messages"]
+ .to_string()
+ .contains("Conversation excerpts")
+ );
+ assert!(fitted.to_string().len() < full.to_string().len());
+ assert_eq!(full["max_tokens"], 400);
+ assert_eq!(fitted["max_tokens"], 400);
+ let events = log.prefix(100, 1024 * 1024).await.unwrap();
+ let mut compositions = vec![];
+ for event in events.events.iter().filter(|event| {
+ matches!(
+ event.event.fact,
+ Fact::ModelRequested {
+ purpose: maka_agent_facts::context::ModelPurpose::Summary,
+ ..
+ }
+ )
+ }) {
+ compositions.push(
+ log.request_composition("session", &event.event.id)
+ .await
+ .unwrap()
+ .unwrap(),
+ );
+ }
+ assert_eq!(compositions.len(), 2);
+ assert_eq!(compositions[0], compositions[1]);
+ assert!(events.events.iter().any(|event| matches!(&event.event.fact,
+ Fact::ContextCheckpointRecorded { checkpoint } if checkpoint.summary.text == "brief arbitrary summary")));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn summary_advertised_tools_never_execute() {
+ use crate::support::agent_loop;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use tokio::io::AsyncWriteExt;
+ let directory = tempfile::tempdir().unwrap();
+ let log = Arc::new(
+ EventLog::open(&directory.path().join("events.sqlite"))
+ .await
+ .unwrap(),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let main = read_request(&mut socket).await;
+ respond(&mut socket, "ordinary answer", "stop").await;
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let summary = read_request(&mut socket).await;
+ assert_eq!(summary["tools"], main["tools"]);
+ let call = serde_json::json!({"id":"summary","object":"chat.completion.chunk","created":1,"model":"test",
+ "choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"forbidden","type":"function",
+ "function":{"name":"echo","arguments":"{}"}}]},"finish_reason":null}]});
+ let end = serde_json::json!({"id":"summary","object":"chat.completion.chunk","created":1,"model":"test",
+ "choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]});
+ let body = format!("data: {call}\n\ndata: {end}\n\ndata: [DONE]\n\n");
+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();
+ });
+ let effects = Arc::new(AtomicUsize::new(0));
+ let worker = engine(log.clone());
+ let mut main = input(&base, "main", false);
+ main.work = agent_loop::input(
+ &base,
+ "main",
+ Arc::new(agent_loop::Effect {
+ log: log.clone(),
+ count: effects.clone(),
+ }),
+ )
+ .work;
+ worker.run(main, CancellationToken::new()).await.unwrap();
+ assert!(
+ worker
+ .run(input(&base, "compact", true), CancellationToken::new())
+ .await
+ .is_err()
+ );
+ worker.drain().await;
+ server.await.unwrap();
+ assert_eq!(effects.load(Ordering::SeqCst), 0);
+ assert!(
+ log.read_model_context("session", None)
+ .await
+ .unwrap()
+ .baseline
+ .is_none()
+ );
+ let events = log.prefix(100, 256 * 1024).await.unwrap();
+ assert!(
+ !events
+ .events
+ .iter()
+ .any(|event| matches!(event.event.fact, Fact::ToolDispatched { .. }))
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn overflow_preserves_system_and_first_goal_or_continuation_summary() {
+ use tokio::io::AsyncWriteExt;
+ const GOAL: &str = "UNIQUE_ORIGINAL_GOAL: recover the launch checklist";
+ const SYSTEM: &str = "Preserve trusted system instructions exactly.";
+ for baseline in [false, true] {
+ let directory = tempfile::tempdir().unwrap();
+ let log = Arc::new(
+ EventLog::open(&directory.path().join("events.sqlite"))
+ .await
+ .unwrap(),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ let mut responses = vec!["initial answer".to_string()];
+ if baseline {
+ responses.push(GOAL.into());
+ }
+ responses.extend(
+ (0..3)
+ .map(|index| format!("large turn {index}: {}", "recent detail ".repeat(3000))),
+ );
+ for response in responses {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ read_request(&mut socket).await;
+ respond(&mut socket, &response, "stop").await;
+ }
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let full = read_request(&mut socket).await;
+ let body = r#"{"error":{"message":"context exceeded","type":"invalid_request_error","code":"context_length_exceeded"}}"#;
+ socket.write_all(format!("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let fitted = read_request(&mut socket).await;
+ respond(&mut socket, "final summary", "stop").await;
+ (full, fitted)
+ });
+ let worker = engine(log.clone());
+ let mut stages = vec![("first", false)];
+ if baseline {
+ stages.push(("baseline", true));
+ }
+ stages.extend([
+ ("one", false),
+ ("two", false),
+ ("three", false),
+ ("final", true),
+ ]);
+ for (id, compact) in stages {
+ let mut run = input(&base, id, compact);
+ run.configuration.system_prompt = Some(maka_agent_facts::execution::SystemPrompt {
+ text: SYSTEM.into(),
+ sources: vec![],
+ policy_revision: 1,
+ });
+ if id == "first"
+ && let maka_agent_engine::RunWork::Message { message, .. } = &mut run.work
+ {
+ *message = GOAL.into();
+ }
+ if id == "final" {
+ run.context = Some(maka_agent_facts::context::ModelRequestContext {
+ provider_id: "fixture".into(),
+ context_window: Some(10_000),
+ model_context_window: Some(10_000),
+ declared_window: None,
+ });
+ }
+ worker.run(run, CancellationToken::new()).await.unwrap();
+ }
+ worker.drain().await;
+ let (full, fitted) = server.await.unwrap();
+ assert_eq!(full["messages"][0], fitted["messages"][0]);
+ assert_eq!(fitted["messages"][0]["role"], "system");
+ assert_eq!(fitted["messages"][0]["content"], SYSTEM);
+ assert!(full["messages"].to_string().contains(GOAL));
+ assert!(
+ !full["messages"]
+ .to_string()
+ .contains("Conversation excerpts")
+ );
+ let excerpt = fitted["messages"][1]["content"].as_str().unwrap();
+ assert!(excerpt.contains("Earlier task or summary:"));
+ assert!(
+ excerpt.contains(GOAL),
+ "first conversational anchor must survive: {excerpt}"
+ );
+ if baseline {
+ assert!(excerpt.contains("Continuation summary:"));
+ }
+ assert!(excerpt.contains("large turn 2"));
+ assert!(fitted.to_string().len() < full.to_string().len());
+ }
+}
diff --git a/plugins/agent/engine/tests/integration/context_overflow.rs b/plugins/agent/engine/tests/integration/context_overflow.rs
index 7c19f44505..5ef682aadb 100644
--- a/plugins/agent/engine/tests/integration/context_overflow.rs
+++ b/plugins/agent/engine/tests/integration/context_overflow.rs
@@ -161,7 +161,7 @@ async fn proactive_failure_spends_the_same_budget_as_overflow_recovery() {
fixture::respond(&mut old, "old-answer", "stop").await;
let mut main = None;
let mut summaries = 0;
- while summaries < 2 || main.is_none() {
+ while summaries < 1 || main.is_none() {
let (mut socket, _) = listener.accept().await.unwrap();
let request = fixture::read_request(&mut socket).await;
if request["messages"]
@@ -169,7 +169,7 @@ async fn proactive_failure_spends_the_same_budget_as_overflow_recovery() {
.contains("Now write the structured summary")
{
summaries += 1;
- fixture::respond(&mut socket, "malformed", "stop").await;
+ fixture::respond(&mut socket, "incomplete", "length").await;
} else {
assert!(main.is_none(), "only one main request before overflow");
assert!(request["messages"].to_string().contains("old-answer"));
@@ -227,7 +227,7 @@ async fn proactive_failure_spends_the_same_budget_as_overflow_recovery() {
}
))
.count(),
- 2
+ 1
);
assert_eq!(
events
diff --git a/plugins/agent/engine/tests/integration/dynamic_tools.rs b/plugins/agent/engine/tests/integration/dynamic_tools.rs
index c504c73818..a5ab161468 100644
--- a/plugins/agent/engine/tests/integration/dynamic_tools.rs
+++ b/plugins/agent/engine/tests/integration/dynamic_tools.rs
@@ -124,14 +124,14 @@ async fn discovery_defers_direct_admission_but_only_defers_descriptions_in_code_
respond_tools(&mut socket, vec![call], 200).await;
let mut summaries = 0;
let mut main = None;
- while summaries < if compact { 1 } else { 2 } || main.is_none() {
+ while summaries < 1 || main.is_none() {
let (mut socket, _) = listener.accept().await.unwrap();
let request = fixture::read_request(&mut socket).await;
if request["messages"].to_string().contains("Now write the structured summary") {
summaries += 1;
assert_eq!(request["max_tokens"], 8000);
- assert!(request.get("tools").is_none());
- fixture::respond(&mut socket, if compact { fixture::SUMMARY } else { "invalid summary" }, "stop").await;
+ assert_eq!(request["tools"], second["tools"]);
+ fixture::respond(&mut socket, if compact { fixture::SUMMARY } else { "incomplete summary" }, if compact { "stop" } else { "length" }).await;
} else {
assert!(main.is_none());
main = Some((socket, request));
diff --git a/plugins/agent/engine/tests/integration/dynamic_tools/session.rs b/plugins/agent/engine/tests/integration/dynamic_tools/session.rs
index d39630b332..8edd3d06ca 100644
--- a/plugins/agent/engine/tests/integration/dynamic_tools/session.rs
+++ b/plugins/agent/engine/tests/integration/dynamic_tools/session.rs
@@ -129,10 +129,10 @@ async fn session_loading_preserves_wire_prefixes_until_committed_compaction_and_
let (mut socket,other)=next(&listener).await;
empty(&other,mode);
fixture::respond(&mut socket,"isolated","stop").await;
- for _ in 0..if success {1} else {2} {
+ for _ in 0..1 {
let (mut socket,summary)=next(&listener).await;
- assert!(summary.get("tools").is_none());
- fixture::respond(&mut socket,if success {fixture::SUMMARY} else {"invalid summary"},"stop").await;
+ assert_eq!(summary["tools"],warm["tools"]);
+ fixture::respond(&mut socket,if success {fixture::SUMMARY} else {"incomplete summary"},if success {"stop"} else {"length"}).await;
}
let (mut socket,compacted)=next(&listener).await;
if success {empty(&compacted,mode);} else {assert_eq!(compacted["tools"],warm["tools"],"a failed summary cannot unload anything");}
@@ -233,7 +233,7 @@ async fn continuation_admission_rejects_changed_loading_before_claiming_the_sour
loaded(&request, ToolMode::Direct);
fixture::respond(&mut socket, "loaded", "stop").await;
let (mut socket, summary) = next(&listener).await;
- assert!(summary.get("tools").is_none());
+ assert_eq!(summary["tools"], request["tools"]);
fixture::respond(&mut socket, fixture::SUMMARY, "stop").await;
let (mut socket, resumed) = next(&listener).await;
empty(&resumed, mode);
diff --git a/plugins/agent/engine/tests/integration/frozen_projection.rs b/plugins/agent/engine/tests/integration/frozen_projection.rs
index 3697022e28..5ec6da9826 100644
--- a/plugins/agent/engine/tests/integration/frozen_projection.rs
+++ b/plugins/agent/engine/tests/integration/frozen_projection.rs
@@ -29,7 +29,6 @@ use maka_agent_facts::event::InvocationOutcome;
use maka_agent_facts::event::RuntimeEvent;
use maka_agent_facts::input::InvocationInput;
use maka_agent_facts::tool_call::ToolCallIdentity;
-use maka_agent_facts::tool_output::DURABLE_TOOL_PROJECTION_FAILURE_MESSAGE;
use maka_agent_facts::tool_output::ToolOutput;
use maka_event_log::EventLog;
use serde_json::json;
@@ -118,20 +117,15 @@ async fn reopened_history_uses_frozen_projection_without_raw_store_access() {
let log = EventLog::open(&path).await.unwrap();
let raw = ToolOutput::Text("raw-only-marker".repeat(800_000));
settled(&log, &raw).await;
- let original = log.prefix(100, 128 * 1024).await.unwrap();
+ let original = log.prefix(100, 16 * 1024 * 1024).await.unwrap();
let expected = project_model_history(&original, "session").unwrap();
assert_eq!(
serde_json::to_value(&expected).unwrap()[2]["content"][0]["output"],
- json!({"type":"error-text","value":DURABLE_TOOL_PROJECTION_FAILURE_MESSAGE})
- );
- assert!(
- !serde_json::to_string(&expected)
- .unwrap()
- .contains("raw-only-marker")
+ json!({"type":"json","value":{"kind":"text","text":"raw-only-marker".repeat(800_000)}})
);
log.close().await.unwrap();
let log = EventLog::open(&path).await.unwrap();
- let reopened = log.prefix(100, 128 * 1024).await.unwrap();
+ let reopened = log.prefix(100, 16 * 1024 * 1024).await.unwrap();
assert_eq!(
serde_json::to_value(&reopened).unwrap(),
serde_json::to_value(&original).unwrap()
diff --git a/plugins/agent/engine/tests/integration/model_interruption/websocket.rs b/plugins/agent/engine/tests/integration/model_interruption/websocket.rs
index 29bc6e19dc..2faca1f8b0 100644
--- a/plugins/agent/engine/tests/integration/model_interruption/websocket.rs
+++ b/plugins/agent/engine/tests/integration/model_interruption/websocket.rs
@@ -289,7 +289,7 @@ async fn interrupted_progress_renews_compaction_before_and_after_a_checkpoint()
item["type"] == "function_call_output" && item["call_id"] == call),
"compaction must cover the settled effect before continuing");
if round == 2 {
- assert!(summary["input"].to_string().contains("Previous continuation summary"));
+ assert!(summary["input"].to_string().contains("Continuation summary"));
}
let event = json!({"type":"response.completed", "response":{"id":format!("summary-{round}"), "output":[{"type":"message", "id":format!("summary-text-{round}"), "content":[{"type":"output_text", "text":SUMMARY}]}]}});
let body = format!("data: {event}\n\n");
diff --git a/plugins/agent/engine/tests/integration/pruning.rs b/plugins/agent/engine/tests/integration/pruning.rs
index e1de970c60..b1f6ad00ae 100644
--- a/plugins/agent/engine/tests/integration/pruning.rs
+++ b/plugins/agent/engine/tests/integration/pruning.rs
@@ -105,13 +105,7 @@ async fn settled_results_are_pruned_before_context_limits_and_survive_failed_sum
tool(&mut socket, call_count).await;
let mut main = None;
let mut summaries = 0;
- let expected_summaries = if !spent {
- 0
- } else if interrupted {
- 1
- } else {
- 2
- };
+ let expected_summaries = if !spent { 0 } else { 1 };
while summaries < expected_summaries || main.is_none() {
let (mut socket, _) = listener.accept().await.unwrap();
let request = fixture::read_request(&mut socket).await;
@@ -126,8 +120,8 @@ async fn settled_results_are_pruned_before_context_limits_and_survive_failed_sum
summaries += 1;
assert!(summaries <= expected_summaries);
assert_eq!(
- request["max_tokens"], 4000,
- "Summary also respects the selected output budget"
+ request["max_tokens"], 8000,
+ "Summary budget is independent of the Main output budget"
);
assert!(
request["messages"]
@@ -142,7 +136,7 @@ async fn settled_results_are_pruned_before_context_limits_and_survive_failed_sum
let body = format!("data: {delta}\n\ndata: {failure}\n\n");
socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).as_bytes()).await.unwrap();
} else {
- fixture::respond(&mut socket, "malformed summary", "stop").await;
+ fixture::respond(&mut socket, "incomplete summary", "length").await;
}
}
let (mut socket, request) = main.unwrap();
diff --git a/plugins/agent/engine/tests/integration/session_import.rs b/plugins/agent/engine/tests/integration/session_import.rs
index 6ddd713355..bfc050b6cd 100644
--- a/plugins/agent/engine/tests/integration/session_import.rs
+++ b/plugins/agent/engine/tests/integration/session_import.rs
@@ -649,7 +649,11 @@ async fn large_import_fits_summary_recovers_overflow_and_continues_after_restart
let first = requests[0].to_string();
let second = requests[1].to_string();
assert!(first.contains("original-goal-marker") && first.contains("Historical update 7599"));
- assert!(first.len() < 200_000, "{}", first.len());
+ assert!(
+ first.len() > large_bytes,
+ "first summary preserves the complete prefix"
+ );
+ assert!(second.len() < 200_000, "overflow retry fits excerpts");
assert!(
second.len() < first.len() * 3 / 4,
"overflow must shrink the actual request"
diff --git a/plugins/agent/engine/tests/integration/support/http.rs b/plugins/agent/engine/tests/integration/support/http.rs
index fe3dbbe507..57af6f18a1 100644
--- a/plugins/agent/engine/tests/integration/support/http.rs
+++ b/plugins/agent/engine/tests/integration/support/http.rs
@@ -41,7 +41,7 @@ pub async fn read_request(socket: &mut TcpStream) -> Value {
.then(|| value.trim().parse().unwrap())
})
.unwrap();
- assert!(length < 512 * 1024);
+ assert!(length < 16 * 1024 * 1024);
while bytes.len() < boundary + length {
let mut chunk = [0; 4096];
let count = socket.read(&mut chunk).await.unwrap();
diff --git a/plugins/agent/engine/tests/integration/support/invocation.rs b/plugins/agent/engine/tests/integration/support/invocation.rs
index a32a78641a..93864b72ba 100644
--- a/plugins/agent/engine/tests/integration/support/invocation.rs
+++ b/plugins/agent/engine/tests/integration/support/invocation.rs
@@ -25,6 +25,7 @@ use maka_agent_facts::execution::ToolMode;
pub fn configuration(tool_mode: ToolMode) -> InvocationConfiguration {
InvocationConfiguration {
+ compaction_prompt: None,
workspace_origin: maka_agent_facts::execution::WorkspaceOrigin::Selected,
approval_policy: maka_agent_facts::execution::ApprovalPolicy::OnRequest,
boundary_revision: 0,
diff --git a/plugins/agent/facts/src/archive.rs b/plugins/agent/facts/src/archive.rs
index afdb175433..f2d3fc2289 100644
--- a/plugins/agent/facts/src/archive.rs
+++ b/plugins/agent/facts/src/archive.rs
@@ -29,7 +29,6 @@ pub use reference::ToolResultAddress;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-pub const MAX_ARCHIVE_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_ARCHIVE_REF_CHARS: usize = 16_384;
pub const ARCHIVE_READ_INSTRUCTIONS: &str = "Read the page below; pass page.next to Read to continue. The address is a Session resource, not a workspace file.";
@@ -153,10 +152,8 @@ impl ArchivedPlaceholder {
pub fn validate(&self) -> Result<(), &'static str> {
self.identity.validate()?;
- if self.identity.original_bytes > MAX_ARCHIVE_BYTES as u64
- || self.original_estimated_tokens > 9_007_199_254_740_991
- {
- return Err("archive exceeds byte or token limit");
+ if self.original_estimated_tokens > 9_007_199_254_740_991 {
+ return Err("archive exceeds token limit");
}
let model = self.model_value()?;
if model.to_string().encode_utf16().count() > MAX_PAGE_CHARS {
@@ -192,3 +189,28 @@ fn model_header(identity: &ArchiveIdentity) -> Result<ModelHeader<'_>, &'static
read_instructions: ARCHIVE_READ_INSTRUCTIONS,
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn archive_body_can_exceed_four_mib_while_model_page_stays_bounded() {
+ let text = "x".repeat(5 * 1024 * 1024);
+ let projection = DurableToolProjection::Text { text: text.clone() };
+ let encoded = encode_projection(&projection).unwrap();
+ assert_eq!(encoded.len(), text.len() + 2);
+ assert_eq!(serde_json::from_slice::<String>(&encoded).unwrap(), text);
+ let placeholder =
+ ArchivedPlaceholder::prepare("event".into(), "call".into(), "Read".into(), &projection)
+ .unwrap()
+ .unwrap();
+ assert_eq!(placeholder.identity.original_bytes, 5 * 1024 * 1024 + 2);
+ let model = placeholder.to_model_projection().unwrap();
+ let DurableToolProjection::Json { value } = model else {
+ panic!()
+ };
+ assert!(value.to_string().encode_utf16().count() <= MAX_PAGE_CHARS);
+ assert!(placeholder.page.next.is_some());
+ }
+}
diff --git a/plugins/agent/facts/src/archive/encoding.rs b/plugins/agent/facts/src/archive/encoding.rs
index c372222216..c841109959 100644
--- a/plugins/agent/facts/src/archive/encoding.rs
+++ b/plugins/agent/facts/src/archive/encoding.rs
@@ -17,7 +17,6 @@
* under the License.
*/
-use super::MAX_ARCHIVE_BYTES;
use crate::{
artifact::content_digest,
attachment::StorageRef,
@@ -77,12 +76,10 @@ pub fn encode_projection(projection: &DurableToolProjection) -> Result<Vec<u8>,
}
}
result.push('}');
- bounded(&result)?;
}
result.push(']');
}
}
- bounded(&result)?;
Ok(result.into_bytes())
}
@@ -97,19 +94,9 @@ pub fn projection_digest(projection: &DurableToolProjection) -> Result<String, &
Ok(content_digest(json.as_bytes()))
}
-fn bounded(output: &str) -> Result<(), &'static str> {
- if output.len() > MAX_ARCHIVE_BYTES {
- Err("archive body exceeds limit")
- } else {
- Ok(())
- }
-}
fn string(output: &mut String, value: &str) -> Result<(), &'static str> {
- if value.len() > MAX_ARCHIVE_BYTES {
- return Err("archive string exceeds limit");
- }
output.push_str(&serde_json::to_string(value).map_err(|_| "invalid string")?);
- bounded(output)
+ Ok(())
}
fn index(key: &str) -> Option<u32> {
let index = key.parse::<u32>().ok()?;
@@ -167,5 +154,5 @@ fn value_json(
output.push('}');
}
}
- bounded(output)
+ Ok(())
}
diff --git a/plugins/agent/facts/src/configuration/policy.rs b/plugins/agent/facts/src/configuration/policy.rs
index 4e664c03c0..11cb395d7f 100644
--- a/plugins/agent/facts/src/configuration/policy.rs
+++ b/plugins/agent/facts/src/configuration/policy.rs
@@ -46,6 +46,8 @@ impl Default for ChatDefaults {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuntimePolicy {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub compaction_prompt: Option<String>,
pub network_proxy: NetworkProxy,
pub personalization: Personalization,
pub memory: MemoryPolicy,
@@ -90,6 +92,7 @@ impl Default for RuntimePolicy {
.map(String::from)
.to_vec(),
},
+ compaction_prompt: None,
personalization: Personalization {
display_name: String::new(),
assistant_tone: String::new(),
diff --git a/plugins/agent/facts/src/context.rs b/plugins/agent/facts/src/context.rs
index fb22b30194..7ea94421a3 100644
--- a/plugins/agent/facts/src/context.rs
+++ b/plugins/agent/facts/src/context.rs
@@ -23,8 +23,7 @@ use serde::{Deserialize, Serialize};
mod checkpoint_mode;
mod summary;
pub use checkpoint_mode::CheckpointMode;
-pub use summary::{SUMMARY_FORMAT_TEMPLATE, validate_summary};
-pub const MAX_SUMMARY_BYTES: usize = 256 * 1024;
+pub use summary::{DEFAULT_COMPACTION_PROMPT, SUMMARY_FORMAT_TEMPLATE};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
@@ -124,6 +123,7 @@ pub struct ContextCheckpoint {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SummaryFormat {
+ /// Legacy wire label; the prompt determines content and no sections are required.
SectionsV1,
}
@@ -136,16 +136,6 @@ pub struct TextSummary {
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SummaryDefect {
- #[error("empty_summary")]
- Empty,
- #[error("summary_too_large")]
- TooLarge,
- #[error("malformed_summary_missing_section")]
- MissingSection,
- #[error("malformed_summary_truncated")]
- Truncated,
- #[error("malformed_summary_too_small_for_fold")]
- TooSmallForFold,
#[error("summary_contains_tool_content")]
ToolContent,
#[error("summary_has_invalid_finish_reason")]
@@ -153,16 +143,9 @@ pub enum SummaryDefect {
}
impl TextSummary {
- pub fn validate(&self) -> Result<(), SummaryDefect> {
- match self.format {
- SummaryFormat::SectionsV1 => validate_summary(&self.text, None),
- }
- }
-
/// Ordinary text parts concatenate in original order; thinking is not a
- /// portable summary. Missing usage stays unknown; roll-forward inputs do
- /// not measure the entire folded span and therefore never receive its floor.
- pub fn from_model_step(step: &ModelStep, initial_fold: bool) -> Result<Self, SummaryDefect> {
+ /// portable summary. The prompt controls the summary's content and format.
+ pub fn from_model_step(step: &ModelStep) -> Result<Self, SummaryDefect> {
if step.finish_reason != ModelFinishReason::Stop {
return Err(SummaryDefect::InvalidFinish);
}
@@ -174,9 +157,6 @@ impl TextSummary {
text: part,
..
} => {
- if part.len() > MAX_SUMMARY_BYTES.saturating_sub(text.len()) {
- return Err(SummaryDefect::TooLarge);
- }
text.push_str(part);
}
ModelPart::Text {
@@ -190,11 +170,9 @@ impl TextSummary {
}
}
}
- let text = text.trim_matches(summary::js_space);
- validate_summary(text, initial_fold.then_some(&step.usage))?;
Ok(Self {
format: SummaryFormat::SectionsV1,
- text: text.into(),
+ text,
})
}
}
@@ -219,9 +197,7 @@ impl ContextCheckpoint {
if let Some(id) = &self.previous_checkpoint_id {
crate::interaction::entity_id(id)?;
}
- self.summary
- .validate()
- .map_err(|_| "invalid checkpoint summary")
+ Ok(())
}
}
@@ -230,6 +206,49 @@ mod tests {
use super::*;
use crate::input::InvocationInput;
+ #[test]
+ fn summary_preserves_custom_text_without_content_heuristics() {
+ for text in [
+ String::new(),
+ " custom JSON or prose:...\n```".into(),
+ "x".repeat(300_000),
+ ] {
+ let step: ModelStep = serde_json::from_value(serde_json::json!({
+ "parts": [
+ {"kind":"text", "text_kind":"thinking", "text":"private reasoning"},
+ {"kind":"text", "text_kind":"text", "text":text}
+ ],
+ "finish_reason":"stop", "usage":{"input_tokens":20000,"output_tokens":1}
+ }))
+ .unwrap();
+ assert_eq!(TextSummary::from_model_step(&step).unwrap().text, text);
+ }
+ }
+
+ #[test]
+ fn summary_requires_completed_text_execution() {
+ let mut step: ModelStep = serde_json::from_value(serde_json::json!({
+ "parts":[{"kind":"text","text_kind":"text","text":"custom summary"}],
+ "finish_reason":"length","usage":{}
+ }))
+ .unwrap();
+ assert_eq!(
+ TextSummary::from_model_step(&step),
+ Err(SummaryDefect::InvalidFinish)
+ );
+ step.finish_reason = ModelFinishReason::Stop;
+ step.parts.push(ModelPart::ToolCall {
+ call: serde_json::from_value(serde_json::json!({
+ "id":"call", "name":"Read", "input":{}, "provider_executed":false
+ }))
+ .unwrap(),
+ });
+ assert_eq!(
+ TextSummary::from_model_step(&step),
+ Err(SummaryDefect::ToolContent)
+ );
+ }
+
#[test]
fn model_purpose_must_match_the_canonical_opening() {
let message = InvocationInput::Message {
diff --git a/plugins/agent/facts/src/context/summary.rs b/plugins/agent/facts/src/context/summary.rs
index abf4b2485c..851ac8f330 100644
--- a/plugins/agent/facts/src/context/summary.rs
+++ b/plugins/agent/facts/src/context/summary.rs
@@ -17,145 +17,13 @@
* under the License.
*/
-use super::{MAX_SUMMARY_BYTES, SummaryDefect};
-use crate::model::ModelUsage;
-
-pub const SUMMARY_FORMAT_TEMPLATE: &str = "## Goal\n[What the user is trying to accomplish]\n\n## Progress\n### Done\n- [Completed work and changes]\n### In Progress\n- [Current work]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Files, commands/results, errors, anything needed to continue; or \"(none)\"]";
-const REQUIRED: [&str; 4] = [
- "## Goal",
- "## Progress",
- "## Next Steps",
- "## Critical Context",
-];
-
-/// Port of history-compact-summary-validation.ts. The compaction layer's empty
-/// gate is included here; supplied usage must belong to the initial fold only.
-pub fn validate_summary(
- text: &str,
- initial_usage: Option<&ModelUsage>,
-) -> Result<(), SummaryDefect> {
- if text.len() > MAX_SUMMARY_BYTES {
- return Err(SummaryDefect::TooLarge);
- }
- let text = text.trim_matches(js_space);
- if text.is_empty() {
- return Err(SummaryDefect::Empty);
- }
- let (sections, open_fence) = scan(text);
- if !sections {
- return Err(SummaryDefect::MissingSection);
- }
- if open_fence
- || text.ends_with("...")
- || text.ends_with([':', ':', ',', ',', '、', ';', ';', '…', '(', '(', '—'])
- {
- return Err(SummaryDefect::Truncated);
- }
- if initial_usage.is_some_and(|usage| matches!((usage.input_tokens, usage.output_tokens), (Some(input), Some(output)) if input > 10_000 && output < 200)) {
- return Err(SummaryDefect::TooSmallForFold);
- }
- Ok(())
+macro_rules! summary_format {
+ () => { "## Goal\n[What the user is trying to accomplish]\n\n## Progress\n### Done\n- [Completed work and changes]\n### In Progress\n- [Current work]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Files, commands/results, errors, anything needed to continue; or \"(none)\"]" };
}
-fn scan(text: &str) -> (bool, bool) {
- let mut open: Option<(u8, usize)> = None;
- let mut matched = 0;
- let mut attributes = false;
- let mut content = [false; 4];
- for line in text
- .split('\n')
- .map(|line| line.strip_suffix('\r').unwrap_or(line))
- {
- let count = |content: &mut [bool; 4]| {
- let trimmed = line.trim_matches(js_space);
- if matched > 0
- && attributes
- && !trimmed.is_empty()
- && !SUMMARY_FORMAT_TEMPLATE.lines().any(|line| line == trimmed)
- && !bare_fence(trimmed)
- {
- content[matched - 1] = true;
- }
- };
- let structural = markdown_start(line);
- if let Some((family, width)) = structural.and_then(fence_run) {
- if open.is_none() {
- open = Some((family, width));
- } else if open
- .is_some_and(|(old_family, old_width)| family == old_family && width >= old_width)
- && line.trim_matches(js_space).len() == width
- {
- open = None;
- } else {
- count(&mut content);
- }
- continue;
- }
- if open.is_some() {
- count(&mut content);
- continue;
- }
- if matched < REQUIRED.len()
- && structural.is_some_and(|line| line.starts_with('#'))
- && line.trim_matches(js_space) == REQUIRED[matched]
- {
- matched += 1;
- attributes = true;
- continue;
- }
- let heading = structural.and_then(heading_level);
- if heading == Some(2) {
- attributes = false;
- continue;
- }
- if heading.is_none() && !thematic_break(line) {
- count(&mut content);
- }
- }
- (
- matched == REQUIRED.len() && content.into_iter().all(|has| has),
- open.is_some(),
- )
-}
-
-// Four spaces make indented code, not a structural Markdown delimiter.
-fn markdown_start(line: &str) -> Option<&str> {
- let spaces = line.bytes().take_while(|byte| *byte == b' ').count();
- (spaces <= 3).then(|| &line[spaces..])
-}
-fn fence_run(line: &str) -> Option<(u8, usize)> {
- let family = *line.as_bytes().first()?;
- if !matches!(family, b'`' | b'~') {
- return None;
- }
- let width = line.bytes().take_while(|byte| *byte == family).count();
- (width >= 3).then_some((family, width))
-}
-fn bare_fence(line: &str) -> bool {
- fence_run(line).is_some_and(|(_, width)| width == line.len())
-}
-fn heading_level(line: &str) -> Option<usize> {
- let width = line.bytes().take_while(|byte| *byte == b'#').count();
- ((1..=6).contains(&width) && line[width..].chars().next().is_none_or(js_space)).then_some(width)
-}
-fn thematic_break(line: &str) -> bool {
- let mut chars = line.chars().filter(|c| !js_space(*c));
- let Some(first) = chars.next() else {
- return false;
- };
- if !matches!(first, '-' | '*' | '_') {
- return false;
- }
- let mut count = 1;
- for character in chars {
- if character != first {
- return false;
- }
- count += 1;
- }
- count >= 3
-}
-pub(super) fn js_space(c: char) -> bool {
- matches!(c, '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
- '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}')
-}
+pub const SUMMARY_FORMAT_TEMPLATE: &str = summary_format!();
+pub const DEFAULT_COMPACTION_PROMPT: &str = concat!(
+ "You are a context summarization assistant.\nRead the conversation between a user and an AI assistant, then produce a structured summary another LLM will use to continue the same task.\nDo NOT continue the conversation. Do NOT answer questions in it. ONLY output the structured summary.\n\nUse this exact format:\n\n",
+ summary_format!(),
+ "\n\nKeep each section concise. Preserve exact file paths, function names, commands, and error messages.\n\nNow write the structured summary of the conversation above. Output only the summary.\n\nThe complete original conversation remains available through Recall when details are needed."
+);
diff --git a/plugins/agent/facts/src/execution.rs b/plugins/agent/facts/src/execution.rs
index b1c74125eb..98357ea90c 100644
--- a/plugins/agent/facts/src/execution.rs
+++ b/plugins/agent/facts/src/execution.rs
@@ -110,6 +110,9 @@ impl SystemPrompt {
/// Later Session mutations must not reinterpret relative paths or grants.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvocationConfiguration {
+ /// Frozen effective instructions for automatic and manual context compaction.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub compaction_prompt: Option<String>,
/// Frozen file-editing policy. Older invocations retain their original unfiltered tools.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub editing_tools: Option<EditingTools>,
diff --git a/plugins/agent/facts/src/tool_output/durable.rs b/plugins/agent/facts/src/tool_output/durable.rs
index 80d4f2982e..9e15a08d47 100644
--- a/plugins/agent/facts/src/tool_output/durable.rs
+++ b/plugins/agent/facts/src/tool_output/durable.rs
@@ -35,7 +35,6 @@ pub const MAX_RAW_TOOL_RESULT_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_RAW_TOOL_RESULT_JSON_DEPTH: usize = 64;
pub const DURABLE_TOOL_PROJECTION_FAILURE_MESSAGE: &str =
"The tool completed, but its model-visible result could not be projected safely.";
-const MAX_PROJECTION_BYTES: usize = 256 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -195,8 +194,7 @@ pub(crate) fn freeze(
)
}),
ToolOutput::Json(value) => {
- if !json_shape(value, &mut 0, 0) || bounded_encode(value, MAX_PROJECTION_BYTES).is_err()
- {
+ if !json_shape(value, &mut 0, 0) {
None
} else {
Some((
@@ -222,14 +220,12 @@ pub(crate) fn freeze(
)),
_ => None,
},
- ToolOutput::Text(text) => (text.len() <= MAX_PROJECTION_BYTES).then(|| {
- (
- DurableToolProjection::Json {
- value: serde_json::json!({"kind":"text","text":text}),
- },
- Vec::new(),
- )
- }),
+ ToolOutput::Text(text) => Some((
+ DurableToolProjection::Json {
+ value: serde_json::json!({"kind":"text","text":text}),
+ },
+ Vec::new(),
+ )),
ToolOutput::Model(result) => Some((
DurableToolProjection::Json {
value: serde_json::json!({
@@ -270,7 +266,7 @@ impl DurableToolProjection {
if !valid {
return Err("invalid durable tool projection");
}
- bounded_encode(self, MAX_PROJECTION_BYTES).map(|_| ())
+ Ok(())
}
}
diff --git a/plugins/agent/native/src/owner.rs b/plugins/agent/native/src/owner.rs
index 219f021082..f4eee61418 100644
--- a/plugins/agent/native/src/owner.rs
+++ b/plugins/agent/native/src/owner.rs
@@ -26,6 +26,7 @@ use maka_agent_engine::{Engine, RunError, RunInput, RunWork};
mod assistant;
mod attachments;
mod auxiliary;
+mod compaction;
mod execution;
mod goal;
mod graph;
@@ -74,6 +75,8 @@ use maka_agent_api::session::SessionConfiguration;
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct MessageBasis {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ compaction_prompt: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
graph: Option<maka_graph::Epoch>,
#[serde(default, skip_serializing_if = "is_agent_collaboration")]
@@ -131,6 +134,7 @@ enum PreparedBackend {
Executor(Box<crate::executor::Backend>),
}
struct Control {
+ compacting: bool,
invocation: Invocation,
basis: MessageBasis,
cancellation: CancellationToken,
@@ -898,6 +902,7 @@ impl Owner {
return Err("agent_planning_unavailable".into());
}
let mut basis = MessageBasis {
+ compaction_prompt: Some(self.effective_compaction_prompt().await?),
graph: None,
collaboration_mode: session.configuration.collaboration_mode,
background_kind: BackgroundKind::Schedule,
diff --git a/plugins/agent/native/src/owner/compaction.rs b/plugins/agent/native/src/owner/compaction.rs
new file mode 100644
index 0000000000..28deb087a3
--- /dev/null
+++ b/plugins/agent/native/src/owner/compaction.rs
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_agent_engine::{RunError, RunInput, RunWork};
+use maka_agent_facts::input::InvocationInput;
+
+impl Owner {
+ pub(super) async fn effective_compaction_prompt(&self) -> Result<String, String> {
+ Ok(self
+ .configuration
+ .runtime_policy()
+ .await
+ .map_err(|_| "agent_configuration_unavailable")?
+ .policy
+ .compaction_prompt
+ .unwrap_or_else(|| maka_agent_facts::context::DEFAULT_COMPACTION_PROMPT.into()))
+ }
+
+ pub async fn compaction_prompt(&self, input: SessionRead) -> Result<CompactionPrompt, String> {
+ self.session(&input.session_id).await?;
+ Ok(CompactionPrompt {
+ compaction_prompt: self.effective_compaction_prompt().await?,
+ default_compaction_prompt: maka_agent_facts::context::DEFAULT_COMPACTION_PROMPT.into(),
+ })
+ }
+
+ pub async fn compact(
+ self: &Arc<Self>,
+ input: Compact,
+ operation: &maka_plugin_core::operation::RecoveryRef,
+ ) -> Result<CompactResult, String> {
+ let mut runs = self.runs.lock().await;
+ let session = self.session(&input.session_id).await?;
+ let identity = self.operation_id(operation);
+ let invocation = Invocation {
+ session_id: input.session_id.clone(),
+ turn_id: format!("t_{identity}"),
+ run_id: format!("r_{identity}"),
+ invocation_id: format!("i_{identity}"),
+ };
+ // The canonical opening is the receipt, including after restart.
+ if let Some(boundary) = self
+ .store
+ .invocation_boundary(&input.session_id, &invocation.invocation_id)
+ .await
+ .map_err(|_| "agent_execution_unavailable")?
+ {
+ if boundary.0.invocation != invocation
+ || !matches!(&boundary.0.input,
+ InvocationInput::ContextCompact { request_fingerprint } if request_fingerprint == &operation.fingerprint)
+ {
+ return Err("agent_compact_conflict".into());
+ }
+ return Ok(CompactResult::Started {
+ execution: execution::project(boundary),
+ });
+ }
+ let rejected = |reason| Ok(CompactResult::Rejected { reason });
+ if runs.closing || self.stop.is_cancelled() || runs.quarantined.contains(&input.session_id)
+ {
+ return rejected(CompactRejection::Closed);
+ }
+ if session.archived {
+ return rejected(CompactRejection::Archived);
+ }
+ if runs.controls.contains_key(&input.session_id)
+ || !self
+ .store
+ .message_queue(&input.session_id)
+ .await
+ .map_err(|_| "agent_queue_unavailable")?
+ .entries
+ .is_empty()
+ {
+ return rejected(CompactRejection::Busy);
+ }
+ if matches!(
+ session.configuration.backend,
+ Some(BackendPreference::Executor { .. })
+ ) {
+ return rejected(CompactRejection::BackendUnavailable);
+ }
+ let workspace = &session.configuration.workspace;
+ if workspace::validate(&self.workspace_roots, workspace, &self.managed_worktrees)
+ .await
+ .is_err()
+ {
+ return rejected(CompactRejection::WorkspaceChanged);
+ }
+ let (source, prepared) = crate::model::Source::select(
+ self.configuration.clone(),
+ self.credentials.clone(),
+ input.model,
+ input.thinking_level,
+ input.session_id.clone(),
+ self.revision.clone(),
+ )
+ .await
+ .map_err(public_error)?;
+ let prompt = match input.prompt {
+ Some(prompt) => prompt,
+ None => self.effective_compaction_prompt().await?,
+ };
+ let permissions = &session.configuration.permissions;
+ let configuration = InvocationConfiguration {
+ compaction_prompt: Some(prompt.clone()),
+ editing_tools: source.accepted.editing_tools,
+ tool_discovery: false,
+ cwd: workspace.path.clone(),
+ workspace_identity: Some(workspace.identity.clone()),
+ workspace_origin: WorkspaceOrigin::Selected,
+ sandbox_mode: match permissions.access {
+ WorkspaceAccess::ReadOnly => SandboxMode::ReadOnly,
+ WorkspaceAccess::WorkspaceWrite => SandboxMode::WorkspaceWrite,
+ WorkspaceAccess::DangerFullAccess => SandboxMode::DangerFullAccess,
+ },
+ approval_policy: if permissions.request_permissions {
+ ApprovalPolicy::OnRequest
+ } else {
+ ApprovalPolicy::Never
+ },
+ boundary_revision: session.configuration.boundary_revision,
+ collaboration_mode: session.configuration.collaboration_mode,
+ orchestration_mode: BehaviorId::default(),
+ tool_mode: source.accepted.tool_mode,
+ model: Some(source.accepted.binding.clone()),
+ thinking_level: source.accepted.thinking_level,
+ system_prompt: None,
+ tool_composition: None,
+ };
+ let basis = MessageBasis {
+ compaction_prompt: Some(prompt),
+ graph: None,
+ collaboration_mode: session.configuration.collaboration_mode,
+ background_kind: BackgroundKind::Schedule,
+ tool_discovery: false,
+ allowed_tools: session.configuration.tools.clone(),
+ background: None,
+ internal_tools: vec![],
+ internal_bindings: BTreeMap::new(),
+ behavior: None,
+ model: Some(source.accepted.clone()),
+ executor: None,
+ workspace: workspace.clone(),
+ fingerprint: operation.fingerprint.clone(),
+ tools: vec![],
+ };
+ let run = RunInput {
+ invocation: invocation.clone(),
+ model_source: Some(Arc::new(source)),
+ model_revision: Some(prepared.revision),
+ provider_id: prepared.provider_id,
+ context: prepared.context,
+ provider: prepared.provider,
+ provider_options: prepared.options,
+ main_output_limit: prepared.main_output_limit,
+ supports_vision: prepared.supports_vision,
+ request_fingerprint: Some(operation.fingerprint.clone()),
+ configuration,
+ work: RunWork::ContextCompact,
+ };
+ let running = match self.engine.start(run, self.stop.child_token()).await {
+ Ok(running) => running,
+ Err(RunError::Busy) => return rejected(CompactRejection::Busy),
+ Err(error) => {
+ if error.is_cleanup_unconfirmed() {
+ runs.quarantined.insert(input.session_id.clone());
+ runs.closing = true;
+ self.stop.cancel();
+ }
+ return Err(public_error(error));
+ }
+ };
+ runs.controls.insert(
+ input.session_id.clone(),
+ Control {
+ compacting: true,
+ invocation: invocation.clone(),
+ basis,
+ cancellation: running.cancellation(),
+ failure: None,
+ },
+ );
+ self.workers.spawn(self.clone().drive(running));
+ let boundary = self
+ .store
+ .invocation_boundary(&input.session_id, &invocation.invocation_id)
+ .await
+ .map_err(|_| "agent_execution_unavailable")?
+ .ok_or("agent_execution_unavailable")?;
+ Ok(CompactResult::Started {
+ execution: execution::project(boundary),
+ })
+ }
+}
diff --git a/plugins/agent/native/src/owner/execution.rs b/plugins/agent/native/src/owner/execution.rs
index bd80a2ed1b..f05282cfd2 100644
--- a/plugins/agent/native/src/owner/execution.rs
+++ b/plugins/agent/native/src/owner/execution.rs
@@ -25,7 +25,7 @@ use maka_agent_facts::event::Fact;
use maka_agent_facts::event::InvocationOutcome;
use maka_event_log::turns::{InvocationState, TurnBoundary};
-fn project((boundary, high_water): (TurnBoundary, u64)) -> Execution {
+pub(super) fn project((boundary, high_water): (TurnBoundary, u64)) -> Execution {
Execution {
session_id: boundary.invocation.session_id,
turn_id: boundary.invocation.turn_id,
@@ -38,6 +38,9 @@ fn project((boundary, high_water): (TurnBoundary, u64)) -> Execution {
InvocationState::WaitingForUser => ExecutionState::Waiting,
InvocationState::Ended { outcome, .. } => match outcome {
InvocationOutcome::HandoffPaused { .. } => ExecutionState::Paused,
+ InvocationOutcome::ContextCompactFinished {
+ outcome: maka_agent_facts::context::CompactOutcome::Failed { .. },
+ } => ExecutionState::Failed,
InvocationOutcome::Completed | InvocationOutcome::ContextCompactFinished { .. } => {
ExecutionState::Completed
}
@@ -295,6 +298,7 @@ impl Owner {
Err(_) => return Ok(parked(Reason::SourceNotResumable)),
};
let basis = MessageBasis {
+ compaction_prompt: configuration.compaction_prompt.clone(),
graph,
collaboration_mode: configuration.collaboration_mode,
background_kind: BackgroundKind::Schedule,
@@ -385,6 +389,7 @@ impl Owner {
runs.controls.insert(
input.session_id,
Control {
+ compacting: false,
invocation: invocation.clone(),
basis,
cancellation: running.cancellation(),
diff --git a/plugins/agent/native/src/owner/notifications.rs b/plugins/agent/native/src/owner/notifications.rs
index dcd0281e13..5114e00cac 100644
--- a/plugins/agent/native/src/owner/notifications.rs
+++ b/plugins/agent/native/src/owner/notifications.rs
@@ -93,6 +93,7 @@ impl Owner {
return Ok(None);
}
let mut basis = MessageBasis {
+ compaction_prompt: Some(self.effective_compaction_prompt().await?),
graph: None,
collaboration_mode: session.configuration.collaboration_mode,
background_kind: BackgroundKind::Schedule,
diff --git a/plugins/agent/native/src/owner/queue.rs b/plugins/agent/native/src/owner/queue.rs
index 164aab5783..d43c3886b8 100644
--- a/plugins/agent/native/src/owner/queue.rs
+++ b/plugins/agent/native/src/owner/queue.rs
@@ -113,6 +113,7 @@ impl Owner {
runs.controls.insert(
running.invocation().session_id.clone(),
Control {
+ compacting: false,
invocation: running.invocation().clone(),
basis,
cancellation: running.cancellation(),
@@ -324,6 +325,7 @@ impl Owner {
.ok_or("agent_session_unavailable")?;
let permissions = &session.configuration.permissions;
let mut configuration = InvocationConfiguration {
+ compaction_prompt: basis.compaction_prompt.clone(),
editing_tools: None,
tool_discovery: basis.tool_discovery,
cwd: basis.workspace.path.clone(),
diff --git a/plugins/agent/native/src/owner/queue/controls.rs b/plugins/agent/native/src/owner/queue/controls.rs
index 6d296fc1a5..5f26b80504 100644
--- a/plugins/agent/native/src/owner/queue/controls.rs
+++ b/plugins/agent/native/src/owner/queue/controls.rs
@@ -22,7 +22,8 @@ use maka_event_log::message_queue::{MessageQueue, QueueCommand, QueueEdit};
impl MessageBasis {
fn same_execution(&self, other: &Self) -> bool {
- self.graph == other.graph
+ self.compaction_prompt == other.compaction_prompt
+ && self.graph == other.graph
&& self.collaboration_mode == other.collaboration_mode
&& self.tool_discovery == other.tool_discovery
&& self.background_kind == other.background_kind
@@ -228,7 +229,10 @@ impl Owner {
entry.expect("targeted promotion").execution.basis.clone(),
)
.map_err(|_| "agent_message_basis_invalid")?;
- if control.basis.executor.is_some() || !basis.same_execution(&control.basis) {
+ if control.compacting
+ || control.basis.executor.is_some()
+ || !basis.same_execution(&control.basis)
+ {
return rejected(QueueRejection::ExecutionChanged);
}
QueueEdit::Promote {
diff --git a/plugins/agent/native/src/owner/scheduler/dispatch.rs b/plugins/agent/native/src/owner/scheduler/dispatch.rs
index d72ec217f2..531ca7fd7e 100644
--- a/plugins/agent/native/src/owner/scheduler/dispatch.rs
+++ b/plugins/agent/native/src/owner/scheduler/dispatch.rs
@@ -149,6 +149,7 @@ impl Owner {
.await
.map_err(public_error)?;
let mut basis = MessageBasis {
+ compaction_prompt: Some(self.effective_compaction_prompt().await?),
graph: None,
collaboration_mode: CollaborationMode::Agent,
background_kind: kind,
diff --git a/plugins/agent/native/src/owner/tests.rs b/plugins/agent/native/src/owner/tests.rs
index 851cf8a053..369bb314f0 100644
--- a/plugins/agent/native/src/owner/tests.rs
+++ b/plugins/agent/native/src/owner/tests.rs
@@ -68,6 +68,9 @@ mod catalog;
#[path = "tests/history_search.rs"]
mod history_search;
+#[path = "tests/compaction.rs"]
+mod compaction;
+
#[path = "tests/execution.rs"]
mod execution;
#[path = "tests/executor.rs"]
diff --git a/plugins/agent/native/src/owner/tests/compaction.rs b/plugins/agent/native/src/owner/tests/compaction.rs
new file mode 100644
index 0000000000..1e7ebff3b8
--- /dev/null
+++ b/plugins/agent/native/src/owner/tests/compaction.rs
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_agent_facts::event::Fact;
+
+#[tokio::test]
+async fn manual_compaction_has_receipt_busy_stop_and_one_shot_prompt() {
+ tokio::time::timeout(Duration::from_secs(45), async {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let f = Fixture::new(&format!("http://{}/v1", listener.local_addr().unwrap()), None).await;
+ let session = f.create("Compact history").await;
+ let policy = f.config.runtime_policy().await.unwrap();
+ f.config.set_compaction_prompt(policy.revision, Some("GLOBAL COMPACTION".into())).await.unwrap();
+ let prompts = f.query("compactionPrompt", json!({"sessionId":session})).await.unwrap();
+ assert_eq!(prompts["compactionPrompt"], "GLOBAL COMPACTION");
+ f.mutation(2,"send",json!({"sessionId":session,"message":"original-needle-429","model":f.selection().await}),Uuid::new_v4()).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap();
+ request(&mut socket).await;
+ response_with_text(&mut socket, "Original answer retained verbatim").await;
+ f.drained().await;
+ let operation = Uuid::new_v4();
+ let input = json!({"sessionId":session,"model":f.selection().await,"prompt":"ONE SHOT COMPACTION"});
+ let started = f.mutation(2,"compact",input.clone(),operation).await.unwrap();
+ assert_eq!(started["kind"], "started", "{started}");
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let sent = request(&mut socket).await;
+ assert!(sent.to_string().contains("ONE SHOT COMPACTION"), "{sent}");
+ assert!(!sent.to_string().contains("GLOBAL COMPACTION"));
+ assert_eq!(f.query("observe",json!({"sessionId":session})).await.unwrap()["compacting"],true);
+ let busy = f.mutation(2,"compact",input.clone(),Uuid::new_v4()).await.unwrap();
+ assert_eq!(busy, json!({"kind":"rejected","reason":"busy"}));
+ response_with_text(&mut socket, "A deliberately short summary without the original unique token.").await;
+ f.drained().await;
+ assert!(!f.query("observe",json!({"sessionId":session})).await.unwrap()["compacting"].as_bool().unwrap_or(false));
+ let facts = service_tools::facts(&f,&session).await;
+ assert!(facts.iter().any(|f| matches!(f, Fact::ContextCheckpointRecorded { .. })), "{facts:?}");
+ assert_eq!(f.mutation(2,"compact",input.clone(),operation).await.unwrap(), started);
+ assert_eq!(f.query("compactionPrompt",json!({"sessionId":session})).await.unwrap()["compactionPrompt"], "GLOBAL COMPACTION");
+ let found = f.query("recall",json!({"terms":["original-needle-429"],"session_id":session})).await.unwrap();
+ assert!(!found["passages"].as_array().unwrap().is_empty(), "{found}");
+ let hit = &found["passages"][0];
+ let through = f.query("observe",json!({"sessionId":session})).await.unwrap()["through"].clone();
+ let history = f.query("history",json!({"sessionId":session,"through":through,"position":{"kind":"after","cursor":{"sequence":hit["anchorSequence"],"offset":0,"field":"body"}}})).await.unwrap();
+ assert!(history.to_string().contains("original-needle-429"), "{history}");
+ f.send(&session).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap(); request(&mut socket).await; response(&mut socket).await;
+ f.drained().await;
+ let stopped = f.mutation(2,"compact",input.clone(),Uuid::new_v4()).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap(); request(&mut socket).await;
+ assert_eq!(f.mutation(2,"stop",json!({"sessionId":session,"invocationId":stopped["execution"]["invocationId"]}),Uuid::new_v4()).await.unwrap()["requested"],true);
+ f.drained().await;
+ let execution = f.query("execution",json!({"sessionId":session,"invocationId":stopped["execution"]["invocationId"]})).await.unwrap();
+ assert_eq!(execution["execution"]["state"],"cancelled");
+ assert!(!f.query("observe",json!({"sessionId":session})).await.unwrap()["compacting"].as_bool().unwrap_or(false));
+ let failed = f.mutation(2,"compact",input,Uuid::new_v4()).await.unwrap();
+ let (mut socket, _) = listener.accept().await.unwrap(); request(&mut socket).await;
+ let delta = json!({"id":"truncated-summary","choices":[{"index":0,"delta":{"content":"cut off"},"finish_reason":null}]});
+ let end = json!({"id":"truncated-summary","choices":[{"index":0,"delta":{},"finish_reason":"length"}]});
+ let body = format!("data: {delta}\n\ndata: {end}\n\ndata: [DONE]\n\n");
+ socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()).as_bytes()).await.unwrap();
+ f.drained().await;
+ let execution = f.query("execution",json!({"sessionId":session,"invocationId":failed["execution"]["invocationId"]})).await.unwrap();
+ assert_eq!(execution["execution"]["state"],"failed");
+ assert!(service_tools::facts(&f,&session).await.iter().any(|fact| matches!(fact,
+ Fact::InvocationEnded { outcome: maka_agent_facts::event::InvocationOutcome::ContextCompactFinished {
+ outcome: maka_agent_facts::context::CompactOutcome::Failed { .. } } })));
+ assert!(matches!(f.owner.session(&session).await.unwrap().execution.unwrap().state,
+ maka_event_log::sessions::SessionExecutionState::Ended { status: maka_agent_facts::event::TerminalStatus::Failed, .. }));
+ f.app.shutdown().await.unwrap();
+ }).await.unwrap();
+}
diff --git a/plugins/agent/native/src/owner/tests/recall.rs b/plugins/agent/native/src/owner/tests/recall.rs
index 79e97e4564..db41c42d0f 100644
--- a/plugins/agent/native/src/owner/tests/recall.rs
+++ b/plugins/agent/native/src/owner/tests/recall.rs
@@ -161,6 +161,29 @@ async fn recall_native_model_tools_expand_exclude_active_turn_and_retain_materia
f.drained().await;
let facts = service_tools::facts(&f,&target).await;
assert_eq!(facts.iter().filter(|fact| matches!(fact,Fact::ToolSettled { outcome: ToolOutcome::Succeeded { .. }, .. })).count(),4,"{facts:?}");
+ // Context checkpoints replace active model input, not original Recall material.
+ let compacted = f.mutation(2,"compact",json!({"sessionId":target,"model":f.selection().await}),Uuid::new_v4()).await.unwrap();
+ assert_eq!(compacted["kind"],"started");
+ let (mut socket,_) = listener.accept().await.unwrap();
+ request(&mut socket).await;
+ response_with_text(&mut socket,"A short overview without the original tool result.").await;
+ f.drained().await;
+ assert!(service_tools::facts(&f,&target).await.iter().any(|fact| matches!(fact,Fact::ContextCheckpointRecorded { .. })));
+ let mut history_input = json!({"sessionId":target,"position":{"kind":"start"}});
+ let mut historical_tools = String::new();
+ loop {
+ let page = f.query("history",history_input.clone()).await.unwrap();
+ history_input["through"] = page["through"].clone();
+ if page["kind"] == "preparing" { continue; }
+ for chunk in page["chunks"].as_array().unwrap() {
+ if matches!(chunk["role"].as_str(),Some("tool_call" | "tool_result")) {
+ historical_tools.push_str(chunk["text"].as_str().unwrap());
+ }
+ }
+ if page["after"].is_null() { break; }
+ history_input["position"] = json!({"kind":"after","cursor":page["after"]});
+ }
+ assert!(historical_tools.contains("historical attachment contents"),"{historical_tools}");
let copies = f.store.list_artifacts(&target,0,128).await.unwrap();
let copied = copies.records.iter().find(|record| record.name == "notes.txt").unwrap();
assert_ne!(copied.id,artifact);
diff --git a/plugins/agent/native/src/owner/tests/settings.rs b/plugins/agent/native/src/owner/tests/settings.rs
index 81be5b01e7..b025e5300b 100644
--- a/plugins/agent/native/src/owner/tests/settings.rs
+++ b/plugins/agent/native/src/owner/tests/settings.rs
@@ -702,3 +702,25 @@ async fn saved_model_survives_restart_and_resolves_locally_at_the_current_revisi
f.config.shutdown().await.unwrap();
}).await.unwrap();
}
+
+#[tokio::test]
+async fn compaction_preferences_accept_custom_prompt_and_reset_to_default() {
+ let f = Fixture::new("http://127.0.0.1:1/v1", None).await;
+ let initial = query(&f, "assistantPreferences", json!({})).await;
+ assert_eq!(
+ initial["compactionPrompt"],
+ initial["defaultCompactionPrompt"]
+ );
+ let (saved,_) = mutate(&f,"updateAssistantPreferences",json!({"expectedRevision":initial["revision"],"mutation":{"kind":"compaction_prompt","prompt":"Custom freeform instructions"}}),None).await;
+ assert_eq!(saved["kind"], "committed");
+ let custom = query(&f, "assistantPreferences", json!({})).await;
+ assert_eq!(custom["compactionPrompt"], "Custom freeform instructions");
+ let (reset,_) = mutate(&f,"updateAssistantPreferences",json!({"expectedRevision":custom["revision"],"mutation":{"kind":"compaction_prompt","prompt":null}}),None).await;
+ assert_eq!(reset["kind"], "committed");
+ let reset = query(&f, "assistantPreferences", json!({})).await;
+ assert_eq!(
+ reset["compactionPrompt"],
+ initial["defaultCompactionPrompt"]
+ );
+ f.app.shutdown().await.unwrap();
+}
diff --git a/plugins/agent/native/src/service.rs b/plugins/agent/native/src/service.rs
index 237e210f9b..c6d6e91916 100644
--- a/plugins/agent/native/src/service.rs
+++ b/plugins/agent/native/src/service.rs
@@ -327,6 +327,7 @@ impl Handler for Agent {
_ => None,
};
let result = encode(Observation {
+ compacting: observed.compacting,
session,
metrics,
remembered_backend,
@@ -409,6 +410,7 @@ impl Handler for Agent {
chunks: chunks
.into_iter()
.map(|chunk| HistoryChunk {
+ compaction: chunk.compaction,
attachments: chunk
.attachments
.into_iter()
@@ -666,6 +668,11 @@ impl Handler for Agent {
)
}
"execution" => encode(owner.execution(decode(input)?).await?),
+ "compactionPrompt" => encode(owner.compaction_prompt(decode(input)?).await?),
+ "compact" => {
+ let operation = context.operation().ok_or("agent_mutation_required")?;
+ encode(owner.compact(decode(input)?, operation).await?)
+ }
"resume" => {
let operation = context.operation().ok_or("agent_mutation_required")?;
encode(owner.resume(decode(input)?, operation).await?)
@@ -924,7 +931,8 @@ fn delivery(event: StoreStreamEvent) -> Delivery {
}
StreamFact::InvocationEnded { failed, .. } => DeliveryFact::Ended { failed },
StreamFact::StepEnded { step_id, .. } => DeliveryFact::StepEnded { step_id },
- StreamFact::MessageSteered
+ StreamFact::ContextChanged
+ | StreamFact::MessageSteered
| StreamFact::ExecutorToolStart { .. }
| StreamFact::ExecutorToolProgress { .. }
| StreamFact::ExecutorToolResult { .. }
diff --git a/plugins/agent/ports/src/session/history.rs b/plugins/agent/ports/src/session/history.rs
index ff31f6d59c..2f4ae32223 100644
--- a/plugins/agent/ports/src/session/history.rs
+++ b/plugins/agent/ports/src/session/history.rs
@@ -219,6 +219,7 @@ impl Read {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Role {
+ Compaction,
User,
Assistant,
ToolCall,
@@ -364,6 +365,8 @@ pub struct HistorySource {
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Chunk {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub compaction: Option<Compaction>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timing: Option<TurnTiming>,
pub field: HistoryField,
@@ -381,6 +384,15 @@ pub struct Chunk {
pub attachments: Vec<AttachmentRef>,
}
+/// Duration of a successfully adopted context checkpoint, in recorded milliseconds.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+#[schemars(rename = "HistoryCompaction")]
+pub struct Compaction {
+ #[schemars(range(max = 9_007_199_254_740_991u64))]
+ pub duration_ms: u64,
+}
+
/// Recorded logical Turn boundaries at the same history fence. An unfinished
/// historical boundary alone does not establish that execution is still live.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
diff --git a/plugins/agent/session-recap/src/recap.rs b/plugins/agent/session-recap/src/recap.rs
index 84f5e158d2..a38de93d6c 100644
--- a/plugins/agent/session-recap/src/recap.rs
+++ b/plugins/agent/session-recap/src/recap.rs
@@ -522,6 +522,7 @@ mod tests {
Ok(history::Page::Ready {
through: 7,
chunks: vec![history::Chunk {
+ compaction: None,
field: Default::default(),
message_id: "m".into(),
turn_id: "t".into(),
diff --git a/plugins/settings/native/src/preferences.rs b/plugins/settings/native/src/preferences.rs
index 828a3e175b..9691372237 100644
--- a/plugins/settings/native/src/preferences.rs
+++ b/plugins/settings/native/src/preferences.rs
@@ -34,6 +34,8 @@ pub struct Read {}
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[schemars(rename = "SettingsAssistantPreferences")]
pub struct Preferences {
+ pub compaction_prompt: String,
+ pub default_compaction_prompt: String,
pub revision: u64,
#[schemars(length(max = 256))]
pub display_name: String,
@@ -60,6 +62,9 @@ pub struct Update {
)]
#[schemars(rename = "SettingsPreferencesMutation")]
pub enum Mutation {
+ CompactionPrompt {
+ prompt: Option<String>,
+ },
Personalization {
#[schemars(length(max = 256))]
display_name: String,
@@ -105,6 +110,11 @@ pub(crate) async fn read(
.await
.map_err(|_| "settings_store_unavailable")?;
super::connections::encode(Preferences {
+ compaction_prompt: snapshot
+ .policy
+ .compaction_prompt
+ .unwrap_or_else(|| maka_agent_facts::context::DEFAULT_COMPACTION_PROMPT.into()),
+ default_compaction_prompt: maka_agent_facts::context::DEFAULT_COMPACTION_PROMPT.into(),
revision: snapshot.revision,
display_name: snapshot.policy.personalization.display_name,
assistant_tone: snapshot.policy.personalization.assistant_tone,
@@ -121,6 +131,11 @@ pub(crate) async fn update(
return super::connections::encode(Updated::Rejected);
};
let result = match input.mutation {
+ Mutation::CompactionPrompt { prompt } => {
+ store
+ .set_compaction_prompt(input.expected_revision, prompt)
+ .await
+ }
Mutation::ShellTitles { enabled } => {
store
.set_shell_titles(input.expected_revision, enabled)
diff --git a/plugins/settings/store/src/policy.rs b/plugins/settings/store/src/policy.rs
index 83deb190af..4dff91f1fd 100644
--- a/plugins/settings/store/src/policy.rs
+++ b/plugins/settings/store/src/policy.rs
@@ -32,6 +32,17 @@ use maka_agent_facts::configuration::validation::revision;
use sqlx::SqliteConnection;
impl ConfigurationStore {
+ pub async fn set_compaction_prompt(
+ &self,
+ expected_revision: u64,
+ prompt: Option<String>,
+ ) -> Result<RuntimePolicyMutationResult> {
+ self.update_policy(expected_revision, move |policy| {
+ policy.compaction_prompt = prompt
+ })
+ .await
+ }
+
pub async fn set_network_proxy(
&self,
expected_revision: u64,
diff --git a/plugins/shared/components.ts b/plugins/shared/components.ts
index 3eb1ce293d..ba2ed6e077 100644
--- a/plugins/shared/components.ts
+++ b/plugins/shared/components.ts
@@ -480,7 +480,7 @@ export function timeline<N extends Node>(
state.browse = null;
return;
}
- const rows = timelineRows(props);
+ const rows = timelineRows(props).filter(({ message }) => message.role !== 'compaction');
if (
state.browse?.request === props.browse &&
rows.some(({ message }) => message.id === state.browse!.id)
@@ -595,6 +595,36 @@ export function timeline<N extends Node>(
state.expanded = state.expanded.filter((id) => tools.some((message) => message.id === id));
const messages: N[] = rows.flatMap((row, index) => {
const { message, result, depth, timing } = row;
+ if (message.role === 'compaction') {
+ if (!message.compaction) return [];
+ const seconds = (message.compaction.durationMs / 1000).toFixed(1).replace(/\.0$/, '');
+ const rule = (side: string) =>
+ ui.box(
+ 'compact-rule-' + side + message.id,
+ ui.rule ? [ui.rule('compact-line-' + side + message.id, 'row')] : [],
+ {
+ terminal: { grow: 1, shrink: true },
+ style: { grow: 1, height: pixels(1) },
+ ...(target === 'desktop' ? { background: props.theme.border } : {}),
+ },
+ );
+ return [
+ ui.box(
+ 'message-' + message.id,
+ [
+ rule('left'),
+ ui.text(
+ 'compacted-label-' + message.id,
+ tuiText(props.locale, 'context-compacted', { seconds }),
+ 12,
+ props.theme.muted,
+ ),
+ rule('right'),
+ ],
+ { row: true, gap: target === 'tui' ? 1 : 12, style: { width: fill, align: 'center' } },
+ ),
+ ];
+ }
const tool = message.role === 'tool_call' || message.role === 'tool_result';
const expanded = state.expanded.includes(message.id);
const structured = tool && hasToolEvidence(message, props);
@@ -666,6 +696,7 @@ export function timeline<N extends Node>(
: props.theme;
const messageNode = messageView(presentation, target, messageTheme, props.locale, {
...message,
+ role: message.role,
traceDepth: depth,
detailStatus: state.details[message.id]?.status ?? null,
separate:
@@ -1279,7 +1310,7 @@ export function timeline<N extends Node>(
if (state.browse && state.browse.request === props.browse && !next.browse) {
// A page split within one message replaces the bounded window. Follow
// its existing landing edge instead of restarting at the first row.
- const rows = timelineRows(props);
+ const rows = timelineRows(props).filter(({ message }) => message.role !== 'compaction');
const row = props.landing.edge === 'end' ? rows.at(-1) : rows[0];
if (row) {
next.browse = { ...state.browse };
@@ -1322,7 +1353,7 @@ export function timeline<N extends Node>(
!props.loading &&
input.kind === 'raw'
) {
- const cards = timelineRows(props);
+ const cards = timelineRows(props).filter(({ message }) => message.role !== 'compaction');
const rows = cards.map(({ message }) => message);
const selected = rows.find((message) => input.key === 'browse-' + message.id);
const at = rows.findIndex((message) => message.id === next.browse!.id);
diff --git a/plugins/shared/contracts.ts b/plugins/shared/contracts.ts
index f62c0f1461..11064c9e45 100644
--- a/plugins/shared/contracts.ts
+++ b/plugins/shared/contracts.ts
@@ -86,6 +86,7 @@ export interface Theme {
markdown: MarkdownAppearance;
}
export interface Message {
+ compaction?: { durationMs: number };
pending?: boolean;
id: string;
// Stable message field/byte-segment identity, including the streaming prefix.
@@ -406,7 +407,8 @@ const messageSchema = object(
pending: { type: 'boolean' },
id: string,
contentKey: { type: 'string', minLength: 1, maxLength: 123, pattern: '^[A-Za-z0-9_-]+$' },
- role: { enum: ['user', 'assistant', 'thinking', 'tool_call', 'tool_result'] },
+ role: { enum: ['user', 'assistant', 'thinking', 'tool_call', 'tool_result', 'compaction'] },
+ compaction: object({ durationMs: { type: 'integer', minimum: 0, maximum: 9007199254740991 } }),
timestamp: {
anyOf: [{ type: 'integer', minimum: 0, maximum: 9007199254740991 }, { type: 'null' }],
},
@@ -1144,6 +1146,7 @@ export const composerFooterContract = component(
sessionId: { anyOf: [string, { type: 'null' }] },
dataSource: { anyOf: [{ $ref: '#/$defs/AgentDataSource' }, { type: 'null' }] },
running: { type: 'boolean' },
+ compacting: { type: 'boolean' },
metrics: { anyOf: [{ $ref: '#/$defs/AgentSessionMetrics' }, { type: 'null' }] },
theme: { $ref: '#/$defs/Theme' },
locale,
@@ -1224,6 +1227,7 @@ export const composerContract = component(
attachments: { type: 'array', maxItems: 8, items: string },
}),
),
+ compact: withDefs(object({ context: string, dataSource: { $ref: '#/$defs/AgentDataSource' } })),
setup: object({ context: string }),
readiness: withDefs({
type: 'array',
diff --git a/plugins/shared/locale-catalogs/components.ts b/plugins/shared/locale-catalogs/components.ts
index 165f151781..4561e9a822 100644
--- a/plugins/shared/locale-catalogs/components.ts
+++ b/plugins/shared/locale-catalogs/components.ts
@@ -126,11 +126,18 @@ const messages = {
export const copy = /* @__PURE__ */ createCopy(messages);
export type Copy = ReturnType<typeof copy>;
+import type { Catalog } from '../locale.js';
+
const terminalMessages = {
+ 'context-compacted': [
+ 'Context compressed ({ $seconds }s)',
+ '上下文已压缩({ $seconds }秒)',
+ '上下文已壓縮({ $seconds }秒)',
+ ],
'chat-prompt-jump': tui_chat_prompt_jump,
'insights-this-session': tui_insights_this_session,
'session-name-too-large': tui_session_name_too_large,
-};
+} satisfies Catalog;
export function tuiText(
locale: string,
key: string,
diff --git a/products/maka/bundle/tests/assistant-preferences.test.mjs b/products/maka/bundle/tests/assistant-preferences.test.mjs
index f3dcca6281..07fafb4f8e 100644
--- a/products/maka/bundle/tests/assistant-preferences.test.mjs
+++ b/products/maka/bundle/tests/assistant-preferences.test.mjs
@@ -39,6 +39,8 @@ for (const target of ['tui', 'desktop'])
revision: 4,
displayName: 'Saved',
assistantTone: '',
+ compactionPrompt: 'Default compression prompt',
+ defaultCompactionPrompt: 'Default compression prompt',
workspaceInstructions: true,
incognitoActive: false,
shellTitles: true,
@@ -106,6 +108,8 @@ for (const target of ['tui', 'desktop'])
revision: 7,
displayName: '',
assistantTone: '',
+ compactionPrompt: 'Default compression prompt',
+ defaultCompactionPrompt: 'Default compression prompt',
workspaceInstructions: true,
incognitoActive: false,
shellTitles: true,
@@ -161,3 +165,104 @@ for (const target of ['tui', 'desktop'])
mutation: { kind: 'shell_titles', enabled: true },
});
});
+
+for (const target of ['tui', 'desktop'])
+ test(`Assistant ${target} saves a custom compression prompt and restores the built-in default`, async () => {
+ const { component } = await import(`../dist/packages/assistant-preferences/${target}.js`);
+ const props = { theme, locale: 'en', open: true, busy: false, shell: { back: 0 } };
+ let out = component.mount(props, {});
+ const event = (input) => (out = component.event(out.frame.state, input, props, {}));
+ const raw = (key) => event({ kind: 'raw', key, event: {} });
+ const finish = (value) =>
+ event({ kind: 'action', key: out.actions[0].key, event: { status: 'succeeded', value } });
+ const observed = (text, revision, receipt = null) => ({
+ revision,
+ snapshot: {
+ text: { owner: 'prompt', revision, bytes: Buffer.byteLength(text) },
+ marked: null,
+ },
+ receipt,
+ });
+ const field = (value) =>
+ event({ kind: 'component', child: 'assistant-compaction', name: 'changed', event: value });
+ const saved = {
+ revision: 4,
+ displayName: 'Saved',
+ assistantTone: '',
+ workspaceInstructions: true,
+ incognitoActive: false,
+ shellTitles: true,
+ compactionPrompt: 'Built-in instructions',
+ defaultCompactionPrompt: 'Built-in instructions',
+ };
+ finish([]);
+ finish(saved);
+ field(observed('', 0));
+ const initial = out.frame.state.fields.compaction.command;
+ assert.deepEqual(initial.edit, { kind: 'reset', text: 'Built-in instructions' });
+ field(
+ observed('Built-in instructions', 1, {
+ owner: initial.owner,
+ sequence: initial.sequence,
+ outcome: { status: 'applied' },
+ }),
+ );
+ const draft = observed('Keep 中文 decisions', 2);
+ field(draft);
+ raw('save-compaction');
+ assert.equal(out.actions[0].resources.text.child, 'assistant-compaction');
+ finish({ metadata: draft.snapshot.text, text: 'Keep 中文 decisions' });
+ assert.deepEqual(out.actions[0].input, {
+ expectedRevision: 4,
+ mutation: { kind: 'compaction_prompt', prompt: 'Keep 中文 decisions' },
+ });
+ assert.equal(valid(out.actions[0].input), true, JSON.stringify(valid.errors));
+ const commit = (revision) =>
+ event({
+ kind: 'action',
+ key: out.actions[0].key,
+ event: {
+ status: 'operation',
+ reply: {
+ reference: {
+ contract: { name: 'maka.settings.Settings', version: 1 },
+ method: 'updateAssistantPreferences',
+ operation: `prompt-${revision}`,
+ },
+ receipt: {
+ kind: 'recorded',
+ outcome: { kind: 'returned', value: { kind: 'committed', revision } },
+ },
+ },
+ },
+ });
+ const unrelated = structuredClone(out.frame.state.fields.name);
+ commit(5);
+ finish({ ...saved, revision: 5, compactionPrompt: 'Keep 中文 decisions' });
+ assert.deepEqual(out.frame.state.fields.name, unrelated);
+ const savedReset = out.frame.state.fields.compaction.command;
+ field(
+ observed(savedReset.edit.text, 3, {
+ owner: savedReset.owner,
+ sequence: savedReset.sequence,
+ outcome: { status: 'applied' },
+ }),
+ );
+ raw('reset-compaction');
+ assert.deepEqual(out.actions[0].input, {
+ expectedRevision: 5,
+ mutation: { kind: 'compaction_prompt', prompt: null },
+ });
+ commit(6);
+ finish({ ...saved, revision: 6 });
+ const pending = out.frame.state.fields.compaction.command;
+ assert.deepEqual(pending.edit, { kind: 'reset', text: 'Built-in instructions' });
+ field(
+ observed(pending.edit.text, 4, {
+ owner: pending.owner,
+ sequence: pending.sequence,
+ outcome: { status: 'applied' },
+ }),
+ );
+ assert.equal(out.frame.state.saved.compactionPrompt, 'Built-in instructions');
+ });
diff --git a/products/maka/bundle/tests/compact.test.mjs b/products/maka/bundle/tests/compact.test.mjs
new file mode 100644
index 0000000000..b287db5814
--- /dev/null
+++ b/products/maka/bundle/tests/compact.test.mjs
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+const { activate } = await import('../dist/packages/appearance/tui.js');
+const theme = activate({ scheme: 'dark' }).Appearance.value;
+const observed = (name, revision, text, receipt) => ({
+ revision,
+ snapshot: { text: { owner: name, revision, bytes: Buffer.byteLength(text) }, marked: null },
+ ...(receipt ? { receipt } : {}),
+});
+async function client(target) {
+ const module = await import(`../dist/packages/agent-screen/${target}.js`);
+ module.activate({ locale: 'en' });
+ const values = { appearance: [theme] };
+ let out = module.component.mount({}, values);
+ Object.assign(out.frame.state, {
+ selected: {
+ id: 'session',
+ title: 'Compact test',
+ labels: [],
+ revision: 1,
+ updatedAt: 1,
+ archived: false,
+ activity: 'idle',
+ boundaryRevision: 7,
+ hasUnread: false,
+ dataSource: {
+ stateDomain: 'a'.repeat(64),
+ deployment: '00000000-0000-0000-0000-000000000001',
+ namespace: ['00000000-0000-0000-0000-000000000002'],
+ },
+ permissions: { access: 'read_only', requestPermissions: true },
+ workspace: { path: '/original', directoryIdentity: 'a'.repeat(64), identity: 'original' },
+ },
+ model: {
+ choice: {
+ selection: { connectionId: '00000000-0000-0000-0000-000000000003', modelId: 'fixture' },
+ name: 'fixture',
+ },
+ thinkingLevel: null,
+ },
+ inspector: null,
+ dialog: null,
+ modelRefreshing: false,
+ pending: {},
+ restoring: false,
+ });
+ const c = {
+ get state() {
+ return out.frame.state;
+ },
+ get out() {
+ return out;
+ },
+ event(input) {
+ out = module.component.event(c.state, input, {}, values);
+ return c;
+ },
+ raw(key) {
+ return c.event({ kind: 'raw', key, event: { kind: 'activate' } });
+ },
+ field(name, observation) {
+ return c.event({
+ kind: 'component',
+ child: 'compact-prompt',
+ name: 'changed',
+ event: observation,
+ });
+ },
+ reply(value, key = out.actions[0].key) {
+ return c.event({ kind: 'action', key, event: { status: 'succeeded', value } });
+ },
+ ready() {
+ c.field('', observed('prompt', 0, ''));
+ const cmd = c.state.compact.command;
+ c.field(
+ '',
+ observed('prompt', 1, cmd.edit.text, {
+ owner: cmd.owner,
+ sequence: cmd.sequence,
+ outcome: { status: 'applied' },
+ }),
+ );
+ },
+ };
+ return c;
+}
+for (const target of ['tui', 'desktop']) {
+ test(`${target} compact confirms the edited one-shot prompt without saving preferences`, async () => {
+ const c = await client(target);
+ c.event({
+ kind: 'component',
+ child: 'composer',
+ name: 'compact',
+ event: { context: 'session', dataSource: c.state.selected.dataSource },
+ });
+ assert.equal(c.state.dialog, 'compact');
+ assert.deepEqual(c.out.actions[0].input, { sessionId: 'session' });
+ assert.equal(c.out.actions[0].method, 'compactionPrompt');
+ c.reply({
+ compactionPrompt: 'Global instructions',
+ defaultCompactionPrompt: 'Built-in instructions',
+ });
+ c.ready();
+ assert.equal(c.state.compact.observation.snapshot.text.bytes, 19);
+ const draft = observed('prompt', 2, 'Preserve 中文 decisions');
+ c.field('', draft);
+ c.raw('compact-confirm');
+ assert.equal(c.out.actions[0].resources.text.child, 'compact-prompt');
+ c.reply({ metadata: draft.snapshot.text, text: 'Preserve 中文 decisions' });
+ assert.equal(c.out.actions[0].method, 'compact');
+ assert.deepEqual(c.out.actions[0].input, {
+ sessionId: 'session',
+ prompt: 'Preserve 中文 decisions',
+ model: { connectionId: '00000000-0000-0000-0000-000000000003', modelId: 'fixture' },
+ thinkingLevel: null,
+ });
+ const key = c.out.actions[0].key;
+ c.event({
+ kind: 'action',
+ key,
+ event: {
+ status: 'operation',
+ reply: {
+ reference: { operation: 'compact-1', method: 'compact' },
+ receipt: {
+ kind: 'recorded',
+ outcome: { kind: 'returned', value: { kind: 'started', execution: {} } },
+ },
+ },
+ },
+ });
+ assert.equal(c.state.dialog, null);
+ assert.equal(
+ c.out.actions.find((action) => action.method === 'observe').input.sessionId,
+ 'session',
+ );
+ });
+ test(`${target} compact cancels locally and refuses a stale session destination`, async () => {
+ const c = await client(target);
+ const open = () =>
+ c.event({
+ kind: 'component',
+ child: 'composer',
+ name: 'compact',
+ event: { context: 'session', dataSource: c.state.selected.dataSource },
+ });
+ open();
+ c.reply({ compactionPrompt: 'Default', defaultCompactionPrompt: 'Default' });
+ c.ready();
+ c.raw('compact-cancel');
+ assert.equal(c.state.dialog, null);
+ open();
+ c.reply({ compactionPrompt: 'Default', defaultCompactionPrompt: 'Default' });
+ c.ready();
+ c.state.selected.id = 'another-session';
+ c.raw('compact-confirm');
+ assert.equal(c.state.compact.sessionId, 'session');
+ assert.equal(
+ c.out.actions.some((action) => action.method === 'compact'),
+ false,
+ );
+ });
+}
+
+for (const target of ['tui', 'desktop'])
+ test(`${target} compact rejects a prompt edited during capture and checks an uncertain receipt`, async () => {
+ const c = await client(target);
+ c.event({
+ kind: 'component',
+ child: 'composer',
+ name: 'compact',
+ event: { context: 'session', dataSource: c.state.selected.dataSource },
+ });
+ c.reply({ compactionPrompt: 'Default', defaultCompactionPrompt: 'Default' });
+ c.ready();
+ const original = observed('prompt', 2, 'Keep original');
+ c.field('', original);
+ c.raw('compact-confirm');
+ const readKey = c.out.actions[0].key;
+ c.field('', observed('prompt', 3, 'Keep new text'));
+ c.reply({ metadata: original.snapshot.text, text: 'Keep original' }, readKey);
+ assert.equal(c.state.compact.failed, true);
+ c.raw('compact-confirm');
+ c.reply({ metadata: c.state.compact.observation.snapshot.text, text: 'Keep new text' });
+ assert.equal(c.out.actions[0].input.prompt, 'Keep new text');
+ const reference = { operation: 'original-compact', method: 'compact' };
+ c.event({
+ kind: 'action',
+ key: c.out.actions[0].key,
+ event: { status: 'operation', reply: { reference, receipt: { kind: 'pending' } } },
+ });
+ c.raw('compact-check');
+ assert.equal(c.out.actions[0].binding, 'receipts');
+ assert.deepEqual(c.out.actions[0].input, reference);
+ c.reply({
+ reference,
+ receipt: {
+ kind: 'recorded',
+ outcome: { kind: 'returned', value: { kind: 'started', execution: {} } },
+ },
+ });
+ assert.equal(c.state.dialog, null);
+ });
diff --git a/products/maka/bundle/tests/compaction-display.test.mjs b/products/maka/bundle/tests/compaction-display.test.mjs
new file mode 100644
index 0000000000..62ad4dd637
--- /dev/null
+++ b/products/maka/bundle/tests/compaction-display.test.mjs
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+const { activate } = await import('../dist/packages/appearance/tui.js');
+const theme = activate({ scheme: 'dark' }).Appearance.value;
+const nodes = (node) =>
+ node && typeof node === 'object'
+ ? [
+ node,
+ ...Object.values(node).flatMap((value) =>
+ Array.isArray(value) ? value.flatMap(nodes) : nodes(value),
+ ),
+ ]
+ : [];
+for (const target of ['tui', 'desktop']) {
+ test(`${target} compaction tints only context and restores the ordinary footer`, async () => {
+ const { component } = await import(`../dist/packages/composer-footer/${target}.js`);
+ const props = {
+ theme,
+ locale: 'en',
+ sessionId: 'session',
+ dataSource: null,
+ running: true,
+ compacting: false,
+ metrics: {
+ modelId: 'fixture',
+ connectionId: null,
+ contextTokens: 100000,
+ contextWindow: 200000,
+ approximate: false,
+ outputTokensPerSecond: 42,
+ },
+ };
+ const idle = component.mount(props);
+ const busy = component.update(idle.frame.state, { ...props, compacting: true });
+ const restored = component.update(busy.frame.state, props);
+ const node = (out, key) => nodes(out.frame.view).find((node) => node.key === key);
+ assert.equal(node(busy, 'session-context-text').text, 'Context 100k / 200k · 50%');
+ assert.notDeepEqual(
+ node(busy, 'session-context-text').color,
+ node(idle, 'session-context-text').color,
+ );
+ assert.deepEqual(node(busy, 'session-rate-text').color, node(idle, 'session-rate-text').color);
+ assert.deepEqual(
+ node(restored, 'session-context-text').color,
+ node(idle, 'session-context-text').color,
+ );
+ const unknown = component.mount({ ...props, metrics: null, compacting: true });
+ assert.equal(node(unknown, 'session-context-text').text, 'Compressing context');
+ });
+ test(`${target} successful compaction is a quiet history divider without message controls`, async () => {
+ const { component } = await import(`../dist/packages/timeline/${target}.js`);
+ const props = {
+ theme,
+ locale: 'zh-CN',
+ copyRequest: null,
+ browse: null,
+ timings: [],
+ markReadEnabled: true,
+ toolContext: { sessionId: 'session', through: 8 },
+ waitingTools: [],
+ liveTools: [],
+ source: null,
+ search: null,
+ loading: false,
+ older: false,
+ newer: false,
+ latest: false,
+ landing: { sequence: 0, edge: 'end' },
+ live: false,
+ messages: [
+ {
+ id: 'checkpoint',
+ contentKey: 'checkpoint',
+ role: 'compaction',
+ compaction: { durationMs: 1250 },
+ text: '',
+ timestamp: 10000,
+ source: null,
+ image: false,
+ continued: false,
+ tool: null,
+ },
+ ],
+ };
+ const tree = nodes(component.mount(props).frame.view);
+ assert.ok(tree.some((node) => node.text === '上下文已压缩(1.3秒)'));
+ assert.ok(tree.some((node) => node.key === 'compact-rule-leftcheckpoint'));
+ assert.ok(tree.some((node) => node.key === 'compact-rule-rightcheckpoint'));
+ assert.ok(!tree.some((node) => node.key === 'source-checkpoint'));
+ assert.ok(!tree.some((node) => node.key === 'mark-read-checkpoint'));
+ if (target === 'tui') {
+ props.browse = 1;
+ const ordinary = (id) => ({
+ ...props.messages[0],
+ id,
+ contentKey: id,
+ role: 'assistant',
+ compaction: undefined,
+ text: 'Answer',
+ });
+ props.messages = [ordinary('before'), props.messages[0], ordinary('after')];
+ const started = component.mount(props);
+ assert.equal(started.frame.state.browse.id, 'before');
+ const moved = component.event(
+ started.frame.state,
+ { kind: 'raw', key: 'browse-next', event: { kind: 'activate' } },
+ props,
+ );
+ assert.equal(moved.frame.state.browse.id, 'after');
+ }
+ });
+}
diff --git a/products/maka/bundle/tests/composer.test.mjs b/products/maka/bundle/tests/composer.test.mjs
index f1e7ffcf27..4cac02c210 100644
--- a/products/maka/bundle/tests/composer.test.mjs
+++ b/products/maka/bundle/tests/composer.test.mjs
@@ -532,3 +532,25 @@ test('pending approval keeps the entire composer border amber through focus and
assert.equal(find(c.out.frame.view).border.focused_color, theme.terminal.accent);
}
});
+
+for (const target of ['tui', 'desktop']) {
+ test(`${target} /compact opens a local command and clears its captured draft`, async () => {
+ const c = await client(target);
+ c.ready('/compact');
+ c.send('/compact');
+ assert.deepEqual(c.out.events, [
+ { name: 'compact', value: { context: 'session', dataSource } },
+ ]);
+ assert.deepEqual(c.editor().command.edit, { kind: 'reset', text: '' });
+ c.clear();
+ c.ready('/compact is a command');
+ c.send('/compact is a command');
+ assert.deepEqual(c.out.actions[0].input, {
+ sessionId: 'session',
+ message: '/compact is a command',
+ attachments: [],
+ model: backend.model,
+ thinkingLevel: null,
+ });
+ });
+}
diff --git a/products/maka/cli/notices.json b/products/maka/cli/notices.json
index 079545af91..01483d32e3 100644
--- a/products/maka/cli/notices.json
+++ b/products/maka/cli/notices.json
@@ -5,8 +5,8 @@
"package-lock.json": "a5af15aca21fabe0e1bdd48784167df4dc81cee17777d54861dcbd641168a4eb",
"package.json": "38baf3beeb5876849ca16e31868d59bfaee769f260c7555b4a8a1847b92e28a1",
"packages/plugin-sdk/src/configurations.ts": "f2e890798ac26c9962e182c43331d570a0a76eabc13fdd8af9b167fcd2e2365f",
- "packages/plugin-sdk/src/contracts.ts": "2b932b6891789e3127b22e94b51921616e05dd3bd2ffb6f986817c93e7f26912",
- "packages/plugin-sdk/src/generated/runtime.ts": "e64e07fbbee40369847faa8161255c0dfbedf7e231b07673c3d6c41ac1e230f7",
+ "packages/plugin-sdk/src/contracts.ts": "2ca8edcb5eca868a6b9fdef780f9a4ef5aba5636edbb1ce608ebd3d52eeb7307",
+ "packages/plugin-sdk/src/generated/runtime.ts": "c047eda314ec8ed841ce919dc8982a5b341e1e848109532c97f2fd55054f35e8",
"packages/plugin-sdk/src/index.ts": "27b68be5a29d1857f7fe361c8c678e77ba21413c79ec3870c1ce30d0faf9323f",
"packages/plugin-sdk/src/native.ts": "2cf374759664132f1eba27b3c49c375174ad7e748e6d28a68ed07dde7ab05bf7",
"packages/plugin-sdk/src/ui.ts": "d6c64e9406c41ad6bbda73435b559aad24c31adb3c5bbb4ab6f49fff8a8330ca",
@@ -43,47 +43,48 @@
"plugins/agent/acp-executor/engine/tests/support/tui-auth.mjs": "b66436ace65b5874b6cd3ab66ece94984552c4a0772a0ae2d9b05db6b9f47d0f",
"plugins/agent/acp-executor/native/Cargo.toml": "6a896cb424d361ef3a98efa56a92ffc8680156473822bd1d38374b60f3f1da66",
"plugins/agent/acp-executor/package.ts": "d85747d6f02da7a316859d04d87706bf425699b90bf4053198a64b50eabd391f",
- "plugins/agent/agent-screen/actions.ts": "e59310d4bc0508fb8a9bbe09d92c55c2601a964be126536506a263a2745e9af4",
+ "plugins/agent/agent-screen/actions.ts": "1bbfa94d989609dc3e4d006a96a3e5f6d20b09496bbe437d50672483d9b70e8a",
"plugins/agent/agent-screen/checklist-view.ts": "e2976d6408df0407af4c26c9221a143761197f800f7a4f620639dad80091192f",
- "plugins/agent/agent-screen/component-events.ts": "b9d4112af44db1162008c795db667e995a050a6147726556edfb162e22b0e8bf",
+ "plugins/agent/agent-screen/compact.ts": "aa90a96bde5769e32b7b3f8a98315997ff5202bc315286eec21710f6a7f08050",
+ "plugins/agent/agent-screen/component-events.ts": "b74e44f6a3a936225d7af7f75148041741b96bdf0d9d48908e0afca36673f4a3",
"plugins/agent/agent-screen/composer-status.ts": "ff8380142e1b247d508b5be10d2089b353019de8a705169703fd53f3008b2db9",
- "plugins/agent/agent-screen/conversation-view.ts": "256e40c6ccd78f11502c77a851f9b8764cb3692acc0d28f227d4d6b45839b518",
+ "plugins/agent/agent-screen/conversation-view.ts": "75fda3997452bab76d56ba5806ae25eebd772f00dbe9ceb01c78c804baf8570e",
"plugins/agent/agent-screen/desktop.ts": "9cd44cb6a5225feead1aa87fc4e2d7935b994022fa38175342330119e72c4660",
- "plugins/agent/agent-screen/events.ts": "efb229195679d01d5a12c0229938f1b1cb4955a8e08033e12fdc95398ce303a4",
- "plugins/agent/agent-screen/frame.ts": "973876ad92fe856235052f68785ac173aab6608c71ca64c67a295d00f0a73a36",
+ "plugins/agent/agent-screen/events.ts": "b2ff520c01548565b1da878a265039edde35fb976229b7b4d0abfa5128a36050",
+ "plugins/agent/agent-screen/frame.ts": "6629873dce002ea72a9fa9cfff8dceced73ea443b7e286adf7962cf2bf2cd391",
"plugins/agent/agent-screen/goal.ts": "613cb2cfd059ff5ca4b3ea2dd0f85a49e852296d57767f2d71e066453900f409",
"plugins/agent/agent-screen/graph.ts": "a60a38979fba5a0dd1dfa944f28ce8d1768c7cd84b3a95bbaddc6731a39922c1",
"plugins/agent/agent-screen/header-view.ts": "cb2793de9c6c2b14d7c956f4414ba11bc526c5f806e97a9561d6e85908110dfb",
- "plugins/agent/agent-screen/index.ts": "822ae06b4c05cfa9a4219b1af520fcbd147eb413baebee9228e40881f6ac9fee",
+ "plugins/agent/agent-screen/index.ts": "e7997d4facaaee2ccc110d6b9b57b1eb07505ad4eef07a601ea3400a2a205137",
"plugins/agent/agent-screen/locale.ts": "8fefbda7a1bb7927f42f059cd0385c5fcc38e9bcd6e6a3bf76896b016e1b3c5c",
- "plugins/agent/agent-screen/messages.ts": "00db50bf8fd20c5d770251e4fffaad8263a7e418055fd68fc19f195342005c49",
+ "plugins/agent/agent-screen/messages.ts": "f231e36f9aabe2e782be48b40748856c9e6f378988e18b05088c2d192168f9de",
"plugins/agent/agent-screen/navigation-view.ts": "4f4df48a7714eabe7159db161a03abddcc742cd5d71fe4cd488a7a301a3979a5",
"plugins/agent/agent-screen/outputs-view.ts": "c77e4b71ccd122bac25c0b2108f3261b3e3b84f3f024487cc389d7042f9932aa",
"plugins/agent/agent-screen/package.ts": "2a9d1635153ff46fe52313bdb70934c0818ac99350665c509e4d47ba2401bd45",
"plugins/agent/agent-screen/pages-view.ts": "661e061479a340a98a53dd20ced7e814930f61d0433a133b05bce2a00181010c",
"plugins/agent/agent-screen/plan.ts": "88f600ede57041a4f83acd485c532324b8ab52842471985c5e8e2b8a76d50a00",
- "plugins/agent/agent-screen/raw-events.ts": "e5c18d013bdfd9157b900e4ee6d9b6ef8899bc0579c3c1198e6361ede0f46f4d",
+ "plugins/agent/agent-screen/raw-events.ts": "665401724b6a339694050f6521f4b3f5adec09582c71f19aa41d852b58618691",
"plugins/agent/agent-screen/recap-view.ts": "eba743e827b0fe0832430955f8d3d1f5a43dd37526a94ecf1d9daab666e58185",
- "plugins/agent/agent-screen/results.ts": "beec0b6715c4907f41861d5ee395e70d030b1b83f89693ffaa6313966b5368ca",
+ "plugins/agent/agent-screen/results.ts": "60146900d6719f99aae89b56e56c93ce8dd36382cd583eea7503ec387d2db7e5",
"plugins/agent/agent-screen/sandbox.ts": "344159383d98bd542f9614f2466f78ceee4b892adce3c9c13c355dd4783c17df",
- "plugins/agent/agent-screen/state.ts": "bd20748a1b84ab953c807ccc7b4bfab159c17aff3abd42f725735be83eea95d7",
+ "plugins/agent/agent-screen/state.ts": "258233d53be6d71df5f70bbc4b74cc73067b53e1043e00cb40a1e21a80cbb437",
"plugins/agent/agent-screen/tui.ts": "3b1de4b1aa847692e94b66262a1a6e8c21d1111d61f5d86ad28d13adb712d856",
"plugins/agent/agent/package.ts": "d4929e8b6e276705dbb3049b840ea64f53dd7d52176e2036d2f769df5e7bc82f",
"plugins/agent/api/Cargo.toml": "7f33b8ad23980598820684a18fbde28a078a8624e951147564da3d121736fecc",
"plugins/agent/assistant-preferences/desktop.ts": "7f5cc8f2087bf85f6b32b94b9110f87cf2acb6d46da9d581efc19c886c2ecd80",
- "plugins/agent/assistant-preferences/index.ts": "92be36dca94795ff9800dad187c959d6a5de4a55e085052ee26dc7cda3220e03",
- "plugins/agent/assistant-preferences/locale.ts": "7878338413723397eed61480a53c2796d5f765f3d3eba4e1e76427b55cf6471e",
+ "plugins/agent/assistant-preferences/index.ts": "9582a397568b912172cb1a275c76a0957959780bac44cd3b12827998a2a9ced8",
+ "plugins/agent/assistant-preferences/locale.ts": "604c27325f390a069c40217af0df7bc3ad5b891a2198e6d4dee804b677258931",
"plugins/agent/assistant-preferences/package.ts": "813f0a197cc326b4a48545f621e7888a2b5e6b213dd2e8d5b955ae69ed7880d0",
"plugins/agent/assistant-preferences/tui.ts": "1a5f4670eddd3ea99ba791125830bb56b653ac8e56aeb31edd5b60f71bd7a62a",
"plugins/agent/assistant/Cargo.toml": "29362b7b0572c4184ca48a9abdc4e37f2018865a7b34454ee457285e4f0687e1",
"plugins/agent/authority/Cargo.toml": "cdd02f3db0cbf67ace86fa60665580a3ae0a949e7cefc067349be05a49f74331",
"plugins/agent/checkpoint/package.ts": "c8915fbad07442cbb3dbbbc2875d640ac570f1eb2bc659c88447369523472da3",
"plugins/agent/composer-footer/desktop.ts": "4d2d66984d181b452c550de68ecf1fd8210d095eacb4b1ed8b70c084fb1b758a",
- "plugins/agent/composer-footer/index.ts": "d965c0c502e45677fd99006b9c2a849d94f0773231693eb73c623263776a18e3",
- "plugins/agent/composer-footer/locale.ts": "eaf74e85cac91778c904d2ada3bbba5c975e1671cf5191061d1e27ab7e177989",
+ "plugins/agent/composer-footer/index.ts": "dfee9a87a571a651a425dc0322122f2f281b0fb9bf52a1cbaf7633e879a8b883",
+ "plugins/agent/composer-footer/locale.ts": "bd05001fd6d38e8a548c391ddae441f4ba659cf7351f417cfa1cac7531c3da1e",
"plugins/agent/composer-footer/package.ts": "256408914147346b046d9447869acdf5d778f5822fe3b392b1ece8f805a10399",
"plugins/agent/composer-footer/tui.ts": "a42a739ba6a216de189ffee699a259f72a1a236ff8d96210a688ee29287939fb",
- "plugins/agent/composer/component.ts": "a27b23b923ff771e82c934f103a2b7778a14185eab3c94da7f761bef46e3b8fa",
+ "plugins/agent/composer/component.ts": "ce5114e2496303bb3b77884c8876b7b6985e627126a9a38605caaf89d9759315",
"plugins/agent/composer/desktop.ts": "781fa9950b60606fd3301d3efc55af43dc95e8585b8a4b8ef4d967e278a8b653",
"plugins/agent/composer/locale.ts": "291a6de52d51617c4d5802524063ea546b7aba3fda826faf4d76fc8e2cc40bb9",
"plugins/agent/composer/package.ts": "d996adc3bfed1e72b4cbdfaf28525c942d38f8a3ff53910d6d76edd7e16a36c7",
@@ -314,8 +315,8 @@
"plugins/shared/appearance-editor.ts": "bb7985e55dedaa5dd138c8c5ea8bd63af80db4b33af164446ce3e5b7e561ecb6",
"plugins/shared/attachments.ts": "e3e49eb56eb7dc28dc70db66dbc57062be502d42c1ed502b6eeae23eb6985bf9",
"plugins/shared/bookmark.ts": "d16b12b7aa9fd900271d6d8469c45d40e9295c8bd949adbcc7280f76e1d79dfc",
- "plugins/shared/components.ts": "eac3ccc60365ac7fd31031f487a40c40f729e7184bb693ff736e9ded9027759c",
- "plugins/shared/contracts.ts": "c94edfec7da14afd3368092363463864feabd96aa161b8945b972d6c3253dc50",
+ "plugins/shared/components.ts": "af68703685acbccf888458ac6502dc4f3fcfd455f5089148a1eb400c68b38c8c",
+ "plugins/shared/contracts.ts": "1f119177f2d8d5e7e2cb2cdb3012f484fd9e48c429cc01a9d64ad16430df1bc1",
"plugins/shared/conversation-search.ts": "5355d6002832ec057511eea9be24f5a910bf43971e10c15e336bc83bde1f03ec",
"plugins/shared/deployment-document.ts": "7e1af7e2b599dffc1eefa0cb19f31d75b2e1f38e20f62989628a631731d711ac",
"plugins/shared/deployment-import.ts": "6515214d9c8a8c27e2810932923e2b8368762fb7c06126ac1b1132996cd9f89b",
@@ -323,7 +324,7 @@
"plugins/shared/instance-settings.ts": "948e4f52e284d2c164afeb209cdadc148b66f3c51d69cfbb4f27de1614cb91f3",
"plugins/shared/locale-catalogs/appearance-editor.ts": "bdd35e85bb5a5d4d1c77e08253d5932c93832cefe31d1c6e7441ed53a284daa0",
"plugins/shared/locale-catalogs/attachments.ts": "0dfbad627b03dd608c1ac065a3f569d13cc88e60dd1ed08df3ba9085cbfe6b42",
- "plugins/shared/locale-catalogs/components.ts": "6d820077d7c778204ecde701ff8774764060a6991419a51a50e83bf571f98a50",
+ "plugins/shared/locale-catalogs/components.ts": "89e35ea9a08460b29ce3646219ace73f674284e98dab8d59e6346668ffee6677",
"plugins/shared/locale-catalogs/conversation-search.ts": "e6b94ba7ae4114fe4db988c90a8e6004bac5e453453d1c7ac0266bf3f76875f1",
"plugins/shared/locale-catalogs/deployment-document.ts": "5ea912a2571b6e88bc98fa639e6363807c3ceb75d27cb9a3ae4e62ecb2539bfb",
"plugins/shared/locale-catalogs/deployment-import.ts": "9e48863d8c90cbe194f8a30ca074ee93d544a2ceafbb70ea43f193ccca8e79f6",
diff --git a/products/maka/cli/src/code.rs b/products/maka/cli/src/code.rs
index f468589492..cc9a7cf402 100644
--- a/products/maka/cli/src/code.rs
+++ b/products/maka/cli/src/code.rs
@@ -171,6 +171,7 @@ pub(super) async fn run(args: Args) -> Result<(), maka_host_runtime::HostError>
invocation.clone(),
Fact::InvocationOpened {
configuration: Some(Box::new(InvocationConfiguration {
+ compaction_prompt: None,
workspace_origin: maka_agent_facts::execution::WorkspaceOrigin::Selected,
system_prompt: None,
editing_tools: None,
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product/chat.rs b/products/maka/cli/tests/integration/terminal/bundled_product/chat.rs
index e5ca11498d..bd05f859b7 100644
--- a/products/maka/cli/tests/integration/terminal/bundled_product/chat.rs
+++ b/products/maka/cli/tests/integration/terminal/bundled_product/chat.rs
@@ -27,6 +27,7 @@ use std::{
use uuid::Uuid;
mod code_mode;
+mod compaction;
mod computer;
mod goal;
mod graph;
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs b/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs
new file mode 100644
index 0000000000..4657c0419c
--- /dev/null
+++ b/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+
+const GLOBAL_PROMPT: &str = "Preserve fixture decisions.";
+const ONCE_PROMPT: &str = "For this compression only, preserve the Unicode decision: 中文.";
+
+fn context_foreground(output: &[u8]) -> Option<[u8; 3]> {
+ let text = String::from_utf8_lossy(output);
+ let before = &text[..text.rfind("Context ")?];
+ let rgb = &before[before.rfind("\x1b[38;2;")? + "\x1b[38;2;".len()..];
+ let mut parts = rgb.split(|c: char| !c.is_ascii_digit());
+ Some([
+ parts.next()?.parse().ok()?,
+ parts.next()?.parse().ok()?,
+ parts.next()?.parse().ok()?,
+ ])
+}
+
+#[test]
+#[ignore = "real bundled product compaction dialog, streamed summary and durable divider after restart"]
+fn default_product_compaction_edits_one_shot_prompt_and_keeps_durable_divider() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let base = format!("http://{}/v1", listener.local_addr().unwrap());
+ let (requests, received) = mpsc::channel();
+ let server = model_server(listener, requests, 2, 1);
+ let directory = tempfile::tempdir().unwrap();
+ let workspace = directory.path().join("workspace");
+ std::fs::create_dir(&workspace).unwrap();
+ let ui = directory.path().join("ui");
+ let host = ui.join("host");
+ let host_guard = HostRootGuard::new(&host);
+ let namespaces = RootNamespaces::for_current_account().unwrap();
+ drop(RootOwner::create(&ui, &namespaces).unwrap());
+ let runtime = tokio::runtime::Runtime::new().unwrap();
+ runtime.block_on(async {
+ seed_connection(&host, &namespaces, &base, json!({})).await;
+ let config = maka_config::ConfigurationStore::for_root(Arc::new(
+ RootOwner::open(&host, &namespaces).unwrap(),
+ ))
+ .await
+ .unwrap();
+ let revision = config.runtime_policy().await.unwrap().revision;
+ assert!(matches!(
+ config
+ .set_compaction_prompt(revision, Some(GLOBAL_PROMPT.into()))
+ .await
+ .unwrap(),
+ maka_agent_facts::configuration::policy::RuntimePolicyMutationResult::Committed { .. }
+ ));
+ config.shutdown().await.unwrap();
+ });
+ let mut tui = Pty::spawn(&[
+ "application",
+ "launch",
+ "--root",
+ ui.to_str().unwrap(),
+ "--workspace",
+ workspace.to_str().unwrap(),
+ "--trust-workspace",
+ "--locale",
+ "en",
+ ]);
+ tui.wait_until_with_timeout(|s| s.contains("Settings"), Duration::from_secs(60));
+ tui.send(b"\x0b");
+ tui.wait_for("Close commands");
+ tui.send(b"New conversation");
+ tui.wait_for("› New conversation");
+ tui.send(b"\r");
+ tui.wait_for("Message…");
+ tui.wait_for("fixture-model");
+ click(&mut tui, "Message…");
+ paste(
+ &mut tui,
+ "Remember the Unicode decision and keep deployment pending.",
+ );
+ tui.wait_for("Remember the Unicode decision and keep deployment pending.");
+ tui.send(b"\r");
+ let (main, mut socket) = next_request(&mut tui, &received);
+ delta(
+ &mut socket,
+ "Decision recorded: 中文. Deployment is still pending.",
+ );
+ complete(&mut socket);
+ tui.wait_for("Deployment is still pending.");
+ tui.wait_for("Workspace conversation");
+ click(&mut tui, "Message…");
+ tui.send(b"/compact");
+ tui.send(b"\r");
+ tui.wait_for("Compact context");
+ tui.wait_for(GLOBAL_PROMPT);
+ evidence(&tui, "compact-confirmation");
+ let idle_context_color = context_foreground(&tui.output).unwrap();
+ eprintln!("compact: native confirmation displays global prompt");
+ assert!(
+ received.try_recv().is_err(),
+ "opening confirmation must not call the model"
+ );
+ let prompt_row = tui
+ .screen
+ .snapshot()
+ .unwrap()
+ .screen
+ .lines()
+ .position(|line| line.contains(GLOBAL_PROMPT))
+ .unwrap();
+ click(&mut tui, GLOBAL_PROMPT);
+ // Native textareas paint their own caret. Clear the known short fixture
+ // prompt and wait for its content row to be completely blank before paste.
+ tui.read();
+ tui.send(b"\x1b[F");
+ tui.send(&[0x7f; 64]);
+ tui.wait_until(|screen| {
+ screen
+ .lines()
+ .nth(prompt_row)
+ .and_then(|line| line.split('│').nth(2))
+ .is_some_and(|content| content.trim().is_empty())
+ });
+ paste(&mut tui, ONCE_PROMPT);
+ tui.wait_for("For this compression only");
+ evidence(&tui, "compact-edited");
+ // The native dialog title also contains Compact; the button includes its
+ // neighboring Cancel control, so locate its row explicitly.
+ let screen = tui.screen.snapshot().unwrap().screen;
+ let (row, line) = screen
+ .lines()
+ .enumerate()
+ .find(|(_, line)| line.contains("Compact") && line.contains("Cancel"))
+ .unwrap();
+ let column = line[..line.find("Compact").unwrap()].width() + 2;
+ tui.send(
+ format!(
+ "\x1b[<0;{};{}M\x1b[<0;{};{}m",
+ column,
+ row + 1,
+ column,
+ row + 1
+ )
+ .as_bytes(),
+ );
+ let (summary, mut socket) = next_request(&mut tui, &received);
+ assert_eq!(
+ summary["messages"].as_array().unwrap().last().unwrap()["content"],
+ ONCE_PROMPT
+ );
+ assert!(!summary["messages"].to_string().contains(GLOBAL_PROMPT));
+ assert!(
+ summary["messages"]
+ .to_string()
+ .contains("Deployment is still pending")
+ );
+ assert_eq!(
+ summary["tools"], main["tools"],
+ "summary retains the captured Main tool surface"
+ );
+ // Hold the real HTTP summary stream open while inspecting the native footer.
+ tui.wait_until(|s| !s.contains("Compact context") && s.contains("Context "));
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while context_foreground(&tui.output) == Some(idle_context_color) {
+ tui.read();
+ assert!(
+ Instant::now() < deadline,
+ "Context foreground did not change while the summary stream was open"
+ );
+ }
+ assert!(context_foreground(&tui.output).is_some());
+ evidence(&tui, "compact-running");
+ eprintln!("compact: exact one-shot instruction and active footer tint verified");
+ assert!(
+ !tui.screen
+ .snapshot()
+ .unwrap()
+ .screen
+ .contains("Context compressed (")
+ );
+ delta(
+ &mut socket,
+ "## Current task\nDeployment is pending.\n## Decisions\nPreserve 中文.\n## Next steps\nFinish deployment.",
+ );
+ complete(&mut socket);
+ tui.wait_for("Context compressed (");
+ tui.wait_until(|s| {
+ s.lines()
+ .any(|line| line.contains("Context compressed (") && line.contains("s)"))
+ });
+ evidence(&tui, "compact-completed");
+ eprintln!("compact: successful durable divider displayed");
+ tui.send(b"\x11");
+ tui.finish();
+ host_guard.stop();
+ server.join().unwrap();
+
+ let mut restored = Pty::spawn(&["application", "launch", "--root", ui.to_str().unwrap()]);
+ restored.wait_until_with_timeout(
+ |s| s.contains("Workspace conversation"),
+ Duration::from_secs(60),
+ );
+ restored.wait_for("Context compressed (");
+ evidence(&restored, "compact-restarted");
+ eprintln!("compact: divider retained after Host and UI restart");
+ restored.send(b"\x11");
+ restored.finish();
+ host_guard.stop();
+ runtime.block_on(async {
+ let config = maka_config::ConfigurationStore::for_root(Arc::new(
+ RootOwner::open(&host, &namespaces).unwrap(),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(
+ config
+ .runtime_policy()
+ .await
+ .unwrap()
+ .policy
+ .compaction_prompt
+ .as_deref(),
+ Some(GLOBAL_PROMPT),
+ "the dialog override must not modify global preferences"
+ );
+ config.shutdown().await.unwrap();
+ });
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org