@peer-agent/runtime-core 0.1.0-rc.5 → 0.1.0-rc.50

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.
@@ -0,0 +1,297 @@
1
+ /**
2
+ * Shared Goal / Plan tool contracts (platform-neutral).
3
+ *
4
+ * Single source of truth for what the model sees about the goal toolchain: the
5
+ * tool description (prompt) and the JSON input schema. Desktop and TUI both
6
+ * project from here, so the model-visible contract cannot drift per surface.
7
+ *
8
+ * Deliberately NOT owned here (stays in each surface's Manifest):
9
+ * - permissionPolicy / runtime adapter / availableInModes (platform policy)
10
+ * - execution logic and goal-plan-store wiring
11
+ *
12
+ * Note: `local-tool-contracts.ts` owns toolName + capabilityId only; input
13
+ * schemas stay with their capability module. This file is the goal capability's
14
+ * schema module.
15
+ */
16
+ export const GOAL_CREATE_PLAN_PROMPT = [
17
+ 'Create a persistent, trackable goal/plan. In Plan mode, call this before side-effecting work',
18
+ 'so the user can review and approve the draft plan. In Goal mode, use it to establish',
19
+ 'the objective, success criteria, boundaries, and trackable subtasks for autonomous execution;',
20
+ 'Goal mode does not require a plan-approval gate before every side-effecting step.',
21
+ 'Provide a clear goal and a complete list of ordered subtasks (each subtask: title, optional dependsOn).',
22
+ 'Write every subtask title and the goal in plain language the user can skim: lead with what the step',
23
+ 'is actually for, keep it to one action per subtask, and prefer everyday words over jargon.',
24
+ 'Do not cram multiple points into one title with inline numbering like (1)(2)(3) or ①②③ — split them',
25
+ 'into separate subtasks instead. Symbols, file paths, line numbers, function and field names may stay,',
26
+ 'but as trailing detail in parentheses, never as the opening of the title. Avoid buzzwords such as',
27
+ '"byte-exact", "contract", "anchor", "invariant" when a plain phrase (e.g. "don\'t break the callers")',
28
+ 'says the same thing. The reader should understand the point of each subtask from its first few words.',
29
+ 'Always provide a short, human-readable title for the plan itself (a few words; verb + object) — it is required',
30
+ 'and shown verbatim in the plan panel / home task card; do not leave it empty.',
31
+ 'Never use the user raw message, confirmation phrases (e.g. 好/就这么做/认可/ok), command output, or file paths as the plan title.',
32
+ 'After you analyze the user intent, set/refresh plan.title to that short intent title (verb + object).',
33
+ 'Do not leave the first-utterance / placeholder title in place once the main intent is clear.',
34
+ 'Keep the title stable afterward unless the goal itself materially changes; do not overwrite it with later chat turns.',
35
+ 'After the tool succeeds, end the user-facing reply with the available next steps in plain language:',
36
+ 'start execution, adjust the plan, or cancel the plan. The plan panel provides the same governed',
37
+ 'actions as clickable controls; do not replace these choices with a vague confirmation-only reply.',
38
+ // 目标线(Goal Thread)派生路由 —— 验收后追问必须挂靠父计划,否则首页平铺成孤立卡片。
39
+ 'If the user is following up on a recently completed plan in this conversation (same theme,',
40
+ 'a refinement, a fix, or another round of the same goal), do NOT create a new top-level plan.',
41
+ 'Pass parentPlanId (the completed plan\'s planId) AND sourceTaskId (a taskId that exists on that',
42
+ 'parent plan — typically the last listed task). The store requires the pair and rejects a',
43
+ 'sourceTaskId that is not on the parent. This makes the new plan the next derived round of the',
44
+ 'same Goal Thread. Only omit both fields when the user is clearly starting a new, unrelated',
45
+ 'request. If the conversation context lists a recently completed plan, use that planId and one',
46
+ 'of its taskIds.',
47
+ ].join(' ');
48
+ export const GOAL_UPDATE_TASK_PROMPT = [
49
+ 'Record execution evidence for a goal/plan subtask (Plan and Goal modes).',
50
+ 'Call this after you finish, fail, or get blocked on a subtask during execution.',
51
+ 'In Plan mode this usually happens after the approved plan starts running; in Goal mode it',
52
+ 'is the normal progress ledger for autonomous work. Mark a subtask "completed" only when',
53
+ 'you can supply the evidenceRefs (artifact refs / tool-result refs) that prove it is done —',
54
+ 'the store rejects a "completed" status without evidenceRefs. Progress is recomputed bottom-up',
55
+ 'from leaf subtasks; do not hand-maintain progress.',
56
+ ].join(' ');
57
+ export const GOAL_GET_PLAN_PROMPT = [
58
+ 'Read back an existing goal/plan (Plan and Goal modes). Read-only and side-effect free.',
59
+ 'Use this to recover the authoritative subtask taskId list and current statuses —',
60
+ 'for example after a long conversation or context compaction when you are unsure of',
61
+ 'the exact taskId to pass to goal_update_task. Pass planId to fetch one plan; omit',
62
+ 'planId to list the active plans for the current conversation. Always trust the',
63
+ 'taskId values returned here over any taskId you remember.',
64
+ ].join(' ');
65
+ export const GOAL_REQUEST_EXPLORER_PROMPT = [
66
+ 'Request a read-only Explorer sub-agent to investigate a focused question (Plan and Goal modes).',
67
+ 'Use this during execution when you need to gather evidence in parallel without',
68
+ 'spending your own turn budget — for example mapping where a symbol is used, confirming a',
69
+ 'config value, or scanning a subtree. The Explorer is strictly read-only (no writes, shell',
70
+ 'side effects, or MCP mutations) and returns findings with evidence refs. Provide a clear',
71
+ '"question" (what to find out) and a short "reason" (why it helps the goal); optionally',
72
+ 'scope it with include/exclude path hints. Calling this only registers the request; the',
73
+ 'Goal Runner dispatches and runs the Explorer after the turn. There is a hard cap on',
74
+ 'concurrent explorers per run, so only request what materially advances the goal.',
75
+ ].join(' ');
76
+ export const GOAL_CREATE_PLAN_INPUT_SCHEMA = {
77
+ type: 'object',
78
+ properties: {
79
+ title: {
80
+ type: 'string',
81
+ description: 'Short, human-readable plan title (a few words). Required — do not omit; '
82
+ + 'the plan panel and floating bar surface this verbatim.',
83
+ },
84
+ goal: {
85
+ type: 'string',
86
+ description: 'The concrete goal this plan aims to achieve, in one or two sentences.',
87
+ },
88
+ targetWorkspacePath: {
89
+ type: 'string',
90
+ description: 'Optional absolute path of the code repository this plan will modify, when it '
91
+ + 'differs from the current conversation workspace (e.g. a knowledge-base workspace '
92
+ + 'driving changes in a separate code repo). If the workspace AGENTS.md documents a '
93
+ + 'linked/associated repository path, extract and pass it here so explorers can locate '
94
+ + 'the target code across repositories. Omit when the goal targets the current workspace.',
95
+ },
96
+ parentPlanId: {
97
+ type: 'string',
98
+ description: 'Optional parent plan id when this is a follow-up / derived round of an existing Goal Thread. '
99
+ + 'Must be paired with sourceTaskId (a taskId that exists on that parent plan). '
100
+ + 'Omit both when the user is clearly starting an unrelated new request.',
101
+ },
102
+ sourceTaskId: {
103
+ type: 'string',
104
+ description: 'Required together with parentPlanId. Pass a taskId from the parent plan (typically the task '
105
+ + 'that triggered this follow-up). The store rejects either field without the other, and '
106
+ + 'rejects a sourceTaskId that is not on the parent plan.',
107
+ },
108
+ tasks: {
109
+ type: 'array',
110
+ description: 'Ordered list of subtasks that make up the plan.',
111
+ items: {
112
+ type: 'object',
113
+ properties: {
114
+ taskId: {
115
+ type: 'string',
116
+ description: 'Optional stable id for the subtask; generated if omitted.',
117
+ },
118
+ title: {
119
+ type: 'string',
120
+ description: 'What this subtask delivers, written in plain language. Lead with the point of the '
121
+ + 'step in everyday words, keep it to one action, and put any file paths, line '
122
+ + 'numbers, function or field names as trailing detail in parentheses rather than at '
123
+ + 'the start. Do not pack several points into one title with ①②③ / (1)(2)(3).',
124
+ },
125
+ dependsOn: {
126
+ type: 'array',
127
+ items: { type: 'string' },
128
+ description: 'taskIds this subtask depends on (must run after them).',
129
+ },
130
+ },
131
+ required: ['title'],
132
+ additionalProperties: false,
133
+ },
134
+ },
135
+ successCriteria: {
136
+ type: 'array',
137
+ description: 'Optional Definition-of-Done for the goal. Each item is a verifiable success '
138
+ + 'criterion. Prefer machine-verifiable kinds (command/test/file-contains/file-exists) '
139
+ + 'so the runtime can auto-verify after acting; use "manual" only when no automated '
140
+ + 'check exists. Plain strings are accepted for backward compatibility and treated as '
141
+ + 'manual criteria. When you can express the goal as executable checks, do so — the '
142
+ + 'completion gate requires non-manual criteria to have a passed verification result '
143
+ + 'with an evidence ref before the plan can complete.',
144
+ items: {
145
+ oneOf: [
146
+ { type: 'string' },
147
+ {
148
+ type: 'object',
149
+ properties: {
150
+ id: {
151
+ type: 'string',
152
+ description: 'Optional stable id for this criterion; generated if omitted.',
153
+ },
154
+ kind: {
155
+ type: 'string',
156
+ enum: ['command', 'test', 'file-contains', 'file-exists', 'manual'],
157
+ description: 'How this criterion is verified. command: run a shell command (exit 0 = pass). '
158
+ + 'test: run a test command. file-contains: a file must contain expect text. '
159
+ + 'file-exists: a path must exist. manual: needs human confirmation.',
160
+ },
161
+ description: {
162
+ type: 'string',
163
+ description: 'Human-readable statement of what "done" means for this criterion.',
164
+ },
165
+ command: {
166
+ type: 'string',
167
+ description: 'Shell/test command to run (for kind=command/test).',
168
+ },
169
+ path: {
170
+ type: 'string',
171
+ description: 'Target file path (for kind=file-contains/file-exists).',
172
+ },
173
+ expect: {
174
+ type: 'string',
175
+ description: 'Expected substring the file must contain (for kind=file-contains).',
176
+ },
177
+ },
178
+ required: ['kind'],
179
+ additionalProperties: false,
180
+ },
181
+ ],
182
+ },
183
+ },
184
+ },
185
+ required: ['title', 'goal', 'tasks'],
186
+ additionalProperties: false,
187
+ };
188
+ export const GOAL_UPDATE_TASK_INPUT_SCHEMA = {
189
+ type: 'object',
190
+ properties: {
191
+ planId: {
192
+ type: 'string',
193
+ description: 'Target goal plan id (planId).',
194
+ },
195
+ taskId: {
196
+ type: 'string',
197
+ description: 'Target subtask id (taskId) within the plan. Must reference a leaf subtask when setting completion.',
198
+ },
199
+ status: {
200
+ type: 'string',
201
+ enum: ['pending', 'running', 'completed', 'failed', 'cancelled', 'waiting_user'],
202
+ description: 'New execution status for the subtask. Use "completed" only with evidenceRefs.',
203
+ },
204
+ evidenceRefs: {
205
+ type: 'array',
206
+ items: { type: 'string' },
207
+ description: 'Artifact refs / tool-result refs that prove the subtask outcome. Required to mark completed.',
208
+ },
209
+ result: {
210
+ type: 'string',
211
+ description: 'Short factual summary of what was produced (optional).',
212
+ },
213
+ failureReason: {
214
+ type: 'string',
215
+ description: 'Why the subtask failed (when status=failed).',
216
+ },
217
+ blockedReason: {
218
+ type: 'string',
219
+ description: 'Why the subtask is blocked / waiting (when status=waiting_user).',
220
+ },
221
+ criterionResults: {
222
+ type: 'array',
223
+ description: 'Optional verification results for the plan\'s success criteria (DoD-as-Code). '
224
+ + 'After acting, run each auto-verifiable criterion\'s check (command/test/file) and '
225
+ + 'record the outcome here so the completion gate can pass. Each result references a '
226
+ + 'criterion id declared in the plan\'s successCriteria; unknown ids are ignored.',
227
+ items: {
228
+ type: 'object',
229
+ properties: {
230
+ criterionId: {
231
+ type: 'string',
232
+ description: 'The id of the success criterion this result verifies.',
233
+ },
234
+ passed: {
235
+ type: 'boolean',
236
+ description: 'Whether the criterion check passed.',
237
+ },
238
+ evidenceRef: {
239
+ type: 'string',
240
+ description: 'Artifact/tool-result ref proving the check outcome (e.g. the shell result ref).',
241
+ },
242
+ detail: {
243
+ type: 'string',
244
+ description: 'Short human-readable detail of what was checked / observed.',
245
+ },
246
+ },
247
+ required: ['criterionId', 'passed'],
248
+ additionalProperties: false,
249
+ },
250
+ },
251
+ },
252
+ required: ['planId', 'taskId'],
253
+ additionalProperties: false,
254
+ };
255
+ export const GOAL_GET_PLAN_INPUT_SCHEMA = {
256
+ type: 'object',
257
+ properties: {
258
+ planId: {
259
+ type: 'string',
260
+ description: 'Target goal plan id (planId) to read back. Omit to list the active plans for the current conversation.',
261
+ },
262
+ },
263
+ required: [],
264
+ additionalProperties: false,
265
+ };
266
+ export const GOAL_REQUEST_EXPLORER_INPUT_SCHEMA = {
267
+ type: 'object',
268
+ properties: {
269
+ question: {
270
+ type: 'string',
271
+ description: 'The focused, read-only question the Explorer should answer (what to find out).',
272
+ },
273
+ reason: {
274
+ type: 'string',
275
+ description: 'Why answering this question helps advance the current goal.',
276
+ },
277
+ scope: {
278
+ type: 'object',
279
+ description: 'Optional path hints to scope the read-only investigation.',
280
+ properties: {
281
+ include: {
282
+ type: 'array',
283
+ items: { type: 'string' },
284
+ description: 'Path globs / directories the Explorer should focus on.',
285
+ },
286
+ exclude: {
287
+ type: 'array',
288
+ items: { type: 'string' },
289
+ description: 'Path globs / directories the Explorer should avoid.',
290
+ },
291
+ },
292
+ additionalProperties: false,
293
+ },
294
+ },
295
+ required: ['question'],
296
+ additionalProperties: false,
297
+ };
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * from './capability-registry.ts';
7
7
  export * from './projection.ts';
