dia-bridge 0.1.1 → 0.2.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/src/logger.mjs ADDED
@@ -0,0 +1,27 @@
1
+ const LEVELS = {
2
+ debug: 10,
3
+ info: 20,
4
+ warn: 30,
5
+ error: 40,
6
+ silent: 100,
7
+ }
8
+
9
+ export function getLogLevel(envLevel = process.env.DIA_LOG_LEVEL) {
10
+ const key = String(envLevel || "warn").toLowerCase().trim()
11
+ return LEVELS[key] ?? LEVELS.warn
12
+ }
13
+
14
+ export function createLogger(scope = "dia-bridge") {
15
+ function emit(levelName, message, extra) {
16
+ if (LEVELS[levelName] < getLogLevel()) return
17
+ const suffix = extra !== undefined ? ` ${JSON.stringify(extra)}` : ""
18
+ process.stderr.write(`[${scope}] [${levelName}] ${message}${suffix}\n`)
19
+ }
20
+
21
+ return {
22
+ debug: (msg, extra) => emit("debug", msg, extra),
23
+ info: (msg, extra) => emit("info", msg, extra),
24
+ warn: (msg, extra) => emit("warn", msg, extra),
25
+ error: (msg, extra) => emit("error", msg, extra),
26
+ }
27
+ }
@@ -9,7 +9,7 @@ export const STANDALONE_DEFAULT_TIMEOUT_MS = 120000
9
9
  export const MCP_TOOL_DEFINITION = {
10
10
  name: "dia_ask",
11
11
  description:
12
- "Send a prompt to the macOS Dia browser AI assistant via Accessibility (AXValue) and return its full reply from disk. Serial execution (one request at a time), macOS host required, typical latency 15-60s.",
12
+ "Send a prompt to the Dia browser AI assistant via macOS Accessibility (AXValue) or Windows UI Automation (ValuePattern) and return its full reply from disk. Serial execution (one request at a time), macOS or Windows host required, typical latency 15-60s.",
13
13
  inputSchema: {
14
14
  type: "object",
15
15
  properties: {
@@ -28,8 +28,61 @@ export const MCP_TOOL_DEFINITION = {
28
28
  required: ["prompt"],
29
29
  additionalProperties: false,
30
30
  },
31
+ annotations: {
32
+ readOnlyHint: false,
33
+ destructiveHint: false,
34
+ idempotentHint: false,
35
+ openWorldHint: true,
36
+ },
31
37
  }
32
38
 
39
+ export const MCP_STATUS_TOOL_DEFINITION = {
40
+ name: "dia_status",
41
+ description:
42
+ "Read-only diagnostic check for Dia browser running state, macOS Accessibility / Windows UIA readiness, mutex busy state, and AgentServer contexts directory.",
43
+ inputSchema: {
44
+ type: "object",
45
+ properties: {},
46
+ additionalProperties: false,
47
+ },
48
+ annotations: {
49
+ readOnlyHint: true,
50
+ destructiveHint: false,
51
+ idempotentHint: true,
52
+ openWorldHint: false,
53
+ },
54
+ }
55
+
56
+ export const MCP_HISTORY_TOOL_DEFINITION = {
57
+ name: "dia_get_chat_history",
58
+ description:
59
+ "Read recent Dia AI assistant replies directly from local AgentServer/contexts/*/logs/feedback.jsonl on disk (read-only, instant, no UI automation).",
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: {
63
+ limit: {
64
+ type: "number",
65
+ description: "Maximum number of recent Dia answers to return (default 5, max 50).",
66
+ minimum: 1,
67
+ maximum: 50,
68
+ },
69
+ },
70
+ additionalProperties: false,
71
+ },
72
+ annotations: {
73
+ readOnlyHint: true,
74
+ destructiveHint: false,
75
+ idempotentHint: true,
76
+ openWorldHint: false,
77
+ },
78
+ }
79
+
80
+ export const MCP_TOOLS = [
81
+ MCP_TOOL_DEFINITION,
82
+ MCP_STATUS_TOOL_DEFINITION,
83
+ MCP_HISTORY_TOOL_DEFINITION,
84
+ ]
85
+
33
86
  function jsonRpcResult(id, result) {
34
87
  return { jsonrpc: "2.0", id, result }
35
88
  }
@@ -68,7 +121,7 @@ export function createMcpDispatcher(options = {}) {
68
121
 
69
122
  const serverInfo = {
70
123
  name: options.name ?? "dia-bridge",
71
- version: options.version ?? "0.1.1",
124
+ version: options.version ?? "0.2.0",
72
125
  }
73
126
 
74
127
  const inflight = new Map()
@@ -113,7 +166,7 @@ export function createMcpDispatcher(options = {}) {
113
166
 
114
167
  if (msg.method === "tools/list") {
115
168
  return jsonRpcResult(msg.id, {
116
- tools: [MCP_TOOL_DEFINITION],
169
+ tools: MCP_TOOLS,
117
170
  })
118
171
  }
119
172
 
@@ -121,7 +174,7 @@ export function createMcpDispatcher(options = {}) {
121
174
  const name = msg.params?.name
122
175
  const args = msg.params?.arguments ?? {}
123
176
 
124
- if (name !== "dia_ask") {
177
+ if (name !== "dia_ask" && name !== "dia_status" && name !== "dia_get_chat_history") {
125
178
  return jsonRpcError(msg.id, -32602, `Unknown tool: ${String(name)}`)
126
179
  }
127
180
 
@@ -140,12 +193,21 @@ export function createMcpDispatcher(options = {}) {
140
193
  }
141
194
 
142
195
  try {
143
- const answer = await bridge.ask(args?.prompt, {
144
- timeoutMs: args?.timeoutMs,
145
- signal: controller.signal,
146
- })
196
+ let text
197
+ if (name === "dia_ask") {
198
+ text = await bridge.ask(args?.prompt, {
199
+ timeoutMs: args?.timeoutMs,
200
+ signal: controller.signal,
201
+ })
202
+ } else if (name === "dia_status") {
203
+ const status = await bridge.getStatus({ signal: controller.signal })
204
+ text = JSON.stringify(status, null, 2)
205
+ } else {
206
+ const history = await bridge.getHistory({ limit: args?.limit })
207
+ text = JSON.stringify(history, null, 2)
208
+ }
147
209
  return jsonRpcResult(msg.id, {
148
- content: [{ type: "text", text: answer }],
210
+ content: [{ type: "text", text }],
149
211
  isError: false,
150
212
  })
151
213
  } catch (err) {
package/src/store.mjs CHANGED
@@ -1,14 +1,50 @@
1
+ import fsSync from "node:fs"
1
2
  import fs from "node:fs/promises"
2
3
  import os from "node:os"
3
4
  import path from "node:path"
4
5
  import { DiaAbortedError, DiaTimeoutError } from "./errors.mjs"
5
6
 
6
- export function getDefaultContextsDir() {
7
- if (process.env.DIA_CONTEXTS_DIR) {
8
- return process.env.DIA_CONTEXTS_DIR
7
+ export function getDefaultContextsDir({
8
+ platform = process.platform,
9
+ env = process.env,
10
+ homedir = os.homedir(),
11
+ readdirSync = fsSync.readdirSync,
12
+ existsSync = fsSync.existsSync,
13
+ } = {}) {
14
+ if (env.DIA_CONTEXTS_DIR) {
15
+ return env.DIA_CONTEXTS_DIR
16
+ }
17
+ if (platform === "win32") {
18
+ const localAppData = env.LOCALAPPDATA || path.join(homedir, "AppData", "Local")
19
+ const packagesDir = path.join(localAppData, "Packages")
20
+ try {
21
+ const entries = readdirSync(packagesDir, { withFileTypes: true })
22
+ const matches = entries
23
+ .filter((entry) => entry.isDirectory() && /^TheBrowserCompany\.Dia_/i.test(entry.name))
24
+ .map((entry) =>
25
+ path.join(
26
+ packagesDir,
27
+ entry.name,
28
+ "LocalCache",
29
+ "Local",
30
+ "Dia",
31
+ "User Data",
32
+ "Default",
33
+ "AgentServer",
34
+ "contexts",
35
+ ),
36
+ )
37
+ if (matches.length > 0) {
38
+ const existing = matches.find((candidate) => existsSync(candidate))
39
+ return existing ?? matches[0]
40
+ }
41
+ } catch {
42
+ // Packages directory missing or unreadable; fall through to standard LocalAppData path
43
+ }
44
+ return path.join(localAppData, "Dia", "User Data", "Default", "AgentServer", "contexts")
9
45
  }
10
46
  return path.join(
11
- os.homedir(),
47
+ homedir,
12
48
  "Library",
13
49
  "Application Support",
14
50
  "Dia",
@@ -394,3 +430,58 @@ export async function pollForNewAnswer(
394
430
  await sleep(Math.min(pollIntervalMs, remaining), signal)
395
431
  }
396
432
  }
433
+
434
+ /**
435
+ * Reads the most recent assistant answers persisted under AgentServer/contexts/<uuid>/logs/feedback.jsonl.
436
+ * Strictly read-only; never reads credentials or tokens.
437
+ */
438
+ export async function readRecentChatHistory(contextsDir, { limit = 5 } = {}) {
439
+ const safeLimit = Math.max(1, Math.min(50, Math.floor(Number(limit) || 5)))
440
+ let dirEntries
441
+ try {
442
+ dirEntries = await fs.readdir(contextsDir, { withFileTypes: true })
443
+ } catch (err) {
444
+ if (err?.code === "ENOENT") return []
445
+ throw err
446
+ }
447
+
448
+ const candidates = []
449
+ for (const entry of dirEntries) {
450
+ if (!entry.isDirectory()) continue
451
+ const contextId = entry.name
452
+ const feedbackPath = path.join(contextsDir, contextId, "logs", "feedback.jsonl")
453
+ try {
454
+ const stat = await fs.stat(feedbackPath)
455
+ if (stat.size > 0) {
456
+ candidates.push({ contextId, feedbackPath, mtimeMs: stat.mtimeMs })
457
+ }
458
+ } catch {
459
+ // skip contexts without feedback.jsonl
460
+ }
461
+ }
462
+
463
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs)
464
+
465
+ const results = []
466
+ for (const item of candidates) {
467
+ if (results.length >= safeLimit) break
468
+ try {
469
+ const raw = await fs.readFile(item.feedbackPath, "utf8")
470
+ const records = parseJsonlDelta(raw)
471
+ for (let i = records.length - 1; i >= 0 && results.length < safeLimit; i--) {
472
+ const answer = extractAnswerFromFeedbackEntry(records[i])
473
+ if (answer) {
474
+ results.push({
475
+ contextId: item.contextId,
476
+ updatedAt: new Date(item.mtimeMs).toISOString(),
477
+ answer,
478
+ })
479
+ }
480
+ }
481
+ } catch {
482
+ // skip unreadable files
483
+ }
484
+ }
485
+
486
+ return results
487
+ }