maka-agent 0.2.0-dev.14.20260902 → 0.2.0-dev.16.20260903

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -20,9 +20,11 @@ import { rawFinishReasonString } from './model-protocol.js';
20
20
  import { buildRuntimeEventModelReplayPlan } from './model-history.js';
21
21
  import { findCheckpointSummaryDefect, SUMMARY_FORMAT_TEMPLATE, } from './history-compact-summary-validation.js';
22
22
  import { effectiveReplayToolResultOutput } from './durable-tool-result-projection.js';
23
+ import { DEFAULT_HISTORY_COMPACT_MAX_OUTPUT_TOKENS, } from './ai-sdk-compaction-contract.js';
23
24
  import { HistoryCompactSummarizerError, isMalformedHistoryCompactSummaryReason, } from './history-compact-error.js';
24
25
  import { isTextHistoryCompactCheckpoint } from './history-compact-checkpoint.js';
25
- import { fitHistoryCompactMessages } from './history-compact-input-fit.js';
26
+ import { normalizeAiSdkUsage } from './model-adapter.js';
27
+ import { classifyError } from './provider-error-classification.js';
26
28
  import { withProviderGenerateTracking } from './provider-request-telemetry.js';
27
29
  export { HistoryCompactSummarizerError } from './history-compact-error.js';
28
30
  // Conversation-summarization prompt (sectioned, modelled on pi/opencode):
@@ -42,6 +44,14 @@ const SUMMARIZATION_SYSTEM_PROMPT = [
42
44
  '',
43
45
  'Keep each section concise. Preserve exact file paths, function names, commands, and error messages.',
44
46
  ].join('\n');
47
+ const SUMMARY_REQUEST_INSTRUCTION = 'Now write the structured summary of the conversation above. Output only the summary.';
48
+ function shortenSummarizationSystemPrompt() {
49
+ return [
50
+ SUMMARIZATION_SYSTEM_PROMPT,
51
+ '',
52
+ 'Your 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.',
53
+ ].join('\n');
54
+ }
45
55
  function repairSummarizationSystemPrompt(reason) {
46
56
  return [
47
57
  SUMMARIZATION_SYSTEM_PROMPT,
@@ -75,11 +85,20 @@ export function buildLlmHistorySummarizer(options) {
75
85
  ],
76
86
  });
77
87
  }
78
- const initialMessages = fitHistoryCompactMessages(projectedMessages, {
79
- maxInputEstimatedTokens: input.inputBudget?.maxEstimatedTokens,
80
- charsPerToken: input.inputBudget?.charsPerToken,
81
- fixedInputChars: SUMMARIZATION_SYSTEM_PROMPT.length,
88
+ // The folded span usually ends on an assistant message. A chat-template
89
+ // model handed a conversation that already ends with its own turn emits
90
+ // an end-of-sequence token and nothing else (Ollama qwen2.5: finish
91
+ // `stop`, one output token, empty text), so the request must end with
92
+ // an instruction the model can answer. Hosted providers do not need the
93
+ // nudge and are not disturbed by it (#4559).
94
+ projectedMessages.push({
95
+ role: 'user',
96
+ content: [{ type: 'text', text: SUMMARY_REQUEST_INSTRUCTION }],
82
97
  });
98
+ // Nothing is trimmed on a local estimate: whether this input fits the
99
+ // summarizer's window is its provider's answer (`input_too_large`, which
100
+ // the planner retreats on), and the output is capped outright (#4559).
101
+ const maxOutputTokens = input.maxOutputTokens ?? DEFAULT_HISTORY_COMPACT_MAX_OUTPUT_TOKENS;
83
102
  // Handed over whole by the backend, which owns every input a tracker
84
103
  // needs — including the run, which no summarizer wiring can know (#1679).
85
104
  const providerRequestTracker = input.providerRequestTracker;
@@ -94,29 +113,44 @@ export function buildLlmHistorySummarizer(options) {
94
113
  ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),
95
114
  })
96
115
  : options.resolveModel();
