@lincyaw/dsh 0.2.0-rc.10 → 0.2.0-rc.101
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/build/client.mjs +0 -2
- package/build/dist/client.js +302 -299
- package/build/dist/client.json +74 -41
- package/cordis.patch.yml +1 -0
- package/package.json +10 -9
- package/src/client/RootLayout.tsx +18 -15
- package/src/client/agent-requests.ts +47 -0
- package/src/client/contract.ts +0 -6
- package/src/client/dsh.d.ts +12 -0
- package/src/client/fallback.tsx +6 -4
- package/src/client/frame.css +0 -10
- package/src/client/index.tsx +8 -7
- package/src/client/layout.ts +9 -6
- package/src/client/messages.ts +6 -10
- package/src/client/navigation-shell.tsx +2 -2
- package/src/client/runtime-diagnostics.tsx +1 -1
- package/src/client/settings-launcher.tsx +19 -0
- package/src/client/settings-opener.ts +6 -0
- package/src/client/speech-settings.tsx +2 -1
- package/src/client/startup.css +47 -0
- package/src/client/startup.ts +17 -0
- package/src/client/styles.css +0 -42
- package/src/client/workspace-events.ts +10 -8
- package/src/node/bindings.ts +100 -8
- package/src/node/context.ts +16 -26
- package/src/node/dsh-types.ts +31 -1
- package/src/node/launch.ts +32 -11
- package/src/node/policy.ts +13 -3
- package/src/node/routes.ts +8 -1
- package/src/node/service.ts +7 -1
- package/src/node/startup.ts +73 -0
- package/src/node/tools.ts +118 -6
- package/src/node/turns.ts +12 -8
- package/src/node/workbench.ts +9 -2
- package/src/node/workspace-events.ts +7 -4
- package/src/startup-messages.ts +15 -0
- package/src/workspace-events.ts +3 -2
- package/src/client/mascot.tsx +0 -37
package/src/node/dsh-types.ts
CHANGED
|
@@ -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):
|
|
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 {
|
package/src/node/launch.ts
CHANGED
|
@@ -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,12 +41,17 @@ 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
|
-
|
|
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. */
|
|
48
53
|
export function isLauncherVariable(name: string): boolean {
|
|
49
|
-
return /^(?:DSH_|PRESMIUM_MODEL_|PRESMIUM_SERVICE_)/.test(name) || ['PRESMIUM_WORKSPACE', 'NODE_ENV', 'PORT'].includes(name)
|
|
54
|
+
return /^(?:DSH_|PRESMIUM_MODEL_|PRESMIUM_SERVICE_|PRESMIUM_MCP_)/.test(name) || ['PRESMIUM_WORKSPACE', 'PRESMIUM_COMMAND', 'NODE_ENV', 'PORT'].includes(name)
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
export function inheritedEnv(env: NodeJS.ProcessEnv, drop: (name: string) => boolean): Record<string, string> {
|
|
@@ -142,10 +147,10 @@ export interface LaunchedWorkspaceServer {
|
|
|
142
147
|
}
|
|
143
148
|
|
|
144
149
|
/** Starts `presmium serve <dir> --port <port, default 0: a free one> [args]` with `launchNode`, in `workspaceServerEnv`. */
|
|
145
|
-
export function launchWorkspaceServer(options: { presmium: string, dir: string, serviceToken: string, port?: number, args?: string[], env?: NodeJS.ProcessEnv, onOutput?(text: string): void }): LaunchedWorkspaceServer {
|
|
150
|
+
export function launchWorkspaceServer(options: { presmium: string, dir: string, serviceToken: string, mcpToken?: string, port?: number, args?: string[], env?: NodeJS.ProcessEnv, onOutput?(text: string): void }): LaunchedWorkspaceServer {
|
|
146
151
|
const server = launchNode('presmium serve', [options.presmium, 'serve', options.dir, '--port', String(options.port ?? 0), ...options.args ?? []], {
|
|
147
152
|
cwd: options.dir,
|
|
148
|
-
env: workspaceServerEnv(options.env ?? process.env, options.serviceToken),
|
|
153
|
+
env: { ...workspaceServerEnv(options.env ?? process.env, options.serviceToken), ...options.mcpToken ? { PRESMIUM_MCP_TOKEN: options.mcpToken } : {} },
|
|
149
154
|
...options.onOutput ? { onOutput: options.onOutput } : {},
|
|
150
155
|
})
|
|
151
156
|
const ready = (async () => {
|
|
@@ -161,16 +166,32 @@ export function writeProfile(dshHome: string, name: string, carrier: Carrier, bu
|
|
|
161
166
|
const dir = join(dshHome, 'profiles', name)
|
|
162
167
|
mkdirSync(join(dir, 'node_modules', '@lincyaw'), { recursive: true })
|
|
163
168
|
mkdirSync(join(dshHome, 'agents'), { recursive: true })
|
|
164
|
-
|
|
169
|
+
const writeChanged = (file: string, content: string) => {
|
|
170
|
+
if (!existsSync(file) || readFileSync(file, 'utf8') !== content) writeFileSync(file, content)
|
|
171
|
+
}
|
|
172
|
+
const manifestFile = join(dir, 'package.json')
|
|
173
|
+
const saved = existsSync(manifestFile) ? JSON.parse(readFileSync(manifestFile, 'utf8')) : {}
|
|
174
|
+
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) throw new TypeError('Invalid profile package manifest')
|
|
175
|
+
const required = ['@deepseek-ai/dsh-base', CARRIERS[carrier], PACKAGE_NAME]
|
|
176
|
+
const extra = Array.isArray(saved.dsh?.profile?.bundles) ? saved.dsh.profile.bundles.filter((bundle: unknown) => typeof bundle === 'string' && !required.includes(bundle) && !Object.values(CARRIERS).includes(bundle as string)) : []
|
|
177
|
+
writeChanged(manifestFile, `${JSON.stringify({
|
|
178
|
+
...saved,
|
|
165
179
|
name: `dsh-profile-${name}`,
|
|
166
180
|
private: true,
|
|
167
|
-
dependencies: {},
|
|
168
|
-
dsh: { profile: { bundles: [
|
|
181
|
+
dependencies: saved.dependencies ?? {},
|
|
182
|
+
dsh: { ...saved.dsh, profile: { ...saved.dsh?.profile, bundles: [...required, ...extra] } },
|
|
169
183
|
}, null, 2)}\n`)
|
|
170
|
-
|
|
184
|
+
const root = join(dir, 'cordis.yml')
|
|
185
|
+
// The Host normalizes this root's comments; keep its file and the author's installed plugins intact.
|
|
186
|
+
if (!existsSync(root)) writeFileSync(root, '# The profile root: an empty entry list; the tree is composed from the bundles and the patches.\n[]\n')
|
|
171
187
|
if (!existsSync(join(dir, 'cordis.patch.yml'))) writeFileSync(join(dir, 'cordis.patch.yml'), '# Your patch layer for this profile (Presmium\'s settings are passed with --patch after it).\n[]\n')
|
|
172
188
|
const link = join(dir, 'node_modules', PACKAGE_NAME)
|
|
173
|
-
|
|
174
|
-
|
|
189
|
+
const target = realpathSync(bundle)
|
|
190
|
+
let current: string | undefined
|
|
191
|
+
try { current = realpathSync(link) } catch {}
|
|
192
|
+
if (current !== target) {
|
|
193
|
+
rmSync(link, { force: true, recursive: true })
|
|
194
|
+
symlinkSync(target, link, 'junction')
|
|
195
|
+
}
|
|
175
196
|
return dir
|
|
176
197
|
}
|
package/src/node/policy.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { homedir } from 'node:os'
|
|
2
2
|
import { join, resolve } from 'node:path'
|
|
3
|
+
import { errorMessage } from '@lincyaw/kernel'
|
|
4
|
+
import type { CatalogCall } from '@lincyaw/mcp/client'
|
|
3
5
|
import { isInside } from '@lincyaw/kernel/node'
|
|
4
6
|
import { describeOperation } from '@lincyaw/mcp/client'
|
|
5
7
|
import type { DshContext, DshPreDecision, DshToolExecution } from './dsh-types.ts'
|
|
6
|
-
import { PREFIX } from './tools.ts'
|
|
8
|
+
import { PREFIX, preparePresmiumCall, resolvePresmiumCall } from './tools.ts'
|
|
7
9
|
|
|
8
10
|
export const name = 'presmium-policy'
|
|
9
11
|
export const inject = ['presmium', 'tools']
|
|
@@ -24,17 +26,22 @@ const displayText = (text: string, lang?: string) => ({ en: text, ...lang ? { [l
|
|
|
24
26
|
|
|
25
27
|
export function apply(ctx: DshContext): void {
|
|
26
28
|
const operatorDir = operatorRoot()
|
|
29
|
+
let authorRoot: string | undefined
|
|
30
|
+
void ctx.presmium.server.ready.then(endpoint => { authorRoot = endpoint.root })
|
|
27
31
|
|
|
28
32
|
ctx.on('tools/pre-execute', async (exec: DshToolExecution, next: () => Promise<DshPreDecision>): Promise<DshPreDecision> => {
|
|
29
33
|
const { bindings } = ctx.presmium
|
|
30
34
|
const binding = bindings.bindingOf(exec.agent)
|
|
31
35
|
if (exec.name.startsWith(PREFIX)) {
|
|
32
|
-
|
|
36
|
+
let resolved: CatalogCall
|
|
37
|
+
try { resolved = await resolvePresmiumCall(binding, exec) } catch (error) { return { kind: 'deny', reason: `Presmium: ${errorMessage(error)}` } }
|
|
38
|
+
const tool = resolved.tool
|
|
33
39
|
if (!binding || !tool) return { kind: 'deny', reason: `Presmium: ${exec.name} is no tool of this session's document` }
|
|
34
40
|
if (tool.kind === 'read') return next()
|
|
41
|
+
try { await preparePresmiumCall(binding, exec, resolved) } catch (error) { return { kind: 'deny', reason: `Presmium: ${errorMessage(error)}` } }
|
|
35
42
|
if (tool.approval === 'allow') return { kind: 'allow' }
|
|
36
43
|
const lang = binding.document.lang
|
|
37
|
-
const title = describeOperation(tool.name,
|
|
44
|
+
const title = describeOperation(tool.name, resolved.arguments, lang)
|
|
38
45
|
return { kind: 'ask', reason: `presmium:${tool.kind} ${tool.name}`, displayReason: displayText(`Presmium · ${title}`, lang) }
|
|
39
46
|
}
|
|
40
47
|
const file = FILE_WRITE_TOOLS.has(exec.name) ? fileOf(exec) : undefined
|
|
@@ -48,8 +55,11 @@ export function apply(ctx: DshContext): void {
|
|
|
48
55
|
ctx.tools.guard((exec) => {
|
|
49
56
|
const file = FILE_WRITE_TOOLS.has(exec.name) ? fileOf(exec) : undefined
|
|
50
57
|
const dir = exec.agent ? ctx.presmium.bindings.workingDirectoryOf(exec.agent) : process.cwd()
|
|
58
|
+
const candidate = ctx.presmium.bindings.candidateRootOf(exec.agent)
|
|
59
|
+
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
60
|
if (file && isInside(resolve(dir, file), operatorDir)) return `Presmium: the operator directory (${operatorDir}) is not the agent's to write`
|
|
52
61
|
const command = exec.name === 'bash' ? (exec.arguments as { command?: unknown } | undefined)?.command : undefined
|
|
62
|
+
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
63
|
if (typeof command === 'string' && command.includes(operatorDir)) return `Presmium: the operator directory (${operatorDir}) is not the agent's to touch`
|
|
54
64
|
return undefined
|
|
55
65
|
})
|
package/src/node/routes.ts
CHANGED
|
@@ -5,12 +5,13 @@ export const name = 'presmium-routes'
|
|
|
5
5
|
export const inject = ['presmium', 'connection']
|
|
6
6
|
|
|
7
7
|
export const ROUTES: Record<string, string> = Object.fromEntries([
|
|
8
|
+
['mcp-settings', `${WORKSPACE_ROUTES}mcp-settings`],
|
|
8
9
|
['speech-settings', `${WORKSPACE_ROUTES}speech-settings`],
|
|
9
10
|
...['project/capabilities', 'project/plan', 'project/apply', 'documents', 'document', 'document/capabilities', 'document/outline', 'document/part', 'document/page/plan', 'document/page/apply', 'document/action/plan', 'document/action/impact', 'document/action/apply', 'document/asset', 'document/events', 'document/change', 'document/image', 'document/audio', 'document/recording/adopt', 'document/media-clip', 'files', 'source', 'source/create', 'source/transaction', 'changes', 'changes/commit', 'changes/discard', 'revisions', 'revisions/revert', 'history/list', 'history/file', 'history/undo', 'history/redo',
|
|
10
11
|
'document/media-clip/validate', 'document/transcription/capabilities', 'document/transcription', 'document/transcription/result', 'document/transcription/cancel',
|
|
11
12
|
'document/transcription/adoption/plan', 'document/transcription/adoption/apply',
|
|
12
13
|
'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}`]),
|
|
14
|
+
'review', 'review/workspace', 'review/open', 'review/step', 'review/accept', 'review/reject', 'review/restore'].map(path => [path, `${WORKSPACE_ROUTES}${path}`]),
|
|
14
15
|
['focus', `${SERVER_ROUTES}focus`],
|
|
15
16
|
['control', `${SERVER_ROUTES}control`],
|
|
16
17
|
['diagnostics', `${SERVER_ROUTES}diagnostics`],
|
|
@@ -37,6 +38,12 @@ export function apply(ctx: DshContext): void {
|
|
|
37
38
|
const value = request.headers.get(name)
|
|
38
39
|
if (value !== null) headers[name] = value
|
|
39
40
|
}
|
|
41
|
+
if (path === 'preview') {
|
|
42
|
+
const browser = new URL(request.url)
|
|
43
|
+
const host = request.headers.get('host')
|
|
44
|
+
if (host) browser.host = host
|
|
45
|
+
headers['x-presmium-preview-origin'] = browser.origin
|
|
46
|
+
}
|
|
40
47
|
const upstream = await ctx.presmium.server.request(`${target}${new URL(request.url).search}`, {
|
|
41
48
|
method: request.method,
|
|
42
49
|
headers,
|
package/src/node/service.ts
CHANGED
|
@@ -12,9 +12,11 @@ import { SERVER_ROUTES, WORKSPACE_ROUTES } from './server-routes.ts'
|
|
|
12
12
|
export const name = 'presmium-service'
|
|
13
13
|
|
|
14
14
|
export interface Config {
|
|
15
|
+
presmium?: string
|
|
15
16
|
url?: string
|
|
16
17
|
token?: string
|
|
17
18
|
root?: string
|
|
19
|
+
candidate?: boolean
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
export interface Endpoint {
|
|
@@ -40,20 +42,23 @@ function cliBin(): string {
|
|
|
40
42
|
/** The workspace server the bundle works with: the one the launcher gives (`url`, `token`), or one it launches itself. */
|
|
41
43
|
export class WorkspaceServerClient {
|
|
42
44
|
readonly ready: Promise<Endpoint>
|
|
45
|
+
readonly presmium: string
|
|
43
46
|
readonly #launched: LaunchedProcess | undefined
|
|
44
47
|
#documents: { at: number, list: Promise<DocumentSummary[]> } | undefined
|
|
45
48
|
#closed = false
|
|
46
49
|
|
|
47
50
|
constructor(config: Config, log: DshLogger) {
|
|
48
51
|
const root = resolve(config.root || process.cwd())
|
|
52
|
+
this.presmium = config.presmium ?? cliBin()
|
|
49
53
|
if (config.url) {
|
|
50
54
|
this.ready = Promise.resolve({ url: config.url.replace(/\/+$/, ''), serviceToken: config.token ?? '', root })
|
|
51
55
|
} else {
|
|
52
56
|
const serviceToken = randomBytes(24).toString('base64url')
|
|
53
57
|
const server = launchWorkspaceServer({
|
|
54
|
-
presmium:
|
|
58
|
+
presmium: this.presmium,
|
|
55
59
|
dir: root,
|
|
56
60
|
serviceToken,
|
|
61
|
+
env: { ...process.env, ...config.candidate ? { PRESMIUM_AGENT_CANDIDATE: '1' } : {} },
|
|
57
62
|
onOutput: (text) => {
|
|
58
63
|
for (const line of text.split('\n').filter(Boolean)) log.debug(`presmium serve: ${line}`)
|
|
59
64
|
},
|
|
@@ -104,6 +109,7 @@ export class WorkspaceServerClient {
|
|
|
104
109
|
this.#closed = true
|
|
105
110
|
if (this.#launched) {
|
|
106
111
|
this.#launched.child.kill('SIGTERM')
|
|
112
|
+
await this.#launched.exited
|
|
107
113
|
return
|
|
108
114
|
}
|
|
109
115
|
await this.request(`${SERVER_ROUTES}tokens`, { method: 'DELETE', body: {} }).then(r => r.body?.cancel(), () => undefined)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { brandMarkup, iconMarkup } from '@lincyaw/design'
|
|
5
|
+
import { STARTUP_MESSAGES } from '../startup-messages.ts'
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url)
|
|
8
|
+
let assets: { css: string, script: string, version: string } | undefined
|
|
9
|
+
export function startupAssets(): { css: string, script: string, version: string } {
|
|
10
|
+
if (!assets) {
|
|
11
|
+
const css = readFileSync(require.resolve('@lincyaw/design/tokens.css'), 'utf8') + '\n'
|
|
12
|
+
+ readFileSync(require.resolve('@lincyaw/design/components.css'), 'utf8') + '\n'
|
|
13
|
+
+ readFileSync(new URL('../client/startup.css', import.meta.url), 'utf8')
|
|
14
|
+
const script = `(${installStartup.toString()})(${JSON.stringify(STARTUP_MESSAGES)})`
|
|
15
|
+
assets = { css, script, version: createHash('sha256').update(css).update(script).digest('hex').slice(0, 16) }
|
|
16
|
+
}
|
|
17
|
+
return assets
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Runs before the framework entry. Only our own ready event hands over the page; there is no timed dismissal. */
|
|
21
|
+
function installStartup(catalog: typeof STARTUP_MESSAGES) {
|
|
22
|
+
const cover = document.getElementById('presmium-startup') as HTMLDialogElement
|
|
23
|
+
const message = cover.querySelector<HTMLElement>('[data-startup-message]')!
|
|
24
|
+
const retry = cover.querySelector<HTMLButtonElement>('[data-startup-retry]')!
|
|
25
|
+
const retrySlot = retry.parentElement!
|
|
26
|
+
const spinner = cover.querySelector<HTMLElement>('[data-startup-spinner]')!
|
|
27
|
+
const details = cover.querySelector<HTMLAnchorElement>('[data-startup-details]')!
|
|
28
|
+
let language = document.documentElement.lang || navigator.language
|
|
29
|
+
let dark = matchMedia('(prefers-color-scheme: dark)').matches
|
|
30
|
+
try {
|
|
31
|
+
language = localStorage.getItem('presmium.startup.locale') || language
|
|
32
|
+
const saved = localStorage.getItem('presmium.startup.dark')
|
|
33
|
+
if (saved !== null) dark = saved === 'true'
|
|
34
|
+
} catch { /* Startup works without browser storage. */ }
|
|
35
|
+
document.documentElement.classList.toggle('dark', dark)
|
|
36
|
+
const t = catalog[language.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en']
|
|
37
|
+
message.textContent = t.opening; retry.textContent = t.retry; details.textContent = t.details
|
|
38
|
+
// Browser-owned modal isolation never overwrites the framework's own inert/aria ownership.
|
|
39
|
+
if (typeof cover.showModal === 'function') { if (cover.open) cover.close(); cover.showModal() }
|
|
40
|
+
cover.addEventListener('cancel', event => event.preventDefault())
|
|
41
|
+
let ended = false
|
|
42
|
+
const release = () => {
|
|
43
|
+
if (ended) return
|
|
44
|
+
ended = true; clearTimeout(timer)
|
|
45
|
+
window.removeEventListener('error', failed, true)
|
|
46
|
+
window.removeEventListener('unhandledrejection', failed)
|
|
47
|
+
window.removeEventListener('presmium:workspace-ready', ready)
|
|
48
|
+
window.removeEventListener('presmium:startup-failed', failed)
|
|
49
|
+
if (cover.open) cover.close()
|
|
50
|
+
cover.remove()
|
|
51
|
+
}
|
|
52
|
+
const ready = () => {
|
|
53
|
+
document.documentElement.dataset.pmStartupReadyMs = String(Math.round(performance.now()))
|
|
54
|
+
release()
|
|
55
|
+
}
|
|
56
|
+
const failed = () => { if (ended) return; message.textContent = t.failed; retrySlot.hidden = false; spinner.hidden = true; message.setAttribute('role', 'alert') }
|
|
57
|
+
const timer = window.setTimeout(() => { if (!ended) { message.textContent = t.slow; retrySlot.hidden = false } }, 30_000)
|
|
58
|
+
retry.addEventListener('click', () => location.reload())
|
|
59
|
+
// The untouched framework report is an explicit diagnostic escape, including an early boot/import failure.
|
|
60
|
+
details.addEventListener('click', event => { event.preventDefault(); release() })
|
|
61
|
+
window.addEventListener('presmium:workspace-ready', ready)
|
|
62
|
+
window.addEventListener('presmium:startup-failed', failed)
|
|
63
|
+
window.addEventListener('error', failed, true)
|
|
64
|
+
window.addEventListener('unhandledrejection', failed)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function startupIndex(html: string): string {
|
|
68
|
+
const { version } = startupAssets()
|
|
69
|
+
const initial = STARTUP_MESSAGES[/<html[^>]*lang=["']zh/i.test(html) ? 'zh-CN' : 'en']
|
|
70
|
+
const cover = `<dialog open id="presmium-startup" class="pm-startup pm-ui" aria-labelledby="presmium-startup-title"><div class="pm-startup__content"><h1 id="presmium-startup-title" class="pm-startup__brand">${brandMarkup()}<span>Presmium Studio</span></h1><p class="pm-startup__status" role="status" aria-live="polite"><span data-startup-spinner aria-hidden="true"><span class="pm-ui-loading pm-startup__spinner">${iconMarkup('loading')}</span></span><span data-startup-message>${initial.opening}</span></p><div class="pm-startup__actions"><span hidden><button type="button" class="pm-ui-button pm-ui-button--ghost" data-density="compact" data-startup-retry>${initial.retry}</button></span><a href="#presmium-startup" class="pm-ui-button pm-ui-button--ghost" data-density="compact" data-startup-details>${initial.details}</a></div></div></dialog>`
|
|
71
|
+
return html.replace('</head>', `<link rel="stylesheet" href="api/presmium/startup.css?v=${version}"></head>`)
|
|
72
|
+
.replace(/<body([^>]*)>/, `<body$1>${cover}<script src="api/presmium/startup.js?v=${version}"></script>`)
|
|
73
|
+
}
|
package/src/node/tools.ts
CHANGED
|
@@ -1,27 +1,137 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import type {
|
|
1
|
+
import { errorMessage, isRecord } from '@lincyaw/kernel'
|
|
2
|
+
import { compactToolCatalog, isOrdinaryMediaCall, mediaResult, prepareMediaArguments, queryToolCatalog, resolveCatalogCall } from '@lincyaw/mcp/client'
|
|
3
|
+
import type { CalledImage, CatalogCall, ListedTool } from '@lincyaw/mcp/client'
|
|
4
|
+
import type { DshAgent, DshAttachments, DshContentBlock, DshContext, DshImageMediaType, DshLlm, DshToolDefinition, DshToolExecution } from './dsh-types.ts'
|
|
5
|
+
import type { DocumentBinding, PreparedBindingCall } from './bindings.ts'
|
|
4
6
|
|
|
5
7
|
export const name = 'presmium-tools'
|
|
6
8
|
export const inject = ['presmium', 'tools']
|
|
7
9
|
|
|
8
10
|
export const PREFIX = 'presmium__'
|
|
11
|
+
export const CANDIDATE_TOOLS = new Set([
|
|
12
|
+
'get_authoring_capabilities', 'get_document', 'get_document_outline', 'read_document_part',
|
|
13
|
+
'plan_document_change', 'apply_document_change', 'plan_page_change', 'apply_page_change',
|
|
14
|
+
'plan_page_duplication', 'apply_page_duplication', 'plan_authoring_action', 'apply_authoring_action', 'read_authoring_action_impact',
|
|
15
|
+
'check_document', 'get_section', 'get_step', 'list_sections', 'deck_info', 'list_documents',
|
|
16
|
+
'run_code', 'capture_slides', 'capture_reading', 'capture_overview',
|
|
17
|
+
])
|
|
9
18
|
|
|
10
|
-
|
|
19
|
+
/** New tools carry their routing with their schema; the names retain compatibility with older servers. */
|
|
20
|
+
export const isCandidateTool = (tool: ListedTool): boolean => tool.workspace ? tool.workspace === 'candidate' : CANDIDATE_TOOLS.has(tool.name)
|
|
21
|
+
|
|
22
|
+
export async function resolvePresmiumCall(binding: DocumentBinding | undefined, exec: Pick<DshToolExecution, 'name' | 'arguments'>) {
|
|
23
|
+
if (!binding || !exec.name.startsWith(PREFIX)) throw new Error('operation-unavailable')
|
|
24
|
+
const target = await resolveCatalogCall(binding.registeredTools ?? binding.tools, exec.name.slice(PREFIX.length), exec.arguments)
|
|
25
|
+
if (!target.discovery && JSON.stringify(binding.tools.find(tool => tool.name === target.tool.name)) !== JSON.stringify(target.tool)) throw new Error('operation-definition-changed')
|
|
26
|
+
return target
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function preparePresmiumCall(binding: DocumentBinding, exec: DshToolExecution, target: CatalogCall) {
|
|
30
|
+
if (target.discovery || !isOrdinaryMediaCall(target.tool.name, target.arguments) && target.tool.name !== 'clone_voice') return
|
|
31
|
+
if (!isRecord(exec.arguments)) throw new Error('operation-arguments-invalid')
|
|
32
|
+
const preparedCalls = binding.preparedCalls ??= new Map()
|
|
33
|
+
const signature = JSON.stringify([target.tool, target.arguments]), previous = preparedCalls.get(exec.token)
|
|
34
|
+
if (previous) {
|
|
35
|
+
if (previous.signature !== signature) throw new Error('operation-definition-changed')
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
if (preparedCalls.size >= 64) throw new Error('operation-preparation-busy')
|
|
39
|
+
const client = isCandidateTool(target.tool) ? binding.client : binding.authorClient
|
|
40
|
+
if (target.tool.name === 'clone_voice') {
|
|
41
|
+
const native = await client.prepareVoiceClone(target.arguments, exec.signal)
|
|
42
|
+
try {
|
|
43
|
+
exec.signal.throwIfAborted()
|
|
44
|
+
if (preparedCalls.size >= 64) throw new Error('operation-preparation-busy')
|
|
45
|
+
preparedCalls.set(exec.token, { signature, arguments: target.arguments, native })
|
|
46
|
+
} catch (error) { await native.close(); throw error }
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
const args = await prepareMediaArguments(target.tool.name, target.arguments, async (name, args) => {
|
|
50
|
+
exec.signal.throwIfAborted()
|
|
51
|
+
const result = await client.call(name, args, exec.signal)
|
|
52
|
+
exec.signal.throwIfAborted()
|
|
53
|
+
if (result.isError) throw new Error(result.text)
|
|
54
|
+
return result.structured ?? JSON.parse(result.text)
|
|
55
|
+
})
|
|
56
|
+
// Validate the fixed native request using the same definition; never rewrite logged arguments.
|
|
57
|
+
const prepared = await resolveCatalogCall(binding.tools, target.tool.name, args)
|
|
58
|
+
exec.signal.throwIfAborted()
|
|
59
|
+
if (preparedCalls.size >= 64) throw new Error('operation-preparation-busy')
|
|
60
|
+
preparedCalls.set(exec.token, { signature, arguments: prepared.arguments })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const IMAGE_TYPES = new Set<string>(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A tool result's images as dsh's durable image blocks, which reach the model beside the text; only when the model of
|
|
67
|
+
* the session's latest request declares image input, as dsh's own MCP client does. Otherwise, and when the attachment
|
|
68
|
+
* store refuses them, one line says they were left out (the text names their files where the tool has any) and the call
|
|
69
|
+
* still succeeds.
|
|
70
|
+
*/
|
|
71
|
+
async function imageBlocks(ctx: DshContext, tool: string, images: CalledImage[], exec: DshToolExecution): Promise<DshContentBlock[]> {
|
|
72
|
+
const leftOut = (why: string): DshContentBlock[] => [{ type: 'text', text: `[${images.length} image${images.length === 1 ? '' : 's'} not attached: ${why}]` }]
|
|
73
|
+
const attachments = ctx.get('attachments') as DshAttachments | undefined
|
|
74
|
+
const llm = ctx.get('llm') as DshLlm | undefined
|
|
75
|
+
const { provider, model } = exec.agent?.session.requestContext() ?? {}
|
|
76
|
+
if (!attachments || !llm || !provider || !model) return leftOut('this session takes no images')
|
|
77
|
+
const info = await llm.resolveModelInfo(provider, model, exec.signal).catch(() => undefined)
|
|
78
|
+
if (!info?.inputModalities?.includes('image')) return leftOut(`the model ${model} does not take images`)
|
|
79
|
+
if (images.some(image => !IMAGE_TYPES.has(image.mimeType))) return leftOut('not PNG, JPEG, WebP or GIF')
|
|
80
|
+
try {
|
|
81
|
+
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)}` })))
|
|
82
|
+
return refs.map(attachment => ({ type: 'image', attachment }))
|
|
83
|
+
} catch (error) {
|
|
84
|
+
return leftOut(errorMessage(error))
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function definition(ctx: DshContext, binding: DocumentBinding, tool: ListedTool): DshToolDefinition {
|
|
89
|
+
const prepared = new Map<symbol, DshContentBlock[]>()
|
|
11
90
|
return {
|
|
12
91
|
name: `${PREFIX}${tool.name}`,
|
|
13
92
|
description: tool.description,
|
|
14
93
|
parameters: tool.inputSchema,
|
|
15
94
|
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
16
95
|
async execute(args, exec) {
|
|
17
|
-
|
|
96
|
+
if (exec.agent && ctx.presmium.bindings.bindingOf(exec.agent) !== binding) throw new Error('operation-binding-changed')
|
|
97
|
+
const target = await resolvePresmiumCall(binding, { name: PREFIX + tool.name, arguments: args })
|
|
98
|
+
if (target.discovery) return JSON.stringify(queryToolCatalog(binding.registeredTools ?? binding.tools, target.arguments))
|
|
99
|
+
const ordinaryMedia = isOrdinaryMediaCall(target.tool.name, target.arguments)
|
|
100
|
+
const needsPreparation = ordinaryMedia || target.tool.name === 'clone_voice'
|
|
101
|
+
let argumentsToSend = target.arguments
|
|
102
|
+
let fixed: PreparedBindingCall | undefined
|
|
103
|
+
if (needsPreparation) {
|
|
104
|
+
const prepared = binding.preparedCalls?.get(exec.token)
|
|
105
|
+
binding.preparedCalls?.delete(exec.token)
|
|
106
|
+
if (!prepared || prepared.signature !== JSON.stringify([target.tool, target.arguments]) || target.tool.name === 'clone_voice' && !prepared.native) {
|
|
107
|
+
await prepared?.native?.close()
|
|
108
|
+
throw new Error('operation-not-prepared')
|
|
109
|
+
}
|
|
110
|
+
fixed = prepared
|
|
111
|
+
argumentsToSend = fixed.arguments
|
|
112
|
+
}
|
|
113
|
+
let result
|
|
114
|
+
try { result = target.tool.name === 'clone_voice' ? await fixed!.native!.call(exec.signal) : await (isCandidateTool(target.tool) ? binding.client : binding.authorClient).call(target.tool.name, argumentsToSend, exec.signal) }
|
|
115
|
+
finally { await fixed?.native?.close() }
|
|
18
116
|
if (result.isError) throw new Error(result.text)
|
|
117
|
+
if (ordinaryMedia) return JSON.stringify(mediaResult(target.tool.name, result.structured ?? JSON.parse(result.text), target.arguments))
|
|
118
|
+
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
119
|
return result.text
|
|
20
120
|
},
|
|
121
|
+
projectContent(exec, result) {
|
|
122
|
+
const content = prepared.get(exec.token)
|
|
123
|
+
prepared.delete(exec.token)
|
|
124
|
+
return result.isError ? undefined : content
|
|
125
|
+
},
|
|
21
126
|
}
|
|
22
127
|
}
|
|
23
128
|
|
|
24
129
|
export function apply(ctx: DshContext): void {
|
|
130
|
+
ctx.on('tools/result', async (exec: Readonly<DshToolExecution>) => {
|
|
131
|
+
const calls = ctx.presmium.bindings.bindingOf(exec.agent)?.preparedCalls, prepared = calls?.get(exec.token)
|
|
132
|
+
calls?.delete(exec.token)
|
|
133
|
+
await prepared?.native?.close()
|
|
134
|
+
})
|
|
25
135
|
const live = new WeakSet<DshAgent>()
|
|
26
136
|
const selections = new WeakMap<DshAgent, () => void>()
|
|
27
137
|
const registered = new WeakMap<DshAgent, { binding?: DocumentBinding, tools?: ListedTool[], stop?: () => void, dispose: (() => void)[] }>()
|
|
@@ -31,10 +141,11 @@ export function apply(ctx: DshContext): void {
|
|
|
31
141
|
if (previous && previous.binding === binding && previous.tools === binding?.tools) return
|
|
32
142
|
previous?.stop?.()
|
|
33
143
|
for (const dispose of previous?.dispose ?? []) dispose()
|
|
144
|
+
if (binding) binding.registeredTools = binding.tools
|
|
34
145
|
registered.set(agent, {
|
|
35
146
|
binding, tools: binding?.tools,
|
|
36
147
|
stop: binding?.toolChanges.watch(() => { if (agent.status === 'idle') install(agent, binding) }),
|
|
37
|
-
dispose: binding
|
|
148
|
+
dispose: binding ? compactToolCatalog(binding.tools).map(tool => agent.ctx.tools.register(definition(ctx, binding, tool))) : [],
|
|
38
149
|
})
|
|
39
150
|
}
|
|
40
151
|
const sync = async (agent: DshAgent) => {
|
|
@@ -57,6 +168,7 @@ export function apply(ctx: DshContext): void {
|
|
|
57
168
|
for (const dispose of previous?.dispose ?? []) dispose()
|
|
58
169
|
})
|
|
59
170
|
ctx.on('agent/pre-step', async ({ agent }: { agent: DshAgent }, next: () => Promise<unknown>) => {
|
|
171
|
+
await ctx.presmium.bindings.refreshCandidate(agent)
|
|
60
172
|
await sync(agent)
|
|
61
173
|
return next()
|
|
62
174
|
})
|
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 { isCandidateTool, PREFIX, resolvePresmiumCall } 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
|
-
|
|
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,14 @@ export function apply(ctx: DshContext): void {
|
|
|
100
102
|
})
|
|
101
103
|
|
|
102
104
|
ctx.on('tools/execute', async (exec: DshToolExecution, next: () => Promise<unknown>) => {
|
|
103
|
-
if (!
|
|
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 target = exec.name.startsWith(PREFIX) ? await resolvePresmiumCall(binding, exec) : undefined
|
|
111
|
+
const tool = target?.tool
|
|
112
|
+
if (!WRITING_TOOLS.has(exec.name) && (!tool || tool.kind === 'read' || !isCandidateTool(tool))) return next()
|
|
106
113
|
const document = ctx.presmium.bindings.bindingOf(exec.agent)?.document.dir ?? ''
|
|
107
114
|
const agentSessionId = rootAgentSessionOf(exec.agent.session.id)
|
|
108
115
|
const state = turnStateOf(agentSessionId)
|
|
@@ -113,12 +120,9 @@ export function apply(ctx: DshContext): void {
|
|
|
113
120
|
}
|
|
114
121
|
state.document = document
|
|
115
122
|
state.wrote = true
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
-
}
|
|
123
|
+
const result = await next()
|
|
124
|
+
await postReview(document, agentSessionId, 'step', { ...state.turn !== undefined ? { turn: state.turn } : {}, label: labelOf(target ? { ...exec, name: PREFIX + target.tool.name, arguments: target.arguments } : exec), tool: target ? PREFIX + target.tool.name : exec.name })
|
|
125
|
+
return result
|
|
122
126
|
})
|
|
123
127
|
|
|
124
128
|
ctx.on('agent/created', ({ agent }: { agent: LiveAgent }) => {
|
package/src/node/workbench.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { startupAssets, startupIndex } from './startup.ts'
|
|
1
2
|
import { LOCAL_AUTHOR } from '@lincyaw/kernel'
|
|
2
3
|
import type { DshContext, DshOtelScalar } from './dsh-types.ts'
|
|
3
4
|
import type { OperationClient, OperationRecord, PresmiumTelemetry } from './telemetry.ts'
|
|
@@ -8,10 +9,10 @@ export const inject = ['presmium', 'connection', 'webServer', 'presmiumTelemetry
|
|
|
8
9
|
const ICON = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0F5F5C"/><path d="M11 8h7.5a6.5 6.5 0 0 1 0 13H15v4h-4zM15 12v5h3.5a2.5 2.5 0 0 0 0-5z" fill="#F7F5F0" fill-rule="evenodd"/></svg>')}`
|
|
9
10
|
|
|
10
11
|
export function brandIndex(html: string): string {
|
|
11
|
-
return html
|
|
12
|
+
return startupIndex(html
|
|
12
13
|
.replace(/<title>[^<]*<\/title>/, '<title>Presmium</title>')
|
|
13
14
|
.replace(/<link rel="(?:icon|manifest)"[^>]*>\s*/g, '')
|
|
14
|
-
.replace('</head>', `<link rel="icon" type="image/svg+xml" href="${ICON}" />\n</head>`)
|
|
15
|
+
.replace('</head>', `<link rel="icon" type="image/svg+xml" href="${ICON}" />\n</head>`))
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
interface WebServer {
|
|
@@ -48,6 +49,12 @@ export function readOperations(body: unknown): { client: OperationClient, record
|
|
|
48
49
|
|
|
49
50
|
export function apply(ctx: DshContext & { webServer: WebServer, presmiumTelemetry: PresmiumTelemetry }): void {
|
|
50
51
|
ctx.effect(() => ctx.webServer.tapIndex(brandIndex))
|
|
52
|
+
ctx.connection.fetch.register({ path: '/api/presmium/startup.js', methods: ['GET'], requestBody: 'buffered', async fetch() {
|
|
53
|
+
return new Response(startupAssets().script, { headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=31536000, immutable' } })
|
|
54
|
+
} })
|
|
55
|
+
ctx.connection.fetch.register({ path: '/api/presmium/startup.css', methods: ['GET'], requestBody: 'buffered', async fetch() {
|
|
56
|
+
return new Response(startupAssets().css, { headers: { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'public, max-age=31536000, immutable' } })
|
|
57
|
+
} })
|
|
51
58
|
ctx.connection.fetch.register({
|
|
52
59
|
path: '/api/presmium/context', methods: ['POST'], requestBody: 'buffered',
|
|
53
60
|
async fetch(request) {
|
|
@@ -27,6 +27,7 @@ const ROUTES = {
|
|
|
27
27
|
review: { path: `${WORKSPACE_ROUTES}review`, event: 'review' },
|
|
28
28
|
ir: { path: `${WORKSPACE_ROUTES}ir/events`, event: 'revision' },
|
|
29
29
|
jobs: { path: `${WORKSPACE_ROUTES}jobs/events`, event: 'job' },
|
|
30
|
+
'agent-activity': { path: `${WORKSPACE_ROUTES}agent-activity/events`, event: 'agent-activity' },
|
|
30
31
|
} as const
|
|
31
32
|
const MAX_SUBSCRIPTIONS = 16
|
|
32
33
|
const MAX_BUFFERED_BYTES = 2 << 20
|
|
@@ -94,13 +95,15 @@ export function apply(ctx: EventContext): void {
|
|
|
94
95
|
const current = () => !closed && !controller.signal.aborted && subscriptions.get(command.id) === entry
|
|
95
96
|
void ctx.presmium.server.ready.then(endpoint => {
|
|
96
97
|
if (!current()) return
|
|
97
|
-
if (command.topic === 'authoring-client') {
|
|
98
|
+
if (command.topic === 'authoring-client' || command.topic === 'authoring-window') {
|
|
99
|
+
const resource = command.topic === 'authoring-window' ? 'authoring-windows' : 'authoring-clients'
|
|
100
|
+
const documentQuery: Record<string, string> = command.topic === 'authoring-client' ? { document: command.document } : {}
|
|
98
101
|
// Keep the client credential on the trusted host, off browser messages and MCP reads.
|
|
99
102
|
let lease: AuthoringClientLease | undefined
|
|
100
103
|
let publication: Promise<void> = Promise.resolve()
|
|
101
104
|
let publications = 0
|
|
102
105
|
const post = async (kind: string, value: unknown) => {
|
|
103
|
-
const path = `${WORKSPACE_ROUTES}
|
|
106
|
+
const path = `${WORKSPACE_ROUTES}${resource}/${kind}?${new URLSearchParams(documentQuery)}`
|
|
104
107
|
const response = await ctx.presmium.server.request(path, { method: 'POST', body: value, signal: controller.signal })
|
|
105
108
|
if (!response.ok) throw new Error('client-publication-refused')
|
|
106
109
|
return response.json() as Promise<unknown>
|
|
@@ -120,8 +123,8 @@ export function apply(ctx: EventContext): void {
|
|
|
120
123
|
if (!current()) return
|
|
121
124
|
if (!validateAuthoringClientLease(value)) throw new Error('client-registration-invalid')
|
|
122
125
|
lease = value
|
|
123
|
-
const query = new URLSearchParams({
|
|
124
|
-
const path = `${WORKSPACE_ROUTES}
|
|
126
|
+
const query = new URLSearchParams({ ...documentQuery, clientId: lease.clientId, epoch: lease.epoch, connectionId: lease.connectionId })
|
|
127
|
+
const path = `${WORKSPACE_ROUTES}${resource}/events?${query}`
|
|
125
128
|
source = new EventSource(new URL(path, endpoint.url), {
|
|
126
129
|
fetch: (_address, init) => ctx.presmium.server.request(path, { headers: { ...Object.fromEntries(new Headers(init?.headers)), 'X-Presmium-Authoring-Client': value.credential }, signal: init?.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal }),
|
|
127
130
|
})
|