dsh-self-context 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/graph.ts ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * The working graph G_t from Self-Context (arXiv:2612.01681), ported to a pure,
3
+ * replayable TypeScript model. Nodes have stable ids and append-only revisions;
4
+ * `remove` tombstones a node so it leaves the model-facing view but stays in
5
+ * history. The same `applyGraphOps` both validates a model call and replays the
6
+ * durable `self-context/graph` events, so live state and replay never diverge.
7
+ */
8
+
9
+ /** Graph operation kinds the model may issue. */
10
+ export const GRAPH_OPS = ['add', 'edit', 'link', 'remove'] as const
11
+ export type GraphOpKind = (typeof GRAPH_OPS)[number]
12
+
13
+ /** One model-issued graph operation, before normalization. */
14
+ export interface GraphOpInput {
15
+ op: GraphOpKind
16
+ id?: string
17
+ type?: string
18
+ content?: string
19
+ status?: string
20
+ parents?: string[]
21
+ }
22
+
23
+ /** One normalized operation as persisted in the session log. */
24
+ export interface GraphOp {
25
+ op: GraphOpKind | 'restore'
26
+ id: string
27
+ type?: string
28
+ content?: string
29
+ status?: string
30
+ parents?: string[]
31
+ }
32
+
33
+ /** One node of the working graph. */
34
+ export interface GraphNode {
35
+ id: string
36
+ type: string
37
+ content: string
38
+ status?: string | undefined
39
+ parents: string[]
40
+ /** Monotonic revision number; 1 on creation. */
41
+ v: number
42
+ /** Tombstoned nodes are hidden from the model but kept in history. */
43
+ removed: boolean
44
+ }
45
+
46
+ /** The whole working graph as plain JSON: nodes by id plus creation order. */
47
+ export interface GraphState {
48
+ nodes: Record<string, GraphNode>
49
+ order: string[]
50
+ }
51
+
52
+ /** Result of applying one batch of model operations. */
53
+ export interface GraphApplyResult {
54
+ /** Normalized operations that took effect, in order; persist these. */
55
+ applied: GraphOp[]
56
+ /** Recoverable problems reported back to the model. */
57
+ errors: string[]
58
+ }
59
+
60
+ /** Limits applied while normalizing model input. */
61
+ export interface GraphLimits {
62
+ maxNodeContentChars: number
63
+ maxNodes: number
64
+ }
65
+
66
+ const ID_PATTERN = /^[A-Za-z][\w.-]{0,39}$/
67
+ const ID_PREFIX: Record<string, string> = { goal: 'g', subgoal: 's', finding: 'f', hypothesis: 'h', plan: 'p', answer: 'a', lead: 'l', deadend: 'd' }
68
+
69
+ /** Own-property node lookup, safe against ids like `constructor`. */
70
+ export function getNode(state: GraphState, id: string): GraphNode | undefined {
71
+ return Object.hasOwn(state.nodes, id) ? state.nodes[id] : undefined
72
+ }
73
+
74
+ function setNode(state: GraphState, id: string, node: GraphNode): void {
75
+ state.nodes[id] = node
76
+ }
77
+
78
+ /** A deep copy that later operations may mutate. */
79
+ export function cloneGraph(state: GraphState): GraphState {
80
+ return { nodes: { ...state.nodes }, order: [...state.order] }
81
+ }
82
+
83
+ /** An empty working graph. */
84
+ export function emptyGraph(): GraphState {
85
+ return { nodes: {}, order: [] }
86
+ }
87
+
88
+ function clean(value: string | undefined, max: number): string | undefined {
89
+ if (value === undefined) return undefined
90
+ const text = value.trim()
91
+ if (text.length === 0) return undefined
92
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`
93
+ }
94
+
95
+ function cleanAttr(value: string | undefined): string | undefined {
96
+ return clean(value?.replace(/\s+/g, ' '), 60)
97
+ }
98
+
99
+ function freshId(state: GraphState, type: string): string {
100
+ const prefix = ID_PREFIX[type] ?? 'n'
101
+ let i = 1
102
+ while (Object.hasOwn(state.nodes, `${prefix}${i}`)) i += 1
103
+ return `${prefix}${i}`
104
+ }
105
+
106
+ function liveCount(state: GraphState): number {
107
+ let count = 0
108
+ for (const node of Object.values(state.nodes)) if (!node.removed) count += 1
109
+ return count
110
+ }
111
+
112
+ /**
113
+ * Apply model operations, mutating `state`. Invalid operations are skipped and
114
+ * reported; valid ones are normalized (fresh ids assigned, unknown parents
115
+ * dropped) so replaying `applied` reproduces exactly the same state.
116
+ * @param state - graph to mutate.
117
+ * @param ops - operations in model order.
118
+ * @param limits - content and size limits.
119
+ * @returns normalized applied operations and recoverable errors.
120
+ */
121
+ export function applyGraphOps(state: GraphState, ops: readonly GraphOpInput[], limits: GraphLimits): GraphApplyResult {
122
+ const applied: GraphOp[] = []
123
+ const errors: string[] = []
124
+ const filterParents = (id: string, parents: readonly string[] | undefined): string[] => {
125
+ const out: string[] = []
126
+ for (const raw of parents ?? []) {
127
+ const parent = raw.trim()
128
+ if (parent.length === 0 || parent === id || out.includes(parent)) continue
129
+ if (!Object.hasOwn(state.nodes, parent)) {
130
+ errors.push(`${id}: parent "${parent}" does not exist; dropped`)
131
+ continue
132
+ }
133
+ out.push(parent)
134
+ }
135
+ return out
136
+ }
137
+ for (const input of ops) {
138
+ const id = input.id?.trim() ?? ''
139
+ if (id.length > 0 && !ID_PATTERN.test(id)) {
140
+ errors.push(`${input.op} "${id}": ids are 1-40 chars of letters, digits, '_', '.', '-' and start with a letter`)
141
+ continue
142
+ }
143
+ const content = clean(input.content, limits.maxNodeContentChars)
144
+ const status = cleanAttr(input.status)
145
+ const type = cleanAttr(input.type)
146
+ switch (input.op) {
147
+ case 'add': {
148
+ const existing = id.length > 0 ? getNode(state, id) : undefined
149
+ if (existing !== undefined) {
150
+ // Self-Context treats add-on-existing-id as a revision that keeps references.
151
+ if (content === undefined && status === undefined) {
152
+ errors.push(`add "${id}": id already exists and there is nothing to revise`)
153
+ continue
154
+ }
155
+ if (existing.removed) {
156
+ applied.push(applyOne(state, { op: 'restore', id }))
157
+ errors.push(`add "${id}": id was removed earlier; restored and revised`)
158
+ } else {
159
+ errors.push(`add "${id}": id already exists; applied as an edit`)
160
+ }
161
+ applied.push(applyOne(state, { op: 'edit', id, ...content === undefined ? {} : { content }, ...status === undefined ? {} : { status } }))
162
+ continue
163
+ }
164
+ if (content === undefined) {
165
+ errors.push(`add "${id || '?'}": content is required`)
166
+ continue
167
+ }
168
+ if (liveCount(state) >= limits.maxNodes) {
169
+ errors.push(`add "${id || '?'}": the graph already holds ${limits.maxNodes} nodes; remove or merge some first`)
170
+ continue
171
+ }
172
+ const nodeType = type ?? 'note'
173
+ const nodeId = id.length > 0 ? id : freshId(state, nodeType)
174
+ const parents = filterParents(nodeId, input.parents)
175
+ applied.push(applyOne(state, {
176
+ op: 'add', id: nodeId, type: nodeType, content,
177
+ ...status === undefined ? {} : { status },
178
+ ...parents.length > 0 ? { parents } : {},
179
+ }))
180
+ continue
181
+ }
182
+ case 'edit': {
183
+ const node = getNode(state, id)
184
+ if (node === undefined) {
185
+ errors.push(`edit "${id}": no such node`)
186
+ continue
187
+ }
188
+ if (content === undefined && status === undefined && type === undefined) {
189
+ errors.push(`edit "${id}": nothing to change`)
190
+ continue
191
+ }
192
+ if (node.removed) applied.push(applyOne(state, { op: 'restore', id }))
193
+ applied.push(applyOne(state, {
194
+ op: 'edit', id,
195
+ ...content === undefined ? {} : { content },
196
+ ...status === undefined ? {} : { status },
197
+ ...type === undefined ? {} : { type },
198
+ }))
199
+ continue
200
+ }
201
+ case 'link': {
202
+ if (getNode(state, id) === undefined) {
203
+ errors.push(`link "${id}": no such node`)
204
+ continue
205
+ }
206
+ const parents = filterParents(id, input.parents)
207
+ if (parents.length === 0) {
208
+ errors.push(`link "${id}": no valid parents given`)
209
+ continue
210
+ }
211
+ applied.push(applyOne(state, { op: 'link', id, parents }))
212
+ continue
213
+ }
214
+ case 'remove': {
215
+ const node = getNode(state, id)
216
+ if (node === undefined || node.removed) {
217
+ errors.push(`remove "${id}": no such live node`)
218
+ continue
219
+ }
220
+ applied.push(applyOne(state, { op: 'remove', id }))
221
+ continue
222
+ }
223
+ default:
224
+ errors.push(`unknown op "${String((input as { op: unknown }).op)}"`)
225
+ }
226
+ }
227
+ return { applied, errors }
228
+ }
229
+
230
+ /**
231
+ * Apply one already-normalized operation. Used for live application and replay.
232
+ * @param state - graph to mutate.
233
+ * @param op - normalized operation.
234
+ * @returns the same operation, for chaining into an applied list.
235
+ */
236
+ export function applyOne(state: GraphState, op: GraphOp): GraphOp {
237
+ const node = getNode(state, op.id)
238
+ switch (op.op) {
239
+ case 'add':
240
+ setNode(state, op.id, {
241
+ id: op.id, type: op.type ?? 'note', content: op.content ?? '',
242
+ ...op.status === undefined ? {} : { status: op.status },
243
+ parents: [...op.parents ?? []], v: 1, removed: false,
244
+ })
245
+ state.order.push(op.id)
246
+ break
247
+ case 'edit':
248
+ if (node === undefined) break
249
+ setNode(state, op.id, {
250
+ ...node,
251
+ ...op.content === undefined ? {} : { content: op.content },
252
+ ...op.status === undefined ? {} : { status: op.status },
253
+ ...op.type === undefined ? {} : { type: op.type },
254
+ v: node.v + 1,
255
+ })
256
+ break
257
+ case 'link':
258
+ if (node === undefined) break
259
+ setNode(state, op.id, { ...node, parents: [...new Set([...node.parents, ...op.parents ?? []])], v: node.v + 1 })
260
+ break
261
+ case 'remove':
262
+ if (node === undefined) break
263
+ setNode(state, op.id, { ...node, removed: true, v: node.v + 1 })
264
+ break
265
+ case 'restore':
266
+ if (node === undefined) break
267
+ setNode(state, op.id, { ...node, removed: false, v: node.v + 1 })
268
+ break
269
+ }
270
+ return op
271
+ }
272
+
273
+ /**
274
+ * Rebuild a graph from persisted operation batches.
275
+ * @param batches - `ops` arrays of `self-context/graph` events in log order.
276
+ * @returns the reconstructed graph.
277
+ */
278
+ export function replayGraph(batches: Iterable<readonly GraphOp[]>): GraphState {
279
+ const state = emptyGraph()
280
+ for (const ops of batches) for (const op of ops) applyOne(state, op)
281
+ return state
282
+ }
283
+
284
+ function attr(value: string): string {
285
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/\n/g, ' ')
286
+ }
287
+
288
+ function body(value: string): string {
289
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;')
290
+ }
291
+
292
+ /**
293
+ * Serialize live nodes in creation order, in the same `<node>` vocabulary the
294
+ * model writes with. Tombstoned nodes are omitted.
295
+ * @param state - graph to render.
296
+ * @returns XML-ish text, or an empty string for an empty graph.
297
+ */
298
+ export function serializeGraph(state: GraphState): string {
299
+ const lines: string[] = []
300
+ for (const id of state.order) {
301
+ const node = getNode(state, id)
302
+ if (node === undefined || node.removed) continue
303
+ const parts = [`id="${attr(node.id)}"`, `type="${attr(node.type)}"`]
304
+ if (node.parents.length > 0) parts.push(`parents="${attr(node.parents.join(','))}"`)
305
+ if (node.status !== undefined) parts.push(`status="${attr(node.status)}"`)
306
+ if (node.v > 1) parts.push(`v="${node.v}"`)
307
+ lines.push(` <node ${parts.join(' ')}>${body(node.content)}</node>`)
308
+ }
309
+ return lines.length === 0 ? '' : `<graph>\n${lines.join('\n')}\n</graph>`
310
+ }
package/src/index.ts ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Self-Context for DeepSeek Harness: graph-based context self-management
3
+ * (Wang et al., arXiv:2612.01681) as an in-process dsh plugin.
4
+ *
5
+ * - `context_graph` edits the working graph G_t; the latest graph is shown to the
6
+ * model as dynamic session context and survives folds and compaction.
7
+ * - `context_history` lists, folds and unfolds whole interaction steps, building
8
+ * the critical history F_t; folds are logged message projections, so the raw
9
+ * history H_t stays in the session log and unfold is lossless.
10
+ *
11
+ * @module dsh-self-context
12
+ */
13
+
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import Schema from '@deepseek-ai/schemastery'
16
+ import type { Session } from '@deepseek-ai/dsh-session'
17
+ import type {} from '@deepseek-ai/dsh-agent'
18
+ import type {} from '@deepseek-ai/dsh-session-projection'
19
+ import type {} from '@deepseek-ai/dsh-system-prompt'
20
+ import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
21
+ import { applyGraphOps, cloneGraph, GRAPH_OPS, type GraphOpInput, type GraphState, serializeGraph } from './graph.ts'
22
+ import { parseStepLabel, selfContextProjections, type StepRef, stepLabel } from './projection.ts'
23
+ import { GRAPH_CONTEXT_HEADER, PROTOCOL } from './prompt.ts'
24
+ import {
25
+ applyGraphEvent, applyStepEvent, emptyGraph, emptySteps, graphStateSchema, type StepInfo, type StepsState, stepsStateSchema,
26
+ } from './state.ts'
27
+
28
+ export * from './graph.ts'
29
+ export * from './projection.ts'
30
+ export { GRAPH_CONTEXT_HEADER, PROTOCOL } from './prompt.ts'
31
+
32
+ export const name = 'self-context'
33
+ export const inject = ['tools', 'sessions', 'sessionProjections', 'systemPrompt']
34
+
35
+ export const GRAPH_TOOL = 'context_graph'
36
+ export const HISTORY_TOOL = 'context_history'
37
+
38
+ /** Plugin configuration. */
39
+ export interface Config {
40
+ /** Register the protocol instructions as a system-prompt section. */
41
+ instructions: boolean
42
+ /** Prompt-section order of the instructions. */
43
+ instructionsOrder: number
44
+ /** Show the working graph as dynamic session context. */
45
+ showGraph: boolean
46
+ /** Order of the graph among dynamic session contexts. */
47
+ graphContextOrder: number
48
+ /** Maximum characters kept per node. */
49
+ maxNodeContentChars: number
50
+ /** Maximum live nodes. */
51
+ maxNodes: number
52
+ /** Maximum characters of one fold summary. */
53
+ maxSummaryChars: number
54
+ }
55
+
56
+ export const Config: Schema<Config> = Schema.object({
57
+ instructions: Schema.boolean().default(true).description('Add the Self-Context protocol to the system prompt.'),
58
+ instructionsOrder: Schema.number().default(9000).description('System-prompt section order of the protocol.'),
59
+ showGraph: Schema.boolean().default(true).description('Show the working graph to the model as session context.'),
60
+ graphContextOrder: Schema.number().default(9000).description('Runtime-context order of the graph.'),
61
+ maxNodeContentChars: Schema.natural().min(20).default(1000).description('Maximum characters per graph node.'),
62
+ maxNodes: Schema.natural().min(1).default(200).description('Maximum live graph nodes.'),
63
+ maxSummaryChars: Schema.natural().min(20).default(400).description('Maximum characters per fold summary.'),
64
+ })
65
+
66
+ function requireSession(exec: { agent?: { session: Session } }, tool: string): Session {
67
+ if (exec.agent === undefined) throw new ToolArgsError([`${tool} can only be called by an agent with a session`])
68
+ return exec.agent.session
69
+ }
70
+
71
+ /** The projection-registry surface shared by dsh 0.2.2 (sync disposer) and 0.2.3+ (awaitable handle). */
72
+ interface ProjectionRegistry {
73
+ register(definition: unknown): unknown
74
+ stateOf(session: Session, key: string): unknown
75
+ }
76
+
77
+ /**
78
+ * Register a host-only projection unit and return a reader for its state.
79
+ * dsh 0.2.2 returns a disposer and 0.2.3 an awaitable handle; both expose
80
+ * `stateOf(session, key)`, so the reader uses that.
81
+ * @param ctx - plugin context.
82
+ * @param definition - projection unit.
83
+ * @returns a state reader that falls back to the empty state.
84
+ */
85
+ async function registerUnit<S>(
86
+ ctx: Context,
87
+ definition: { key: string; init: () => S; apply: (state: S, event: never) => S; stateSchema: unknown; stateVersion: number },
88
+ ): Promise<(session: Session) => S> {
89
+ const registry = ctx.sessionProjections as unknown as ProjectionRegistry
90
+ await registry.register(definition)
91
+ return session => (registry.stateOf(session, definition.key) as S | undefined) ?? definition.init()
92
+ }
93
+
94
+ function formatK(chars: number): string {
95
+ return chars < 1000 ? `${chars} chars` : `${(chars / 1000).toFixed(1)}k chars`
96
+ }
97
+
98
+ /**
99
+ * Render the steps still on the surface.
100
+ * @param steps - step index.
101
+ * @param onSurface - current surface sequences.
102
+ * @returns one line per step.
103
+ */
104
+ export function renderStepList(steps: StepsState, onSurface: ReadonlySet<number>): string {
105
+ const lines: string[] = []
106
+ let raw = 0
107
+ for (const label of steps.order) {
108
+ const info = steps.steps[label]
109
+ if (info === undefined || !onSurface.has(info.assistantSeq)) continue
110
+ if (info.folded !== undefined) {
111
+ lines.push(`${label} [folded] ${info.folded}`)
112
+ continue
113
+ }
114
+ raw += info.chars
115
+ const calls = info.calls.length === 0 ? '(reply only)' : info.calls.join('; ')
116
+ lines.push(`${label} ${formatK(info.chars)} ${calls}${info.pending.length > 0 ? ' [running]' : ''}`)
117
+ }
118
+ if (lines.length === 0) return 'No steps are in context yet.'
119
+ return `Steps in context (turn.step), ${formatK(raw)} unfolded:\n${lines.join('\n')}`
120
+ }
121
+
122
+ /**
123
+ * Mount the working graph, history tools, projections and prompt contributions.
124
+ * @param ctx - plugin context.
125
+ * @param config - validated configuration.
126
+ */
127
+ export async function apply(ctx: Context, config: Config): Promise<void> {
128
+ for (const projection of selfContextProjections) ctx.sessions.registerMessageProjection(projection)
129
+
130
+ const graphOf = await registerUnit<GraphState>(ctx, {
131
+ key: 'selfContext.graph',
132
+ stateSchema: graphStateSchema,
133
+ init: emptyGraph,
134
+ apply: applyGraphEvent,
135
+ stateVersion: 1,
136
+ })
137
+ const stepsOf = await registerUnit<StepsState>(ctx, {
138
+ key: 'selfContext.steps',
139
+ stateSchema: stepsStateSchema,
140
+ init: emptySteps,
141
+ apply: applyStepEvent,
142
+ stateVersion: 1,
143
+ })
144
+
145
+ if (config.instructions) {
146
+ ctx.systemPrompt.section({ name: 'self-context:protocol', order: config.instructionsOrder, text: PROTOCOL, interpolate: false })
147
+ }
148
+ if (config.showGraph) {
149
+ ctx.systemPrompt.context({
150
+ name: 'self-context:graph',
151
+ order: config.graphContextOrder,
152
+ required: true,
153
+ interpolate: false,
154
+ // The agent being assembled for carries its session (absent on diagnostics).
155
+ text: ({ agent }) => {
156
+ const session = agent?.session
157
+ if (session === undefined) return ''
158
+ const graph = serializeGraph(graphOf(session))
159
+ return graph === '' ? '' : `${GRAPH_CONTEXT_HEADER}\n${graph}`
160
+ },
161
+ })
162
+ }
163
+
164
+ ctx.tools.register(defineTool({
165
+ name: GRAPH_TOOL,
166
+ description:
167
+ 'Edit your working graph: the durable record of goals, findings, hypotheses, plans, dead ends and your current answer. '
168
+ + 'It stays visible after old steps are folded or compacted. Send only the changes.',
169
+ parameters: {
170
+ ops: {
171
+ type: 'array',
172
+ required: true,
173
+ description: 'Changes to apply in order.',
174
+ items: {
175
+ type: 'object',
176
+ additionalProperties: false,
177
+ properties: {
178
+ op: { type: 'string', required: true, enum: [...GRAPH_OPS], description: 'add | edit | link | remove' },
179
+ id: { type: 'string', description: 'Node id, e.g. "f3". Optional on add (generated); required otherwise.' },
180
+ type: { type: 'string', description: 'goal, subgoal, finding, hypothesis, plan, lead, deadend, answer, …' },
181
+ content: { type: 'string', description: 'One line: what was established and where (file:line, command, URL).' },
182
+ status: { type: 'string', description: 'e.g. pending, active, done, failed.' },
183
+ parents: { type: 'array', items: { type: 'string' }, description: 'Ids this node rests on (add, link).' },
184
+ },
185
+ },
186
+ },
187
+ },
188
+ output: {
189
+ schema: {
190
+ type: 'object',
191
+ additionalProperties: false,
192
+ properties: {
193
+ applied: { type: 'integer', required: true },
194
+ nodes: { type: 'integer', required: true },
195
+ errors: { type: 'array', required: true, items: { type: 'string' } },
196
+ graph: { type: 'string', required: true },
197
+ },
198
+ },
199
+ // Runtime context is refreshed only when a user message is admitted, so within
200
+ // a long turn this result is how the model sees the current graph and its ids.
201
+ render: (_args, value) => [{
202
+ type: 'text',
203
+ text: `Graph updated: ${value.applied} change(s) applied, ${value.nodes} live node(s).`
204
+ + (value.errors.length > 0 ? `\nProblems:\n- ${value.errors.join('\n- ')}` : '')
205
+ + (value.graph === '' ? '' : `\nCurrent graph:\n${value.graph}`),
206
+ }],
207
+ },
208
+ execute(args, exec) {
209
+ const session = requireSession(exec, GRAPH_TOOL)
210
+ if (args.ops.length === 0) throw new ToolArgsError(['ops must contain at least one operation'])
211
+ const draft = cloneGraph(graphOf(session))
212
+ const { applied, errors } = applyGraphOps(draft, args.ops as GraphOpInput[], config)
213
+ if (applied.length > 0) session.append('self-context/graph', { ops: applied })
214
+ const nodes = Object.values(draft.nodes).filter(node => !node.removed).length
215
+ return Promise.resolve({ applied: applied.length, nodes, errors, graph: serializeGraph(draft) })
216
+ },
217
+ presentCall: args => ({ card: 'generic', title: 'Update working graph', kind: 'other', rawInput: args.ops }),
218
+ }))
219
+
220
+ ctx.tools.register(defineTool({
221
+ name: HISTORY_TOOL,
222
+ description:
223
+ 'Manage your own conversation history. "list" shows steps (turn.step) in context; "fold" replaces finished steps '
224
+ + 'with your one-line summary to free context; "unfold" restores folded steps exactly.',
225
+ parameters: {
226
+ op: { type: 'string', required: true, enum: ['list', 'fold', 'unfold'] },
227
+ steps: { type: 'array', items: { type: 'string' }, description: 'Step labels like "3.2" (fold, unfold).' },
228
+ summary: { type: 'string', description: 'fold only: one line saying what the folded steps showed.' },
229
+ },
230
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
231
+ execute(args, exec) {
232
+ const session = requireSession(exec, HISTORY_TOOL)
233
+ const index = stepsOf(session)
234
+ const onSurface = new Set<number>(session.surface.nodes)
235
+ if (args.op === 'list') return Promise.resolve(renderStepList(index, onSurface))
236
+
237
+ const labels = args.steps ?? []
238
+ if (labels.length === 0) throw new ToolArgsError([`${args.op} needs steps, e.g. ["3.2"]`])
239
+ const refs: StepRef[] = []
240
+ const problems: string[] = []
241
+ for (const label of labels) {
242
+ const ref = parseStepLabel(label)
243
+ const info: StepInfo | undefined = ref === undefined ? undefined : index.steps[stepLabel(ref)]
244
+ if (ref === undefined) problems.push(`"${label}" is not a turn.step label`)
245
+ else if (info === undefined || !onSurface.has(info.assistantSeq)) problems.push(`step ${label} is not in context`)
246
+ else if (refs.some(seen => stepLabel(seen) === stepLabel(ref))) problems.push(`step ${label} is listed twice`)
247
+ else if (args.op === 'fold' && info.folded !== undefined) problems.push(`step ${label} is already folded`)
248
+ else if (args.op === 'fold' && info.pending.length > 0) problems.push(`step ${label} is still running`)
249
+ else if (args.op === 'unfold' && info.folded === undefined) problems.push(`step ${label} is not folded`)
250
+ else refs.push(ref)
251
+ }
252
+ if (problems.length > 0) throw new ToolArgsError(problems)
253
+
254
+ if (args.op === 'unfold') {
255
+ session.append('self-context/unfold', { steps: refs })
256
+ return Promise.resolve(`Unfolded ${refs.map(stepLabel).join(', ')}; the original steps are back in context.`)
257
+ }
258
+ const summary = (args.summary ?? '').replace(/\s+/g, ' ').trim()
259
+ if (summary.length === 0) throw new ToolArgsError(['fold needs a one-line summary of what the steps showed'])
260
+ const bounded = summary.length <= config.maxSummaryChars ? summary : `${summary.slice(0, config.maxSummaryChars - 1)}…`
261
+ const freed = refs.reduce((total, ref) => total + (index.steps[stepLabel(ref)]?.chars ?? 0), 0)
262
+ session.append('self-context/fold', { steps: refs, summary: bounded })
263
+ return Promise.resolve(`Folded ${refs.map(stepLabel).join(', ')} (about ${formatK(freed)} hidden). Unfold restores them.`)
264
+ },
265
+ presentCall: args => ({
266
+ card: 'generic',
267
+ title: args.op === 'list' ? 'List context steps' : `${args.op === 'fold' ? 'Fold' : 'Unfold'} ${(args.steps ?? []).join(', ')}`,
268
+ kind: 'other',
269
+ }),
270
+ }))
271
+ }