compressed-context 0.1.0 → 0.1.1

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 (55) hide show
  1. package/package.json +64 -64
  2. package/src/compression/active-summary-cache.ts +50 -50
  3. package/src/compression/adopt.ts +57 -57
  4. package/src/compression/auto.ts +372 -372
  5. package/src/compression/babel.ts +85 -85
  6. package/src/compression/block.ts +25 -25
  7. package/src/compression/cache-history.ts +75 -75
  8. package/src/compression/compaction.ts +189 -189
  9. package/src/compression/decompress-tool.ts +74 -74
  10. package/src/compression/decompress.ts +292 -292
  11. package/src/compression/deleted-sessions.ts +24 -24
  12. package/src/compression/distill.ts +220 -220
  13. package/src/compression/events.ts +275 -275
  14. package/src/compression/markdown.ts +53 -53
  15. package/src/compression/normalize.ts +114 -114
  16. package/src/compression/render.ts +70 -70
  17. package/src/compression/schema.ts +84 -84
  18. package/src/compression/select.ts +123 -123
  19. package/src/compression/session-message.ts +112 -112
  20. package/src/compression/settings-rpc.ts +111 -111
  21. package/src/compression/settings.ts +175 -175
  22. package/src/compression/state.ts +248 -248
  23. package/src/compression/summarize.ts +595 -595
  24. package/src/compression/summary.ts +73 -73
  25. package/src/compression/tool.ts +142 -142
  26. package/src/compression/transcript-store.ts +258 -258
  27. package/src/compression/transcript.ts +63 -63
  28. package/src/compression/validate.ts +81 -81
  29. package/src/i18n/en.ts +93 -93
  30. package/src/i18n/index.ts +28 -28
  31. package/src/i18n/types.ts +89 -89
  32. package/src/i18n/zh.ts +93 -93
  33. package/src/index.ts +108 -108
  34. package/src/shared/blocks.ts +17 -17
  35. package/src/shared/cache.ts +199 -199
  36. package/src/shared/format.ts +23 -23
  37. package/src/shared/media.ts +184 -184
  38. package/src/shared/parse.ts +25 -25
  39. package/src/shared/parts.ts +72 -72
  40. package/src/shared/rpc.ts +145 -145
  41. package/src/shared/scan.ts +32 -32
  42. package/src/shared/settings.ts +471 -471
  43. package/src/shared/stats.ts +142 -142
  44. package/src/shared/tokens.ts +259 -259
  45. package/src/tui/chart/cache-chart.ts +237 -237
  46. package/src/tui/chart/color.ts +58 -58
  47. package/src/tui/index.tsx +111 -111
  48. package/src/tui/panel/cache.tsx +203 -203
  49. package/src/tui/panel/data.ts +105 -105
  50. package/src/tui/panel/index.tsx +176 -176
  51. package/src/tui/panel/summaries.tsx +192 -192
  52. package/src/tui/settings/dialogs.tsx +215 -215
  53. package/src/tui/settings/options.ts +238 -238
  54. package/src/tui/settings.tsx +418 -418
  55. package/src/tui/types.ts +4 -4
