dsh-context-mode 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -59,6 +59,8 @@ MCP `initialize` and `tools/list`, registers each returned tool through the DSH
59
59
  tool registry, and forwards every call over MCP stdio. The child is terminated
60
60
  when the Cordis plugin is disposed.
61
61
 
62
+ The adapter injects active memory from DSH's durable Session log into the next model assembly. DSH remains the source of truth for session recovery and compaction continuity; context-mode's hook-specific SessionDB analytics are not duplicated by this wrapper.
63
+
62
64
  The bridge sets `CONTEXT_MODE_PLATFORM=pi` for compatibility with context-mode's
63
65
  existing adapter defaults, while `CONTEXT_MODE_DIR` keeps DSH data separate from
64
66
  Pi and Claude Code data. `CONTEXT_MODE_PROJECT_DIR` pins project hashing to the
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAOlD,eAAO,MAAM,IAAI,qBAAqB,CAAA;AAEtC,qDAAqD;AACrD,MAAM,WAAW,MAAM;IACrB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,yDAAyD;IACzD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,6DAA6D;IAC7D,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAC5B;AAED,eAAO,MAAM,MAAM,EAAE,WAAW,CAAC,MAAM,CAMrC,CAAA;AAqCF,+EAA+E;AAC/E,wBAAsB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,MAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAkE5E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AASlD,eAAO,MAAM,IAAI,qBAAqB,CAAA;AAEtC,qDAAqD;AACrD,MAAM,WAAW,MAAM;IACrB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,yDAAyD;IACzD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,6DAA6D;IAC7D,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAC5B;AAED,eAAO,MAAM,MAAM,EAAE,WAAW,CAAC,MAAM,CAMrC,CAAA;AAqCF,+EAA+E;AAC/E,wBAAsB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,MAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAwE5E"}
@@ -11,6 +11,8 @@ import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
12
  import z from '@deepseek-ai/schemastery';
13
13
  import { McpStdioClient } from './mcp-client.js';
14
+ import { installBashRoutingGuard } from './routing.js';
15
+ import { installSessionMemory } from './session-memory.js';
14
16
  export const name = 'dsh-context-mode';