97
- const generateSummary = async (step, instructions, messages) => {
116
+ let step = 0;
117
+ const generateSummary = async (instructions, messages) => {
98
118
  providerRequestTracker?.setStep(step);
119
+ step += 1;
99
120
  const result = await generateText({
100
121
  model,
101
122
  instructions,
102
123
  messages,
124
+ maxOutputTokens,
103
125
  ...(options.providerOptions !== undefined
104
126
  ? { providerOptions: options.providerOptions }
105
127
  : {}),
106
128
  ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),
107
129
  });
108
- if (rawFinishReasonString(result.finishReason) === 'length') {
109
- throw new HistoryCompactSummarizerError('output_length');
110
- }
111
- const defect = findCheckpointSummaryDefect(result.text, {
112
- coveredRuntimeEvents: input.source.foldedRuntimeEvents,
113
- ...(input.inputBudget?.charsPerToken !== undefined
114
- ? { charsPerToken: input.inputBudget.charsPerToken }
115
- : {}),
116
- });
117
- return { text: result.text, defect };
130
+ const usage = normalizeAiSdkUsage(result.usage);
131
+ const truncated = rawFinishReasonString(result.finishReason) === 'length';
132
+ // The size floor compares the summary with what it replaces. On a
133
+ // roll-forward the request carries the previous summary plus the new
134
+ // increment, so its input tokens are not the covered span and the
135
+ // floor would judge the wrong number; it applies to the initial fold
136
+ // only (#4559).
137
+ const spanUsage = previousCheckpoint === undefined && usage !== undefined && usage.inputTokens > 0
138
+ ? { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens }
139
+ : undefined;
140
+ const defect = truncated
141
+ ? undefined
142
+ : findCheckpointSummaryDefect(result.text, spanUsage ? { summarizerUsage: spanUsage } : undefined);
143
+ return { text: result.text, defect, truncated };
118
144
  };
119
- const initial = await generateSummary(0, SUMMARIZATION_SYSTEM_PROMPT, initialMessages);
145
+ let initial = await generateSummary(SUMMARIZATION_SYSTEM_PROMPT, projectedMessages);
146
+ if (initial.truncated) {
147
+ // The provider cut the summary at the output cap. One shorter attempt;
148
+ // a second cut is the provider saying this span will not summarize
149
+ // inside the cap, and the fold fails open.
150
+ initial = await generateSummary(shortenSummarizationSystemPrompt(), projectedMessages);
151
+ if (initial.truncated)
152
+ throw new HistoryCompactSummarizerError('output_length');
153
+ }
120
154
  if (!initial.defect)
121
155
  return initial.text;