@@ -1,73 +1,73 @@
1
- import { isBabelSummary, isMarkdownSummary, type Summary, type SummaryFields } from "./schema.ts"
2
- import { markdownGoal } from "./markdown.ts"
3
-
4
- /** 输入:条目;输出:Markdown 列表;空列表输出 `- (none)`。 */
5
- function bullets(items: readonly string[]): string {
6
- if (items.length === 0) return "- (none)"
7
- return items.map((item) => `- ${item}`).join("\n")
8
- }
9
-
10
- /** 输入:JSON 摘要字段;输出:Markdown 正文。 */
11
- export function renderFields(fields: SummaryFields): string {
12
- return [
13
- "## Goal",
14
- fields.goal,
15
- "",
16
- "## Constraints",
17
- bullets(fields.constraints),
18
- "",
19
- "## Decisions",
20
- bullets(fields.decisions),
21
- "",
22
- "## Progress",
23
- "### Completed",
24
- bullets(fields.progress.completed),
25
- "### Active",
26
- bullets(fields.progress.active),
27
- "### Blocked",
28
- bullets(fields.progress.blocked),
29
- "",
30
- "## Open Items",
31
- bullets(fields.open_items),
32
- "",
33
- "## Files",
34
- bullets(fields.files),
35
- "",
36
- "## Facts",
37
- bullets(fields.facts),
38
- ].join("\n")
39
- }
40
-
41
- /** 输入:摘要;输出:块标题。 */
42
- export function summaryTitle(summary: Summary): string {
43
- return summary.title
44
- }
45
-
46
- /** 输入:摘要;输出:用于候选描述的短目标。 */
47
- export function summaryGoal(summary: Summary): string {
48
- if (isBabelSummary(summary)) return summary.goal
49
- return isMarkdownSummary(summary) ? markdownGoal(summary.text) : summary.goal
50
- }
51
-
52
- /** 输入:摘要;输出:渲染后的正文。 */
53
- export function summaryBody(summary: Summary): string {
54
- if (isBabelSummary(summary) || isMarkdownSummary(summary)) return summary.text
55
- return renderFields(summary)
56
- }
57
-
58
- /** 输入:摘要;输出:正文实际字符数。 */
59
- export function summaryChars(summary: Summary): number {
60
- if (isBabelSummary(summary) || isMarkdownSummary(summary)) return summary.text.length
61
- return [
62
- summary.title,
63
- summary.goal,
64
- ...summary.constraints,
65
- ...summary.decisions,
66
- ...summary.progress.completed,
67
- ...summary.progress.active,
68
- ...summary.progress.blocked,
69
- ...summary.open_items,
70
- ...summary.files,
71
- ...summary.facts,
72
- ].join("\n").length
73
- }
1
+ import { isBabelSummary, isMarkdownSummary, type Summary, type SummaryFields } from "./schema.ts"
2
+ import { markdownGoal } from "./markdown.ts"
3
+
4
+ /** 输入:条目;输出:Markdown 列表;空列表输出 `- (none)`。 */
5
+ function bullets(items: readonly string[]): string {
6
+ if (items.length === 0) return "- (none)"
7
+ return items.map((item) => `- ${item}`).join("\n")
8
+ }
9
+
10
+ /** 输入:JSON 摘要字段;输出:Markdown 正文。 */
11
+ export function renderFields(fields: SummaryFields): string {
12
+ return [
13
+ "## Goal",
14
+ fields.goal,
15
+ "",
16
+ "## Constraints",
17
+ bullets(fields.constraints),
18
+ "",
19
+ "## Decisions",
20
+ bullets(fields.decisions),
21
+ "",
22
+ "## Progress",
23
+ "### Completed",
24
+ bullets(fields.progress.completed),
25
+ "### Active",
26
+ bullets(fields.progress.active),
27
+ "### Blocked",
28
+ bullets(fields.progress.blocked),
29
+ "",
30
+ "## Open Items",
31
+ bullets(fields.open_items),
32
+ "",
33
+ "## Files",
34
+ bullets(fields.files),
35
+ "",
36
+ "## Facts",
37
+ bullets(fields.facts),
38
+ ].join("\n")
39
+ }
40
+
41
+ /** 输入:摘要;输出:块标题。 */
42
+ export function summaryTitle(summary: Summary): string {
43
+ return summary.title
44
+ }
45
+
46
+ /** 输入:摘要;输出:用于候选描述的短目标。 */
47
+ export function summaryGoal(summary: Summary): string {
48
+ if (isBabelSummary(summary)) return summary.goal
49
+ return isMarkdownSummary(summary) ? markdownGoal(summary.text) : summary.goal
50
+ }
51
+
52
+ /** 输入:摘要;输出:渲染后的正文。 */
53
+ export function summaryBody(summary: Summary): string {
54
+ if (isBabelSummary(summary) || isMarkdownSummary(summary)) return summary.text
55
+ return renderFields(summary)
56
+ }
57
+
58
+ /** 输入:摘要;输出:正文实际字符数。 */
59
+ export function summaryChars(summary: Summary): number {
60
+ if (isBabelSummary(summary) || isMarkdownSummary(summary)) return summary.text.length
61
+ return [
62
+ summary.title,
63
+ summary.goal,
64
+ ...summary.constraints,
65
+ ...summary.decisions,
66
+ ...summary.progress.completed,
67
+ ...summary.progress.active,
68
+ ...summary.progress.blocked,
69
+ ...summary.open_items,
70
+ ...summary.files,
71
+ ...summary.facts,
72
+ ].join("\n").length
73
+ }
@@ -1,142 +1,142 @@
1
- import type { Plugin } from "@opencode/plugin"
2
- import { Schema } from "effect"
3
-
4
- import { resolveSummaryLimits } from "../shared/settings.ts"
5
- import { createT1Block } from "./block.ts"
6
- import { toSummary } from "./normalize.ts"
7
- import { SummaryInput } from "./schema.ts"
8
- import { RESOLVED_WINDOW_KEY, loadServerSettings, windowKey } from "./settings.ts"
9
- import { eligibleMessages, messageRange, type MessageLike } from "./select.ts"
10
- import { sessionMessagesToMessageLikes } from "./session-message.ts"
11
- import { loadState, saveState, withPending } from "./state.ts"
12
- import type { Disposable } from "./settings-rpc.ts"
13
- import { buildTranscript } from "./transcript.ts"
14
- import { saveTranscript } from "./transcript-store.ts"
15
- import { MIN_SOURCE_CHARS, validateSummary } from "./validate.ts"
16
-
17
- const DESCRIPTION =
18
- "Compress the conversation so far into a structured checkpoint. Call this when the context is getting full. " +
19
- "It covers every message since the last compressed block, up to the current user message, and replaces them with " +
20
- "one block. In JSON mode provide `goal` plus the optional fields; in Markdown mode provide `markdown`; in Babel " +
21
- "mode provide `babel` with first line `T=<short title>|G=<one-line goal>` and a dense body. Omit any " +
22
- "optional field that has no real content instead of inventing entries. Do not call while a compression is already " +
23
- "pending. " +
24
- "Add a short title if useful. " +
25
- "The block is the only remaining record of those messages, so copy exact paths with line numbers, signatures, the " +
26
- "code lines that carry the logic, error text, versions, config keys, thresholds, and measured values. " +
27
- "Use `files` only for real file paths; put config keys and function names in `facts`. " +
28
- "Put work in `progress.completed` only when it was actually finished; plans go in `progress.active` or `open_items`. " +
29
- "Give the reason for each decision, keep the objective and any pivots, why important actions were taken, unanswered " +
30
- "questions, and work the user still expects. Describe the past as past, not as a new instruction. " +
31
- "Leave out logs, repeated reads, exploration that produced nothing, abandoned attempts (one line on why), and " +
32
- "repeated status checks. If space is tight, keep objective and constraints first, then decisions and reasons, then " +
33
- "exact technical facts, then conclusions, then lessons. Write short factual entries, not prose."
34
-
35
- function failure(message: string) {
36
- return {
37
- output: { block: "", status: "error" },
38
- content: `ERROR: ${message}`,
39
- metadata: { error: true },
40
- }
41
- }
42
-
43
- /**
44
- * 输入:服务端上下文。
45
- * 输出:注册 compress 工具。
46
- * 预期:执行时从会话上下文按需取消息,不再把整段历史常驻内存。
47
- */
48
- export async function registerCompressTool(
49
- ctx: Plugin.Context,
50
- legacyCache?: ReadonlyMap<string, readonly MessageLike[]>,
51
- ): Promise<Disposable> {
52
- const registration = await ctx.tool.transform((tools) => {
53
- tools.add({
54
- name: "compress",
55
- options: { codemode: false },
56
- description: DESCRIPTION,
57
- input: SummaryInput,
58
- output: Schema.Struct({ block: Schema.String, status: Schema.String }),
59
- execute: async (input, toolCtx) => {
60
- const sessionID = toolCtx.sessionID
61
- const state = await loadState(ctx.storage, sessionID)
62
- if (state.terminal !== undefined) return failure(state.terminal)
63
- if (state.pending || state.phase !== undefined) return failure("compression already in progress")
64
-
65
- let eligible: readonly MessageLike[] | undefined
66
- try {
67
- const raw = await ctx.session.context({ sessionID })
68
- eligible = eligibleMessages(sessionMessagesToMessageLikes(raw))
69
- } catch {
70
- // 兼容旧测试替身;生产路径不传 legacyCache。
71
- eligible = legacyCache === undefined ? undefined : (legacyCache.get(sessionID) ?? [])
72
- }
73
- if (eligible === undefined) return failure("failed to read session context")
74
- const transcript = buildTranscript(eligible)
75
- const sourceChars = transcript.length
76
- if (eligible.length === 0) return failure("nothing to compress")
77
- if (sourceChars < MIN_SOURCE_CHARS) {
78
- return failure(
79
- `not enough content to compress (${sourceChars.toString()} chars, min ${MIN_SOURCE_CHARS.toString()})`,
80
- )
81
- }
82
-
83
- const settings = await loadServerSettings(ctx.storage)
84
- if (!settings.enableCompressTool) return failure("compress tool is disabled in settings")
85
- // 优先用当前会话模型自己的窗口;取不到再回退最近一次解析值。
86
- let windowTokens: number | undefined
87
- try {
88
- const session = await ctx.session.get({ sessionID })
89
- const model = session.model
90
- const stored =
91
- model === undefined ? undefined : await ctx.storage.get(windowKey(model.providerID, model.id))
92
- if (typeof stored === "number" && stored > 0) windowTokens = stored
93
- } catch {
94
- // 会话或模型未知:回退到最近一次解析值
95
- }
96
- if (windowTokens === undefined) {
97
- const resolved = await ctx.storage.get(RESOLVED_WINDOW_KEY)
98
- if (typeof resolved === "number" && resolved > 0) windowTokens = resolved
99
- }
100
- const limits = resolveSummaryLimits(settings, windowTokens)
101
- const summary = toSummary(input, settings.summaryFormat)
102
- if (summary === undefined) return failure("invalid summary shape")
103
- const validation = validateSummary(summary, sourceChars, undefined, limits.blockChars)
104
- if (!validation.ok) return failure(validation.message)
105
-
106
- const range = messageRange(eligible)
107
- if (range === undefined) {
108
- return failure("messages are missing ids")
109
- }
110
-
111
- const block = createT1Block({
112
- blocks: state.blocks,
113
- summary,
114
- fromId: range.fromId,
115
- toId: range.toId,
116
- sourceChars,
117
- })
118
-
119
- // transcript 落盘失败不应阻断摘要;解压时会降级为占位符。
120
- try {
121
- await saveTranscript(ctx.storage, sessionID, block, eligible)
122
- } catch {
123
- // best effort
124
- }
125
-
126
- await saveState(ctx.storage, sessionID, withPending(state, block))
127
- try {
128
- await ctx.session.compact({ sessionID })
129
- } catch (error) {
130
- await saveState(ctx.storage, sessionID, { ...state, lastError: String(error) })
131
- return failure(`failed to start compaction: ${String(error)}`)
132
- }
133
-
134
- return {
135
- output: { block: block.id, status: "queued" },
136
- content: `queued compression ${block.id}`,
137
- }
138
- },
139
- })
140
- })
141
- return registration
142
- }
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import { Schema } from "effect"
3
+
4
+ import { resolveSummaryLimits } from "../shared/settings.ts"
5
+ import { createT1Block } from "./block.ts"
6
+ import { toSummary } from "./normalize.ts"
7
+ import { SummaryInput } from "./schema.ts"
8
+ import { RESOLVED_WINDOW_KEY, loadServerSettings, windowKey } from "./settings.ts"
9
+ import { eligibleMessages, messageRange, type MessageLike } from "./select.ts"
10
+ import { sessionMessagesToMessageLikes } from "./session-message.ts"
11
+ import { loadState, saveState, withPending } from "./state.ts"
12
+ import type { Disposable } from "./settings-rpc.ts"
13
+ import { buildTranscript } from "./transcript.ts"
14
+ import { saveTranscript } from "./transcript-store.ts"
15
+ import { MIN_SOURCE_CHARS, validateSummary } from "./validate.ts"
16
+
17
+ const DESCRIPTION =
18
+ "Compress the conversation so far into a structured checkpoint. Call this when the context is getting full. " +
19
+ "It covers every message since the last compressed block, up to the current user message, and replaces them with " +
20
+ "one block. In JSON mode provide `goal` plus the optional fields; in Markdown mode provide `markdown`; in Babel " +
21
+ "mode provide `babel` with first line `T=<short title>|G=<one-line goal>` and a dense body. Omit any " +
22
+ "optional field that has no real content instead of inventing entries. Do not call while a compression is already " +
23
+ "pending. " +
24
+ "Add a short title if useful. " +
25
+ "The block is the only remaining record of those messages, so copy exact paths with line numbers, signatures, the " +
26
+ "code lines that carry the logic, error text, versions, config keys, thresholds, and measured values. " +
27
+ "Use `files` only for real file paths; put config keys and function names in `facts`. " +
28
+ "Put work in `progress.completed` only when it was actually finished; plans go in `progress.active` or `open_items`. " +
29
+ "Give the reason for each decision, keep the objective and any pivots, why important actions were taken, unanswered " +
30
+ "questions, and work the user still expects. Describe the past as past, not as a new instruction. " +
31
+ "Leave out logs, repeated reads, exploration that produced nothing, abandoned attempts (one line on why), and " +
32
+ "repeated status checks. If space is tight, keep objective and constraints first, then decisions and reasons, then " +
33
+ "exact technical facts, then conclusions, then lessons. Write short factual entries, not prose."
34
+
35
+ function failure(message: string) {
36
+ return {
37
+ output: { block: "", status: "error" },
38
+ content: `ERROR: ${message}`,
39
+ metadata: { error: true },
40
+ }
41
+ }
42
+
43
+ /**
44
+ * 输入:服务端上下文。
45
+ * 输出:注册 compress 工具。
46
+ * 预期:执行时从会话上下文按需取消息,不再把整段历史常驻内存。
47
+ */
48
+ export async function registerCompressTool(
49
+ ctx: Plugin.Context,
50
+ legacyCache?: ReadonlyMap<string, readonly MessageLike[]>,
51
+ ): Promise<Disposable> {
52
+ const registration = await ctx.tool.transform((tools) => {
53
+ tools.add({
54
+ name: "compress",
55
+ options: { codemode: false },
56
+ description: DESCRIPTION,
57
+ input: SummaryInput,
58
+ output: Schema.Struct({ block: Schema.String, status: Schema.String }),
59
+ execute: async (input, toolCtx) => {
60
+ const sessionID = toolCtx.sessionID
61
+ const state = await loadState(ctx.storage, sessionID)
62
+ if (state.terminal !== undefined) return failure(state.terminal)
63
+ if (state.pending || state.phase !== undefined) return failure("compression already in progress")
64
+
65
+ let eligible: readonly MessageLike[] | undefined
66
+ try {
67
+ const raw = await ctx.session.context({ sessionID })
68
+ eligible = eligibleMessages(sessionMessagesToMessageLikes(raw))
69
+ } catch {
70
+ // 兼容旧测试替身;生产路径不传 legacyCache。
71
+ eligible = legacyCache === undefined ? undefined : (legacyCache.get(sessionID) ?? [])
72
+ }
73
+ if (eligible === undefined) return failure("failed to read session context")
74
+ const transcript = buildTranscript(eligible)
75
+ const sourceChars = transcript.length
76
+ if (eligible.length === 0) return failure("nothing to compress")
77
+ if (sourceChars < MIN_SOURCE_CHARS) {
78
+ return failure(
79
+ `not enough content to compress (${sourceChars.toString()} chars, min ${MIN_SOURCE_CHARS.toString()})`,
80
+ )
81
+ }
82
+
83
+ const settings = await loadServerSettings(ctx.storage)
84
+ if (!settings.enableCompressTool) return failure("compress tool is disabled in settings")
85
+ // 优先用当前会话模型自己的窗口;取不到再回退最近一次解析值。
86
+ let windowTokens: number | undefined
87
+ try {
88
+ const session = await ctx.session.get({ sessionID })
89
+ const model = session.model
90
+ const stored =
91
+ model === undefined ? undefined : await ctx.storage.get(windowKey(model.providerID, model.id))
92
+ if (typeof stored === "number" && stored > 0) windowTokens = stored
93
+ } catch {
94
+ // 会话或模型未知:回退到最近一次解析值
95
+ }
96
+ if (windowTokens === undefined) {
97
+ const resolved = await ctx.storage.get(RESOLVED_WINDOW_KEY)
98
+ if (typeof resolved === "number" && resolved > 0) windowTokens = resolved
99
+ }
100
+ const limits = resolveSummaryLimits(settings, windowTokens)
101
+ const summary = toSummary(input, settings.summaryFormat)
102
+ if (summary === undefined) return failure("invalid summary shape")
103
+ const validation = validateSummary(summary, sourceChars, undefined, limits.blockChars)
104
+ if (!validation.ok) return failure(validation.message)
105
+
106
+ const range = messageRange(eligible)
107
+ if (range === undefined) {
108
+ return failure("messages are missing ids")
109
+ }
110
+
111
+ const block = createT1Block({
112
+ blocks: state.blocks,
113
+ summary,
114
+ fromId: range.fromId,
115
+ toId: range.toId,
116
+ sourceChars,
117
+ })
118
+
119
+ // transcript 落盘失败不应阻断摘要;解压时会降级为占位符。
120
+ try {
121
+ await saveTranscript(ctx.storage, sessionID, block, eligible)
122
+ } catch {
123
+ // best effort
124
+ }
125
+
126
+ await saveState(ctx.storage, sessionID, withPending(state, block))
127
+ try {
128
+ await ctx.session.compact({ sessionID })
129
+ } catch (error) {
130
+ await saveState(ctx.storage, sessionID, { ...state, lastError: String(error) })
131
+ return failure(`failed to start compaction: ${String(error)}`)
132
+ }
133
+
134
+ return {
135
+ output: { block: block.id, status: "queued" },
136
+ content: `queued compression ${block.id}`,
137
+ }
138
+ },
139
+ })
140
+ })
141
+ return registration
142
+ }