8
8
  export * from './projection-materializers.ts';
9
9
  export * from './local-tool-contracts.ts';
10
+ export * from './goal-tool-contracts.ts';
10
11
  export * from './context-compaction.ts';
11
12
  export * from './goal-keep-policy.ts';
12
13
  export * from './goal-checkpoint.ts';
@@ -20,3 +21,6 @@ export * from './context-accounting-lifecycle.ts';
20
21
  export * from './context-usage-breakdown.ts';
21
22
  export * from './conversation-history-projector.ts';
22
23
  export * from './runtime-usage-accounting.ts';
24
+ export * from './project-input-recovery.ts';
25
+ export * from './resource-edit-state.ts';
26
+ export * from './input-prediction.ts';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export * from "./capability-registry.js";
7
7
  export * from "./projection.js";
8
8
  export * from "./projection-materializers.js";
9
9
  export * from "./local-tool-contracts.js";
10
+ export * from "./goal-tool-contracts.js";
10
11
  export * from "./context-compaction.js";
11
12
  export * from "./goal-keep-policy.js";
12
13
  export * from "./goal-checkpoint.js";
@@ -20,3 +21,6 @@ export * from "./context-accounting-lifecycle.js";
20
21
  export * from "./context-usage-breakdown.js";
21
22
  export * from "./conversation-history-projector.js";