122
156
  if (!isMalformedHistoryCompactSummaryReason(initial.defect)) {
@@ -126,18 +160,22 @@ export function buildLlmHistorySummarizer(options) {
126
160
  // be bounded: one stricter attempt, then the caller's failure circuit
127
161
  // records the stable defect for this compaction input.
128
162
  const repairInstructions = repairSummarizationSystemPrompt(initial.defect);
129
- const repairMessages = fitHistoryCompactMessages(projectedMessages, {
130
- maxInputEstimatedTokens: input.inputBudget?.maxEstimatedTokens,
131
- charsPerToken: input.inputBudget?.charsPerToken,
132
- fixedInputChars: repairInstructions.length,
133
- });
134
163
  let repaired;
135
164
  try {
136
- repaired = await generateSummary(1, repairInstructions, repairMessages);
165
+ repaired = await generateSummary(repairInstructions, projectedMessages);
166
+ if (repaired.truncated)
167
+ throw new HistoryCompactSummarizerError('output_length');
137
168
  }
138
169
  catch (error) {
139
170
  if (isAbortError(error))
140
171
  throw error;
172
+ // The repair prompt is longer than the first one. If that is what pushed
173
+ // the fold past the summarizer provider's window, the rejection is the
174
+ // planner's retreat signal, not a repair failure to file under the
175
+ // initial defect (#4559).
176
+ if (classifyError(error) === 'ContextLength') {
177
+ throw new HistoryCompactSummarizerError('input_too_large', { cause: error });
178
+ }
141
179
  throw new HistoryCompactSummarizerError(initial.defect, {
142
180
  cause: error instanceof HistoryCompactSummarizerError
143
181
  ? error
@@ -161,6 +199,12 @@ export function buildLlmHistorySummarizer(options) {
161
199
  throw error;
162
200
  if (error instanceof HistoryCompactSummarizerError)
163
201
  throw error;
202
+ // The summarizer's provider is the one judge of whether this fold fits
203
+ // its own window: a context-length rejection is the signal the planner
204
+ // retreats on, so it must keep its name here (#4559).
205
+ if (classifyError(error) === 'ContextLength') {
206
+ throw new HistoryCompactSummarizerError('input_too_large', { cause: error });
207
+ }
164
208
  throw new HistoryCompactSummarizerError('provider_error', { cause: error });
165
209
  }
166
210
  };
@@ -16,8 +16,6 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { estimateTokens } from './context-budget-helpers.js';
20
- import { estimateRuntimeEventsTokens } from './model-history.js';
21
19
  // The single authority on what a history-compact checkpoint summary must look
22
20
  // like (#3029). The summarization prompt is built from the same constants and
23
21
  // the load side can consume the same predicate, so the mandated format and
@@ -64,12 +62,13 @@ export const REQUIRED_SUMMARY_SECTIONS = [
64
62
  // parroting the format back cannot pass as a checkpoint.
65
63
  const TEMPLATE_PLACEHOLDER_LINES = new Set(SUMMARY_FORMAT_TEMPLATE.map((line) => line.trim()).filter((line) => line.length > 0));
66
64
  // Floors for the incident's shape: folding a large span into a paragraph
67
- // cannot be a faithful checkpoint. Folds above ~10k estimated tokens require
68
- // at least ~200 estimated tokens of summary, both measured at the session's
69
- // chars-per-token estimate so CJK-heavy sessions are floored consistently.
70
- const LARGE_FOLD_ESTIMATED_TOKENS = 10_000;
65
+ // cannot be a faithful checkpoint. Folds whose summarizer request the provider
66
+ // counted above ~10k input tokens require at least ~200 output tokens of
67
+ // summary. Both sides are the summarizer call's REAL usage, so the floor holds
68
+ // in the provider's own tokenizer and needs no chars-per-token guess (#4559);
69
+ // a producer that reports no usage is not floored.
70
+ const LARGE_FOLD_INPUT_TOKENS = 10_000;
71
71
  const LARGE_FOLD_SUMMARY_TOKENS_FLOOR = 200;
72
- const DEFAULT_CHARS_PER_TOKEN = 4;
73
72
  // Best-effort signals that a provider stopped mid-thought. Fence state is
74
73
  // derived by the structural scanner below, so write admission and legacy-load
75
74
  // quarantine cannot disagree about Markdown fence semantics. A trailing
@@ -93,17 +92,11 @@ export function findCheckpointSummaryDefect(summary, foldContext) {
93
92
  const truncationDefect = findTruncationDefect(trimmed, scan);
94
93
  if (truncationDefect !== undefined)
95
94
  return truncationDefect;
96
- if (foldContext !== undefined) {
97
- // Clamped so a zero/negative estimate cannot zero out the floor.
98
- const charsPerToken = Math.max(1, foldContext.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN);
99
- // Both sides use the shared ceil-based estimator so the floor cannot
100
- // disagree with the repository's estimated-token semantics at the
101
- // boundary.
102
- if (estimateTokens(trimmed.length, charsPerToken) < LARGE_FOLD_SUMMARY_TOKENS_FLOOR &&
103
- estimateRuntimeEventsTokens(foldContext.coveredRuntimeEvents, charsPerToken) >
104
- LARGE_FOLD_ESTIMATED_TOKENS) {
105
- return 'malformed_summary_too_small_for_fold';
106
- }
95
+ const usage = foldContext?.summarizerUsage;
96
+ if (usage !== undefined &&
97
+ usage.outputTokens < LARGE_FOLD_SUMMARY_TOKENS_FLOOR &&
98
+ usage.inputTokens > LARGE_FOLD_INPUT_TOKENS) {
99
+ return 'malformed_summary_too_small_for_fold';
107
100
  }
108
101
  return undefined;
109
102
  }
@@ -16,31 +16,11 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { finitePositive } from './context-budget-helpers.js';
20
19
  import { estimateRuntimeEventChars, estimateRuntimeEventsTokens } from './model-history.js';
21
20
  import { compactionDecisionDiagnosticPatch } from './compaction-boundary.js';
22
21
  import { HistoryCompactSummarizerError, } from './history-compact-error.js';
23
22
  import { findCheckpointSummaryDefect } from './history-compact-summary-validation.js';
24
- import { buildHistoryCompactCheckpoint, historyCompactCheckpointToRuntimeEvent, matchHistoryCompactCheckpointPrefix, midTurnHeadAnchorEvent, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
25
- /**
26
- * Estimate the token size of the next provider request: the last request's real
27
- * usage plus a signed char/4 payload delta for content the provider has not yet
28
- * counted (or no longer carries). Without a usable usage sample the caller
29
- * passes the whole payload as the delta against a zero baseline, so this stays
30
- * one formula. This mirrors how surveyed peers avoid pure character guessing.
31
- */
32
- export function estimateNextRequestTokens(input) {
33
- const charsPerToken = Math.max(1, input.charsPerToken ?? 4);
34
- const prior = input.priorUsageTokens !== undefined && Number.isFinite(input.priorUsageTokens)
35
- ? Math.max(0, Math.floor(input.priorUsageTokens))
36
- : 0;
37
- return Math.max(0, prior + estimateSignedChars(input.appendedChars, charsPerToken));
38
- }
39
- /** Proactive threshold: the next request would cross `contextWindow - reserve`. */
40
- export function exceedsHighWater(estimatedTokens, contextWindow, reserveTokens) {
41
- const highWater = Math.max(1, contextWindow - Math.max(0, reserveTokens));
42
- return estimatedTokens > highWater;
43
- }
23
+ import { buildHistoryCompactCheckpoint, historyCompactCheckpointToRuntimeEvent, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
44
24
  /**
45
25
  * Select the largest contiguous covered prefix that is safe to fold:
46
26
  *
@@ -113,13 +93,6 @@ function straddlesToolPair(spans, cut) {
113
93
  }
114
94
  return false;
115
95
  }
116
- function estimateSignedChars(chars, charsPerToken) {
117
- const value = Math.trunc(chars ?? 0);
118
- if (!Number.isFinite(value) || value === 0)
119
- return 0;
120
- const magnitude = Math.ceil(Math.abs(value) / charsPerToken);
121
- return value > 0 ? magnitude : -magnitude;
122
- }
123
96
  /**
124
97
  * Execute a triggered compaction command by deterministically folding the
125
98
  * largest safe prefix. Trigger policy is owned by callers; once this function
@@ -127,6 +100,41 @@ function estimateSignedChars(chars, charsPerToken) {
127
100
  * when it cannot fold a safe completed prefix it FAILS OPEN (keep the raw
128
101
  * projection + diagnostic) and the request goes out unchanged.
129
102
  */
103
+ /**
104
+ * How many ordered events the last request THIS ROUTE had accepted covered.
105
+ *
106
+ * A span is only proven for the model and connection that accepted it: a token
107
+ * count is a number in one tokenizer, and a session's history can span runs on
108
+ * several routes. So the newest reply produced on the summarizer's own route
109
+ * ends the span, found through the run headers rather than by role alone —
110
+ * everything before its first event was in a request that route accepted.
111
+ * A ledger with no reply from this route has nothing proven, and the caller
112
+ * must not invent a boundary.
113
+ */
114
+ function acceptedInputBoundary(events, runHeaders, route) {
115
+ if (!route)
116
+ return undefined;
117
+ const onRoute = (event) => {
118
+ if (event?.role !== 'model')
119
+ return false;
120
+ const header = runHeaders.find((candidate) => candidate.runId === event.runId);
121
+ if (!header || header.modelId !== route.modelId)
122
+ return false;
123
+ return header.llmConnectionId === route.connectionId;
124
+ };
125
+ let index = -1;
126
+ for (let cursor = events.length - 1; cursor >= 0; cursor -= 1) {
127
+ if (onRoute(events[cursor])) {
128
+ index = cursor;
129
+ break;
130
+ }
131
+ }
132
+ if (index < 0)
133
+ return undefined;
134
+ while (index > 0 && onRoute(events[index - 1]))
135
+ index -= 1;
136
+ return index;
137
+ }
130
138
  export async function planHistoryCompaction(input) {
131
139
  const phase = input.phase ?? 'mid_turn';
132
140
  const charsPerToken = Math.max(1, input.charsPerToken ?? 4);
@@ -184,7 +192,25 @@ export async function planHistoryCompaction(input) {
184
192
  catch (error) {
185
193
  if (error instanceof HistoryCompactSummarizerError) {
186
194
  if (error.reason === 'input_too_large') {
187
- maxCoveredCount = boundary.coveredCount - 1;
195
+ // The summarizer's provider said this span does not fit its own
196
+ // window; that is the only fit signal the fold listens to. Retreat to
197
+ // the span the last accepted request's input covered: that span was
198
+ // accepted by this model on this connection, so it is provably within
199
+ // capacity, where halving the range is a guess that can overshoot
200
+ // (throwing away verbatim history for nothing) or undershoot (paying
201
+ // another round trip). Only one retreat is available, because there
202
+ // is only one proven boundary; a rejection of that span too is the
203
+ // provider saying this fold cannot be made, and the fold fails open
204
+ // (#4559).
205
+ const proven = acceptedInputBoundary(input.orderedEvents, input.runHeaders ?? [], input.acceptedRoute);
206
+ if (proven === undefined || proven >= boundary.coveredCount) {
207
+ return {
208
+ decision: 'fail_open',
209
+ reason: 'summarizer_failed',
210
+ diagnosticReason: error.reason,
211
+ };
212
+ }
213
+ maxCoveredCount = proven;
188
214
  continue;
189
215
  }
190
216
  return {
@@ -203,10 +229,8 @@ export async function planHistoryCompaction(input) {
203
229
  // history. The default summarizer already threw with the same reasons; any
204
230
  // other producer is validated here.
205
231
  if (typeof compacted === 'string') {
206
- const defect = findCheckpointSummaryDefect(compacted, {
207
- coveredRuntimeEvents,
208
- charsPerToken,
209
- });
232
+ // An external producer reports no usage; only the structural checks apply.
233
+ const defect = findCheckpointSummaryDefect(compacted);
210
234
  if (defect) {
211
235
  return { decision: 'fail_open', reason: 'summarizer_failed', diagnosticReason: defect };
212
236
  }
@@ -244,27 +268,8 @@ export async function planHistoryCompaction(input) {
244
268
  }
245
269
  return { decision: 'fail_open', reason: 'no_safe_completed_span' };
246
270
  }
247
- /** The single current-policy gate for every checkpoint entering model replay. */
248
- export function evaluateHistoryCompactCheckpointReplay(checkpoint, replayTail, charsPerToken, maxHistoryEstimatedTokens = undefined, options = {}) {
249
- const charsPerTokenResolved = options.charsPerToken ?? charsPerToken ?? 4;
250
- const checkpointTokens = checkpoint.version === 3
251
- ? checkpoint.estimatedTokens
252
- : estimateRuntimeEventsTokens([historyCompactCheckpointToRuntimeEvent(checkpoint)], charsPerTokenResolved);
253
- const replayTokens = checkpointTokens + estimateRuntimeEventsTokens(replayTail, charsPerTokenResolved);
254
- const maxHistoryTokens = finitePositive(options.maxHistoryEstimatedTokens ?? maxHistoryEstimatedTokens);
255
- if (maxHistoryTokens !== undefined && replayTokens > maxHistoryTokens) {
256
- return { fits: false, checkpointTokens, replayTokens, reason: 'prefix_over_budget' };
257
- }
258
- if (options.sourceReplayEvents) {
259
- const sourceReplayTokens = estimateRuntimeEventsTokens(options.sourceReplayEvents, charsPerTokenResolved);
260
- if (replayTokens >= sourceReplayTokens) {
261
- return { fits: false, checkpointTokens, replayTokens, reason: 'replacement_not_smaller' };
262
- }
263
- }
264
- return { fits: true, checkpointTokens, replayTokens };
265
- }
266
271
  /** Replay the latest durable checkpoint when it exactly covers the ledger prefix. */
267
- export function applyRuntimeEventHistoryCompact(events, policy, charsPerToken = 4, maxHistoryEstimatedTokens, options = {}) {
272
+ export function applyRuntimeEventHistoryCompact(events, policy, charsPerToken = 4) {
268
273
  const checkpoint = policy?.enabled === true ? policy.checkpoint : undefined;
269
274
  if (!checkpoint)
270
275
  return { events: [...events], diagnosticPatch: {} };
@@ -282,25 +287,13 @@ export function applyRuntimeEventHistoryCompact(events, policy, charsPerToken =
282
287
  }),
283
288
  };
284
289
  }
285
- const headAnchor = checkpoint.phase === 'mid_turn'
286
- ? midTurnHeadAnchorEvent(checkpoint, match.coveredRuntimeEvents)
287
- : undefined;
288
- const replayTail = headAnchor
289
- ? [headAnchor, ...match.successorRuntimeEvents]
290
- : [...match.successorRuntimeEvents];
291
- const fit = evaluateHistoryCompactCheckpointReplay(checkpoint, replayTail, charsPerToken, maxHistoryEstimatedTokens, { ...options, sourceReplayEvents: options.sourceReplayEvents ?? compactableEvents });
292
- if (!fit.fits) {
293
- return {
294
- events: [...events],
295
- diagnosticPatch: compactionDecisionDiagnosticPatch({
296
- stage: 'priorReplay',
297
- sourceKind: 'runtimeEvents',
298
- decision: 'failedOpen',
299
- boundaryKind: 'historyCompact',
300
- failOpenReason: fit.reason,
301
- }),
302
- };
303
- }
290
+ // A matching checkpoint always replays as `[block, tail]`: the fold chose
291
+ // the boundary structurally, and whether the result fits is the provider's
292
+ // answer, not a local estimate's (#4559). The token figures below are
293
+ // diagnostics only.
294
+ const checkpointTokens = checkpoint.version === 3
295
+ ? checkpoint.estimatedTokens
296
+ : estimateRuntimeEventsTokens([historyCompactCheckpointToRuntimeEvent(checkpoint)], charsPerToken);
304
297
  return {
305
298
  events: projectHistoryCompactCheckpointReplay(checkpoint, match.coveredRuntimeEvents, match.successorRuntimeEvents),
306
299
  checkpoint,
@@ -317,7 +310,7 @@ export function applyRuntimeEventHistoryCompact(events, policy, charsPerToken =
317
310
  bodySha256: [checkpoint.coverage.sourceDigest],
318
311
  },
319
312
  estimatedTokensBefore: estimateRuntimeEventsTokens(match.coveredRuntimeEvents, charsPerToken),
320
- estimatedTokensAfter: fit.checkpointTokens,
313
+ estimatedTokensAfter: checkpointTokens,
321
314
  }),
322
315
  };
323
316
  }
@@ -55,6 +55,16 @@ export class RuntimeInteractionFailStopError extends Error {
55
55
  this.authorityFailure = authorityFailure;
56
56
  }
57
57
  }
58
+ export function isHostedInteractionRequestEvent(event) {
59
+ return (event.type === 'user_question_request' ||
60
+ event.type === 'form_request' ||
61
+ event.type === 'sandbox_boundary_request');
62
+ }
63
+ export function isHostedInteractionSettlementAckEvent(event) {
64
+ return (event.type === 'user_question_answer_ack' ||
65
+ event.type === 'form_answer_ack' ||
66
+ event.type === 'sandbox_boundary_decision_ack');
67
+ }
58
68
  /** Exact-Run bridge between RuntimeKernel and backend Interaction producers. */
59
69
  export class RuntimeInteractionRunBinding {
60
70
  owner;
@@ -127,6 +137,38 @@ export class RuntimeInteractionRunBinding {
127
137
  throw new RuntimeInteractionInvariantError(`Question ${tracked.requestId} completed admission after Interaction publication sealed`);
128
138
  }
129
139
  }
140
+ async admitFormRequest(input) {
141
+ const tracked = this.trackForm(input.request, input.settlement);
142
+ try {
143
+ await this.owner.acceptFormRequest({
144
+ request: input.request,
145
+ continuation: tracked.continuation,
146
+ });
147
+ }
148
+ catch (error) {
149
+ tracked.completePublicationBarrier();
150
+ if (!tracked.settlementStarted)
151
+ this.continuations.delete(tracked.requestId);
152
+ throw error;
153
+ }
154
+ if (tracked.settlementStarted) {
155
+ try {
156
+ await tracked.settlementPromise;
157
+ throw new RuntimeInteractionInvariantError(`Form ${tracked.requestId} settled during pending-only admission`);
158
+ }
159
+ finally {
160
+ tracked.completePublicationBarrier();
161
+ }
162
+ }
163
+ tracked.admissionState = 'pending';
164
+ if (this.publicationsSealed) {
165
+ tracked.completePublicationBarrier();
166
+ throw new RuntimeInteractionInvariantError(`Form ${tracked.requestId} completed admission after Interaction publication sealed`);
167
+ }
168
+ }
169
+ withdrawFormRequest(requestId) {
170
+ return this.owner.withdrawFormRequest(requestId);
171
+ }
130
172
  async admitSandboxBoundaryRequest(input) {
131
173
  const tracked = this.trackSandboxBoundary(input.request, input.settlement);
132
174
  try {
@@ -274,6 +316,31 @@ export class RuntimeInteractionRunBinding {
274
316
  this.continuations.set(request.requestId, tracked);
275
317
  return tracked;
276
318
  }
319
+ trackForm(request, local) {
320
+ this.assertNewContinuation(request);
321
+ let tracked;
322
+ const publication = createInteractionPublicationBarrier();
323
+ const continuation = Object.freeze({
324
+ requestId: request.requestId,
325
+ turnId: this.turnId,
326
+ runId: this.runId,
327
+ waitForPublication: () => publication.publicationBarrier,
328
+ applyAnswer: (answer) => this.settleTracked(tracked, () => local.applyAnswer(answer), { kind: 'form_answer', answer }, 'form answer'),
329
+ applyClosure: (reason) => this.settleTracked(tracked, () => local.applyClosure(reason), { kind: 'closure', reason }, 'form closure'),
330
+ });
331
+ tracked = {
332
+ requestId: request.requestId,
333
+ request,
334
+ continuation,
335
+ ...publication,
336
+ admissionState: undefined,
337
+ published: false,
338
+ settlementStarted: false,
339
+ settled: false,
340
+ };
341
+ this.continuations.set(request.requestId, tracked);
342
+ return tracked;
343
+ }
277
344
  trackSandboxBoundary(request, local) {
278
345
  this.assertNewContinuation(request);
279
346
  let tracked;
@@ -345,6 +412,8 @@ function settlementMatchesAck(tracked, event) {
345
412
  return false;
346
413
  if (event.type === 'user_question_answer_ack')
347
414
  return outcome.kind === 'question_answer';
415
+ if (event.type === 'form_answer_ack')
416
+ return outcome.kind === 'form_answer';
348
417
  if (outcome.kind !== 'sandbox_boundary_decision')
349
418
  return false;
350
419
  const { request, boundary } = outcome.settlement;
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { jsonSchema } from 'ai';
21
+ import { truncateUtf16Safe } from '@maka/core/text-sanitize';
21
22
  const MAX_PROVIDER_TOOL_NAME = 64;
22
23
  const HASH_CHARS = 10;
23
24
  const MAX_NATIVE_IMAGE_BASE64_CHARS = 20_000_000;
@@ -70,6 +71,11 @@ export function buildMcpTools(provider, options = {}) {
70
71
  ...(executionContext.emitProgress
71
72
  ? { emitProgress: executionContext.emitProgress }
72
73
  : {}),
74
+ ...(executionContext.requestUserForm
75
+ ? {
76
+ requestInteraction: (form, interactionOptions) => executionContext.requestUserForm(form, interactionOptions),
77
+ }
78
+ : {}),
73
79
  }),
74
80
  cancel: () => prepared.cancel(),
75
81
  };
@@ -99,6 +105,11 @@ export function buildMcpTools(provider, options = {}) {
99
105
  cwd: context.cwd,
100
106
  },
101
107
  ...(context.emitProgress ? { emitProgress: context.emitProgress } : {}),
108
+ ...(context.requestUserForm
109
+ ? {
110
+ requestInteraction: (form, interactionOptions) => context.requestUserForm(form, interactionOptions),
111
+ }
112
+ : {}),
102
113
  });
103
114
  },
104
115
  toModelOutput: ({ output }) => mcpResultToModelOutput(output),
@@ -210,9 +221,10 @@ function summarizeNonVisualBlock(block) {
210
221
  function clipModelText(value, limit) {
211
222
  if (value.length <= limit)
212
223
  return value;
224
+ // The marker is all-BMP, so slicing it can't split a pair.
213
225
  if (limit <= TRUNCATION_MARKER.length)
214
226
  return TRUNCATION_MARKER.slice(0, limit);
215
- return `${value.slice(0, limit - TRUNCATION_MARKER.length)}${TRUNCATION_MARKER}`;
227
+ return `${truncateUtf16Safe(value, limit - TRUNCATION_MARKER.length)}${TRUNCATION_MARKER}`;
216
228
  }
217
229
  function safeJsonStringify(value) {
218
230
  try {
@@ -954,17 +954,6 @@ function preparedMemoryRangeFits(prepared, trigger) {
954
954
  return ((prepared.coverage.evidence.length === 0 && trigger !== 'remember') ||
955
955
  memoryRequestFits(prepared.snapshot, prepared.firstPrompt, 'proposal'));
956
956
  }
957
- function memoryRangeEventWeight({ event }) {
958
- if (!event.partial &&
959
- event.content?.kind === 'text' &&
960
- ((event.role === 'user' && event.author === 'user') ||
961
- (event.role === 'model' && event.author === 'agent'))) {
962
- // Text appears once in the interpretation messages and, for user text, once
963
- // more in the bounded evidence index when it cannot be referenced by position.
964
- return Math.max(1, event.content.text.length * (event.role === 'user' ? 2 : 1));
965
- }
966
- return 1;
967
- }
968
957
  function memoryRequestFits(snapshot, prompt, stage) {
969
958
  const contextWindow = snapshot.sourceContextWindowTokens;
970
959
  if (contextWindow === undefined)
@@ -1026,6 +1015,17 @@ function safeJsonLength(value) {
1026
1015
  return Number.MAX_SAFE_INTEGER;
1027
1016
  }
1028
1017
  }
1018
+ function memoryRangeEventWeight({ event }) {
1019
+ if (!event.partial &&
1020
+ event.content?.kind === 'text' &&
1021
+ ((event.role === 'user' && event.author === 'user') ||
1022
+ (event.role === 'model' && event.author === 'agent'))) {
1023
+ // Text appears once in the interpretation messages and, for user text, once
1024
+ // more in the bounded evidence index when it cannot be referenced by position.
1025
+ return Math.max(1, event.content.text.length * (event.role === 'user' ? 2 : 1));
1026
+ }
1027
+ return 1;
1028
+ }
1029
1029
  function memoryEvidenceContainsSensitiveText(evidence) {
1030
1030
  return evidence.some(({ events }) => events.some(({ content }) => content?.kind === 'text' && redactSecrets(content.text) !== content.text));
1031
1031
  }
@@ -79,6 +79,7 @@ export class ModelAdapter {
79
79
  throw new Error(`No API key stored for connection "${this.input.connection.slug}"`);
80
80
  }
81
81
  return this.input.modelFactory({
82
+ sessionId: this.input.sessionId,
82
83
  connection: this.input.connection,
83
84
  apiKey: this.input.apiKey,
84
85
  modelId: this.input.modelId,
@@ -634,19 +635,36 @@ function translateChunk(chunk, openAiChatReasoningTransportState, runtime, runti
634
635
  },
635
636
  ];
636
637
  }
637
- case 'text-start':
638
- return [{ kind: 'text-start' }];
638
+ case 'text-start': {
639
+ const providerOptions = chunk.providerMetadata && typeof chunk.providerMetadata === 'object'
640
+ ? chunk.providerMetadata
641
+ : undefined;
642
+ const providerItemBoundary = runtime !== undefined &&
643
+ hasOpenAiResponsesAdapter(runtime) &&
644
+ providerOptions !== undefined;
645
+ return [
646
+ {
647
+ kind: 'text-start',
648
+ ...(providerItemBoundary ? { providerItemBoundary: true } : {}),
649
+ },
650
+ ];
651
+ }
639
652
  case 'text-delta': {
640
653
  const text = chunk.text ?? chunk.textDelta ?? chunk.delta ?? '';
641
654
  return text ? [{ kind: 'text', text }] : [];
642
655
  }
643
656
  case 'text-end': {
644
- if (!chunk.providerMetadata || typeof chunk.providerMetadata !== 'object')
645
- return [];
657
+ const providerOptions = chunk.providerMetadata && typeof chunk.providerMetadata === 'object'
658
+ ? chunk.providerMetadata
659
+ : undefined;
660
+ const providerItemBoundary = runtime !== undefined &&
661
+ hasOpenAiResponsesAdapter(runtime) &&
662
+ providerOptions !== undefined;
646
663
  return [
647
664
  {
648
- kind: 'text-metadata',
649
- providerOptions: chunk.providerMetadata,
665
+ kind: 'text-end',
666
+ ...(providerOptions !== undefined ? { providerOptions } : {}),
667
+ ...(providerItemBoundary ? { providerItemBoundary: true } : {}),
650
668
  },
651
669
  ];
652
670
  }