@dinoxx/dinox-cli 2.16.1 → 2.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -0
- package/dist/commands/editor/index.d.ts +4 -0
- package/dist/commands/editor/index.js +155 -0
- package/dist/commands/notes/contentPatch.d.ts +23 -0
- package/dist/commands/notes/contentPatch.js +37 -0
- package/dist/commands/schema/renderSkills.js +1 -0
- package/dist/commands/schema/spec.js +2 -0
- package/dist/daemon/server.d.ts +2 -1
- package/dist/daemon/server.js +22 -2
- package/dist/dsh-plugin/cordis.patch.yml +3 -0
- package/dist/dsh-plugin/lib/client.js +2145 -0
- package/dist/dsh-plugin/lib/index.js +369 -0
- package/dist/dsh-plugin/package.json +32 -0
- package/dist/dsh-plugin/runtime.json +5 -0
- package/dist/editor/anchor.d.ts +46 -0
- package/dist/editor/anchor.js +129 -0
- package/dist/editor/blockIds.d.ts +21 -0
- package/dist/editor/blockIds.js +51 -0
- package/dist/editor/blocks.d.ts +47 -0
- package/dist/editor/blocks.js +236 -0
- package/dist/editor/compat.d.ts +32 -0
- package/dist/editor/compat.js +392 -0
- package/dist/editor/daemon.d.ts +10 -0
- package/dist/editor/daemon.js +56 -0
- package/dist/editor/document.d.ts +74 -0
- package/dist/editor/document.js +88 -0
- package/dist/editor/i18n.d.ts +23 -0
- package/dist/editor/i18n.js +61 -0
- package/dist/editor/install.d.ts +72 -0
- package/dist/editor/install.js +239 -0
- package/dist/editor/mcp.d.ts +22 -0
- package/dist/editor/mcp.js +222 -0
- package/dist/editor/meta.d.ts +70 -0
- package/dist/editor/meta.js +163 -0
- package/dist/editor/paths.d.ts +2 -0
- package/dist/editor/paths.js +13 -0
- package/dist/editor/persistence.d.ts +4 -0
- package/dist/editor/persistence.js +35 -0
- package/dist/editor/saveGuard.d.ts +9 -0
- package/dist/editor/saveGuard.js +38 -0
- package/dist/editor/schema.d.ts +14 -0
- package/dist/editor/schema.js +38 -0
- package/dist/editor/service.d.ts +326 -0
- package/dist/editor/service.js +1007 -0
- package/dist/editor-ui/mcp-app.html +765 -0
- package/dist/gateway/adapters/acp.d.ts +8 -0
- package/dist/gateway/adapters/acp.js +38 -2
- package/dist/gateway/agentTaskHost.d.ts +135 -0
- package/dist/gateway/agentTaskHost.js +410 -0
- package/dist/gateway/config.js +2 -2
- package/dist/gateway/deviceHost.d.ts +6 -1
- package/dist/gateway/deviceHost.js +22 -4
- package/dist/gateway/mcpCommandTools.d.ts +1 -1
- package/dist/gateway/mcpCommandTools.js +2 -2
- package/dist/gateway/processTree.d.ts +15 -0
- package/dist/gateway/processTree.js +60 -0
- package/dist/gateway/protocol.js +2 -1
- package/dist/gateway/service.d.ts +1 -1
- package/dist/gateway/service.js +3 -1
- package/dist/gateway/taskJournal.d.ts +14 -0
- package/dist/gateway/taskJournal.js +47 -0
- package/dist/gateway/threadStore.d.ts +7 -1
- package/dist/gateway/threadStore.js +14 -3
- package/dist/gateway/types.d.ts +7 -3
- package/dist/gateway/types.js +3 -1
- package/dist/integrations/dsh/host.d.ts +53 -0
- package/dist/integrations/dsh/host.js +237 -0
- package/dist/integrations/dsh/mcpClient.d.ts +66 -0
- package/dist/integrations/dsh/mcpClient.js +192 -0
- package/dist/utils/errorCodes.d.ts +28 -0
- package/dist/utils/errorCodes.js +7 -0
- package/dist/vendor/electron/shared/remote-device-agent.d.ts +2 -0
- package/package.json +9 -2
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// src/integrations/dsh/host.ts
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
// src/integrations/dsh/mcpClient.ts
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
var PROTOCOL_VERSION = "2025-06-18";
|
|
10
|
+
var McpStdioClient = class {
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.options = options;
|
|
13
|
+
}
|
|
14
|
+
child = null;
|
|
15
|
+
ready = null;
|
|
16
|
+
nextId = 1;
|
|
17
|
+
pending = /* @__PURE__ */ new Map();
|
|
18
|
+
buffer = "";
|
|
19
|
+
failures = 0;
|
|
20
|
+
retryAt = 0;
|
|
21
|
+
closed = false;
|
|
22
|
+
async listTools() {
|
|
23
|
+
const result = await this.request("tools/list", {}, 3e4);
|
|
24
|
+
return result.tools ?? [];
|
|
25
|
+
}
|
|
26
|
+
async callTool(name2, args, options = {}) {
|
|
27
|
+
const params = { name: name2, arguments: args };
|
|
28
|
+
if (options.meta) params._meta = options.meta;
|
|
29
|
+
return await this.request("tools/call", params, options.timeoutMs ?? 4e4);
|
|
30
|
+
}
|
|
31
|
+
close() {
|
|
32
|
+
this.closed = true;
|
|
33
|
+
this.failAll(new Error("The Dinox editor connection closed"));
|
|
34
|
+
this.child?.kill();
|
|
35
|
+
this.child = null;
|
|
36
|
+
this.ready = null;
|
|
37
|
+
}
|
|
38
|
+
async request(method, params, timeoutMs) {
|
|
39
|
+
await this.connect();
|
|
40
|
+
return this.send(method, params, timeoutMs);
|
|
41
|
+
}
|
|
42
|
+
connect() {
|
|
43
|
+
if (this.closed) return Promise.reject(new Error("The Dinox editor connection closed"));
|
|
44
|
+
if (this.ready) return this.ready;
|
|
45
|
+
const wait = Math.max(0, this.retryAt - Date.now());
|
|
46
|
+
this.ready = (async () => {
|
|
47
|
+
if (wait) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
48
|
+
this.start();
|
|
49
|
+
await this.send("initialize", {
|
|
50
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
51
|
+
capabilities: {},
|
|
52
|
+
clientInfo: { name: "dinox-dsh-editor", version: "1" }
|
|
53
|
+
}, 3e4);
|
|
54
|
+
this.notify("notifications/initialized");
|
|
55
|
+
this.failures = 0;
|
|
56
|
+
})();
|
|
57
|
+
this.ready.catch(() => {
|
|
58
|
+
this.ready = null;
|
|
59
|
+
});
|
|
60
|
+
return this.ready;
|
|
61
|
+
}
|
|
62
|
+
start() {
|
|
63
|
+
const spawnProcess = this.options.spawnProcess ?? spawn;
|
|
64
|
+
const child = spawnProcess(this.options.command, this.options.args, {
|
|
65
|
+
env: this.options.env ?? process.env,
|
|
66
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
67
|
+
});
|
|
68
|
+
this.child = child;
|
|
69
|
+
this.buffer = "";
|
|
70
|
+
child.stdout.setEncoding("utf8");
|
|
71
|
+
child.stdout.on("data", (chunk) => this.onData(chunk));
|
|
72
|
+
child.stderr.setEncoding("utf8");
|
|
73
|
+
child.stderr.on("data", (chunk) => {
|
|
74
|
+
const text = chunk.trim();
|
|
75
|
+
if (text) this.options.log?.(text.slice(0, 2e3));
|
|
76
|
+
});
|
|
77
|
+
const gone = (reason) => {
|
|
78
|
+
if (this.child !== child) return;
|
|
79
|
+
this.child = null;
|
|
80
|
+
this.ready = null;
|
|
81
|
+
this.failures++;
|
|
82
|
+
const backoff = this.options.backoffMs ?? ((attempt) => Math.min(3e4, 500 * 2 ** (attempt - 1)));
|
|
83
|
+
this.retryAt = Date.now() + backoff(this.failures);
|
|
84
|
+
this.failAll(new Error(`The Dinox editor process ${reason}`));
|
|
85
|
+
if (!this.closed) this.options.log?.(`dino editor mcp ${reason}; restarting on next use`);
|
|
86
|
+
};
|
|
87
|
+
child.on("error", (error) => gone(`could not start (${error.message})`));
|
|
88
|
+
child.on("exit", (code, signal) => gone(`exited (${signal ?? code})`));
|
|
89
|
+
child.stdin.on("error", () => void 0);
|
|
90
|
+
}
|
|
91
|
+
send(method, params, timeoutMs) {
|
|
92
|
+
const child = this.child;
|
|
93
|
+
if (!child) return Promise.reject(new Error("The Dinox editor process is not running"));
|
|
94
|
+
const id = this.nextId++;
|
|
95
|
+
return new Promise((resolve, reject) => {
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
this.pending.delete(id);
|
|
98
|
+
reject(new Error(`The Dinox editor did not answer ${method} in time`));
|
|
99
|
+
}, timeoutMs);
|
|
100
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
101
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
|
|
102
|
+
`);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
notify(method) {
|
|
106
|
+
this.child?.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method })}
|
|
107
|
+
`);
|
|
108
|
+
}
|
|
109
|
+
onData(chunk) {
|
|
110
|
+
this.buffer += chunk;
|
|
111
|
+
let newline;
|
|
112
|
+
while ((newline = this.buffer.indexOf("\n")) >= 0) {
|
|
113
|
+
const line = this.buffer.slice(0, newline).trim();
|
|
114
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
115
|
+
if (!line) continue;
|
|
116
|
+
let message2;
|
|
117
|
+
try {
|
|
118
|
+
message2 = JSON.parse(line);
|
|
119
|
+
} catch {
|
|
120
|
+
this.options.log?.(`ignored a non-JSON line from dino editor mcp (${line.length} chars)`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (typeof message2.method === "string") {
|
|
124
|
+
if (message2.id !== void 0) {
|
|
125
|
+
const result = message2.method === "ping" ? {} : void 0;
|
|
126
|
+
const reply = result ? { jsonrpc: "2.0", id: message2.id, result } : { jsonrpc: "2.0", id: message2.id, error: { code: -32601, message: "Method not found" } };
|
|
127
|
+
this.child?.stdin.write(`${JSON.stringify(reply)}
|
|
128
|
+
`);
|
|
129
|
+
}
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const pending = typeof message2.id === "number" ? this.pending.get(message2.id) : void 0;
|
|
133
|
+
if (!pending) continue;
|
|
134
|
+
this.pending.delete(message2.id);
|
|
135
|
+
clearTimeout(pending.timer);
|
|
136
|
+
if (message2.error) pending.reject(new Error(message2.error.message || "The Dinox editor request failed"));
|
|
137
|
+
else pending.resolve(message2.result);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
failAll(error) {
|
|
141
|
+
for (const [id, pending] of this.pending) {
|
|
142
|
+
clearTimeout(pending.timer);
|
|
143
|
+
pending.reject(error);
|
|
144
|
+
this.pending.delete(id);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
function resultText(result) {
|
|
149
|
+
const text = (result.content ?? []).map((part) => part.type === "text" ? part.text ?? "" : "").join("\n");
|
|
150
|
+
if (result.isError) throw new Error(text || "The Dinox editor request failed");
|
|
151
|
+
return text;
|
|
152
|
+
}
|
|
153
|
+
var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "oneOf", "properties", "required", "additionalProperties", "items", "enum", "const", "description", "title", "default", "examples"]);
|
|
154
|
+
function toDshSchema(schema) {
|
|
155
|
+
const walk = (node) => {
|
|
156
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
157
|
+
if (!node || typeof node !== "object") return node;
|
|
158
|
+
const out = {};
|
|
159
|
+
for (const [key, value] of Object.entries(node)) {
|
|
160
|
+
if (!SCHEMA_KEYS.has(key)) continue;
|
|
161
|
+
if (key === "properties" && value && typeof value === "object") {
|
|
162
|
+
out.properties = Object.fromEntries(Object.entries(value).map(([name2, child]) => [name2, walk(child)]));
|
|
163
|
+
} else if (key === "additionalProperties") {
|
|
164
|
+
out[key] = value !== false;
|
|
165
|
+
} else if (key === "items" || key === "oneOf") {
|
|
166
|
+
out[key] = walk(value);
|
|
167
|
+
} else {
|
|
168
|
+
out[key] = value;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
};
|
|
173
|
+
const root = walk(schema);
|
|
174
|
+
return root && root.type === "object" ? root : { type: "object", properties: {} };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/integrations/dsh/host.ts
|
|
178
|
+
var name = "dinox-editor";
|
|
179
|
+
var inject = ["tools", "webServer", "agents"];
|
|
180
|
+
var ROUTE = "/dinox-editor";
|
|
181
|
+
var SESSION_PREFIX = "dsh:";
|
|
182
|
+
var MAX_BODY = 8 * 1024 * 1024;
|
|
183
|
+
var MAX_WAIT_MS = 25e3;
|
|
184
|
+
var UI_METHODS = /* @__PURE__ */ new Set(["sync", "save", "resolve", "search", "open", "log", "catalog", "updateMeta"]);
|
|
185
|
+
var SESSION_META_KEY = "dinox.ai/editorSession";
|
|
186
|
+
function resolveRuntime(pluginLib = path.dirname(fileURLToPath(import.meta.url)), env = process.env) {
|
|
187
|
+
const fallbackCli = path.resolve(pluginLib, "..", "..", "dinox.js");
|
|
188
|
+
let recorded = {};
|
|
189
|
+
try {
|
|
190
|
+
recorded = JSON.parse(readFileSync(path.join(pluginLib, "..", "runtime.json"), "utf8"));
|
|
191
|
+
} catch {
|
|
192
|
+
}
|
|
193
|
+
const node = env.DINOX_EDITOR_NODE || (recorded.node && existsSync(recorded.node) ? recorded.node : process.execPath);
|
|
194
|
+
const cli = env.DINOX_EDITOR_CLI || (recorded.cli && existsSync(recorded.cli) ? recorded.cli : fallbackCli);
|
|
195
|
+
return { node, cli };
|
|
196
|
+
}
|
|
197
|
+
var log = (message2) => console.error(`[dinox-editor] ${message2}`);
|
|
198
|
+
function apply(ctx, options = {}) {
|
|
199
|
+
const write = options.log ?? log;
|
|
200
|
+
const client = options.client ?? (() => {
|
|
201
|
+
const runtime = resolveRuntime();
|
|
202
|
+
return new McpStdioClient({ command: runtime.node, args: [runtime.cli, "editor", "mcp", "--session", "dsh"], log: write });
|
|
203
|
+
})();
|
|
204
|
+
ctx.effect(() => () => client.close());
|
|
205
|
+
const call = async (method, params, timeoutMs) => {
|
|
206
|
+
const result = await client.callTool("dinox_editor_rpc", { method, params }, { timeoutMs });
|
|
207
|
+
if (result.isError) resultText(result);
|
|
208
|
+
return result.structuredContent?.value;
|
|
209
|
+
};
|
|
210
|
+
const registerTools = async () => {
|
|
211
|
+
const tools = await client.listTools();
|
|
212
|
+
for (const tool of tools) {
|
|
213
|
+
if (isAppOnly(tool)) continue;
|
|
214
|
+
ctx.effect(() => ctx.tools.register(dshTool(tool, client)));
|
|
215
|
+
}
|
|
216
|
+
write(`registered ${tools.filter((tool) => !isAppOnly(tool)).length} editor tools`);
|
|
217
|
+
};
|
|
218
|
+
void retry(registerTools, write);
|
|
219
|
+
const debounce = options.contextDebounceMs ?? 1200;
|
|
220
|
+
const contexts = /* @__PURE__ */ new Map();
|
|
221
|
+
const queueContext = (sessionId, text) => {
|
|
222
|
+
const entry = contexts.get(sessionId) ?? { timer: null, last: "" };
|
|
223
|
+
contexts.set(sessionId, entry);
|
|
224
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
225
|
+
entry.timer = setTimeout(() => {
|
|
226
|
+
entry.timer = null;
|
|
227
|
+
if (text === entry.last) return;
|
|
228
|
+
entry.last = text;
|
|
229
|
+
const agent = ctx.agents.get(sessionId);
|
|
230
|
+
if (!agent) return;
|
|
231
|
+
void Promise.resolve(agent.inject(contextMessage(text))).catch((error) => write(`context not delivered: ${message(error)}`));
|
|
232
|
+
}, debounce);
|
|
233
|
+
};
|
|
234
|
+
ctx.effect(() => () => {
|
|
235
|
+
for (const entry of contexts.values()) if (entry.timer) clearTimeout(entry.timer);
|
|
236
|
+
});
|
|
237
|
+
ctx.effect(() => ctx.webServer.register({
|
|
238
|
+
kind: "prefix",
|
|
239
|
+
path: ROUTE,
|
|
240
|
+
handler: async (req, res) => {
|
|
241
|
+
try {
|
|
242
|
+
const action = new URL(req.url ?? "/", "http://dsh.invalid").pathname.slice(ROUTE.length + 1);
|
|
243
|
+
if (action !== "rpc" && action !== "opens" && action !== "context") return send(res, 404, { error: { message: "Unknown route" } });
|
|
244
|
+
if (req.method !== "POST") {
|
|
245
|
+
res.setHeader("Allow", "POST");
|
|
246
|
+
return send(res, 405, { error: { message: "Method not allowed" } });
|
|
247
|
+
}
|
|
248
|
+
if (!allowedOrigin(req)) return send(res, 403, { error: { message: "Cross-origin request refused" } });
|
|
249
|
+
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
|
|
250
|
+
return send(res, 415, { error: { message: "Expected application/json" } });
|
|
251
|
+
}
|
|
252
|
+
const body = await readJson(req);
|
|
253
|
+
if (action === "opens") {
|
|
254
|
+
const waitMs2 = clampWait(body.waitMs);
|
|
255
|
+
const value2 = await call("watchOpens", { cursor: body.cursor, waitMs: waitMs2 }, waitMs2 + 15e3);
|
|
256
|
+
const opens = value2.opens.filter((open) => open.session.startsWith(SESSION_PREFIX)).map((open) => ({ ...open, sessionId: open.session.slice(SESSION_PREFIX.length) }));
|
|
257
|
+
return send(res, 200, { value: { cursor: value2.cursor, opens } });
|
|
258
|
+
}
|
|
259
|
+
const sessionId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : null;
|
|
260
|
+
if (!sessionId) return send(res, 400, { error: { message: "sessionId is required" } });
|
|
261
|
+
if (action === "context") {
|
|
262
|
+
if (typeof body.text === "string") queueContext(sessionId, body.text.slice(0, 4e3));
|
|
263
|
+
return send(res, 200, { value: { ok: true } });
|
|
264
|
+
}
|
|
265
|
+
const method = String(body.method);
|
|
266
|
+
if (!UI_METHODS.has(method)) return send(res, 400, { error: { message: `Unknown editor method ${method}` } });
|
|
267
|
+
const params = body.params && typeof body.params === "object" && !Array.isArray(body.params) ? body.params : {};
|
|
268
|
+
const waitMs = method === "sync" ? clampWait(params.waitMs) : 0;
|
|
269
|
+
const forwarded = { ...params, session: SESSION_PREFIX + sessionId, ...method === "sync" ? { waitMs } : {} };
|
|
270
|
+
const value = await call(method, forwarded, method === "sync" ? waitMs + 15e3 : 4e4);
|
|
271
|
+
return send(res, 200, { value });
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (res.writableEnded) return;
|
|
274
|
+
const status = error.status ?? 502;
|
|
275
|
+
send(res, status, { error: { message: message(error) } });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
280
|
+
function isAppOnly(tool) {
|
|
281
|
+
const visibility = tool._meta?.ui?.visibility;
|
|
282
|
+
return Array.isArray(visibility) && !visibility.includes("model");
|
|
283
|
+
}
|
|
284
|
+
function dshTool(tool, client) {
|
|
285
|
+
return {
|
|
286
|
+
name: tool.name,
|
|
287
|
+
description: `${tool.description ?? ""} The note opens in the Dinox tab of the right sidebar.`.trim(),
|
|
288
|
+
parameters: toDshSchema(tool.inputSchema),
|
|
289
|
+
timeoutMs: 45e3,
|
|
290
|
+
output: {
|
|
291
|
+
schema: { type: "object", additionalProperties: true },
|
|
292
|
+
render: (_args, value) => [{ type: "text", text: value?.text ?? "" }]
|
|
293
|
+
},
|
|
294
|
+
execute: async (args, exec) => {
|
|
295
|
+
const sessionId = exec?.agent?.session?.id;
|
|
296
|
+
if (typeof sessionId !== "string" || !sessionId) throw new Error("This tool needs an agent session");
|
|
297
|
+
const result = await client.callTool(tool.name, args ?? {}, { meta: { [SESSION_META_KEY]: SESSION_PREFIX + sessionId } });
|
|
298
|
+
return { text: resultText(result) };
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
function contextMessage(text) {
|
|
303
|
+
const body = `[Dinox editor] ${text}`;
|
|
304
|
+
return Object.freeze({
|
|
305
|
+
id: randomUUID(),
|
|
306
|
+
role: "user",
|
|
307
|
+
source: Object.freeze({ kind: "cordis-host-runner" }),
|
|
308
|
+
content: Object.freeze([Object.freeze({ type: "text", text: body })])
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
async function retry(task, write) {
|
|
312
|
+
for (let attempt = 1; ; attempt++) {
|
|
313
|
+
try {
|
|
314
|
+
await task();
|
|
315
|
+
return;
|
|
316
|
+
} catch (error) {
|
|
317
|
+
write(`editor tools unavailable (${message(error)}); retrying`);
|
|
318
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(6e4, 1e3 * 2 ** attempt)));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function allowedOrigin(req) {
|
|
323
|
+
const origin = req.headers.origin;
|
|
324
|
+
if (!origin) return true;
|
|
325
|
+
if (origin === "dsh-app://app") return true;
|
|
326
|
+
try {
|
|
327
|
+
return new URL(origin).host === req.headers.host;
|
|
328
|
+
} catch {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function clampWait(value) {
|
|
333
|
+
return Math.max(0, Math.min(MAX_WAIT_MS, Number(value) || 0));
|
|
334
|
+
}
|
|
335
|
+
async function readJson(req) {
|
|
336
|
+
const chunks = [];
|
|
337
|
+
let size = 0;
|
|
338
|
+
for await (const chunk of req) {
|
|
339
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
340
|
+
size += buffer.length;
|
|
341
|
+
if (size > MAX_BODY) throw Object.assign(new Error("Request body exceeds 8MB"), { status: 413 });
|
|
342
|
+
chunks.push(buffer);
|
|
343
|
+
}
|
|
344
|
+
let value;
|
|
345
|
+
try {
|
|
346
|
+
value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
347
|
+
} catch {
|
|
348
|
+
throw Object.assign(new Error("Request body is not JSON"), { status: 400 });
|
|
349
|
+
}
|
|
350
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw Object.assign(new Error("Expected a JSON object"), { status: 400 });
|
|
351
|
+
return value;
|
|
352
|
+
}
|
|
353
|
+
function send(res, status, value) {
|
|
354
|
+
res.statusCode = status;
|
|
355
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
356
|
+
res.setHeader("Cache-Control", "no-store");
|
|
357
|
+
res.end(JSON.stringify(value));
|
|
358
|
+
}
|
|
359
|
+
function message(error) {
|
|
360
|
+
return error instanceof Error ? error.message : String(error);
|
|
361
|
+
}
|
|
362
|
+
export {
|
|
363
|
+
ROUTE,
|
|
364
|
+
allowedOrigin,
|
|
365
|
+
apply,
|
|
366
|
+
inject,
|
|
367
|
+
name,
|
|
368
|
+
resolveRuntime
|
|
369
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dinox-editor-dsh",
|
|
3
|
+
"version": "2.18.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Dinox note editor for DeepSeek Harness Desktop (built by @dinoxx/dinox-cli)",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "lib/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./lib/index.js",
|
|
10
|
+
"./client": "./lib/client.js",
|
|
11
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"lib/",
|
|
16
|
+
"cordis.patch.yml",
|
|
17
|
+
"runtime.json"
|
|
18
|
+
],
|
|
19
|
+
"dsh": {
|
|
20
|
+
"client": {
|
|
21
|
+
"platform": "web",
|
|
22
|
+
"inject": [
|
|
23
|
+
"@deepseek-ai/dsh-client-ui-sidebar-right",
|
|
24
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
"bundle": {
|
|
28
|
+
"patch": "./cordis.patch.yml"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {}
|
|
32
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Node as PMNode } from '@tiptap/pm/model';
|
|
2
|
+
/**
|
|
3
|
+
* One text projection of a document, shared by the daemon (validating a
|
|
4
|
+
* model's suggestion) and the editor UI (placing it). Textblocks are joined by
|
|
5
|
+
* a blank line, hard breaks become `\n`, opaque nodes contribute their label
|
|
6
|
+
* and other inline atoms the object replacement character.
|
|
7
|
+
*/
|
|
8
|
+
export type TextIndex = {
|
|
9
|
+
text: string;
|
|
10
|
+
/** Document position of every character of `text`; -1 for block separators. */
|
|
11
|
+
positions: number[];
|
|
12
|
+
/** Every textblock in document order: its node position and its range in `text`. */
|
|
13
|
+
blocks: Array<{
|
|
14
|
+
pos: number;
|
|
15
|
+
start: number;
|
|
16
|
+
end: number;
|
|
17
|
+
}>;
|
|
18
|
+
};
|
|
19
|
+
export declare function buildTextIndex(doc: PMNode): TextIndex;
|
|
20
|
+
/** Markdown a model tends to quote back, reduced to the text it renders as. */
|
|
21
|
+
export declare function normalizeAnchor(find: string): string;
|
|
22
|
+
export type AnchorMatch = {
|
|
23
|
+
status: 'ok';
|
|
24
|
+
start: number;
|
|
25
|
+
end: number;
|
|
26
|
+
anchor: string;
|
|
27
|
+
};
|
|
28
|
+
export type AnchorLocation = AnchorMatch | {
|
|
29
|
+
status: 'missing';
|
|
30
|
+
} | {
|
|
31
|
+
status: 'ambiguous';
|
|
32
|
+
count: number;
|
|
33
|
+
};
|
|
34
|
+
/** Locates `find` exactly once; tries it verbatim, then with Markdown syntax removed. */
|
|
35
|
+
export declare function locateAnchor(text: string, find: string): AnchorLocation;
|
|
36
|
+
/**
|
|
37
|
+
* Like `locateAnchor`, but several occurrences resolve to the one nearest
|
|
38
|
+
* `near` (a text offset recorded when the anchor was made), so a sentence
|
|
39
|
+
* that repeats elsewhere in the note still lands where it was meant.
|
|
40
|
+
*/
|
|
41
|
+
export declare function locateNear(text: string, find: string, near: number | undefined): AnchorLocation;
|
|
42
|
+
/** Maps a text range onto document positions; null when it starts or ends on a separator. */
|
|
43
|
+
export declare function rangeOf(index: TextIndex, start: number, end: number): {
|
|
44
|
+
from: number;
|
|
45
|
+
to: number;
|
|
46
|
+
} | null;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { opaqueLabel } from './compat.js';
|
|
2
|
+
const BLOCK_SEPARATOR = '\n\n';
|
|
3
|
+
const OBJECT_REPLACEMENT = '';
|
|
4
|
+
function inlineLabel(node) {
|
|
5
|
+
if (node.type.name === 'hardBreak')
|
|
6
|
+
return '\n';
|
|
7
|
+
if (node.type.name.startsWith('dxOpaque'))
|
|
8
|
+
return opaqueLabel(node.toJSON());
|
|
9
|
+
// Inline atoms read the way the CLI's Markdown shows them.
|
|
10
|
+
const label = (key) => String(node.attrs[key] ?? '').trim();
|
|
11
|
+
const labels = {
|
|
12
|
+
hashtag: () => `#${label('label') || label('id')}`,
|
|
13
|
+
bidlink: () => label('label') || label('id'),
|
|
14
|
+
mention: () => label('label') || label('id'),
|
|
15
|
+
location: () => label('name'),
|
|
16
|
+
time: () => label('iso'),
|
|
17
|
+
};
|
|
18
|
+
const text = labels[node.type.name]?.();
|
|
19
|
+
return text || OBJECT_REPLACEMENT;
|
|
20
|
+
}
|
|
21
|
+
export function buildTextIndex(doc) {
|
|
22
|
+
let text = '';
|
|
23
|
+
const positions = [];
|
|
24
|
+
const blocks = [];
|
|
25
|
+
let first = true;
|
|
26
|
+
doc.descendants((node, pos) => {
|
|
27
|
+
if (!node.isTextblock)
|
|
28
|
+
return true;
|
|
29
|
+
if (!first) {
|
|
30
|
+
text += BLOCK_SEPARATOR;
|
|
31
|
+
positions.push(-1, -1);
|
|
32
|
+
}
|
|
33
|
+
first = false;
|
|
34
|
+
const start = text.length;
|
|
35
|
+
node.forEach((child, offset) => {
|
|
36
|
+
const at = pos + 1 + offset;
|
|
37
|
+
if (child.isText) {
|
|
38
|
+
const value = child.text ?? '';
|
|
39
|
+
for (let i = 0; i < value.length; i++)
|
|
40
|
+
positions.push(at + i);
|
|
41
|
+
text += value;
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const label = inlineLabel(child);
|
|
45
|
+
for (let i = 0; i < label.length; i++)
|
|
46
|
+
positions.push(at);
|
|
47
|
+
text += label;
|
|
48
|
+
});
|
|
49
|
+
blocks.push({ pos, start, end: text.length });
|
|
50
|
+
return false;
|
|
51
|
+
});
|
|
52
|
+
return { text, positions, blocks };
|
|
53
|
+
}
|
|
54
|
+
/** Markdown a model tends to quote back, reduced to the text it renders as. */
|
|
55
|
+
export function normalizeAnchor(find) {
|
|
56
|
+
const lines = find.replace(/\r\n?/g, '\n').split('\n');
|
|
57
|
+
const blocks = [];
|
|
58
|
+
let current = [];
|
|
59
|
+
const flush = () => {
|
|
60
|
+
if (current.length)
|
|
61
|
+
blocks.push(current.join('\n'));
|
|
62
|
+
current = [];
|
|
63
|
+
};
|
|
64
|
+
for (const raw of lines) {
|
|
65
|
+
if (/^\s*$/.test(raw) || /^\s*(```|~~~)/.test(raw) || /^\s*([-*_])\s*(\1\s*){2,}$/.test(raw)) {
|
|
66
|
+
flush();
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
let line = raw.replace(/^\s{0,3}(?:#{1,6}\s+|(?:>\s?)+|[-*+]\s+(?:\[[ xX]\]\s+)?|\d+[.)]\s+(?:\[[ xX]\]\s+)?)/, '');
|
|
70
|
+
line = line
|
|
71
|
+
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
72
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
|
73
|
+
.replace(/(\*\*|__|~~|==)(?=\S)([\s\S]*?\S)\1/g, '$2')
|
|
74
|
+
.replace(/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\w)/g, '$1$2')
|
|
75
|
+
.replace(/(^|[^\w])_(?=\S)([^_]*?\S)_(?!\w)/g, '$1$2')
|
|
76
|
+
.replace(/`([^`]+)`/g, '$1')
|
|
77
|
+
.replace(/\\([\\`*_{}[\]()#+\-.!>~|])/g, '$1');
|
|
78
|
+
current.push(line);
|
|
79
|
+
}
|
|
80
|
+
flush();
|
|
81
|
+
return blocks.join(BLOCK_SEPARATOR).trim();
|
|
82
|
+
}
|
|
83
|
+
function occurrences(text, needle) {
|
|
84
|
+
const found = [];
|
|
85
|
+
for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1))
|
|
86
|
+
found.push(at);
|
|
87
|
+
return found;
|
|
88
|
+
}
|
|
89
|
+
/** Locates `find` exactly once; tries it verbatim, then with Markdown syntax removed. */
|
|
90
|
+
export function locateAnchor(text, find) {
|
|
91
|
+
const candidates = [...new Set([find, normalizeAnchor(find)])].filter(Boolean);
|
|
92
|
+
let ambiguous = 0;
|
|
93
|
+
for (const candidate of candidates) {
|
|
94
|
+
const found = occurrences(text, candidate);
|
|
95
|
+
if (found.length === 1)
|
|
96
|
+
return { status: 'ok', start: found[0], end: found[0] + candidate.length, anchor: candidate };
|
|
97
|
+
if (found.length > 1)
|
|
98
|
+
ambiguous = Math.max(ambiguous, found.length);
|
|
99
|
+
}
|
|
100
|
+
return ambiguous ? { status: 'ambiguous', count: ambiguous } : { status: 'missing' };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Like `locateAnchor`, but several occurrences resolve to the one nearest
|
|
104
|
+
* `near` (a text offset recorded when the anchor was made), so a sentence
|
|
105
|
+
* that repeats elsewhere in the note still lands where it was meant.
|
|
106
|
+
*/
|
|
107
|
+
export function locateNear(text, find, near) {
|
|
108
|
+
const located = locateAnchor(text, find);
|
|
109
|
+
if (located.status !== 'ambiguous' || near === undefined || !Number.isFinite(near))
|
|
110
|
+
return located;
|
|
111
|
+
for (const candidate of [...new Set([find, normalizeAnchor(find)])].filter(Boolean)) {
|
|
112
|
+
const found = occurrences(text, candidate);
|
|
113
|
+
if (found.length < 2)
|
|
114
|
+
continue;
|
|
115
|
+
const best = found.reduce((a, b) => (Math.abs(b - near) < Math.abs(a - near) ? b : a));
|
|
116
|
+
return { status: 'ok', start: best, end: best + candidate.length, anchor: candidate };
|
|
117
|
+
}
|
|
118
|
+
return located;
|
|
119
|
+
}
|
|
120
|
+
/** Maps a text range onto document positions; null when it starts or ends on a separator. */
|
|
121
|
+
export function rangeOf(index, start, end) {
|
|
122
|
+
if (end <= start)
|
|
123
|
+
return null;
|
|
124
|
+
const from = index.positions[start];
|
|
125
|
+
const last = index.positions[end - 1];
|
|
126
|
+
if (from === undefined || last === undefined || from < 0 || last < 0)
|
|
127
|
+
return null;
|
|
128
|
+
return { from, to: last + 1 };
|
|
129
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Extension } from '@tiptap/core';
|
|
2
|
+
/**
|
|
3
|
+
* Block ids (`attrs.id`). Every Dinox client gives its blocks an id: the
|
|
4
|
+
* desktop with SafeUniqueID (uuidv7), the app with UniqueID. The ids are the
|
|
5
|
+
* note's own identity for a block: tasks, reminders and the OpenAPI address a
|
|
6
|
+
* task by its taskItem id. The editor keeps them, gives new blocks one, and
|
|
7
|
+
* reads blocks to the model by them.
|
|
8
|
+
*
|
|
9
|
+
* The union of the desktop's (notion-like-editor.tsx) and the app's
|
|
10
|
+
* (lib/tiptap/blockIdTypes.ts) types that the editor schema has as nodes.
|
|
11
|
+
*/
|
|
12
|
+
export declare const BLOCK_ID_TYPES: readonly ["paragraph", "heading", "blockquote", "codeBlock", "bulletList", "orderedList", "listItem", "taskList", "taskItem", "table", "image", "video", "mermaid", "mindgraph"];
|
|
13
|
+
/** Declares `id` on the block types, so the schema keeps it (null when absent, dropped on save). */
|
|
14
|
+
export declare const BlockIdAttribute: Extension<any, any>;
|
|
15
|
+
export declare const blockIdOf: (value: unknown) => string | null;
|
|
16
|
+
/**
|
|
17
|
+
* A short handle for a block id, for the model: the end of the id (the random
|
|
18
|
+
* part of a uuidv7), at least five characters, longer when that is taken. The
|
|
19
|
+
* same block reads the same in every session and every AI app.
|
|
20
|
+
*/
|
|
21
|
+
export declare function shortBlockId(id: string, taken: (alias: string) => boolean): string;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Extension } from '@tiptap/core';
|
|
2
|
+
/**
|
|
3
|
+
* Block ids (`attrs.id`). Every Dinox client gives its blocks an id: the
|
|
4
|
+
* desktop with SafeUniqueID (uuidv7), the app with UniqueID. The ids are the
|
|
5
|
+
* note's own identity for a block: tasks, reminders and the OpenAPI address a
|
|
6
|
+
* task by its taskItem id. The editor keeps them, gives new blocks one, and
|
|
7
|
+
* reads blocks to the model by them.
|
|
8
|
+
*
|
|
9
|
+
* The union of the desktop's (notion-like-editor.tsx) and the app's
|
|
10
|
+
* (lib/tiptap/blockIdTypes.ts) types that the editor schema has as nodes.
|
|
11
|
+
*/
|
|
12
|
+
export const BLOCK_ID_TYPES = [
|
|
13
|
+
'paragraph', 'heading', 'blockquote', 'codeBlock',
|
|
14
|
+
'bulletList', 'orderedList', 'listItem', 'taskList', 'taskItem',
|
|
15
|
+
'table', 'image', 'video', 'mermaid', 'mindgraph',
|
|
16
|
+
];
|
|
17
|
+
/** Declares `id` on the block types, so the schema keeps it (null when absent, dropped on save). */
|
|
18
|
+
export const BlockIdAttribute = Extension.create({
|
|
19
|
+
name: 'dxBlockId',
|
|
20
|
+
addGlobalAttributes() {
|
|
21
|
+
return [{
|
|
22
|
+
types: [...BLOCK_ID_TYPES],
|
|
23
|
+
attributes: {
|
|
24
|
+
id: {
|
|
25
|
+
default: null,
|
|
26
|
+
// The second half of a split is a new block; it gets its own id.
|
|
27
|
+
keepOnSplit: false,
|
|
28
|
+
parseHTML: (element) => element.getAttribute('data-id'),
|
|
29
|
+
renderHTML: (attributes) => (attributes.id ? { 'data-id': attributes.id } : {}),
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
}];
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
export const blockIdOf = (value) => (typeof value === 'string' && value ? value : null);
|
|
36
|
+
/**
|
|
37
|
+
* A short handle for a block id, for the model: the end of the id (the random
|
|
38
|
+
* part of a uuidv7), at least five characters, longer when that is taken. The
|
|
39
|
+
* same block reads the same in every session and every AI app.
|
|
40
|
+
*/
|
|
41
|
+
export function shortBlockId(id, taken) {
|
|
42
|
+
const compact = id.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
|
|
43
|
+
if (!compact)
|
|
44
|
+
return '';
|
|
45
|
+
for (let length = Math.min(5, compact.length); length <= compact.length; length++) {
|
|
46
|
+
const alias = compact.slice(-length);
|
|
47
|
+
if (!taken(alias))
|
|
48
|
+
return alias;
|
|
49
|
+
}
|
|
50
|
+
return '';
|
|
51
|
+
}
|