dsh-self-context 0.0.0-stage → 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.
- package/LICENSE +202 -0
- package/README.md +122 -2
- package/cordis.patch.yml +11 -0
- package/lib/graph.d.ts +103 -0
- package/lib/graph.js +304 -0
- package/lib/index.d.ts +53 -0
- package/lib/index.js +246 -0
- package/lib/projection.d.ts +92 -0
- package/lib/projection.js +184 -0
- package/lib/prompt.d.ts +9 -0
- package/lib/prompt.js +28 -0
- package/lib/state.d.ts +52 -0
- package/lib/state.js +130 -0
- package/package.json +77 -3
- package/src/graph.ts +353 -0
- package/src/index.ts +279 -0
- package/src/projection.ts +224 -0
- package/src/prompt.ts +30 -0
- package/src/state.ts +160 -0
package/src/graph.ts
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
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
|
+
/**
|
|
24
|
+
* Read the `ops` a model sent, repairing the two shapes seen from real models:
|
|
25
|
+
* the array sent as a JSON string, and an operation without `op` (an edit
|
|
26
|
+
* when `exists` says its id is a live node, otherwise an add). Returns the
|
|
27
|
+
* operations and the problems that make the call unusable.
|
|
28
|
+
*/
|
|
29
|
+
export function readGraphOps(raw: unknown, exists: (id: string) => boolean = () => false): { ops: GraphOpInput[]; problems: string[] } {
|
|
30
|
+
let value = raw
|
|
31
|
+
if (typeof value === 'string') {
|
|
32
|
+
try {
|
|
33
|
+
value = JSON.parse(value)
|
|
34
|
+
} catch {
|
|
35
|
+
return { ops: [], problems: ['ops must be an array of operations (a JSON string of one was not valid JSON)'] }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(value)) return { ops: [], problems: ['ops must be an array of operations'] }
|
|
39
|
+
const ops: GraphOpInput[] = []
|
|
40
|
+
const problems: string[] = []
|
|
41
|
+
const text = (field: unknown): string | undefined => typeof field === 'string' ? field : typeof field === 'number' ? String(field) : undefined
|
|
42
|
+
value.forEach((item: unknown, index) => {
|
|
43
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
|
|
44
|
+
problems.push(`ops[${index}] must be an object`)
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
const entry = item as Record<string, unknown>
|
|
48
|
+
const id = typeof entry.id === 'string' ? entry.id.trim() : ''
|
|
49
|
+
const op = entry.op !== undefined ? entry.op : id !== '' && exists(id) ? 'edit' : 'add'
|
|
50
|
+
if (typeof op !== 'string' || !(GRAPH_OPS as readonly string[]).includes(op)) {
|
|
51
|
+
problems.push(`ops[${index}].op must be one of ${GRAPH_OPS.join(', ')}`)
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
const parents = Array.isArray(entry.parents) ? entry.parents.map(text).filter((parent): parent is string => parent !== undefined) : undefined
|
|
55
|
+
const out: GraphOpInput = { op: op as GraphOpKind }
|
|
56
|
+
for (const key of ['id', 'type', 'content', 'status'] as const) {
|
|
57
|
+
const field = text(entry[key])
|
|
58
|
+
if (field !== undefined) out[key] = field
|
|
59
|
+
}
|
|
60
|
+
if (parents !== undefined) out.parents = parents
|
|
61
|
+
ops.push(out)
|
|
62
|
+
})
|
|
63
|
+
return { ops, problems }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One normalized operation as persisted in the session log. */
|
|
67
|
+
export interface GraphOp {
|
|
68
|
+
op: GraphOpKind | 'restore'
|
|
69
|
+
id: string
|
|
70
|
+
type?: string
|
|
71
|
+
content?: string
|
|
72
|
+
status?: string
|
|
73
|
+
parents?: string[]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** One node of the working graph. */
|
|
77
|
+
export interface GraphNode {
|
|
78
|
+
id: string
|
|
79
|
+
type: string
|
|
80
|
+
content: string
|
|
81
|
+
status?: string | undefined
|
|
82
|
+
parents: string[]
|
|
83
|
+
/** Monotonic revision number; 1 on creation. */
|
|
84
|
+
v: number
|
|
85
|
+
/** Tombstoned nodes are hidden from the model but kept in history. */
|
|
86
|
+
removed: boolean
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The whole working graph as plain JSON: nodes by id plus creation order. */
|
|
90
|
+
export interface GraphState {
|
|
91
|
+
nodes: Record<string, GraphNode>
|
|
92
|
+
order: string[]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Result of applying one batch of model operations. */
|
|
96
|
+
export interface GraphApplyResult {
|
|
97
|
+
/** Normalized operations that took effect, in order; persist these. */
|
|
98
|
+
applied: GraphOp[]
|
|
99
|
+
/** Recoverable problems reported back to the model. */
|
|
100
|
+
errors: string[]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Limits applied while normalizing model input. */
|
|
104
|
+
export interface GraphLimits {
|
|
105
|
+
maxNodeContentChars: number
|
|
106
|
+
maxNodes: number
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const ID_PATTERN = /^[A-Za-z][\w.-]{0,39}$/
|
|
110
|
+
const ID_PREFIX: Record<string, string> = { goal: 'g', subgoal: 's', finding: 'f', hypothesis: 'h', plan: 'p', answer: 'a', lead: 'l', deadend: 'd' }
|
|
111
|
+
|
|
112
|
+
/** Own-property node lookup, safe against ids like `constructor`. */
|
|
113
|
+
export function getNode(state: GraphState, id: string): GraphNode | undefined {
|
|
114
|
+
return Object.hasOwn(state.nodes, id) ? state.nodes[id] : undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function setNode(state: GraphState, id: string, node: GraphNode): void {
|
|
118
|
+
state.nodes[id] = node
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A deep copy that later operations may mutate. */
|
|
122
|
+
export function cloneGraph(state: GraphState): GraphState {
|
|
123
|
+
return { nodes: { ...state.nodes }, order: [...state.order] }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** An empty working graph. */
|
|
127
|
+
export function emptyGraph(): GraphState {
|
|
128
|
+
return { nodes: {}, order: [] }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function clean(value: string | undefined, max: number): string | undefined {
|
|
132
|
+
if (value === undefined) return undefined
|
|
133
|
+
const text = value.trim()
|
|
134
|
+
if (text.length === 0) return undefined
|
|
135
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function cleanAttr(value: string | undefined): string | undefined {
|
|
139
|
+
return clean(value?.replace(/\s+/g, ' '), 60)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function freshId(state: GraphState, type: string): string {
|
|
143
|
+
const prefix = ID_PREFIX[type] ?? 'n'
|
|
144
|
+
let i = 1
|
|
145
|
+
while (Object.hasOwn(state.nodes, `${prefix}${i}`)) i += 1
|
|
146
|
+
return `${prefix}${i}`
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function liveCount(state: GraphState): number {
|
|
150
|
+
let count = 0
|
|
151
|
+
for (const node of Object.values(state.nodes)) if (!node.removed) count += 1
|
|
152
|
+
return count
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Apply model operations, mutating `state`. Invalid operations are skipped and
|
|
157
|
+
* reported; valid ones are normalized (fresh ids assigned, unknown parents
|
|
158
|
+
* dropped) so replaying `applied` reproduces exactly the same state.
|
|
159
|
+
* @param state - graph to mutate.
|
|
160
|
+
* @param ops - operations in model order.
|
|
161
|
+
* @param limits - content and size limits.
|
|
162
|
+
* @returns normalized applied operations and recoverable errors.
|
|
163
|
+
*/
|
|
164
|
+
export function applyGraphOps(state: GraphState, ops: readonly GraphOpInput[], limits: GraphLimits): GraphApplyResult {
|
|
165
|
+
const applied: GraphOp[] = []
|
|
166
|
+
const errors: string[] = []
|
|
167
|
+
const filterParents = (id: string, parents: readonly string[] | undefined): string[] => {
|
|
168
|
+
const out: string[] = []
|
|
169
|
+
for (const raw of parents ?? []) {
|
|
170
|
+
const parent = raw.trim()
|
|
171
|
+
if (parent.length === 0 || parent === id || out.includes(parent)) continue
|
|
172
|
+
if (!Object.hasOwn(state.nodes, parent)) {
|
|
173
|
+
errors.push(`${id}: parent "${parent}" does not exist; dropped`)
|
|
174
|
+
continue
|
|
175
|
+
}
|
|
176
|
+
out.push(parent)
|
|
177
|
+
}
|
|
178
|
+
return out
|
|
179
|
+
}
|
|
180
|
+
for (const input of ops) {
|
|
181
|
+
const id = input.id?.trim() ?? ''
|
|
182
|
+
if (id.length > 0 && !ID_PATTERN.test(id)) {
|
|
183
|
+
errors.push(`${input.op} "${id}": ids are 1-40 chars of letters, digits, '_', '.', '-' and start with a letter`)
|
|
184
|
+
continue
|
|
185
|
+
}
|
|
186
|
+
const content = clean(input.content, limits.maxNodeContentChars)
|
|
187
|
+
const status = cleanAttr(input.status)
|
|
188
|
+
const type = cleanAttr(input.type)
|
|
189
|
+
switch (input.op) {
|
|
190
|
+
case 'add': {
|
|
191
|
+
const existing = id.length > 0 ? getNode(state, id) : undefined
|
|
192
|
+
if (existing !== undefined) {
|
|
193
|
+
// Self-Context treats add-on-existing-id as a revision that keeps references.
|
|
194
|
+
if (content === undefined && status === undefined) {
|
|
195
|
+
errors.push(`add "${id}": id already exists and there is nothing to revise`)
|
|
196
|
+
continue
|
|
197
|
+
}
|
|
198
|
+
if (existing.removed) {
|
|
199
|
+
applied.push(applyOne(state, { op: 'restore', id }))
|
|
200
|
+
errors.push(`add "${id}": id was removed earlier; restored and revised`)
|
|
201
|
+
} else {
|
|
202
|
+
errors.push(`add "${id}": id already exists; applied as an edit`)
|
|
203
|
+
}
|
|
204
|
+
applied.push(applyOne(state, { op: 'edit', id, ...content === undefined ? {} : { content }, ...status === undefined ? {} : { status } }))
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (content === undefined) {
|
|
208
|
+
errors.push(`add "${id || '?'}": content is required`)
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
if (liveCount(state) >= limits.maxNodes) {
|
|
212
|
+
errors.push(`add "${id || '?'}": the graph already holds ${limits.maxNodes} nodes; remove or merge some first`)
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
const nodeType = type ?? 'note'
|
|
216
|
+
const nodeId = id.length > 0 ? id : freshId(state, nodeType)
|
|
217
|
+
const parents = filterParents(nodeId, input.parents)
|
|
218
|
+
applied.push(applyOne(state, {
|
|
219
|
+
op: 'add', id: nodeId, type: nodeType, content,
|
|
220
|
+
...status === undefined ? {} : { status },
|
|
221
|
+
...parents.length > 0 ? { parents } : {},
|
|
222
|
+
}))
|
|
223
|
+
continue
|
|
224
|
+
}
|
|
225
|
+
case 'edit': {
|
|
226
|
+
const node = getNode(state, id)
|
|
227
|
+
if (node === undefined) {
|
|
228
|
+
errors.push(`edit "${id}": no such node`)
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
if (content === undefined && status === undefined && type === undefined) {
|
|
232
|
+
errors.push(`edit "${id}": nothing to change`)
|
|
233
|
+
continue
|
|
234
|
+
}
|
|
235
|
+
if (node.removed) applied.push(applyOne(state, { op: 'restore', id }))
|
|
236
|
+
applied.push(applyOne(state, {
|
|
237
|
+
op: 'edit', id,
|
|
238
|
+
...content === undefined ? {} : { content },
|
|
239
|
+
...status === undefined ? {} : { status },
|
|
240
|
+
...type === undefined ? {} : { type },
|
|
241
|
+
}))
|
|
242
|
+
continue
|
|
243
|
+
}
|
|
244
|
+
case 'link': {
|
|
245
|
+
if (getNode(state, id) === undefined) {
|
|
246
|
+
errors.push(`link "${id}": no such node`)
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
const parents = filterParents(id, input.parents)
|
|
250
|
+
if (parents.length === 0) {
|
|
251
|
+
errors.push(`link "${id}": no valid parents given`)
|
|
252
|
+
continue
|
|
253
|
+
}
|
|
254
|
+
applied.push(applyOne(state, { op: 'link', id, parents }))
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
case 'remove': {
|
|
258
|
+
const node = getNode(state, id)
|
|
259
|
+
if (node === undefined || node.removed) {
|
|
260
|
+
errors.push(`remove "${id}": no such live node`)
|
|
261
|
+
continue
|
|
262
|
+
}
|
|
263
|
+
applied.push(applyOne(state, { op: 'remove', id }))
|
|
264
|
+
continue
|
|
265
|
+
}
|
|
266
|
+
default:
|
|
267
|
+
errors.push(`unknown op "${String((input as { op: unknown }).op)}"`)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return { applied, errors }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Apply one already-normalized operation. Used for live application and replay.
|
|
275
|
+
* @param state - graph to mutate.
|
|
276
|
+
* @param op - normalized operation.
|
|
277
|
+
* @returns the same operation, for chaining into an applied list.
|
|
278
|
+
*/
|
|
279
|
+
export function applyOne(state: GraphState, op: GraphOp): GraphOp {
|
|
280
|
+
const node = getNode(state, op.id)
|
|
281
|
+
switch (op.op) {
|
|
282
|
+
case 'add':
|
|
283
|
+
setNode(state, op.id, {
|
|
284
|
+
id: op.id, type: op.type ?? 'note', content: op.content ?? '',
|
|
285
|
+
...op.status === undefined ? {} : { status: op.status },
|
|
286
|
+
parents: [...op.parents ?? []], v: 1, removed: false,
|
|
287
|
+
})
|
|
288
|
+
state.order.push(op.id)
|
|
289
|
+
break
|
|
290
|
+
case 'edit':
|
|
291
|
+
if (node === undefined) break
|
|
292
|
+
setNode(state, op.id, {
|
|
293
|
+
...node,
|
|
294
|
+
...op.content === undefined ? {} : { content: op.content },
|
|
295
|
+
...op.status === undefined ? {} : { status: op.status },
|
|
296
|
+
...op.type === undefined ? {} : { type: op.type },
|
|
297
|
+
v: node.v + 1,
|
|
298
|
+
})
|
|
299
|
+
break
|
|
300
|
+
case 'link':
|
|
301
|
+
if (node === undefined) break
|
|
302
|
+
setNode(state, op.id, { ...node, parents: [...new Set([...node.parents, ...op.parents ?? []])], v: node.v + 1 })
|
|
303
|
+
break
|
|
304
|
+
case 'remove':
|
|
305
|
+
if (node === undefined) break
|
|
306
|
+
setNode(state, op.id, { ...node, removed: true, v: node.v + 1 })
|
|
307
|
+
break
|
|
308
|
+
case 'restore':
|
|
309
|
+
if (node === undefined) break
|
|
310
|
+
setNode(state, op.id, { ...node, removed: false, v: node.v + 1 })
|
|
311
|
+
break
|
|
312
|
+
}
|
|
313
|
+
return op
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Rebuild a graph from persisted operation batches.
|
|
318
|
+
* @param batches - `ops` arrays of `self-context/graph` events in log order.
|
|
319
|
+
* @returns the reconstructed graph.
|
|
320
|
+
*/
|
|
321
|
+
export function replayGraph(batches: Iterable<readonly GraphOp[]>): GraphState {
|
|
322
|
+
const state = emptyGraph()
|
|
323
|
+
for (const ops of batches) for (const op of ops) applyOne(state, op)
|
|
324
|
+
return state
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function attr(value: string): string {
|
|
328
|
+
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/\n/g, ' ')
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function body(value: string): string {
|
|
332
|
+
return value.replace(/&/g, '&').replace(/</g, '<')
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Serialize live nodes in creation order, in the same `<node>` vocabulary the
|
|
337
|
+
* model writes with. Tombstoned nodes are omitted.
|
|
338
|
+
* @param state - graph to render.
|
|
339
|
+
* @returns XML-ish text, or an empty string for an empty graph.
|
|
340
|
+
*/
|
|
341
|
+
export function serializeGraph(state: GraphState): string {
|
|
342
|
+
const lines: string[] = []
|
|
343
|
+
for (const id of state.order) {
|
|
344
|
+
const node = getNode(state, id)
|
|
345
|
+
if (node === undefined || node.removed) continue
|
|
346
|
+
const parts = [`id="${attr(node.id)}"`, `type="${attr(node.type)}"`]
|
|
347
|
+
if (node.parents.length > 0) parts.push(`parents="${attr(node.parents.join(','))}"`)
|
|
348
|
+
if (node.status !== undefined) parts.push(`status="${attr(node.status)}"`)
|
|
349
|
+
if (node.v > 1) parts.push(`v="${node.v}"`)
|
|
350
|
+
lines.push(` <node ${parts.join(' ')}>${body(node.content)}</node>`)
|
|
351
|
+
}
|
|
352
|
+
return lines.length === 0 ? '' : `<graph>\n${lines.join('\n')}\n</graph>`
|
|
353
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
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, getNode, GRAPH_OPS, type GraphState, readGraphOps, 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
|
+
required: true,
|
|
172
|
+
description: 'Changes to apply in order.',
|
|
173
|
+
// Some models send the array as a JSON string; readGraphOps accepts both.
|
|
174
|
+
oneOf: [
|
|
175
|
+
{
|
|
176
|
+
type: 'array',
|
|
177
|
+
items: {
|
|
178
|
+
type: 'object',
|
|
179
|
+
additionalProperties: false,
|
|
180
|
+
properties: {
|
|
181
|
+
op: { type: 'string', enum: [...GRAPH_OPS], description: 'add | edit | link | remove. Omitted: edit when the id exists, otherwise add.' },
|
|
182
|
+
id: { type: 'string', description: 'Node id, e.g. "f3". Optional on add (generated); required otherwise.' },
|
|
183
|
+
type: { type: 'string', description: 'goal, subgoal, finding, hypothesis, plan, lead, deadend, answer, …' },
|
|
184
|
+
content: { type: 'string', description: 'One line: what was established and where (file:line, command, URL).' },
|
|
185
|
+
status: { type: 'string', description: 'e.g. pending, active, done, failed.' },
|
|
186
|
+
parents: { type: 'array', items: { type: 'string' }, description: 'Ids this node rests on (add, link).' },
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
{ type: 'string', description: 'The same array as JSON text.' },
|
|
191
|
+
],
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
output: {
|
|
195
|
+
schema: {
|
|
196
|
+
type: 'object',
|
|
197
|
+
additionalProperties: false,
|
|
198
|
+
properties: {
|
|
199
|
+
applied: { type: 'integer', required: true },
|
|
200
|
+
nodes: { type: 'integer', required: true },
|
|
201
|
+
errors: { type: 'array', required: true, items: { type: 'string' } },
|
|
202
|
+
graph: { type: 'string', required: true },
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
// Runtime context is refreshed only when a user message is admitted, so within
|
|
206
|
+
// a long turn this result is how the model sees the current graph and its ids.
|
|
207
|
+
render: (_args, value) => [{
|
|
208
|
+
type: 'text',
|
|
209
|
+
text: `Graph updated: ${value.applied} change(s) applied, ${value.nodes} live node(s).`
|
|
210
|
+
+ (value.errors.length > 0 ? `\nProblems:\n- ${value.errors.join('\n- ')}` : '')
|
|
211
|
+
+ (value.graph === '' ? '' : `\nCurrent graph:\n${value.graph}`),
|
|
212
|
+
}],
|
|
213
|
+
},
|
|
214
|
+
execute(args, exec) {
|
|
215
|
+
const session = requireSession(exec, GRAPH_TOOL)
|
|
216
|
+
const draft = cloneGraph(graphOf(session))
|
|
217
|
+
const { ops, problems } = readGraphOps(args.ops, id => getNode(draft, id)?.removed === false)
|
|
218
|
+
if (problems.length > 0) throw new ToolArgsError(problems)
|
|
219
|
+
if (ops.length === 0) throw new ToolArgsError(['ops must contain at least one operation'])
|
|
220
|
+
const { applied, errors } = applyGraphOps(draft, ops, config)
|
|
221
|
+
if (applied.length > 0) session.append('self-context/graph', { ops: applied })
|
|
222
|
+
const nodes = Object.values(draft.nodes).filter(node => !node.removed).length
|
|
223
|
+
return Promise.resolve({ applied: applied.length, nodes, errors, graph: serializeGraph(draft) })
|
|
224
|
+
},
|
|
225
|
+
presentCall: args => ({ card: 'generic', title: 'Update working graph', kind: 'other', rawInput: readGraphOps(args.ops).ops }),
|
|
226
|
+
}))
|
|
227
|
+
|
|
228
|
+
ctx.tools.register(defineTool({
|
|
229
|
+
name: HISTORY_TOOL,
|
|
230
|
+
description:
|
|
231
|
+
'Manage your own conversation history. "list" shows steps (turn.step) in context; "fold" replaces finished steps '
|
|
232
|
+
+ 'with your one-line summary to free context; "unfold" restores folded steps exactly.',
|
|
233
|
+
parameters: {
|
|
234
|
+
op: { type: 'string', required: true, enum: ['list', 'fold', 'unfold'] },
|
|
235
|
+
steps: { type: 'array', items: { type: 'string' }, description: 'Step labels like "3.2" (fold, unfold).' },
|
|
236
|
+
summary: { type: 'string', description: 'fold only: one line saying what the folded steps showed.' },
|
|
237
|
+
},
|
|
238
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
239
|
+
execute(args, exec) {
|
|
240
|
+
const session = requireSession(exec, HISTORY_TOOL)
|
|
241
|
+
const index = stepsOf(session)
|
|
242
|
+
const onSurface = new Set<number>(session.surface.nodes)
|
|
243
|
+
if (args.op === 'list') return Promise.resolve(renderStepList(index, onSurface))
|
|
244
|
+
|
|
245
|
+
const labels = args.steps ?? []
|
|
246
|
+
if (labels.length === 0) throw new ToolArgsError([`${args.op} needs steps, e.g. ["3.2"]`])
|
|
247
|
+
const refs: StepRef[] = []
|
|
248
|
+
const problems: string[] = []
|
|
249
|
+
for (const label of labels) {
|
|
250
|
+
const ref = parseStepLabel(label)
|
|
251
|
+
const info: StepInfo | undefined = ref === undefined ? undefined : index.steps[stepLabel(ref)]
|
|
252
|
+
if (ref === undefined) problems.push(`"${label}" is not a turn.step label`)
|
|
253
|
+
else if (info === undefined || !onSurface.has(info.assistantSeq)) problems.push(`step ${label} is not in context`)
|
|
254
|
+
else if (refs.some(seen => stepLabel(seen) === stepLabel(ref))) problems.push(`step ${label} is listed twice`)
|
|
255
|
+
else if (args.op === 'fold' && info.folded !== undefined) problems.push(`step ${label} is already folded`)
|
|
256
|
+
else if (args.op === 'fold' && info.pending.length > 0) problems.push(`step ${label} is still running`)
|
|
257
|
+
else if (args.op === 'unfold' && info.folded === undefined) problems.push(`step ${label} is not folded`)
|
|
258
|
+
else refs.push(ref)
|
|
259
|
+
}
|
|
260
|
+
if (problems.length > 0) throw new ToolArgsError(problems)
|
|
261
|
+
|
|
262
|
+
if (args.op === 'unfold') {
|
|
263
|
+
session.append('self-context/unfold', { steps: refs })
|
|
264
|
+
return Promise.resolve(`Unfolded ${refs.map(stepLabel).join(', ')}; the original steps are back in context.`)
|
|
265
|
+
}
|
|
266
|
+
const summary = (args.summary ?? '').replace(/\s+/g, ' ').trim()
|
|
267
|
+
if (summary.length === 0) throw new ToolArgsError(['fold needs a one-line summary of what the steps showed'])
|
|
268
|
+
const bounded = summary.length <= config.maxSummaryChars ? summary : `${summary.slice(0, config.maxSummaryChars - 1)}…`
|
|
269
|
+
const freed = refs.reduce((total, ref) => total + (index.steps[stepLabel(ref)]?.chars ?? 0), 0)
|
|
270
|
+
session.append('self-context/fold', { steps: refs, summary: bounded })
|
|
271
|
+
return Promise.resolve(`Folded ${refs.map(stepLabel).join(', ')} (about ${formatK(freed)} hidden). Unfold restores them.`)
|
|
272
|
+
},
|
|
273
|
+
presentCall: args => ({
|
|
274
|
+
card: 'generic',
|
|
275
|
+
title: args.op === 'list' ? 'List context steps' : `${args.op === 'fold' ? 'Fold' : 'Unfold'} ${(args.steps ?? []).join(', ')}`,
|
|
276
|
+
kind: 'other',
|
|
277
|
+
}),
|
|
278
|
+
}))
|
|
279
|
+
}
|