22
23
  export * from "./runtime-usage-accounting.js";
24
+ export * from "./project-input-recovery.js";
25
+ export * from "./resource-edit-state.js";
26
+ export * from "./input-prediction.js";
@@ -0,0 +1,40 @@
1
+ import { type InputCandidate, type InputPredictionPort, type InputPredictionSurface } from '@peer-agent/protocol';
2
+ export interface PredictionInput {
3
+ readonly workspaceId: string;
4
+ readonly conversationId: string;
5
+ readonly surface: InputPredictionSurface;
6
+ readonly text: string;
7
+ readonly selectionStart: number;
8
+ readonly selectionEnd: number;
9
+ readonly contextVersion: string;
10
+ readonly quoteMessageId?: string;
11
+ readonly eligible: boolean;
12
+ readonly active: boolean;
13
+ readonly composing: boolean;
14
+ }
15
+ export interface PredictionView {
16
+ readonly status: 'idle' | 'waiting' | 'requesting' | 'visible' | 'accepting';
17
+ readonly candidate: InputCandidate | null;
18
+ }
19
+ /** Owns every asynchronous generation; the editor retains all draft ownership. */
20
+ export declare function createInputPredictionController({ port, createId, now, apply, debounceMs, validationMs, }: {
21
+ port: InputPredictionPort;
22
+ createId: () => string;
23
+ now?: () => number;
24
+ apply: (text: string, input: PredictionInput) => void;
25
+ debounceMs?: {
26
+ next_turn: number;
27
+ continuation: number;
28
+ };
29
+ validationMs?: number;
30
+ }): {
31
+ composerInstanceId: string;
32
+ update: (next: PredictionInput) => void;
33
+ accept: () => Promise<boolean>;
34
+ invalidate: () => void;
35
+ suppressDraft(text: string): void;
36
+ dismiss(): void;
37
+ getSnapshot: () => PredictionView;
38
+ subscribe(listener: () => void): () => void;
39
+ dispose(): void;
40
+ };
@@ -0,0 +1,143 @@
1
+ import { INPUT_PREDICTION_LIMITS } from '@peer-agent/protocol';
2
+ const IDLE_VIEW = Object.freeze({ status: 'idle', candidate: null });
3
+ const WAITING_VIEW = Object.freeze({ status: 'waiting', candidate: null });
4
+ const REQUESTING_VIEW = Object.freeze({ status: 'requesting', candidate: null });
5
+ function samePredictionInput(a, b) {
6
+ return a !== null
7
+ && a.workspaceId === b.workspaceId
8
+ && a.conversationId === b.conversationId
9
+ && a.surface === b.surface
10
+ && a.text === b.text
11
+ && a.selectionStart === b.selectionStart
12
+ && a.selectionEnd === b.selectionEnd
13
+ && a.contextVersion === b.contextVersion
14
+ && a.quoteMessageId === b.quoteMessageId
15
+ && a.eligible === b.eligible
16
+ && a.active === b.active
17
+ && a.composing === b.composing;
18
+ }
19
+ /** Owns every asynchronous generation; the editor retains all draft ownership. */
20
+ export function createInputPredictionController({ port, createId, now = Date.now, apply, debounceMs = { next_turn: 300, continuation: 500 }, validationMs = INPUT_PREDICTION_LIMITS.validationMs, }) {
21
+ let input = null, dismissed = '', acceptedText = null;
22
+ let version = 0, generation = 0, requestId = null, disposed = false;
23
+ let timer, expiry;
24
+ let view = IDLE_VIEW;
25
+ const listeners = new Set();
26
+ function publish(next) {
27
+ if (view.status === next.status && view.candidate === next.candidate)
28
+ return;
29
+ view = next;
30
+ for (const listener of listeners)
31
+ listener();
32
+ }
33
+ function stopPending() {
34
+ generation++;
35
+ clearTimeout(timer);
36
+ clearTimeout(expiry);
37
+ if (requestId)
38
+ void port.cancel({ requestId, composerInstanceId }).catch(() => { });
39
+ requestId = null;
40
+ }
41
+ function cancel() {
42
+ stopPending();
43
+ publish(IDLE_VIEW);
44
+ }
45
+ const composerInstanceId = createId();
46
+ const eligible = (value) => value.eligible && value.active && !value.composing
47
+ && !!value.workspaceId && !!value.conversationId && !!value.contextVersion
48
+ && value.selectionStart === value.selectionEnd && value.selectionEnd === value.text.length
49
+ && value.text.length <= INPUT_PREDICTION_LIMITS.draftLength;
50
+ async function request() {
51
+ if (!input || disposed || !eligible(input))
52
+ return;
53
+ const captured = input, ticket = generation, draftVersion = version;
54
+ requestId = createId();
55
+ const id = requestId;
56
+ publish(REQUESTING_VIEW);
57
+ try {
58
+ const result = await port.request({ requestId: id, composerInstanceId,
59
+ workspaceId: captured.workspaceId, conversationId: captured.conversationId, surface: captured.surface,
60
+ mode: captured.text ? 'continuation' : 'next_turn', draftVersion,
61
+ draftText: captured.text, selectionStart: captured.selectionStart, selectionEnd: captured.selectionEnd,
62
+ ...(captured.quoteMessageId ? { quoteMessageId: captured.quoteMessageId } : {}),
63
+ });
64
+ if (disposed || generation !== ticket || version !== draftVersion || !input || !eligible(input))
65
+ return;
66
+ const candidate = result.kind === 'candidate' ? result.candidate : null;
67
+ if (!candidate || candidate.requestId !== id || candidate.composerInstanceId !== composerInstanceId
68
+ || candidate.workspaceId !== captured.workspaceId || candidate.conversationId !== captured.conversationId
69
+ || candidate.draftVersion !== draftVersion || candidate.mode !== (captured.text ? 'continuation' : 'next_turn')
70
+ || typeof candidate.insertionText !== 'string' || !candidate.insertionText.trim()
71
+ || !Number.isFinite(Date.parse(candidate.expiresAt)) || Date.parse(candidate.expiresAt) <= now()) {
72
+ publish(IDLE_VIEW);
73
+ return;
74
+ }
75
+ publish({ status: 'visible', candidate });
76
+ expiry = setTimeout(cancel, Math.max(0, Date.parse(candidate.expiresAt) - now()));
77
+ }
78
+ catch {
79
+ if (!disposed && generation === ticket)
80
+ publish(IDLE_VIEW);
81
+ }
82
+ }
83
+ function update(next) {
84
+ if (disposed)
85
+ return;
86
+ if (samePredictionInput(input, next))
87
+ return;
88
+ const sameContext = input?.contextVersion === next.contextVersion && input?.conversationId === next.conversationId;
89
+ if (!sameContext || (next.text !== input?.text && next.text !== acceptedText))
90
+ acceptedText = null;
91
+ input = next;
92
+ version++;
93
+ stopPending();
94
+ const semanticKey = JSON.stringify([next.workspaceId, next.conversationId, next.contextVersion, next.text, next.quoteMessageId]);
95
+ if (!eligible(next) || dismissed === semanticKey || acceptedText === next.text) {
96
+ publish(IDLE_VIEW);
97
+ return;
98
+ }
99
+ publish(WAITING_VIEW);
100
+ timer = setTimeout(() => { void request(); }, next.text ? debounceMs.continuation : debounceMs.next_turn);
101
+ }
102
+ async function accept() {
103
+ if (!input || !eligible(input) || view.status !== 'visible' || !view.candidate)
104
+ return false;
105
+ const captured = input, candidate = view.candidate, ticket = generation, draftVersion = version;
106
+ if (Date.parse(candidate.expiresAt) <= now()) {
107
+ cancel();
108
+ return false;
109
+ }
110
+ publish({ status: 'accepting', candidate });
111
+ let timeout;
112
+ try {
113
+ const result = await Promise.race([port.validate({ requestId: candidate.requestId,
114
+ candidateId: candidate.candidateId, composerInstanceId }),
115
+ new Promise(resolve => { timeout = setTimeout(() => resolve({ kind: 'unavailable' }), validationMs); })]);
116
+ if (disposed || generation !== ticket || version !== draftVersion || !input || !eligible(input))
117
+ return false;
118
+ if (result.kind !== 'valid' || Date.parse(candidate.expiresAt) <= now()) {
119
+ cancel();
120
+ return false;
121
+ }
122
+ acceptedText = captured.text + candidate.insertionText;
123
+ cancel();
124
+ apply(acceptedText, captured);
125
+ return true;
126
+ }
127
+ catch {
128
+ if (generation === ticket)
129
+ cancel();
130
+ return false;
131
+ }
132
+ finally {
133
+ clearTimeout(timeout);
134
+ }
135
+ }
136
+ return { composerInstanceId, update, accept, invalidate: cancel,
137
+ suppressDraft(text) { acceptedText = text; cancel(); },
138
+ dismiss() { if (input)
139
+ dismissed = JSON.stringify([input.workspaceId, input.conversationId, input.contextVersion, input.text, input.quoteMessageId]); cancel(); },
140
+ getSnapshot: () => view,
141
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
142
+ dispose() { disposed = true; cancel(); listeners.clear(); }, };
143
+ }
@@ -2,6 +2,12 @@ export declare const MICROCOMPACTION_CONFIG: Readonly<{
2
2
  keepRecentCount: 8;
3
3
  triggerChars: 6000;
4
4
  previewChars: 800;
5
+ /**
6
+ * Hard cap for one tool-result body in a provider request.
7
+ * The recent window stays more complete than older history, but it cannot
8
+ * carry a multi-megabyte tool body. File reads under this cap stay inline.
9
+ */
10
+ recentToolResultChars: 32000;
5
11
  }>;
