@lincyaw/dsh 0.2.0-rc.3 → 0.2.0-rc.31

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.
@@ -9,6 +9,8 @@ export interface DshLogger {
9
9
  export interface DshSession {
10
10
  readonly id: string
11
11
  readonly header?: { cwd?: string }
12
+ /** The route the session's latest model request resolved to (its latest `request/context`). */
13
+ requestContext(): { provider: string, model: string } | undefined
12
14
  }
13
15
 
14
16
  export interface DshAgent {
@@ -20,6 +22,8 @@ export interface DshAgent {
20
22
 
21
23
  export interface DshToolExecution {
22
24
  readonly callId: string
25
+ /** The registry's identity of the call, the same in `execute` and `projectContent`. */
26
+ readonly token: symbol
23
27
  readonly name: string
24
28
  readonly arguments: unknown
25
29
  readonly agent?: DshAgent
@@ -31,12 +35,38 @@ export type DshPreDecision =
31
35
  | { kind: 'deny', reason: string }
32
36
  | { kind: 'ask', reason?: string, displayReason?: { en: string, [locale: string]: string } }
33
37
 
38
+ export type DshImageMediaType = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif'
39
+
40
+ /** A durable image of dsh's attachment store (`ImageAttachmentRef`). */
41
+ export interface DshImageRef {
42
+ attachmentId: string
43
+ mediaType: DshImageMediaType
44
+ bytes: number
45
+ width: number
46
+ height: number
47
+ name?: string
48
+ }
49
+
50
+ export type DshContentBlock = { type: 'text', text: string } | { type: 'image', attachment: DshImageRef }
51
+
34
52
  export interface DshToolDefinition {
35
53
  name: string
36
54
  description: string
37
55
  parameters: Record<string, unknown>
38
- output: { schema: Record<string, unknown>, render(args: unknown, value: unknown): { type: 'text', text: string }[] }
56
+ output: { schema: Record<string, unknown>, render(args: unknown, value: unknown): DshContentBlock[] }
39
57
  execute(args: unknown, exec: DshToolExecution): Promise<unknown>
58
+ /** Content prepared during `execute` that replaces `output.render`'s, installed before `tools/post-execute`. */
59
+ projectContent?(exec: Readonly<DshToolExecution>, result: { readonly isError: boolean }): DshContentBlock[] | undefined
60
+ }
61
+
62
+ /** dsh's `attachments` service (`@deepseek-ai/dsh-attachment`), as far as tool results with images use it. */
63
+ export interface DshAttachments {
64
+ saveImages(inputs: readonly { data: Uint8Array, mediaType: DshImageMediaType, name?: string }[]): Promise<readonly DshImageRef[]>
65
+ }
66
+
67
+ /** dsh's `llm` service, as far as the input a model takes is concerned. */
68
+ export interface DshLlm {
69
+ resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<{ inputModalities?: readonly string[] }>
40
70
  }
41
71
 
42
72
  export interface DshTools {
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process'
2
2
  import type { ChildProcess } from 'node:child_process'
3
3
  import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
4
4
  import { createRequire } from 'node:module'
5
- import { dirname, join } from 'node:path'
5
+ import { delimiter, dirname, join } from 'node:path'
6
6
  import { fileURLToPath } from 'node:url'
7
7
  import { machineState, NODE_RESOURCE_ARGS, nodeResourceArgs, resourceEnvironment } from '@lincyaw/kernel/node'
8
8
  export { bracketIPv6, systemLocale } from '@lincyaw/kernel/node'
@@ -41,7 +41,12 @@ export function dshBin(from = PACKAGE_DIR): string {
41
41
  }
42
42
 
43
43
  export function launchEnv(dshHome: string, env: NodeJS.ProcessEnv = process.env): Record<string, string> {
44
- return resourceEnvironment({ DSH_HOME: dshHome, DSH_AGENTS_HOME: join(dshHome, 'agents'), DSH_TELEMETRY_MODE: 'DISABLED', PRESMIUM_MAX_THREADS: env.PRESMIUM_MAX_THREADS }, 'interactive')
44
+ // The native addon's shared CJS loader resolves its optional platform package from its own directory.
45
+ // Strict pnpm installs keep that package beside the entry package instead; expose its declared dependencies.
46
+ const nativeModules = dirname(dirname(createRequire(import.meta.url).resolve('node-addon-require-builtin/package.json')))
47
+ return resourceEnvironment({ DSH_HOME: dshHome, DSH_AGENTS_HOME: join(dshHome, 'agents'), DSH_TELEMETRY_MODE: 'DISABLED', PRESMIUM_MAX_THREADS: env.PRESMIUM_MAX_THREADS,
48
+ NODE_PATH: [nativeModules, env.NODE_PATH].filter(Boolean).join(delimiter),
49
+ }, 'interactive')
45
50
  }
46
51
 
47
52
  /** The variables a launcher sets for the processes it starts; they are never inherited from its own environment. */
@@ -24,6 +24,8 @@ const displayText = (text: string, lang?: string) => ({ en: text, ...lang ? { [l
24
24
 
25
25
  export function apply(ctx: DshContext): void {
26
26
  const operatorDir = operatorRoot()
27
+ let authorRoot: string | undefined
28
+ void ctx.presmium.server.ready.then(endpoint => { authorRoot = endpoint.root })
27
29
 
28
30
  ctx.on('tools/pre-execute', async (exec: DshToolExecution, next: () => Promise<DshPreDecision>): Promise<DshPreDecision> => {
29
31
  const { bindings } = ctx.presmium
@@ -48,8 +50,11 @@ export function apply(ctx: DshContext): void {
48
50
  ctx.tools.guard((exec) => {
49
51
  const file = FILE_WRITE_TOOLS.has(exec.name) ? fileOf(exec) : undefined
50
52
  const dir = exec.agent ? ctx.presmium.bindings.workingDirectoryOf(exec.agent) : process.cwd()
53
+ const candidate = ctx.presmium.bindings.candidateRootOf(exec.agent)
54
+ if (candidate && authorRoot && file && isInside(resolve(dir, file), authorRoot) && !isInside(resolve(dir, file), candidate)) return 'Presmium: write in your current candidate workspace using relative paths. The author workspace changed independently; read the current candidate file and retry.'
51
55
  if (file && isInside(resolve(dir, file), operatorDir)) return `Presmium: the operator directory (${operatorDir}) is not the agent's to write`
52
56
  const command = exec.name === 'bash' ? (exec.arguments as { command?: unknown } | undefined)?.command : undefined
57
+ if (candidate && authorRoot && typeof command === 'string' && command.replaceAll(candidate, '').includes(authorRoot)) return 'Presmium: use your current candidate workspace instead of the author workspace absolute path. Read the file there and retry.'
53
58
  if (typeof command === 'string' && command.includes(operatorDir)) return `Presmium: the operator directory (${operatorDir}) is not the agent's to touch`
54
59
  return undefined
55
60
  })
@@ -10,7 +10,7 @@ export const ROUTES: Record<string, string> = Object.fromEntries([
10
10
  'document/media-clip/validate', 'document/transcription/capabilities', 'document/transcription', 'document/transcription/result', 'document/transcription/cancel',
11
11
  'document/transcription/adoption/plan', 'document/transcription/adoption/apply',
12
12
  'ir', 'ir/events', 'preview', 'build', 'check', 'jobs', 'jobs/cancel', 'jobs/events', 'voice-catalog', 'voice-capabilities',
13
- 'review', 'review/open', 'review/step', 'review/accept', 'review/reject', 'review/restore'].map(path => [path, `${WORKSPACE_ROUTES}${path}`]),
13
+ 'review', 'review/workspace', 'review/open', 'review/step', 'review/accept', 'review/reject', 'review/restore'].map(path => [path, `${WORKSPACE_ROUTES}${path}`]),
14
14
  ['focus', `${SERVER_ROUTES}focus`],
15
15
  ['control', `${SERVER_ROUTES}control`],
16
16
  ['diagnostics', `${SERVER_ROUTES}diagnostics`],
@@ -37,6 +37,12 @@ export function apply(ctx: DshContext): void {
37
37
  const value = request.headers.get(name)
38
38
  if (value !== null) headers[name] = value
39
39
  }
40
+ if (path === 'preview') {
41
+ const browser = new URL(request.url)
42
+ const host = request.headers.get('host')
43
+ if (host) browser.host = host
44
+ headers['x-presmium-preview-origin'] = browser.origin
45
+ }
40
46
  const upstream = await ctx.presmium.server.request(`${target}${new URL(request.url).search}`, {
41
47
  method: request.method,
42
48
  headers,
@@ -15,6 +15,7 @@ export interface Config {
15
15
  url?: string
16
16
  token?: string
17
17
  root?: string
18
+ candidate?: boolean
18
19
  }
19
20
 
20
21
  export interface Endpoint {
@@ -54,6 +55,7 @@ export class WorkspaceServerClient {
54
55
  presmium: cliBin(),
55
56
  dir: root,
56
57
  serviceToken,
58
+ env: { ...process.env, ...config.candidate ? { PRESMIUM_AGENT_CANDIDATE: '1' } : {} },
57
59
  onOutput: (text) => {
58
60
  for (const line of text.split('\n').filter(Boolean)) log.debug(`presmium serve: ${line}`)
59
61
  },
@@ -104,6 +106,7 @@ export class WorkspaceServerClient {
104
106
  this.#closed = true
105
107
  if (this.#launched) {
106
108
  this.#launched.child.kill('SIGTERM')
109
+ await this.#launched.exited
107
110
  return
108
111
  }
109
112
  await this.request(`${SERVER_ROUTES}tokens`, { method: 'DELETE', body: {} }).then(r => r.body?.cancel(), () => undefined)
package/src/node/tools.ts CHANGED
@@ -1,23 +1,63 @@
1
- import type { ListedTool } from '@lincyaw/mcp/client'
2
- import type { DshAgent, DshContext, DshToolDefinition } from './dsh-types.ts'
1
+ import { errorMessage } from '@lincyaw/kernel'
2
+ import type { CalledImage, ListedTool } from '@lincyaw/mcp/client'
3
+ import type { DshAgent, DshAttachments, DshContentBlock, DshContext, DshImageMediaType, DshLlm, DshToolDefinition, DshToolExecution } from './dsh-types.ts'
3
4
  import type { DocumentBinding } from './bindings.ts'
4
5
 
5
6
  export const name = 'presmium-tools'
6
7
  export const inject = ['presmium', 'tools']
7
8
 
8
9
  export const PREFIX = 'presmium__'
10
+ export const CANDIDATE_TOOLS = new Set([
11
+ 'get_authoring_capabilities', 'get_document', 'get_document_outline', 'read_document_part',
12
+ 'plan_document_change', 'apply_document_change', 'plan_page_change', 'apply_page_change',
13
+ 'plan_page_duplication', 'apply_page_duplication', 'plan_authoring_action', 'apply_authoring_action', 'read_authoring_action_impact',
14
+ 'check_document', 'get_section', 'get_step', 'list_sections', 'deck_info', 'list_documents',
15
+ 'run_code', 'capture_slides', 'capture_reading', 'capture_overview',
16
+ ])
9
17
 
10
- function definition(binding: DocumentBinding, tool: ListedTool): DshToolDefinition {
18
+ const IMAGE_TYPES = new Set<string>(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
19
+
20
+ /**
21
+ * A tool result's images as dsh's durable image blocks, which reach the model beside the text; only when the model of
22
+ * the session's latest request declares image input, as dsh's own MCP client does. Otherwise, and when the attachment
23
+ * store refuses them, one line says they were left out (the text names their files where the tool has any) and the call
24
+ * still succeeds.
25
+ */
26
+ async function imageBlocks(ctx: DshContext, tool: string, images: CalledImage[], exec: DshToolExecution): Promise<DshContentBlock[]> {
27
+ const leftOut = (why: string): DshContentBlock[] => [{ type: 'text', text: `[${images.length} image${images.length === 1 ? '' : 's'} not attached: ${why}]` }]
28
+ const attachments = ctx.get('attachments') as DshAttachments | undefined
29
+ const llm = ctx.get('llm') as DshLlm | undefined
30
+ const { provider, model } = exec.agent?.session.requestContext() ?? {}
31
+ if (!attachments || !llm || !provider || !model) return leftOut('this session takes no images')
32
+ const info = await llm.resolveModelInfo(provider, model, exec.signal).catch(() => undefined)
33
+ if (!info?.inputModalities?.includes('image')) return leftOut(`the model ${model} does not take images`)
34
+ if (images.some(image => !IMAGE_TYPES.has(image.mimeType))) return leftOut('not PNG, JPEG, WebP or GIF')
35
+ try {
36
+ const refs = await attachments.saveImages(images.map((image, n) => ({ data: Buffer.from(image.data, 'base64'), mediaType: image.mimeType as DshImageMediaType, name: `${tool}-${n + 1}.${image.mimeType.slice('image/'.length)}` })))
37
+ return refs.map(attachment => ({ type: 'image', attachment }))
38
+ } catch (error) {
39
+ return leftOut(errorMessage(error))
40
+ }
41
+ }
42
+
43
+ function definition(ctx: DshContext, binding: DocumentBinding, tool: ListedTool): DshToolDefinition {
44
+ const prepared = new Map<symbol, DshContentBlock[]>()
11
45
  return {
12
46
  name: `${PREFIX}${tool.name}`,
13
47
  description: tool.description,
14
48
  parameters: tool.inputSchema,
15
49
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
16
50
  async execute(args, exec) {
17
- const result = await binding.client.call(tool.name, (args ?? {}) as Record<string, unknown>, exec.signal)
51
+ const result = await (CANDIDATE_TOOLS.has(tool.name) ? binding.client : binding.authorClient).call(tool.name, (args ?? {}) as Record<string, unknown>, exec.signal)
18
52
  if (result.isError) throw new Error(result.text)
53
+ if (result.images.length > 0) prepared.set(exec.token, [...result.text ? [{ type: 'text' as const, text: result.text }] : [], ...await imageBlocks(ctx, tool.name, result.images, exec)])
19
54
  return result.text
20
55
  },
56
+ projectContent(exec, result) {
57
+ const content = prepared.get(exec.token)
58
+ prepared.delete(exec.token)
59
+ return result.isError ? undefined : content
60
+ },
21
61
  }
22
62
  }
23
63
 
@@ -34,7 +74,7 @@ export function apply(ctx: DshContext): void {
34
74
  registered.set(agent, {
35
75
  binding, tools: binding?.tools,
36
76
  stop: binding?.toolChanges.watch(() => { if (agent.status === 'idle') install(agent, binding) }),
37
- dispose: binding?.tools.map(tool => agent.ctx.tools.register(definition(binding, tool))) ?? [],
77
+ dispose: binding?.tools.map(tool => agent.ctx.tools.register(definition(ctx, binding, tool))) ?? [],
38
78
  })
39
79
  }
40
80
  const sync = async (agent: DshAgent) => {
@@ -57,6 +97,7 @@ export function apply(ctx: DshContext): void {
57
97
  for (const dispose of previous?.dispose ?? []) dispose()
58
98
  })
59
99
  ctx.on('agent/pre-step', async ({ agent }: { agent: DshAgent }, next: () => Promise<unknown>) => {
100
+ await ctx.presmium.bindings.refreshCandidate(agent)
60
101
  await sync(agent)
61
102
  return next()
62
103
  })
package/src/node/turns.ts CHANGED
@@ -3,6 +3,7 @@ import { errorMessage } from '@lincyaw/kernel'
3
3
  import { isInside } from '@lincyaw/kernel/node'
4
4
  import type { DshAgent, DshContext, DshToolExecution } from './dsh-types.ts'
5
5
  import { WORKSPACE_ROUTES } from './server-routes.ts'
6
+ import { CANDIDATE_TOOLS, PREFIX } from './tools.ts'
6
7
 
7
8
  // What a writing tool answers when the change cannot be recorded. The AI reads it and tells the author in their own
8
9
  // language, so it names what the author sees (Version History) and none of the internals behind it.
@@ -83,7 +84,8 @@ export function apply(ctx: DshContext): void {
83
84
  if (path === 'open' && response.status === 404) throw new Error(NOT_RECORDED)
84
85
  let reason = text
85
86
  try {
86
- reason = (JSON.parse(text) as { error?: string, detail?: string }).error ?? reason
87
+ const failure = JSON.parse(text) as { error?: string, next?: string, paths?: string[] }
88
+ reason = [failure.error, failure.paths?.join(', '), failure.next].filter(Boolean).join(' ') || reason
87
89
  } catch {
88
90
  }
89
91
  throw new Error(reason || `the review answered ${response.status}`)
@@ -100,9 +102,13 @@ export function apply(ctx: DshContext): void {
100
102
  })
101
103
 
102
104
  ctx.on('tools/execute', async (exec: DshToolExecution, next: () => Promise<unknown>) => {
103
- if (!WRITING_TOOLS.has(exec.name) || !exec.agent) return next()
105
+ if (!exec.agent) return next()
104
106
  const { root } = await ctx.presmium.server.ready
105
107
  if (!isInside(ctx.presmium.bindings.workingDirectoryOf(exec.agent), root)) return next()
108
+ await ctx.presmium.bindings.candidateOf(exec.agent)
109
+ const binding = ctx.presmium.bindings.bindingOf(exec.agent)
110
+ const tool = exec.name.startsWith(PREFIX) ? binding?.tools.find(tool => `${PREFIX}${tool.name}` === exec.name) : undefined
111
+ if (!WRITING_TOOLS.has(exec.name) && (!tool || tool.kind === 'read' || !CANDIDATE_TOOLS.has(tool.name))) return next()
106
112
  const document = ctx.presmium.bindings.bindingOf(exec.agent)?.document.dir ?? ''
107
113
  const agentSessionId = rootAgentSessionOf(exec.agent.session.id)
108
114
  const state = turnStateOf(agentSessionId)
@@ -113,12 +119,9 @@ export function apply(ctx: DshContext): void {
113
119
  }
114
120
  state.document = document
115
121
  state.wrote = true
116
- try {
117
- return await next()
118
- } finally {
119
- await postReview(document, agentSessionId, 'step', { ...state.turn !== undefined ? { turn: state.turn } : {}, label: labelOf(exec), tool: exec.name })
120
- .catch((error: unknown) => log.warn(`presmium-turns: no checkpoint after ${exec.name} in ${agentSessionId}: ${errorMessage(error)}`))
121
- }
122
+ const result = await next()
123
+ await postReview(document, agentSessionId, 'step', { ...state.turn !== undefined ? { turn: state.turn } : {}, label: labelOf(exec), tool: exec.name })
124
+ return result
122
125
  })
123
126
 
124
127
  ctx.on('agent/created', ({ agent }: { agent: LiveAgent }) => {
@@ -1,37 +0,0 @@
1
- import { PmMascot, PmSegmented, setMascotEnabled, useAssistantMascot, useMascotEnabled, WorkbenchProvider } from '@lincyaw/workbench'
2
- import type { Workbench } from '@lincyaw/workbench'
3
- import { MASCOT_SETTING, MASCOT_SLOT } from './contract.ts'
4
- import { useClientMessages } from './messages.ts'
5
-
6
- /** The session header's standard prop: a selector over the bound session's snapshot. */
7
- type UseSession = <T>(select: (snapshot: { running?: boolean }) => T) => T
8
-
9
- function Kitten({ running }: { running: boolean }) {
10
- return <span className="pmw-conversation-mascot"><PmMascot size="small" action={useAssistantMascot(running)} /></span>
11
- }
12
-
13
- function MascotSetting({ workbench }: { workbench: Workbench }) {
14
- const t = useClientMessages(workbench)
15
- const on = useMascotEnabled()
16
- return (
17
- <div className="pmw-mascot-setting pm-ui" data-pmw-setting="mascot">
18
- <div className="pmw-mascot-setting__copy">
19
- <p className="pmw-mascot-setting__title">{t.mascot}</p>
20
- <p className="pmw-mascot-setting__hint">{t.mascotHint}</p>
21
- </div>
22
- <PmSegmented label={t.mascot} value={on ? 'show' : 'hide'} options={[{ value: 'show', label: t.mascotShow }, { value: 'hide', label: t.mascotHide }]} onChange={value => setMascotEnabled(value === 'show')} />
23
- </div>
24
- )
25
- }
26
-
27
- /** Puts the kitten in the conversation's header, where it acts out what the assistant is doing, and its switch in
28
- * Settings → General. */
29
- export function registerMascot(ctx: DshClientContext, workbench: Workbench): void {
30
- ctx.effect(() => ctx.slots.inject(MASCOT_SLOT.name, () => ctx.slots.register({ name: MASCOT_SLOT.name, id: MASCOT_SLOT.id, order: -100 }, ({ useSession }: { useSession: UseSession }) => {
31
- const running = useSession(snapshot => Boolean(snapshot.running))
32
- return <WorkbenchProvider workbench={workbench}><Kitten running={running} /></WorkbenchProvider>
33
- })), 'presmium: the kitten beside the conversation')
34
- ctx.effect(() => ctx.slots.inject(MASCOT_SETTING.name, () => ctx.slots.register({ name: MASCOT_SETTING.name, id: MASCOT_SETTING.id, order: 1000 }, () => (
35
- <WorkbenchProvider workbench={workbench}><MascotSetting workbench={workbench} /></WorkbenchProvider>
36
- ))), 'presmium: the kitten\'s switch in Settings')
37
- }