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/LICENSE +202 -0
- package/README.md +112 -2
- package/cordis.patch.yml +11 -0
- package/lib/graph.d.ts +93 -0
- package/lib/graph.js +258 -0
- package/lib/index.d.ts +53 -0
- package/lib/index.js +237 -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 +310 -0
- package/src/index.ts +271 -0
- package/src/projection.ts +224 -0
- package/src/prompt.ts +30 -0
- package/src/state.ts +160 -0
package/lib/graph.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
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
|
+
/** Graph operation kinds the model may issue. */
|
|
9
|
+
export const GRAPH_OPS = ['add', 'edit', 'link', 'remove'];
|
|
10
|
+
const ID_PATTERN = /^[A-Za-z][\w.-]{0,39}$/;
|
|
11
|
+
const ID_PREFIX = { goal: 'g', subgoal: 's', finding: 'f', hypothesis: 'h', plan: 'p', answer: 'a', lead: 'l', deadend: 'd' };
|
|
12
|
+
/** Own-property node lookup, safe against ids like `constructor`. */
|
|
13
|
+
export function getNode(state, id) {
|
|
14
|
+
return Object.hasOwn(state.nodes, id) ? state.nodes[id] : undefined;
|
|
15
|
+
}
|
|
16
|
+
function setNode(state, id, node) {
|
|
17
|
+
state.nodes[id] = node;
|
|
18
|
+
}
|
|
19
|
+
/** A deep copy that later operations may mutate. */
|
|
20
|
+
export function cloneGraph(state) {
|
|
21
|
+
return { nodes: { ...state.nodes }, order: [...state.order] };
|
|
22
|
+
}
|
|
23
|
+
/** An empty working graph. */
|
|
24
|
+
export function emptyGraph() {
|
|
25
|
+
return { nodes: {}, order: [] };
|
|
26
|
+
}
|
|
27
|
+
function clean(value, max) {
|
|
28
|
+
if (value === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
const text = value.trim();
|
|
31
|
+
if (text.length === 0)
|
|
32
|
+
return undefined;
|
|
33
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
34
|
+
}
|
|
35
|
+
function cleanAttr(value) {
|
|
36
|
+
return clean(value?.replace(/\s+/g, ' '), 60);
|
|
37
|
+
}
|
|
38
|
+
function freshId(state, type) {
|
|
39
|
+
const prefix = ID_PREFIX[type] ?? 'n';
|
|
40
|
+
let i = 1;
|
|
41
|
+
while (Object.hasOwn(state.nodes, `${prefix}${i}`))
|
|
42
|
+
i += 1;
|
|
43
|
+
return `${prefix}${i}`;
|
|
44
|
+
}
|
|
45
|
+
function liveCount(state) {
|
|
46
|
+
let count = 0;
|
|
47
|
+
for (const node of Object.values(state.nodes))
|
|
48
|
+
if (!node.removed)
|
|
49
|
+
count += 1;
|
|
50
|
+
return count;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Apply model operations, mutating `state`. Invalid operations are skipped and
|
|
54
|
+
* reported; valid ones are normalized (fresh ids assigned, unknown parents
|
|
55
|
+
* dropped) so replaying `applied` reproduces exactly the same state.
|
|
56
|
+
* @param state - graph to mutate.
|
|
57
|
+
* @param ops - operations in model order.
|
|
58
|
+
* @param limits - content and size limits.
|
|
59
|
+
* @returns normalized applied operations and recoverable errors.
|
|
60
|
+
*/
|
|
61
|
+
export function applyGraphOps(state, ops, limits) {
|
|
62
|
+
const applied = [];
|
|
63
|
+
const errors = [];
|
|
64
|
+
const filterParents = (id, parents) => {
|
|
65
|
+
const out = [];
|
|
66
|
+
for (const raw of parents ?? []) {
|
|
67
|
+
const parent = raw.trim();
|
|
68
|
+
if (parent.length === 0 || parent === id || out.includes(parent))
|
|
69
|
+
continue;
|
|
70
|
+
if (!Object.hasOwn(state.nodes, parent)) {
|
|
71
|
+
errors.push(`${id}: parent "${parent}" does not exist; dropped`);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
out.push(parent);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
};
|
|
78
|
+
for (const input of ops) {
|
|
79
|
+
const id = input.id?.trim() ?? '';
|
|
80
|
+
if (id.length > 0 && !ID_PATTERN.test(id)) {
|
|
81
|
+
errors.push(`${input.op} "${id}": ids are 1-40 chars of letters, digits, '_', '.', '-' and start with a letter`);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const content = clean(input.content, limits.maxNodeContentChars);
|
|
85
|
+
const status = cleanAttr(input.status);
|
|
86
|
+
const type = cleanAttr(input.type);
|
|
87
|
+
switch (input.op) {
|
|
88
|
+
case 'add': {
|
|
89
|
+
const existing = id.length > 0 ? getNode(state, id) : undefined;
|
|
90
|
+
if (existing !== undefined) {
|
|
91
|
+
// Self-Context treats add-on-existing-id as a revision that keeps references.
|
|
92
|
+
if (content === undefined && status === undefined) {
|
|
93
|
+
errors.push(`add "${id}": id already exists and there is nothing to revise`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (existing.removed) {
|
|
97
|
+
applied.push(applyOne(state, { op: 'restore', id }));
|
|
98
|
+
errors.push(`add "${id}": id was removed earlier; restored and revised`);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
errors.push(`add "${id}": id already exists; applied as an edit`);
|
|
102
|
+
}
|
|
103
|
+
applied.push(applyOne(state, { op: 'edit', id, ...content === undefined ? {} : { content }, ...status === undefined ? {} : { status } }));
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (content === undefined) {
|
|
107
|
+
errors.push(`add "${id || '?'}": content is required`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (liveCount(state) >= limits.maxNodes) {
|
|
111
|
+
errors.push(`add "${id || '?'}": the graph already holds ${limits.maxNodes} nodes; remove or merge some first`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
const nodeType = type ?? 'note';
|
|
115
|
+
const nodeId = id.length > 0 ? id : freshId(state, nodeType);
|
|
116
|
+
const parents = filterParents(nodeId, input.parents);
|
|
117
|
+
applied.push(applyOne(state, {
|
|
118
|
+
op: 'add', id: nodeId, type: nodeType, content,
|
|
119
|
+
...status === undefined ? {} : { status },
|
|
120
|
+
...parents.length > 0 ? { parents } : {},
|
|
121
|
+
}));
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
case 'edit': {
|
|
125
|
+
const node = getNode(state, id);
|
|
126
|
+
if (node === undefined) {
|
|
127
|
+
errors.push(`edit "${id}": no such node`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (content === undefined && status === undefined && type === undefined) {
|
|
131
|
+
errors.push(`edit "${id}": nothing to change`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (node.removed)
|
|
135
|
+
applied.push(applyOne(state, { op: 'restore', id }));
|
|
136
|
+
applied.push(applyOne(state, {
|
|
137
|
+
op: 'edit', id,
|
|
138
|
+
...content === undefined ? {} : { content },
|
|
139
|
+
...status === undefined ? {} : { status },
|
|
140
|
+
...type === undefined ? {} : { type },
|
|
141
|
+
}));
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
case 'link': {
|
|
145
|
+
if (getNode(state, id) === undefined) {
|
|
146
|
+
errors.push(`link "${id}": no such node`);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const parents = filterParents(id, input.parents);
|
|
150
|
+
if (parents.length === 0) {
|
|
151
|
+
errors.push(`link "${id}": no valid parents given`);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
applied.push(applyOne(state, { op: 'link', id, parents }));
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
case 'remove': {
|
|
158
|
+
const node = getNode(state, id);
|
|
159
|
+
if (node === undefined || node.removed) {
|
|
160
|
+
errors.push(`remove "${id}": no such live node`);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
applied.push(applyOne(state, { op: 'remove', id }));
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
default:
|
|
167
|
+
errors.push(`unknown op "${String(input.op)}"`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { applied, errors };
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Apply one already-normalized operation. Used for live application and replay.
|
|
174
|
+
* @param state - graph to mutate.
|
|
175
|
+
* @param op - normalized operation.
|
|
176
|
+
* @returns the same operation, for chaining into an applied list.
|
|
177
|
+
*/
|
|
178
|
+
export function applyOne(state, op) {
|
|
179
|
+
const node = getNode(state, op.id);
|
|
180
|
+
switch (op.op) {
|
|
181
|
+
case 'add':
|
|
182
|
+
setNode(state, op.id, {
|
|
183
|
+
id: op.id, type: op.type ?? 'note', content: op.content ?? '',
|
|
184
|
+
...op.status === undefined ? {} : { status: op.status },
|
|
185
|
+
parents: [...op.parents ?? []], v: 1, removed: false,
|
|
186
|
+
});
|
|
187
|
+
state.order.push(op.id);
|
|
188
|
+
break;
|
|
189
|
+
case 'edit':
|
|
190
|
+
if (node === undefined)
|
|
191
|
+
break;
|
|
192
|
+
setNode(state, op.id, {
|
|
193
|
+
...node,
|
|
194
|
+
...op.content === undefined ? {} : { content: op.content },
|
|
195
|
+
...op.status === undefined ? {} : { status: op.status },
|
|
196
|
+
...op.type === undefined ? {} : { type: op.type },
|
|
197
|
+
v: node.v + 1,
|
|
198
|
+
});
|
|
199
|
+
break;
|
|
200
|
+
case 'link':
|
|
201
|
+
if (node === undefined)
|
|
202
|
+
break;
|
|
203
|
+
setNode(state, op.id, { ...node, parents: [...new Set([...node.parents, ...op.parents ?? []])], v: node.v + 1 });
|
|
204
|
+
break;
|
|
205
|
+
case 'remove':
|
|
206
|
+
if (node === undefined)
|
|
207
|
+
break;
|
|
208
|
+
setNode(state, op.id, { ...node, removed: true, v: node.v + 1 });
|
|
209
|
+
break;
|
|
210
|
+
case 'restore':
|
|
211
|
+
if (node === undefined)
|
|
212
|
+
break;
|
|
213
|
+
setNode(state, op.id, { ...node, removed: false, v: node.v + 1 });
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
return op;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Rebuild a graph from persisted operation batches.
|
|
220
|
+
* @param batches - `ops` arrays of `self-context/graph` events in log order.
|
|
221
|
+
* @returns the reconstructed graph.
|
|
222
|
+
*/
|
|
223
|
+
export function replayGraph(batches) {
|
|
224
|
+
const state = emptyGraph();
|
|
225
|
+
for (const ops of batches)
|
|
226
|
+
for (const op of ops)
|
|
227
|
+
applyOne(state, op);
|
|
228
|
+
return state;
|
|
229
|
+
}
|
|
230
|
+
function attr(value) {
|
|
231
|
+
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/\n/g, ' ');
|
|
232
|
+
}
|
|
233
|
+
function body(value) {
|
|
234
|
+
return value.replace(/&/g, '&').replace(/</g, '<');
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Serialize live nodes in creation order, in the same `<node>` vocabulary the
|
|
238
|
+
* model writes with. Tombstoned nodes are omitted.
|
|
239
|
+
* @param state - graph to render.
|
|
240
|
+
* @returns XML-ish text, or an empty string for an empty graph.
|
|
241
|
+
*/
|
|
242
|
+
export function serializeGraph(state) {
|
|
243
|
+
const lines = [];
|
|
244
|
+
for (const id of state.order) {
|
|
245
|
+
const node = getNode(state, id);
|
|
246
|
+
if (node === undefined || node.removed)
|
|
247
|
+
continue;
|
|
248
|
+
const parts = [`id="${attr(node.id)}"`, `type="${attr(node.type)}"`];
|
|
249
|
+
if (node.parents.length > 0)
|
|
250
|
+
parts.push(`parents="${attr(node.parents.join(','))}"`);
|
|
251
|
+
if (node.status !== undefined)
|
|
252
|
+
parts.push(`status="${attr(node.status)}"`);
|
|
253
|
+
if (node.v > 1)
|
|
254
|
+
parts.push(`v="${node.v}"`);
|
|
255
|
+
lines.push(` <node ${parts.join(' ')}>${body(node.content)}</node>`);
|
|
256
|
+
}
|
|
257
|
+
return lines.length === 0 ? '' : `<graph>\n${lines.join('\n')}\n</graph>`;
|
|
258
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
14
|
+
import Schema from '@deepseek-ai/schemastery';
|
|
15
|
+
import { type StepsState } from './state.ts';
|
|
16
|
+
export * from './graph.ts';
|
|
17
|
+
export * from './projection.ts';
|
|
18
|
+
export { GRAPH_CONTEXT_HEADER, PROTOCOL } from './prompt.ts';
|
|
19
|
+
export declare const name = "self-context";
|
|
20
|
+
export declare const inject: string[];
|
|
21
|
+
export declare const GRAPH_TOOL = "context_graph";
|
|
22
|
+
export declare const HISTORY_TOOL = "context_history";
|
|
23
|
+
/** Plugin configuration. */
|
|
24
|
+
export interface Config {
|
|
25
|
+
/** Register the protocol instructions as a system-prompt section. */
|
|
26
|
+
instructions: boolean;
|
|
27
|
+
/** Prompt-section order of the instructions. */
|
|
28
|
+
instructionsOrder: number;
|
|
29
|
+
/** Show the working graph as dynamic session context. */
|
|
30
|
+
showGraph: boolean;
|
|
31
|
+
/** Order of the graph among dynamic session contexts. */
|
|
32
|
+
graphContextOrder: number;
|
|
33
|
+
/** Maximum characters kept per node. */
|
|
34
|
+
maxNodeContentChars: number;
|
|
35
|
+
/** Maximum live nodes. */
|
|
36
|
+
maxNodes: number;
|
|
37
|
+
/** Maximum characters of one fold summary. */
|
|
38
|
+
maxSummaryChars: number;
|
|
39
|
+
}
|
|
40
|
+
export declare const Config: Schema<Config>;
|
|
41
|
+
/**
|
|
42
|
+
* Render the steps still on the surface.
|
|
43
|
+
* @param steps - step index.
|
|
44
|
+
* @param onSurface - current surface sequences.
|
|
45
|
+
* @returns one line per step.
|
|
46
|
+
*/
|
|
47
|
+
export declare function renderStepList(steps: StepsState, onSurface: ReadonlySet<number>): string;
|
|
48
|
+
/**
|
|
49
|
+
* Mount the working graph, history tools, projections and prompt contributions.
|
|
50
|
+
* @param ctx - plugin context.
|
|
51
|
+
* @param config - validated configuration.
|
|
52
|
+
*/
|
|
53
|
+
export declare function apply(ctx: Context, config: Config): Promise<void>;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
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
|
+
import Schema from '@deepseek-ai/schemastery';
|
|
14
|
+
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools';
|
|
15
|
+
import { applyGraphOps, cloneGraph, GRAPH_OPS, serializeGraph } from "./graph.js";
|
|
16
|
+
import { parseStepLabel, selfContextProjections, stepLabel } from "./projection.js";
|
|
17
|
+
import { GRAPH_CONTEXT_HEADER, PROTOCOL } from "./prompt.js";
|
|
18
|
+
import { applyGraphEvent, applyStepEvent, emptyGraph, emptySteps, graphStateSchema, stepsStateSchema, } from "./state.js";
|
|
19
|
+
export * from "./graph.js";
|
|
20
|
+
export * from "./projection.js";
|
|
21
|
+
export { GRAPH_CONTEXT_HEADER, PROTOCOL } from "./prompt.js";
|
|
22
|
+
export const name = 'self-context';
|
|
23
|
+
export const inject = ['tools', 'sessions', 'sessionProjections', 'systemPrompt'];
|
|
24
|
+
export const GRAPH_TOOL = 'context_graph';
|
|
25
|
+
export const HISTORY_TOOL = 'context_history';
|
|
26
|
+
export const Config = Schema.object({
|
|
27
|
+
instructions: Schema.boolean().default(true).description('Add the Self-Context protocol to the system prompt.'),
|
|
28
|
+
instructionsOrder: Schema.number().default(9000).description('System-prompt section order of the protocol.'),
|
|
29
|
+
showGraph: Schema.boolean().default(true).description('Show the working graph to the model as session context.'),
|
|
30
|
+
graphContextOrder: Schema.number().default(9000).description('Runtime-context order of the graph.'),
|
|
31
|
+
maxNodeContentChars: Schema.natural().min(20).default(1000).description('Maximum characters per graph node.'),
|
|
32
|
+
maxNodes: Schema.natural().min(1).default(200).description('Maximum live graph nodes.'),
|
|
33
|
+
maxSummaryChars: Schema.natural().min(20).default(400).description('Maximum characters per fold summary.'),
|
|
34
|
+
});
|
|
35
|
+
function requireSession(exec, tool) {
|
|
36
|
+
if (exec.agent === undefined)
|
|
37
|
+
throw new ToolArgsError([`${tool} can only be called by an agent with a session`]);
|
|
38
|
+
return exec.agent.session;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Register a host-only projection unit and return a reader for its state.
|
|
42
|
+
* dsh 0.2.2 returns a disposer and 0.2.3 an awaitable handle; both expose
|
|
43
|
+
* `stateOf(session, key)`, so the reader uses that.
|
|
44
|
+
* @param ctx - plugin context.
|
|
45
|
+
* @param definition - projection unit.
|
|
46
|
+
* @returns a state reader that falls back to the empty state.
|
|
47
|
+
*/
|
|
48
|
+
async function registerUnit(ctx, definition) {
|
|
49
|
+
const registry = ctx.sessionProjections;
|
|
50
|
+
await registry.register(definition);
|
|
51
|
+
return session => registry.stateOf(session, definition.key) ?? definition.init();
|
|
52
|
+
}
|
|
53
|
+
function formatK(chars) {
|
|
54
|
+
return chars < 1000 ? `${chars} chars` : `${(chars / 1000).toFixed(1)}k chars`;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Render the steps still on the surface.
|
|
58
|
+
* @param steps - step index.
|
|
59
|
+
* @param onSurface - current surface sequences.
|
|
60
|
+
* @returns one line per step.
|
|
61
|
+
*/
|
|
62
|
+
export function renderStepList(steps, onSurface) {
|
|
63
|
+
const lines = [];
|
|
64
|
+
let raw = 0;
|
|
65
|
+
for (const label of steps.order) {
|
|
66
|
+
const info = steps.steps[label];
|
|
67
|
+
if (info === undefined || !onSurface.has(info.assistantSeq))
|
|
68
|
+
continue;
|
|
69
|
+
if (info.folded !== undefined) {
|
|
70
|
+
lines.push(`${label} [folded] ${info.folded}`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
raw += info.chars;
|
|
74
|
+
const calls = info.calls.length === 0 ? '(reply only)' : info.calls.join('; ');
|
|
75
|
+
lines.push(`${label} ${formatK(info.chars)} ${calls}${info.pending.length > 0 ? ' [running]' : ''}`);
|
|
76
|
+
}
|
|
77
|
+
if (lines.length === 0)
|
|
78
|
+
return 'No steps are in context yet.';
|
|
79
|
+
return `Steps in context (turn.step), ${formatK(raw)} unfolded:\n${lines.join('\n')}`;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Mount the working graph, history tools, projections and prompt contributions.
|
|
83
|
+
* @param ctx - plugin context.
|
|
84
|
+
* @param config - validated configuration.
|
|
85
|
+
*/
|
|
86
|
+
export async function apply(ctx, config) {
|
|
87
|
+
for (const projection of selfContextProjections)
|
|
88
|
+
ctx.sessions.registerMessageProjection(projection);
|
|
89
|
+
const graphOf = await registerUnit(ctx, {
|
|
90
|
+
key: 'selfContext.graph',
|
|
91
|
+
stateSchema: graphStateSchema,
|
|
92
|
+
init: emptyGraph,
|
|
93
|
+
apply: applyGraphEvent,
|
|
94
|
+
stateVersion: 1,
|
|
95
|
+
});
|
|
96
|
+
const stepsOf = await registerUnit(ctx, {
|
|
97
|
+
key: 'selfContext.steps',
|
|
98
|
+
stateSchema: stepsStateSchema,
|
|
99
|
+
init: emptySteps,
|
|
100
|
+
apply: applyStepEvent,
|
|
101
|
+
stateVersion: 1,
|
|
102
|
+
});
|
|
103
|
+
if (config.instructions) {
|
|
104
|
+
ctx.systemPrompt.section({ name: 'self-context:protocol', order: config.instructionsOrder, text: PROTOCOL, interpolate: false });
|
|
105
|
+
}
|
|
106
|
+
if (config.showGraph) {
|
|
107
|
+
ctx.systemPrompt.context({
|
|
108
|
+
name: 'self-context:graph',
|
|
109
|
+
order: config.graphContextOrder,
|
|
110
|
+
required: true,
|
|
111
|
+
interpolate: false,
|
|
112
|
+
// The agent being assembled for carries its session (absent on diagnostics).
|
|
113
|
+
text: ({ agent }) => {
|
|
114
|
+
const session = agent?.session;
|
|
115
|
+
if (session === undefined)
|
|
116
|
+
return '';
|
|
117
|
+
const graph = serializeGraph(graphOf(session));
|
|
118
|
+
return graph === '' ? '' : `${GRAPH_CONTEXT_HEADER}\n${graph}`;
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
ctx.tools.register(defineTool({
|
|
123
|
+
name: GRAPH_TOOL,
|
|
124
|
+
description: 'Edit your working graph: the durable record of goals, findings, hypotheses, plans, dead ends and your current answer. '
|
|
125
|
+
+ 'It stays visible after old steps are folded or compacted. Send only the changes.',
|
|
126
|
+
parameters: {
|
|
127
|
+
ops: {
|
|
128
|
+
type: 'array',
|
|
129
|
+
required: true,
|
|
130
|
+
description: 'Changes to apply in order.',
|
|
131
|
+
items: {
|
|
132
|
+
type: 'object',
|
|
133
|
+
additionalProperties: false,
|
|
134
|
+
properties: {
|
|
135
|
+
op: { type: 'string', required: true, enum: [...GRAPH_OPS], description: 'add | edit | link | remove' },
|
|
136
|
+
id: { type: 'string', description: 'Node id, e.g. "f3". Optional on add (generated); required otherwise.' },
|
|
137
|
+
type: { type: 'string', description: 'goal, subgoal, finding, hypothesis, plan, lead, deadend, answer, …' },
|
|
138
|
+
content: { type: 'string', description: 'One line: what was established and where (file:line, command, URL).' },
|
|
139
|
+
status: { type: 'string', description: 'e.g. pending, active, done, failed.' },
|
|
140
|
+
parents: { type: 'array', items: { type: 'string' }, description: 'Ids this node rests on (add, link).' },
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
output: {
|
|
146
|
+
schema: {
|
|
147
|
+
type: 'object',
|
|
148
|
+
additionalProperties: false,
|
|
149
|
+
properties: {
|
|
150
|
+
applied: { type: 'integer', required: true },
|
|
151
|
+
nodes: { type: 'integer', required: true },
|
|
152
|
+
errors: { type: 'array', required: true, items: { type: 'string' } },
|
|
153
|
+
graph: { type: 'string', required: true },
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
// Runtime context is refreshed only when a user message is admitted, so within
|
|
157
|
+
// a long turn this result is how the model sees the current graph and its ids.
|
|
158
|
+
render: (_args, value) => [{
|
|
159
|
+
type: 'text',
|
|
160
|
+
text: `Graph updated: ${value.applied} change(s) applied, ${value.nodes} live node(s).`
|
|
161
|
+
+ (value.errors.length > 0 ? `\nProblems:\n- ${value.errors.join('\n- ')}` : '')
|
|
162
|
+
+ (value.graph === '' ? '' : `\nCurrent graph:\n${value.graph}`),
|
|
163
|
+
}],
|
|
164
|
+
},
|
|
165
|
+
execute(args, exec) {
|
|
166
|
+
const session = requireSession(exec, GRAPH_TOOL);
|
|
167
|
+
if (args.ops.length === 0)
|
|
168
|
+
throw new ToolArgsError(['ops must contain at least one operation']);
|
|
169
|
+
const draft = cloneGraph(graphOf(session));
|
|
170
|
+
const { applied, errors } = applyGraphOps(draft, args.ops, config);
|
|
171
|
+
if (applied.length > 0)
|
|
172
|
+
session.append('self-context/graph', { ops: applied });
|
|
173
|
+
const nodes = Object.values(draft.nodes).filter(node => !node.removed).length;
|
|
174
|
+
return Promise.resolve({ applied: applied.length, nodes, errors, graph: serializeGraph(draft) });
|
|
175
|
+
},
|
|
176
|
+
presentCall: args => ({ card: 'generic', title: 'Update working graph', kind: 'other', rawInput: args.ops }),
|
|
177
|
+
}));
|
|
178
|
+
ctx.tools.register(defineTool({
|
|
179
|
+
name: HISTORY_TOOL,
|
|
180
|
+
description: 'Manage your own conversation history. "list" shows steps (turn.step) in context; "fold" replaces finished steps '
|
|
181
|
+
+ 'with your one-line summary to free context; "unfold" restores folded steps exactly.',
|
|
182
|
+
parameters: {
|
|
183
|
+
op: { type: 'string', required: true, enum: ['list', 'fold', 'unfold'] },
|
|
184
|
+
steps: { type: 'array', items: { type: 'string' }, description: 'Step labels like "3.2" (fold, unfold).' },
|
|
185
|
+
summary: { type: 'string', description: 'fold only: one line saying what the folded steps showed.' },
|
|
186
|
+
},
|
|
187
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
188
|
+
execute(args, exec) {
|
|
189
|
+
const session = requireSession(exec, HISTORY_TOOL);
|
|
190
|
+
const index = stepsOf(session);
|
|
191
|
+
const onSurface = new Set(session.surface.nodes);
|
|
192
|
+
if (args.op === 'list')
|
|
193
|
+
return Promise.resolve(renderStepList(index, onSurface));
|
|
194
|
+
const labels = args.steps ?? [];
|
|
195
|
+
if (labels.length === 0)
|
|
196
|
+
throw new ToolArgsError([`${args.op} needs steps, e.g. ["3.2"]`]);
|
|
197
|
+
const refs = [];
|
|
198
|
+
const problems = [];
|
|
199
|
+
for (const label of labels) {
|
|
200
|
+
const ref = parseStepLabel(label);
|
|
201
|
+
const info = ref === undefined ? undefined : index.steps[stepLabel(ref)];
|
|
202
|
+
if (ref === undefined)
|
|
203
|
+
problems.push(`"${label}" is not a turn.step label`);
|
|
204
|
+
else if (info === undefined || !onSurface.has(info.assistantSeq))
|
|
205
|
+
problems.push(`step ${label} is not in context`);
|
|
206
|
+
else if (refs.some(seen => stepLabel(seen) === stepLabel(ref)))
|
|
207
|
+
problems.push(`step ${label} is listed twice`);
|
|
208
|
+
else if (args.op === 'fold' && info.folded !== undefined)
|
|
209
|
+
problems.push(`step ${label} is already folded`);
|
|
210
|
+
else if (args.op === 'fold' && info.pending.length > 0)
|
|
211
|
+
problems.push(`step ${label} is still running`);
|
|
212
|
+
else if (args.op === 'unfold' && info.folded === undefined)
|
|
213
|
+
problems.push(`step ${label} is not folded`);
|
|
214
|
+
else
|
|
215
|
+
refs.push(ref);
|
|
216
|
+
}
|
|
217
|
+
if (problems.length > 0)
|
|
218
|
+
throw new ToolArgsError(problems);
|
|
219
|
+
if (args.op === 'unfold') {
|
|
220
|
+
session.append('self-context/unfold', { steps: refs });
|
|
221
|
+
return Promise.resolve(`Unfolded ${refs.map(stepLabel).join(', ')}; the original steps are back in context.`);
|
|
222
|
+
}
|
|
223
|
+
const summary = (args.summary ?? '').replace(/\s+/g, ' ').trim();
|
|
224
|
+
if (summary.length === 0)
|
|
225
|
+
throw new ToolArgsError(['fold needs a one-line summary of what the steps showed']);
|
|
226
|
+
const bounded = summary.length <= config.maxSummaryChars ? summary : `${summary.slice(0, config.maxSummaryChars - 1)}…`;
|
|
227
|
+
const freed = refs.reduce((total, ref) => total + (index.steps[stepLabel(ref)]?.chars ?? 0), 0);
|
|
228
|
+
session.append('self-context/fold', { steps: refs, summary: bounded });
|
|
229
|
+
return Promise.resolve(`Folded ${refs.map(stepLabel).join(', ')} (about ${formatK(freed)} hidden). Unfold restores them.`);
|
|
230
|
+
},
|
|
231
|
+
presentCall: args => ({
|
|
232
|
+
card: 'generic',
|
|
233
|
+
title: args.op === 'list' ? 'List context steps' : `${args.op === 'fold' ? 'Fold' : 'Unfold'} ${(args.steps ?? []).join(', ')}`,
|
|
234
|
+
kind: 'other',
|
|
235
|
+
}),
|
|
236
|
+
}));
|
|
237
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable event declarations and pure message projections for Self-Context
|
|
3
|
+
* history management (the T operator): Fold replaces one complete interaction
|
|
4
|
+
* step — its assistant message plus every paired tool result — with a short
|
|
5
|
+
* summary note; Unfold restores the original step losslessly.
|
|
6
|
+
*
|
|
7
|
+
* The session log is never rewritten. A fold is a `self-context/fold` event
|
|
8
|
+
* interpreted by a registered `SessionMessageProjection`, exactly like the
|
|
9
|
+
* first-party image-offload plugin, so live sessions, resume, fork and detached
|
|
10
|
+
* replay all reconstruct the same model-visible history.
|
|
11
|
+
*
|
|
12
|
+
* This module is browser-safe and free of host-only imports so detached readers
|
|
13
|
+
* can pass `selfContextProjections` to `foldSurface()`.
|
|
14
|
+
*/
|
|
15
|
+
import type { AssistantMessage, Message, ToolResultMessage } from '@deepseek-ai/dsh-llm';
|
|
16
|
+
import type { SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session/types';
|
|
17
|
+
import type { SessionMessageProjection } from '@deepseek-ai/dsh-session/surface';
|
|
18
|
+
import type { GraphOp } from './graph.ts';
|
|
19
|
+
/** Identifies one interaction step: one model call plus the tools it requested. */
|
|
20
|
+
export interface StepRef {
|
|
21
|
+
turn: number;
|
|
22
|
+
step: number;
|
|
23
|
+
}
|
|
24
|
+
declare module '@deepseek-ai/dsh-session/types' {
|
|
25
|
+
interface SessionEventMap {
|
|
26
|
+
/** Normalized working-graph operations from one context_graph call. Log-only; replay folds them in order. */
|
|
27
|
+
'self-context/graph': {
|
|
28
|
+
ops: GraphOp[];
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Hide complete interaction steps behind a model-written summary. The assistant
|
|
32
|
+
* message and its tool results keep their surface positions and identities.
|
|
33
|
+
* @messageProjection
|
|
34
|
+
*/
|
|
35
|
+
'self-context/fold': {
|
|
36
|
+
steps: StepRef[];
|
|
37
|
+
summary: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Restore previously folded steps to their original logged messages.
|
|
41
|
+
* @messageProjection
|
|
42
|
+
*/
|
|
43
|
+
'self-context/unfold': {
|
|
44
|
+
steps: StepRef[];
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Marker opening every folded assistant note; also how a fold is recognized. */
|
|
49
|
+
export declare const FOLD_MARK = "[Folded step ";
|
|
50
|
+
/** Model-facing step label, e.g. `3.2`. */
|
|
51
|
+
export declare function stepLabel(ref: StepRef): string;
|
|
52
|
+
/**
|
|
53
|
+
* Parse a model-facing step label.
|
|
54
|
+
* @param label - text like `3.2`.
|
|
55
|
+
* @returns the step reference, or undefined when malformed.
|
|
56
|
+
*/
|
|
57
|
+
export declare function parseStepLabel(label: string): StepRef | undefined;
|
|
58
|
+
/** Whether a projected assistant message is currently a fold note. */
|
|
59
|
+
export declare function isFoldNote(message: Message | null | undefined): boolean;
|
|
60
|
+
/** Surface members of one step, in surface order. */
|
|
61
|
+
export interface StepMembers {
|
|
62
|
+
assistantSeq: SessionSeq;
|
|
63
|
+
assistant: AssistantMessage;
|
|
64
|
+
tools: {
|
|
65
|
+
seq: SessionSeq;
|
|
66
|
+
message: ToolResultMessage;
|
|
67
|
+
}[];
|
|
68
|
+
}
|
|
69
|
+
type EventReader = (seq: SessionSeq) => SessionEvent | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Collect the current surface nodes belonging to each step, keyed by label.
|
|
72
|
+
* Only steps that produced an assistant message are returned.
|
|
73
|
+
* @param nodes - current surface sequences in model order.
|
|
74
|
+
* @param read - event lookup by sequence.
|
|
75
|
+
* @returns members of every step present on the surface, in surface order.
|
|
76
|
+
*/
|
|
77
|
+
export declare function collectSteps(nodes: readonly SessionSeq[], read: EventReader): Map<string, StepMembers>;
|
|
78
|
+
/**
|
|
79
|
+
* Explain why a step cannot be folded, or return undefined when it can.
|
|
80
|
+
* A step folds only when every tool call it made has its result on the surface,
|
|
81
|
+
* which also excludes the step still waiting for the current tool call.
|
|
82
|
+
* @param members - the step's surface members with original messages.
|
|
83
|
+
* @returns a reason, or undefined.
|
|
84
|
+
*/
|
|
85
|
+
export declare function foldBlocker(members: StepMembers): string | undefined;
|
|
86
|
+
/** Pure interpretation of `self-context/fold`. */
|
|
87
|
+
export declare const foldProjection: SessionMessageProjection<'self-context/fold'>;
|
|
88
|
+
/** Pure interpretation of `self-context/unfold`. */
|
|
89
|
+
export declare const unfoldProjection: SessionMessageProjection<'self-context/unfold'>;
|
|
90
|
+
/** Every projection this plugin owns, for registration and detached replay. */
|
|
91
|
+
export declare const selfContextProjections: readonly [SessionMessageProjection<"self-context/fold">, SessionMessageProjection<"self-context/unfold">];
|
|
92
|
+
export {};
|