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
|
@@ -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 {};
|
|
@@ -0,0 +1,184 @@
|
|
|
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
|
+
/** Marker opening every folded assistant note; also how a fold is recognized. */
|
|
16
|
+
export const FOLD_MARK = '[Folded step ';
|
|
17
|
+
/** Model-facing step label, e.g. `3.2`. */
|
|
18
|
+
export function stepLabel(ref) {
|
|
19
|
+
return `${ref.turn}.${ref.step}`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Parse a model-facing step label.
|
|
23
|
+
* @param label - text like `3.2`.
|
|
24
|
+
* @returns the step reference, or undefined when malformed.
|
|
25
|
+
*/
|
|
26
|
+
export function parseStepLabel(label) {
|
|
27
|
+
const match = /^\s*(\d{1,9})\.(\d{1,9})\s*$/.exec(label);
|
|
28
|
+
if (match === null)
|
|
29
|
+
return undefined;
|
|
30
|
+
return { turn: Number(match[1]), step: Number(match[2]) };
|
|
31
|
+
}
|
|
32
|
+
/** Whether a projected assistant message is currently a fold note. */
|
|
33
|
+
export function isFoldNote(message) {
|
|
34
|
+
const first = message?.content[0];
|
|
35
|
+
return message?.role === 'assistant' && first?.type === 'text' && first.text.startsWith(FOLD_MARK);
|
|
36
|
+
}
|
|
37
|
+
function freeze(value) {
|
|
38
|
+
if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
|
|
39
|
+
Object.freeze(value);
|
|
40
|
+
for (const child of Object.values(value))
|
|
41
|
+
freeze(child);
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Collect the current surface nodes belonging to each step, keyed by label.
|
|
47
|
+
* Only steps that produced an assistant message are returned.
|
|
48
|
+
* @param nodes - current surface sequences in model order.
|
|
49
|
+
* @param read - event lookup by sequence.
|
|
50
|
+
* @returns members of every step present on the surface, in surface order.
|
|
51
|
+
*/
|
|
52
|
+
export function collectSteps(nodes, read) {
|
|
53
|
+
const steps = new Map();
|
|
54
|
+
const orphanTools = new Map();
|
|
55
|
+
for (const seq of nodes) {
|
|
56
|
+
const event = read(seq);
|
|
57
|
+
if (event?.type === 'assistant/message') {
|
|
58
|
+
const label = stepLabel(event.data);
|
|
59
|
+
steps.set(label, { assistantSeq: seq, assistant: event.data.message, tools: orphanTools.get(label) ?? [] });
|
|
60
|
+
orphanTools.delete(label);
|
|
61
|
+
}
|
|
62
|
+
else if (event?.type === 'tool/result') {
|
|
63
|
+
const label = stepLabel(event.data);
|
|
64
|
+
const entry = { seq, message: event.data.message };
|
|
65
|
+
const members = steps.get(label);
|
|
66
|
+
if (members === undefined)
|
|
67
|
+
orphanTools.set(label, [...orphanTools.get(label) ?? [], entry]);
|
|
68
|
+
else
|
|
69
|
+
members.tools.push(entry);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return steps;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Explain why a step cannot be folded, or return undefined when it can.
|
|
76
|
+
* A step folds only when every tool call it made has its result on the surface,
|
|
77
|
+
* which also excludes the step still waiting for the current tool call.
|
|
78
|
+
* @param members - the step's surface members with original messages.
|
|
79
|
+
* @returns a reason, or undefined.
|
|
80
|
+
*/
|
|
81
|
+
export function foldBlocker(members) {
|
|
82
|
+
const calls = members.assistant.content.filter(block => block.type === 'tool-call');
|
|
83
|
+
const results = new Set(members.tools.map(tool => tool.message.toolCallId));
|
|
84
|
+
for (const call of calls) {
|
|
85
|
+
if (!results.has(call.id))
|
|
86
|
+
return 'it is still running or lost a tool result';
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
function contextReader(context) {
|
|
91
|
+
return seq => context.events[seq - context.baseSeq];
|
|
92
|
+
}
|
|
93
|
+
function current(context, seq, original) {
|
|
94
|
+
return context.messages.get(seq) ?? original;
|
|
95
|
+
}
|
|
96
|
+
function validRefs(value, type) {
|
|
97
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
98
|
+
throw new Error(`${type}: steps must be a nonempty array`);
|
|
99
|
+
const seen = new Set();
|
|
100
|
+
return value.map((item) => {
|
|
101
|
+
const ref = item;
|
|
102
|
+
if (typeof ref !== 'object' || ref === null || !Number.isSafeInteger(ref.turn) || !Number.isSafeInteger(ref.step)
|
|
103
|
+
|| ref.turn < 0 || ref.step < 0) {
|
|
104
|
+
throw new Error(`${type}: each step must be { turn, step } with non-negative integers`);
|
|
105
|
+
}
|
|
106
|
+
const label = stepLabel(ref);
|
|
107
|
+
if (seen.has(label))
|
|
108
|
+
throw new Error(`${type}: duplicate step ${label}`);
|
|
109
|
+
seen.add(label);
|
|
110
|
+
return { turn: ref.turn, step: ref.step };
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
function foldedAssistant(original, text) {
|
|
114
|
+
// Calls stay paired with their results so every provider accepts the history;
|
|
115
|
+
// arguments collapse to `{}`, which adapters already use for unusable history.
|
|
116
|
+
const calls = original.content
|
|
117
|
+
.filter(block => block.type === 'tool-call')
|
|
118
|
+
.map(block => ({ ...block, arguments: '{}' }));
|
|
119
|
+
// Thinking signatures describe the original blocks; drop them with those blocks.
|
|
120
|
+
const { replayState: _dropped, ...source } = original.source;
|
|
121
|
+
return freeze({ ...original, source: source, content: [{ type: 'text', text }, ...calls] });
|
|
122
|
+
}
|
|
123
|
+
function foldedTool(original, anchor) {
|
|
124
|
+
return freeze({ ...original, content: [{ type: 'text', text: `[Result folded into step ${anchor}.]` }] });
|
|
125
|
+
}
|
|
126
|
+
/** Pure interpretation of `self-context/fold`. */
|
|
127
|
+
export const foldProjection = {
|
|
128
|
+
type: 'self-context/fold',
|
|
129
|
+
project(event, context) {
|
|
130
|
+
const data = event.data;
|
|
131
|
+
if (typeof data !== 'object' || data === null || typeof data.summary !== 'string' || data.summary.trim().length === 0) {
|
|
132
|
+
throw new Error('self-context/fold: summary must be a nonempty string');
|
|
133
|
+
}
|
|
134
|
+
const refs = validRefs(data.steps, 'self-context/fold');
|
|
135
|
+
const steps = collectSteps(context.nodes, contextReader(context));
|
|
136
|
+
const anchor = stepLabel(refs[0]);
|
|
137
|
+
const out = new Map();
|
|
138
|
+
refs.forEach((ref, index) => {
|
|
139
|
+
const label = stepLabel(ref);
|
|
140
|
+
const members = steps.get(label);
|
|
141
|
+
if (members === undefined)
|
|
142
|
+
throw new Error(`self-context/fold: step ${label} is not on the current surface`);
|
|
143
|
+
if (isFoldNote(current(context, members.assistantSeq, members.assistant))) {
|
|
144
|
+
throw new Error(`self-context/fold: step ${label} is already folded`);
|
|
145
|
+
}
|
|
146
|
+
const blocker = foldBlocker(members);
|
|
147
|
+
if (blocker !== undefined)
|
|
148
|
+
throw new Error(`self-context/fold: step ${label} cannot fold because ${blocker}`);
|
|
149
|
+
const restore = `Restore with context_history op="unfold" steps=["${label}"].`;
|
|
150
|
+
const text = index === 0
|
|
151
|
+
? `${FOLD_MARK}${label}] ${data.summary} [Original text, reasoning, tool calls and results hidden. ${restore}]`
|
|
152
|
+
: `${FOLD_MARK}${label}] Covered by the summary at step ${anchor}. [${restore}]`;
|
|
153
|
+
out.set(members.assistantSeq, foldedAssistant(members.assistant, text));
|
|
154
|
+
for (const tool of members.tools)
|
|
155
|
+
out.set(tool.seq, foldedTool(tool.message, anchor));
|
|
156
|
+
});
|
|
157
|
+
return out;
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
/** Pure interpretation of `self-context/unfold`. */
|
|
161
|
+
export const unfoldProjection = {
|
|
162
|
+
type: 'self-context/unfold',
|
|
163
|
+
project(event, context) {
|
|
164
|
+
const refs = validRefs(event.data.steps, 'self-context/unfold');
|
|
165
|
+
const steps = collectSteps(context.nodes, contextReader(context));
|
|
166
|
+
const out = new Map();
|
|
167
|
+
for (const ref of refs) {
|
|
168
|
+
const label = stepLabel(ref);
|
|
169
|
+
const members = steps.get(label);
|
|
170
|
+
if (members === undefined)
|
|
171
|
+
throw new Error(`self-context/unfold: step ${label} is not on the current surface`);
|
|
172
|
+
if (!isFoldNote(current(context, members.assistantSeq, members.assistant))) {
|
|
173
|
+
throw new Error(`self-context/unfold: step ${label} is not folded`);
|
|
174
|
+
}
|
|
175
|
+
// The log keeps the originals; restoring them is lossless.
|
|
176
|
+
out.set(members.assistantSeq, members.assistant);
|
|
177
|
+
for (const tool of members.tools)
|
|
178
|
+
out.set(tool.seq, tool.message);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
/** Every projection this plugin owns, for registration and detached replay. */
|
|
184
|
+
export const selfContextProjections = [foldProjection, unfoldProjection];
|
package/lib/prompt.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing protocol text, adapted from Self-Context's NATIVE_PROTOCOL
|
|
3
|
+
* (src/self_context/engine/proxy/native_prompts.py) from inline `<graph>` blocks
|
|
4
|
+
* to the two dsh tools this plugin registers.
|
|
5
|
+
*/
|
|
6
|
+
/** Instructions registered as a system-prompt section. */
|
|
7
|
+
export declare const PROTOCOL = "# Context self-management\n\nYou manage your own context with two tools. Nothing is trimmed for you until the model window is about to overflow, so keep the context lean yourself.\n\n## Working graph (context_graph)\nAlongside the conversation you keep a working graph. Every context_graph result shows the current graph with its node ids, and the graph is shown again as session context at the start of each turn; it survives when older steps are folded or compacted. It is yours: record what you have established and the lines of work you are pursuing.\n- Ops: add / edit / link / remove. Types, statuses and wording are yours to choose; typical types are goal, subgoal, finding, hypothesis, plan, lead, deadend, answer. Omit an id on add to get one generated.\n- After a result that bears on the task, add ONE node stating what you established and where (file:line, command, document id, URL). Do not narrate actions you are about to take.\n- Record dead ends too (what you tried and why it failed) so you do not repeat them once the steps that showed them are gone.\n- A preview (search snippet, grep hit, listing) is a lead, not evidence: record it as type \"lead\" and open the source before treating it as a finding.\n- Keep one node holding your current best answer, fix or working hypothesis, and edit it as the evidence changes.\n- Remove only what later evidence disproved. Give a node several parents (or link it) when a conclusion rests on several lines of work.\n- When the graph shows the task is done, finish rather than re-checking.\n\n## History (context_history)\nEvery model call plus the tools it ran is one step, labelled turn.step (for example 3.2). op \"list\" shows the steps currently in context with their size and whether they are folded.\n- Once a step's result is captured in the graph, or turned out useless, fold it: op \"fold\" with steps [\"3.2\",\"3.4\"] and a one-line summary of what they showed replaces their text, reasoning, tool calls and results with that note. Record what you need in the graph BEFORE folding.\n- Never fold a step holding a lead you have not followed up.\n- op \"unfold\" restores the original steps exactly when you need the raw output again.\n- Folding older steps keeps you focused; prefer folding large, finished tool outputs.";
|
|
8
|
+
/** Header placed above the working graph snapshot. */
|
|
9
|
+
export declare const GRAPH_CONTEXT_HEADER = "Your working graph (edit it with context_graph):";
|
package/lib/prompt.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing protocol text, adapted from Self-Context's NATIVE_PROTOCOL
|
|
3
|
+
* (src/self_context/engine/proxy/native_prompts.py) from inline `<graph>` blocks
|
|
4
|
+
* to the two dsh tools this plugin registers.
|
|
5
|
+
*/
|
|
6
|
+
/** Instructions registered as a system-prompt section. */
|
|
7
|
+
export const PROTOCOL = `# Context self-management
|
|
8
|
+
|
|
9
|
+
You manage your own context with two tools. Nothing is trimmed for you until the model window is about to overflow, so keep the context lean yourself.
|
|
10
|
+
|
|
11
|
+
## Working graph (context_graph)
|
|
12
|
+
Alongside the conversation you keep a working graph. Every context_graph result shows the current graph with its node ids, and the graph is shown again as session context at the start of each turn; it survives when older steps are folded or compacted. It is yours: record what you have established and the lines of work you are pursuing.
|
|
13
|
+
- Ops: add / edit / link / remove. Types, statuses and wording are yours to choose; typical types are goal, subgoal, finding, hypothesis, plan, lead, deadend, answer. Omit an id on add to get one generated.
|
|
14
|
+
- After a result that bears on the task, add ONE node stating what you established and where (file:line, command, document id, URL). Do not narrate actions you are about to take.
|
|
15
|
+
- Record dead ends too (what you tried and why it failed) so you do not repeat them once the steps that showed them are gone.
|
|
16
|
+
- A preview (search snippet, grep hit, listing) is a lead, not evidence: record it as type "lead" and open the source before treating it as a finding.
|
|
17
|
+
- Keep one node holding your current best answer, fix or working hypothesis, and edit it as the evidence changes.
|
|
18
|
+
- Remove only what later evidence disproved. Give a node several parents (or link it) when a conclusion rests on several lines of work.
|
|
19
|
+
- When the graph shows the task is done, finish rather than re-checking.
|
|
20
|
+
|
|
21
|
+
## History (context_history)
|
|
22
|
+
Every model call plus the tools it ran is one step, labelled turn.step (for example 3.2). op "list" shows the steps currently in context with their size and whether they are folded.
|
|
23
|
+
- Once a step's result is captured in the graph, or turned out useless, fold it: op "fold" with steps ["3.2","3.4"] and a one-line summary of what they showed replaces their text, reasoning, tool calls and results with that note. Record what you need in the graph BEFORE folding.
|
|
24
|
+
- Never fold a step holding a lead you have not followed up.
|
|
25
|
+
- op "unfold" restores the original steps exactly when you need the raw output again.
|
|
26
|
+
- Folding older steps keeps you focused; prefer folding large, finished tool outputs.`;
|
|
27
|
+
/** Header placed above the working graph snapshot. */
|
|
28
|
+
export const GRAPH_CONTEXT_HEADER = 'Your working graph (edit it with context_graph):';
|
package/lib/state.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-only Session projection units. dsh forbids new synchronous reads of
|
|
3
|
+
* historical events, so the plugin folds what its tools need — the working
|
|
4
|
+
* graph and a per-step index — incrementally from committed events, and reads
|
|
5
|
+
* that state after resume or fork without scanning the log.
|
|
6
|
+
*/
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm';
|
|
9
|
+
import type { SessionEvent } from '@deepseek-ai/dsh-session/types';
|
|
10
|
+
import { emptyGraph, type GraphState } from './graph.ts';
|
|
11
|
+
/** What the history tool knows about one step. */
|
|
12
|
+
export interface StepInfo {
|
|
13
|
+
turn: number;
|
|
14
|
+
step: number;
|
|
15
|
+
/** Surface sequence of the step's assistant message. */
|
|
16
|
+
assistantSeq: number;
|
|
17
|
+
/** Surface sequences of its tool results. */
|
|
18
|
+
toolSeqs: number[];
|
|
19
|
+
/** Tool calls the step requested, as short `name args` previews. */
|
|
20
|
+
calls: string[];
|
|
21
|
+
/** Call ids still waiting for a result. */
|
|
22
|
+
pending: string[];
|
|
23
|
+
/** Model-visible characters in the original step. */
|
|
24
|
+
chars: number;
|
|
25
|
+
/** Summary note while folded. */
|
|
26
|
+
folded?: string | undefined;
|
|
27
|
+
}
|
|
28
|
+
/** Step index state: labels in log order. */
|
|
29
|
+
export interface StepsState {
|
|
30
|
+
order: string[];
|
|
31
|
+
steps: Record<string, StepInfo>;
|
|
32
|
+
}
|
|
33
|
+
export declare const graphStateSchema: z.ZodType<GraphState>;
|
|
34
|
+
export declare const stepsStateSchema: z.ZodType<StepsState>;
|
|
35
|
+
/** Model-visible characters of message content. */
|
|
36
|
+
export declare function contentChars(content: readonly ContentBlock[]): number;
|
|
37
|
+
/**
|
|
38
|
+
* Pure transition of the working graph unit.
|
|
39
|
+
* @param state - graph after all prior events.
|
|
40
|
+
* @param event - next committed event.
|
|
41
|
+
* @returns the next graph, or the same reference when unchanged.
|
|
42
|
+
*/
|
|
43
|
+
export declare function applyGraphEvent(state: GraphState, event: SessionEvent): GraphState;
|
|
44
|
+
/**
|
|
45
|
+
* Pure transition of the step index unit.
|
|
46
|
+
* @param state - index after all prior events.
|
|
47
|
+
* @param event - next committed event.
|
|
48
|
+
* @returns the next index, or the same reference when unchanged.
|
|
49
|
+
*/
|
|
50
|
+
export declare function applyStepEvent(state: StepsState, event: SessionEvent): StepsState;
|
|
51
|
+
export declare const emptySteps: () => StepsState;
|
|
52
|
+
export { emptyGraph };
|
package/lib/state.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-only Session projection units. dsh forbids new synchronous reads of
|
|
3
|
+
* historical events, so the plugin folds what its tools need — the working
|
|
4
|
+
* graph and a per-step index — incrementally from committed events, and reads
|
|
5
|
+
* that state after resume or fork without scanning the log.
|
|
6
|
+
*/
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { applyOne, cloneGraph, emptyGraph } from "./graph.js";
|
|
9
|
+
import { stepLabel } from "./projection.js";
|
|
10
|
+
const graphNodeSchema = z.object({
|
|
11
|
+
id: z.string(),
|
|
12
|
+
type: z.string(),
|
|
13
|
+
content: z.string(),
|
|
14
|
+
status: z.string().optional(),
|
|
15
|
+
parents: z.array(z.string()),
|
|
16
|
+
v: z.number(),
|
|
17
|
+
removed: z.boolean(),
|
|
18
|
+
});
|
|
19
|
+
export const graphStateSchema = z.object({
|
|
20
|
+
nodes: z.record(z.string(), graphNodeSchema),
|
|
21
|
+
order: z.array(z.string()),
|
|
22
|
+
});
|
|
23
|
+
const stepInfoSchema = z.object({
|
|
24
|
+
turn: z.number(),
|
|
25
|
+
step: z.number(),
|
|
26
|
+
assistantSeq: z.number(),
|
|
27
|
+
toolSeqs: z.array(z.number()),
|
|
28
|
+
calls: z.array(z.string()),
|
|
29
|
+
pending: z.array(z.string()),
|
|
30
|
+
chars: z.number(),
|
|
31
|
+
folded: z.string().optional(),
|
|
32
|
+
});
|
|
33
|
+
export const stepsStateSchema = z.object({
|
|
34
|
+
order: z.array(z.string()),
|
|
35
|
+
steps: z.record(z.string(), stepInfoSchema),
|
|
36
|
+
});
|
|
37
|
+
/** Model-visible characters of message content. */
|
|
38
|
+
export function contentChars(content) {
|
|
39
|
+
let total = 0;
|
|
40
|
+
for (const block of content) {
|
|
41
|
+
if (block.type === 'text' || block.type === 'reasoning')
|
|
42
|
+
total += block.text.length;
|
|
43
|
+
else if (block.type === 'tool-call')
|
|
44
|
+
total += block.name.length + block.arguments.length;
|
|
45
|
+
}
|
|
46
|
+
return total;
|
|
47
|
+
}
|
|
48
|
+
function preview(name, args) {
|
|
49
|
+
const compact = args.replace(/\s+/g, ' ');
|
|
50
|
+
return `${name} ${compact.length > 80 ? `${compact.slice(0, 79)}…` : compact}`;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Pure transition of the working graph unit.
|
|
54
|
+
* @param state - graph after all prior events.
|
|
55
|
+
* @param event - next committed event.
|
|
56
|
+
* @returns the next graph, or the same reference when unchanged.
|
|
57
|
+
*/
|
|
58
|
+
export function applyGraphEvent(state, event) {
|
|
59
|
+
if (event.type !== 'self-context/graph' || event.data.ops.length === 0)
|
|
60
|
+
return state;
|
|
61
|
+
const next = cloneGraph(state);
|
|
62
|
+
for (const op of event.data.ops)
|
|
63
|
+
applyOne(next, op);
|
|
64
|
+
return next;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Pure transition of the step index unit.
|
|
68
|
+
* @param state - index after all prior events.
|
|
69
|
+
* @param event - next committed event.
|
|
70
|
+
* @returns the next index, or the same reference when unchanged.
|
|
71
|
+
*/
|
|
72
|
+
export function applyStepEvent(state, event) {
|
|
73
|
+
switch (event.type) {
|
|
74
|
+
case 'assistant/message': {
|
|
75
|
+
const label = stepLabel(event.data);
|
|
76
|
+
const calls = event.data.message.content.filter(block => block.type === 'tool-call');
|
|
77
|
+
const info = {
|
|
78
|
+
turn: event.data.turn,
|
|
79
|
+
step: event.data.step,
|
|
80
|
+
assistantSeq: event.seq,
|
|
81
|
+
toolSeqs: [],
|
|
82
|
+
calls: calls.map(call => preview(call.name, call.arguments)),
|
|
83
|
+
pending: calls.map(call => call.id),
|
|
84
|
+
chars: contentChars(event.data.message.content),
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
order: Object.hasOwn(state.steps, label) ? state.order : [...state.order, label],
|
|
88
|
+
steps: { ...state.steps, [label]: info },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
case 'tool/result': {
|
|
92
|
+
const label = stepLabel(event.data);
|
|
93
|
+
const info = state.steps[label];
|
|
94
|
+
if (info === undefined)
|
|
95
|
+
return state;
|
|
96
|
+
return {
|
|
97
|
+
order: state.order,
|
|
98
|
+
steps: {
|
|
99
|
+
...state.steps,
|
|
100
|
+
[label]: {
|
|
101
|
+
...info,
|
|
102
|
+
toolSeqs: [...info.toolSeqs, event.seq],
|
|
103
|
+
pending: info.pending.filter(id => id !== event.data.message.toolCallId),
|
|
104
|
+
chars: info.chars + contentChars(event.data.message.content),
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
case 'self-context/fold':
|
|
110
|
+
case 'self-context/unfold': {
|
|
111
|
+
const steps = { ...state.steps };
|
|
112
|
+
const summary = event.type === 'self-context/fold' ? event.data.summary : undefined;
|
|
113
|
+
event.data.steps.forEach((ref, index) => {
|
|
114
|
+
const label = stepLabel(ref);
|
|
115
|
+
const info = steps[label];
|
|
116
|
+
if (info === undefined)
|
|
117
|
+
return;
|
|
118
|
+
const { folded: _previous, ...rest } = info;
|
|
119
|
+
steps[label] = summary === undefined
|
|
120
|
+
? rest
|
|
121
|
+
: { ...rest, folded: index === 0 ? summary : `see step ${stepLabel(event.data.steps[0])}` };
|
|
122
|
+
});
|
|
123
|
+
return { order: state.order, steps };
|
|
124
|
+
}
|
|
125
|
+
default:
|
|
126
|
+
return state;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export const emptySteps = () => ({ order: [], steps: {} });
|
|
130
|
+
export { emptyGraph };
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-self-context",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Self-Context (arXiv:2612.01681) for DeepSeek Harness: a working graph plus reversible fold/unfold of the agent's own history",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"dsh-plugin",
|
|
7
|
+
"deepseek-harness",
|
|
8
|
+
"context-management",
|
|
9
|
+
"self-context"
|
|
10
|
+
],
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "lib/index.js",
|
|
14
|
+
"types": "lib/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./lib/index.d.ts",
|
|
18
|
+
"default": "./lib/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./projection": {
|
|
21
|
+
"types": "./lib/projection.d.ts",
|
|
22
|
+
"default": "./lib/projection.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"lib",
|
|
28
|
+
"src",
|
|
29
|
+
"cordis.patch.yml"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"dsh": ">=0.2.2-rc.5 <0.3.0"
|
|
33
|
+
},
|
|
34
|
+
"dsh": {
|
|
35
|
+
"bundle": {
|
|
36
|
+
"patch": "./cordis.patch.yml"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@deepseek-ai/cordis": "*",
|
|
41
|
+
"@deepseek-ai/dsh-agent": "*",
|
|
42
|
+
"@deepseek-ai/dsh-llm": "*",
|
|
43
|
+
"@deepseek-ai/dsh-session": "*",
|
|
44
|
+
"@deepseek-ai/dsh-session-projection": "*",
|
|
45
|
+
"@deepseek-ai/dsh-system-prompt": "*",
|
|
46
|
+
"@deepseek-ai/dsh-tools": "*",
|
|
47
|
+
"@deepseek-ai/schemastery": "*",
|
|
48
|
+
"zod": "^4.4.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@deepseek-ai/cordis": "4.1.0",
|
|
52
|
+
"@deepseek-ai/dsh-agent": "0.2.2-rc.5",
|
|
53
|
+
"@deepseek-ai/dsh-agent-loop": "0.2.2-rc.5",
|
|
54
|
+
"@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.5",
|
|
55
|
+
"@deepseek-ai/dsh-brand": "0.2.2-rc.5",
|
|
56
|
+
"@deepseek-ai/dsh-llm": "0.2.2-rc.5",
|
|
57
|
+
"@deepseek-ai/dsh-session": "0.2.2-rc.5",
|
|
58
|
+
"@deepseek-ai/dsh-session-projection": "0.2.2-rc.5",
|
|
59
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.2-rc.5",
|
|
60
|
+
"@deepseek-ai/dsh-tools": "0.2.2-rc.5",
|
|
61
|
+
"@deepseek-ai/schemastery": "3.19.0",
|
|
62
|
+
"@types/node": "^22.20.0",
|
|
63
|
+
"typescript": "^6.0.3",
|
|
64
|
+
"vitest": "^4.1.11",
|
|
65
|
+
"zod": "4.6.6"
|
|
66
|
+
},
|
|
67
|
+
"repository": {
|
|
68
|
+
"type": "git",
|
|
69
|
+
"url": "git+https://github.com/natgurlain/dsh-self-context.git"
|
|
70
|
+
},
|
|
71
|
+
"homepage": "https://github.com/natgurlain/dsh-self-context#readme",
|
|
72
|
+
"publishConfig": {
|
|
73
|
+
"access": "public"
|
|
74
|
+
},
|
|
75
|
+
"scripts": {
|
|
76
|
+
"build": "tsc -p tsconfig.build.json",
|
|
77
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
78
|
+
"test": "vitest run"
|
|
79
|
+
}
|
|
6
80
|
}
|