6
12
  /** 宽松消息形状:兼容 Desktop apiMessages 与 TUI ModelMessage(无索引签名接口)。 */
7
13
  export type MicrocompactMessage = {
@@ -31,8 +37,16 @@ export declare function extractRecoverableClues(text: unknown, { limit }?: {
31
37
  paths: string[];
32
38
  suggestedRetrieval: string[];
33
39
  };
40
+ /**
41
+ * Bound one tool-result body before it is serialized into a provider request.
42
+ * Small and already-structured results pass through. Oversized text keeps a
43
+ * retrieval skeleton or a short preview, including original size.
44
+ */
45
+ export declare function boundProviderToolResultContent(content: string, maxChars?: number): string;
34
46
  /**
35
47
  * 对「最近 keepRecentCount 条非 system 消息之外」的历史消息做证据引用化/预览化。
36
48
  * system 与 `_compaction` handoff 不参与;已是 local_*_ref 的结果保留骨架不重复截断。
37
49
  */
38
- export declare function microcompactMessagesForContext<TMessage extends MicrocompactMessage>(messages: readonly TMessage[], options?: Partial<typeof MICROCOMPACTION_CONFIG>): MicrocompactResult<TMessage>;
50
+ export declare function microcompactMessagesForContext<TMessage extends MicrocompactMessage>(messages: readonly TMessage[], options?: Partial<typeof MICROCOMPACTION_CONFIG> & {
51
+ preserveLatestUserTurn?: boolean;
52
+ }): MicrocompactResult<TMessage>;