15
17
  export const Config = z.object({
16
18
  enabled: z.boolean().default(true),
@@ -61,10 +63,14 @@ export async function apply(ctx, config = {}) {
61
63
  let client;
62
64
  ctx.effect(() => () => {
63
65
  disposed = true;
66
+ client?.shutdown();
64
67
  for (const dispose of disposers.splice(0))
65
68
  dispose();
66
- client?.shutdown();
67
69
  }, 'dsh-context-mode MCP bridge');
70
+ const routingDisposer = installBashRoutingGuard(tools);
71
+ disposers.push(routingDisposer);
72
+ const memoryDisposer = installSessionMemory(ctx);
73
+ disposers.push(memoryDisposer);
68
74
  const skillDisposer = registerBundledSkill(ctx);
69
75
  if (skillDisposer !== undefined)
70
76
  disposers.push(skillDisposer);
@@ -81,6 +87,7 @@ export async function apply(ctx, config = {}) {
81
87
  bridge.start();
82
88
  await bridge.initialize(resolved.handshakeTimeoutMs);
83
89
  const catalog = await bridge.listTools(resolved.handshakeTimeoutMs);
90
+ const systemPrompt = ctx.get('systemPrompt', false);
84
91
  for (const tool of catalog) {
85
92
  if (disposed)
86
93
  return;
@@ -92,12 +99,13 @@ export async function apply(ctx, config = {}) {
92
99
  }
93
100
  }
94
101
  if (disposers.length > 0) {
95
- const systemPrompt = ctx.get('systemPrompt', false);
96
- systemPrompt?.section({
97
- name: 'dsh-context-mode:routing',
98
- order: systemPrompt.getSectionOrder('TOOL_CORDIS'),
99
- text: ({ scope }) => ctx.tools.get('ctx_execute', scope) === undefined ? '' : ROUTING_TEXT,
100
- });
102
+ if (systemPrompt !== undefined) {
103
+ disposers.push(systemPrompt.section({
104
+ name: 'dsh-context-mode:routing',
105
+ order: systemPrompt.getSectionOrder('TOOL_CORDIS'),
106
+ text: ({ scope }) => tools.get('ctx_execute', scope) === undefined ? '' : ROUTING_TEXT,
107
+ }));
108
+ }
101
109
  }
102
110
  ctx.logger.info(`dsh-context-mode: registered ${disposers.length} context-mode tools`);
103
111
  }
@@ -0,0 +1,8 @@
1
+ import type { ToolRuntime } from '@deepseek-ai/dsh-tools';
2
+ /** Install the Pi-equivalent guard for context-flooding Bash requests. */
3
+ export declare function installBashRoutingGuard(tools: ToolRuntime): () => void;
4
+ /** Remove quoted arguments before evaluating shell command routing tokens. */
5
+ export declare function stripQuotedContent(command: string): string;
6
+ /** Return whether a curl or wget segment writes output away from the model. */
7
+ export declare function isSafeCurlWget(segment: string): boolean;
8
+ //# sourceMappingURL=routing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing.d.ts","sourceRoot":"","sources":["../../src/routing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAYxE,0EAA0E;AAC1E,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,IAAI,CAmBtE;AAED,8EAA8E;AAC9E,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAK1D;AAED,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAcvD"}
@@ -0,0 +1,60 @@
1
+ const BLOCKED_HTTP_PATTERNS = [
2
+ /\bfetch\s*\(/,
3
+ /\brequests\.get\s*\(/,
4
+ /\brequests\.post\s*\(/,
5
+ /\bhttp\.get\s*\(/,
6
+ /\bhttp\.request\s*\(/,
7
+ /\burllib\.request/,
8
+ /\bInvoke-WebRequest\b/,
9
+ ];
10
+ /** Install the Pi-equivalent guard for context-flooding Bash requests. */
11
+ export function installBashRoutingGuard(tools) {
12
+ return tools.guard((execution) => {
13
+ if (execution.name !== 'bash')
14
+ return undefined;
15
+ const args = execution.arguments;
16
+ if (args === null || typeof args !== 'object' || Array.isArray(args))
17
+ return undefined;
18
+ const command = args.command;
19
+ if (typeof command !== 'string' || command.length === 0)
20
+ return undefined;
21
+ const stripped = stripQuotedContent(command);
22
+ if (BLOCKED_HTTP_PATTERNS.some(pattern => pattern.test(stripped))) {
23
+ return 'Use context-mode tools (ctx_execute, ctx_fetch_and_index) instead of inline HTTP clients. Raw fetch/requests/http output floods the context window.';
24
+ }
25
+ if (!/(^|\s|&&|\||;)(curl|wget)\s/i.test(stripped))
26
+ return undefined;
27
+ const unsafe = stripped.split(/\s*(?:&&|\|\||;)\s*/).some(segment => !isSafeCurlWget(segment));
28
+ if (unsafe) {
29
+ return 'Use context-mode tools (ctx_execute, ctx_fetch_and_index) instead of inline HTTP clients. Raw curl/wget output floods the context window. For an MCP-down escape hatch, use silent + file output: `curl -s -o /tmp/x.json URL` or `wget -q -O /tmp/x.json URL`.';
30
+ }
31
+ return undefined;
32
+ });
33
+ }
34
+ /** Remove quoted arguments before evaluating shell command routing tokens. */
35
+ export function stripQuotedContent(command) {
36
+ return command
37
+ .replace(/<<-?\s*["']?(\w+)["']?[\s\S]*?\n\s*\1/g, '')
38
+ .replace(/'[^']*'/g, "''")
39
+ .replace(/"[^"]*"/g, '""');
40
+ }
41
+ /** Return whether a curl or wget segment writes output away from the model. */
42
+ export function isSafeCurlWget(segment) {
43
+ const value = segment.trim();
44
+ const isCurl = /\bcurl\b/i.test(value);
45
+ const isWget = /\bwget\b/i.test(value);
46
+ if (!isCurl && !isWget)
47
+ return true;
48
+ const hasFileOutput = isCurl
49
+ ? /\s(-o|--output)\s/.test(value) || /\s>\s*/.test(value) || /\s>>\s*/.test(value)
50
+ : /\s(-O|--output-document)\s/.test(value) || /\s>\s*/.test(value) || /\s>>\s*/.test(value);
51
+ if (!hasFileOutput)
52
+ return false;
53
+ if (isCurl && /\s(-o|--output)\s+(-|\/dev\/stdout)(\s|$)/.test(value))
54
+ return false;
55
+ if (isWget && /\s(-O|--output-document)\s+(-|\/dev\/stdout)(\s|$)/.test(value))
56
+ return false;
57
+ if (/\s(-v|--verbose|--trace)\b/.test(value))
58
+ return false;
59
+ return isCurl ? /\s-[a-zA-Z]*s|--silent/.test(value) : /\s-[a-zA-Z]*q|--quiet/.test(value);
60
+ }
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ /** Register dynamic active-memory context over DSH's durable Session log. */
3
+ export declare function installSessionMemory(ctx: Context): () => void;
4
+ //# sourceMappingURL=session-memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-memory.d.ts","sourceRoot":"","sources":["../../src/session-memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAgClD,6EAA6E;AAC7E,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,IAAI,CAY7D"}
@@ -0,0 +1,127 @@
1
+ const CONTEXT_NAME = 'dsh-context-mode:active-memory';
2
+ const MAX_EVENTS = 50;
3
+ const MAX_LINE_LENGTH = 480;
4
+ const MAX_MEMORY_LENGTH = 2_000;
5
+ /** Register dynamic active-memory context over DSH's durable Session log. */
6
+ export function installSessionMemory(ctx) {
7
+ const prompt = ctx.get('systemPrompt', false);
8
+ if (prompt === undefined)
9
+ return () => { };
10
+ const states = new WeakMap();
11
+ return prompt.context({
12
+ name: CONTEXT_NAME,
13
+ order: prompt.getContextOrder('SUBAGENT_DELEGATION') + 1,
14
+ text: rawContext => {
15
+ const context = rawContext;
16
+ return buildMemory(context.agent ?? context.scope, states);
17
+ },
18
+ });
19
+ }
20
+ function buildMemory(scope, states) {
21
+ const session = sessionFromScope(scope);
22
+ if (session === undefined)
23
+ return '';
24
+ const key = session;
25
+ let state = states.get(key);
26
+ if (state === undefined) {
27
+ state = { session };
28
+ states.set(key, state);
29
+ }
30
+ const events = session.snapshotEvents();
31
+ const lines = [];
32
+ const summary = [...events].reverse().find(event => event.type === 'compaction/summary');
33
+ if (summary !== undefined && summary.seq !== state.summarySeq) {
34
+ const text = summaryText(summary.data);
35
+ if (text.length > 0)
36
+ lines.push(`<resume_snapshot>\n${text}\n</resume_snapshot>`);
37
+ state = { ...state, summarySeq: summary.seq };
38
+ states.set(key, state);
39
+ }
40
+ for (const event of events.slice(-MAX_EVENTS)) {
41
+ const line = memoryLine(event);
42
+ if (line !== undefined)
43
+ lines.push(line);
44
+ }
45
+ if (lines.length === 0)
46
+ return '';
47
+ let text = lines.join('\n');
48
+ if (text.length > MAX_MEMORY_LENGTH)
49
+ text = text.slice(text.length - MAX_MEMORY_LENGTH);
50
+ return `<active_memory>\n${text}\n</active_memory>`;
51
+ }
52
+ function sessionFromScope(scope) {
53
+ if (scope === null || typeof scope !== 'object')
54
+ return undefined;
55
+ const session = scope.session;
56
+ return session !== undefined && typeof session.snapshotEvents === 'function' ? session : undefined;
57
+ }
58
+ function memoryLine(event) {
59
+ if (event.type === 'user/message') {
60
+ const source = event.data && typeof event.data === 'object'
61
+ ? event.data.source
62
+ : undefined;
63
+ if (source?.kind === 'plugin')
64
+ return undefined;
65
+ const text = extractText(event.data);
66
+ return text.length > 0 ? `user: ${clip(text)}` : undefined;
67
+ }
68
+ if (event.type === 'tool/call') {
69
+ const name = fieldString(event.data, 'name');
70
+ return name === undefined ? undefined : `tool call: ${name}`;
71
+ }
72
+ if (event.type === 'tool/result') {
73
+ const name = fieldString(event.data, 'name');
74
+ const failed = fieldBoolean(event.data, 'isError') === true;
75
+ return name === undefined ? undefined : `tool result${failed ? ' (error)' : ''}: ${name}`;
76
+ }
77
+ if (event.type.startsWith('plan/') || event.type.startsWith('goal/') || event.type.startsWith('todo/')) {
78
+ return `${event.type}: ${clip(JSON.stringify(event.data) ?? '')}`;
79
+ }
80
+ return undefined;
81
+ }
82
+ function summaryText(data) {
83
+ if (data === null || typeof data !== 'object')
84
+ return '';
85
+ const summary = data.summary;
86
+ if (!Array.isArray(summary))
87
+ return '';
88
+ return summary
89
+ .map(block => block && typeof block === 'object' && typeof block.text === 'string'
90
+ ? block.text
91
+ : '')
92
+ .filter(Boolean)
93
+ .join('\n')
94
+ .slice(0, MAX_MEMORY_LENGTH);
95
+ }
96
+ function extractText(data) {
97
+ if (data === null || typeof data !== 'object')
98
+ return '';
99
+ const content = data.message?.content
100
+ ?? data.content;
101
+ if (typeof content === 'string')
102
+ return content;
103
+ if (!Array.isArray(content))
104
+ return '';
105
+ return content
106
+ .map(block => block && typeof block === 'object' && typeof block.text === 'string'
107
+ ? block.text
108
+ : '')
109
+ .filter(Boolean)
110
+ .join('\n');
111
+ }
112
+ function fieldString(data, field) {
113
+ if (data === null || typeof data !== 'object')
114
+ return undefined;
115
+ const value = data[field];
116
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
117
+ }
118
+ function fieldBoolean(data, field) {
119
+ if (data === null || typeof data !== 'object')
120
+ return undefined;
121
+ const value = data[field];
122
+ return typeof value === 'boolean' ? value : undefined;
123
+ }
124
+ function clip(value) {
125
+ const normalized = value.replace(/\s+/g, ' ').trim();
126
+ return normalized.length <= MAX_LINE_LENGTH ? normalized : `${normalized.slice(0, MAX_LINE_LENGTH - 1)}…`;
127
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-mode",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Expose context-mode MCP tools as native DeepSeek Harness tools",
5
5
  "keywords": [
6
6
  "dsh",