OpenTalon / app · opentalon.ai / native / service.cjs
| 1 | const taskHistory = require('./task-history.cjs') |
| 2 | const taskActivity = require('./task-activity.cjs') |
| 3 | const taskFiles = require('./task-files.cjs') |
| 4 | // Private JSON-line transport between the Swift application and the shared local service. |
| 5 | // The network-facing connector retains its own allowlist and authentication. |
| 6 | const fs = require('node:fs') |
| 7 | const os = require('node:os') |
| 8 | const path = require('node:path') |
| 9 | const readline = require('node:readline') |
| 10 | const { backup, DatabaseSync } = require('node:sqlite') |
| 11 | const { randomUUID } = require('node:crypto') |
| 12 | const { DailyBackup } = require('./daily-backup.cjs') |
| 13 | const { execFile } = require('node:child_process') |
| 14 | const { promisify } = require('node:util') |
| 15 | const { Store } = require('./store.cjs') |
| 16 | const { AgentRunner, askAgent, draftTask } = require('./agent-runner.cjs') |
| 17 | const { assertAgentReady, agentWorkingDirectory } = require('./agent-readiness.cjs') |
| 18 | const { Connector, errorView } = require('./mcp.cjs') |
| 19 | const { tools, validateAction, AppError } = require('./contracts.cjs') |
| 20 | const { agentIds } = require('./agent-models.cjs') |
| 21 | const { setupFields, terminalCommand, saveClaudeExtension, prepareProjectSetup, writeProjectSetup } = |
| 22 | require('./agent-setup.cjs') |
| 23 | |
| 24 | const runFile = promisify(execFile) |
| 25 | const [folder, executable, version, visibility] = process.argv.slice(2) |
| 26 | let windowOpen = visibility === 'visible' |
| 27 | const send = (value) => process.stdout.write(JSON.stringify(value) + '\n') |
| 28 | const changed = () => send({ event: 'changed' }) |
| 29 | const local = (request) => connector.configuration(request) |
| 30 | const maxRequest = 20 * 1024 * 1024 |
| 31 | let store, connector, runner, daily, migrationFolder |
| 32 | const projects = new Map() |
| 33 | let chatController |
| 34 | const chatTools = tools.filter(({ name }) => [ |
| 35 | 'list_boards', 'create_board', 'rename_board', 'set_board_icon', |
| 36 | 'list_tasks', 'get_task', 'create_task', 'update_task', 'set_task_plan', 'get_task_history', 'restore_task_revision', 'move_task', |
| 37 | 'trash_task', 'list_trash', 'restore_task', 'list_task_comments', 'list_task_activity', 'add_task_activity', |
| 38 | ].includes(name)) |
| 39 | |
| 40 | // Chat and drafting have no model picker. Gemini still needs a named model, never the CLI's own. |
| 41 | const defaultModel = (agent) => store.agentModelCatalog().models.find((model) => model.agent === agent)?.id |
| 42 | |
| 43 | async function chat(input) { |
| 44 | const { message, history, projectId, agent: selectedAgent } = input |
| 45 | if (typeof message !== 'string' || !message.trim() || message.length > 4000 || |
| 46 | !Array.isArray(history) || history.length > 16 || history.some((entry) => |
| 47 | !['user', 'assistant'].includes(entry?.role) || typeof entry.text !== 'string' || entry.text.length > 16000)) |
| 48 | throw new AppError('INVALID_ARGUMENT', 'Enter a message up to 4,000 characters.') |
| 49 | if (!connector.status().enabled || !connector.status().running) |
| 50 | throw new AppError('CONNECTION_DISABLED', 'Turn on the local agent connection in Settings to start chatting.') |
| 51 | const project = projectId ? store.board(projectId).name : undefined |
| 52 | if (selectedAgent !== undefined && !agentIds.includes(selectedAgent)) |
| 53 | throw new AppError('INVALID_ARGUMENT', 'Choose Claude, Codex or Gemini for this chat.') |
| 54 | const settings = store.agentSettings(projectId) |
| 55 | const agent = selectedAgent ?? settings.defaultAgent |
| 56 | const workingFolder = agentWorkingDirectory(settings.workingFolder) |
| 57 | const controller = new AbortController() |
| 58 | chatController = controller |
| 59 | let directory, chatConnector |
| 60 | try { |
| 61 | directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'opentalon-chat-')) |
| 62 | chatConnector = new Connector({ |
| 63 | folder: directory, executable, stdioCommand: process.execPath, version, toolCatalog: chatTools, |
| 64 | call: async (name, args) => { |
| 65 | if (controller.signal.aborted || !connector.status().running) |
| 66 | throw new AppError('CONNECTION_DISABLED', 'This chat connection is closed.') |
| 67 | if (args.status === 'Sent to agent' || args.notifyAgent === true || args.images?.length) |
| 68 | throw new AppError('TOOL_UNAVAILABLE', 'Use the task’s Send to agent or attachment controls for this action.') |
| 69 | const result = await dispatch(name, args) |
| 70 | if (chatTools.find((tool) => tool.name === name)?.mutates) { |
| 71 | const record = result.task ?? result.board ?? (name === 'add_task_activity' ? store.task(args.taskId) : null) |
| 72 | send({ event: 'agent-chat-activity', name, title: record?.title ?? record?.name }) |
| 73 | } |
| 74 | return result |
| 75 | }, |
| 76 | }) |
| 77 | await chatConnector.enable(true) |
| 78 | const config = chatConnector.configuration('stdio').mcpServers.opentalon |
| 79 | config.env.OPENTALON_MCP_NO_LAUNCH = '1' |
| 80 | return await askAgent(agent, { |
| 81 | directory, workingFolder, config, permissionMode: settings.permissionMode, |
| 82 | message, history, project, signal: controller.signal, model: defaultModel(agent), |
| 83 | }) |
| 84 | } finally { |
| 85 | await chatConnector?.stop().catch(() => {}) |
| 86 | if (directory) await fs.promises.rm(directory, { recursive: true, force: true }).catch(() => {}) |
| 87 | chatController = undefined |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | async function dispatch(name, input, origin = 'Connected agent') { |
| 92 | validateAction(name, input, true) |
| 93 | const sendsToAgent = input.status === 'Sent to agent' || |
| 94 | name === 'recover_agent_run' || |
| 95 | (name === 'companion_set_task_field' && input.field === 'status' && input.value === 'Sent to agent') |
| 96 | if (sendsToAgent && (!connector.status().enabled || !connector.status().running)) |
| 97 | throw new AppError('MCP_DISABLED', 'Connect MCP in Settings to use agents.') |
| 98 | switch (name) { |
| 99 | case 'recover_agent_run': |
| 100 | if (runner.suspended || runner.stopping || runner.current?.job.taskId === input.taskId) |
| 101 | throw new AppError('BUSY', 'Wait for the current agent turn or workspace operation to finish.') |
| 102 | return store.dispatch(name, input, origin) |
| 103 | case 'check_task_comments': |
| 104 | if (!connector.status().enabled || !connector.status().running) |
| 105 | throw new AppError('MCP_DISABLED', 'Connect MCP in Settings to use agents.') |
| 106 | if (runner.suspended || runner.stopping) |
| 107 | throw new AppError('BUSY', 'Try again after the current workspace operation.') |
| 108 | return store.queueCommentFollowups() |
| 109 | case 'add_user_comment': { |
| 110 | if (!connector.status().enabled || !connector.status().running) input = { ...input, notifyAgent: false } |
| 111 | const result = await store.dispatch(name, input, origin) |
| 112 | if (input.notifyAgent) |
| 113 | void store.queueCommentFollowups().catch((error) => console.error('OpenTalon comment dispatch:', error.message)) |
| 114 | return result |
| 115 | } |
| 116 | case 'withdraw_revision_request': { |
| 117 | const result = await store.dispatch(name, input, origin) |
| 118 | // Only the turn that carried this request is ended. A replayed request finds nothing left to stop. |
| 119 | if (result.run?.stop) await runner.stopWithdrawnTurn(result.run.id) |
| 120 | else if (result.run?.notify) await runner.notifyWithdrawal(result.run.id, result.run.notify) |
| 121 | return result |
| 122 | } |
| 123 | case 'agent_runtime_status': return runner.status() |
| 124 | case 'stop_agent_run': return runner.stop(input.runId) |
| 125 | case 'open_agent_thread': return runner.openThread(input.runId) |
| 126 | case 'answer_agent_approval': return runner.answer(input.runId, input.approvalId, input.allow) |
| 127 | case 'get_app_status': |
| 128 | return { ...(await store.dispatch(name, input)), processId: process.ppid, windowOpen } |
| 129 | case 'confirm_destructive_action': |
| 130 | runner.suspended = true |
| 131 | try { |
| 132 | if (runner.current || runner.ticking) |
| 133 | throw new AppError('AGENT_RUNNING', 'Stop the current agent run before continuing.') |
| 134 | const result = await store.dispatch(name, input, origin) |
| 135 | if (result.safetyBackup && daily?.status().enabled) |
| 136 | void daily.run({ force: true }).catch(() => {}) |
| 137 | if (migrationFolder) discardMigration() |
| 138 | return result |
| 139 | } finally { |
| 140 | runner.suspended = false |
| 141 | } |
| 142 | case 'connection_status': return connector.status() |
| 143 | case 'set_connection': |
| 144 | if (!input.enabled) chatController?.abort() |
| 145 | return connector.enable(input.enabled) |
| 146 | case 'reset_connection_key': return connector.reset() |
| 147 | case 'agent_setup_fields': return setupFields(local('stdio')) |
| 148 | case 'copy_terminal_setup': return { value: terminalCommand(local('stdio'), input.client) } |
| 149 | case 'client_configuration': return { value: JSON.stringify(local(input.transport), null, 2) } |
| 150 | default: return store.dispatch(name, input, origin) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | function discardMigration() { |
| 155 | if (migrationFolder) fs.rmSync(migrationFolder, { recursive: true, force: true }) |
| 156 | migrationFolder = undefined |
| 157 | } |
| 158 | |
| 159 | async function testConnection() { |
| 160 | const setup = local('stdio').mcpServers.opentalon |
| 161 | try { |
| 162 | const request = runFile(setup.command, setup.args, { |
| 163 | env: { ...process.env, ...setup.env }, |
| 164 | timeout: 5000, |
| 165 | maxBuffer: 256 * 1024, |
| 166 | }) |
| 167 | request.child.stdin.on('error', () => {}) |
| 168 | const messages = [ |
| 169 | { |
| 170 | id: 1, |
| 171 | method: 'initialize', |
| 172 | params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'OpenTalon connection test', version } }, |
| 173 | }, |
| 174 | { method: 'notifications/initialized' }, |
| 175 | { id: 2, method: 'tools/call', params: { name: 'get_app_status', arguments: {} } }, |
| 176 | ] |
| 177 | request.child.stdin.end(messages.map((message) => JSON.stringify({ jsonrpc: '2.0', ...message })).join('\n') + '\n') |
| 178 | const { stdout } = await request |
| 179 | const replies = stdout.trim().split('\n').map((line) => JSON.parse(line)) |
| 180 | const initialized = replies.find((reply) => reply.id === 1)?.result |
| 181 | const status = replies.find((reply) => reply.id === 2)?.result |
| 182 | if (initialized?.serverInfo?.name !== 'OpenTalon' || status?.isError || |
| 183 | status?.structuredContent?.available !== true || status.structuredContent.dataLocation !== folder) |
| 184 | throw new Error('Unexpected response from the connector.') |
| 185 | return {} |
| 186 | } catch { |
| 187 | throw new AppError('CONNECTION_TEST_FAILED', 'OpenTalon did not respond through its MCP connector. Reopen OpenTalon and try again.') |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | function agentOptions(boardId) { |
| 192 | if (boardId !== undefined) store.board(boardId) |
| 193 | const connection = connector.status() |
| 194 | const settings = store.agentSettings(boardId) |
| 195 | const runtimes = runner.status() |
| 196 | const availableAgents = Object.entries(runtimes).filter(([, runtime]) => runtime.installed).map(([agent]) => agent) |
| 197 | const defaultAgent = availableAgents.length === 1 ? availableAgents[0] : settings.defaultAgent |
| 198 | return { |
| 199 | agentConnectionReady: connection.enabled && connection.running, |
| 200 | defaultAgent, |
| 201 | workingFolder: settings.workingFolder, |
| 202 | availableAgents, |
| 203 | agentModels: store.agentModelCatalog().models.filter(({ agent }) => availableAgents.includes(agent)), |
| 204 | needsSetup: !settings.workingFolder || !availableAgents.length || !connector.status().running, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | async function privateAction(name, input) { |
| 209 | switch (name) { |
| 210 | case 'snapshot': |
| 211 | validateAction(name, input, true) |
| 212 | return { ...store.snapshot({ includeRecordedCompletions: true }), agentConnectionReady: connector.status().enabled && connector.status().running } |
| 213 | case 'native_agent_options': return agentOptions(input.boardId) |
| 214 | case 'native_phone_snapshot': { |
| 215 | const workspace = store.snapshot({ includeRecordedCompletions: true }) |
| 216 | const commentsByTask = Object.create(null) |
| 217 | const filesByTask = Object.create(null) |
| 218 | const visibleTasks = new Set(workspace.tasks.filter(task => !task.deleted).map(task => task.id)) |
| 219 | for (const attachment of taskFiles.list(store)) { |
| 220 | if (visibleTasks.has(attachment.taskId)) (filesByTask[attachment.taskId] ??= []).push(attachment) |
| 221 | } |
| 222 | for (const task of workspace.tasks.filter(task => !task.deleted)) { |
| 223 | const comments = store.comments(task.id).filter(comment => comment.source === 'user') |
| 224 | if (comments.length) commentsByTask[task.id] = comments.map(({id,text,createdAt,delivery,pickedUpAt,source,actedOnAt,activityID,activityState})=>({id,text,createdAt,delivery,pickedUpAt,source,actedOnAt,activityID,activityState})) |
| 225 | } |
| 226 | return { |
| 227 | workspace, commentsByTask, filesByTask, activityByTask: Object.fromEntries(workspace.tasks.filter(task=>!task.deleted).map(task=>[task.id, taskActivity.page(store, task.id, undefined, 5)])), historyByTask: Object.fromEntries(workspace.tasks.filter(task => !task.deleted).map(task => [task.id, taskHistory.page(store, task.id, undefined, 1)])), ...agentOptions(), |
| 228 | } |
| 229 | } |
| 230 | case 'native_test_connection': return testConnection() |
| 231 | case 'native_stop_chat': |
| 232 | chatController?.abort() |
| 233 | return {} |
| 234 | case 'native_window_state': |
| 235 | windowOpen = input.visible === true |
| 236 | return {} |
| 237 | case 'native_daily_status': return daily.status() |
| 238 | case 'native_daily_configure': |
| 239 | try { |
| 240 | const result = await daily.configure(input) |
| 241 | void daily.run().catch(() => {}) |
| 242 | return result |
| 243 | } catch (error) { |
| 244 | throw new AppError('BACKUP_FOLDER', 'Could not save the daily backup settings. Choose an existing writable folder.') |
| 245 | } |
| 246 | case 'native_daily_run': |
| 247 | try { |
| 248 | return await daily.run({ force: true }) |
| 249 | } catch (error) { |
| 250 | throw new AppError('BACKUP_FAILED', error.message) |
| 251 | } |
| 252 | case 'native_save_extension': |
| 253 | local('stdio') |
| 254 | return saveClaudeExtension(input.path, connector.file, version) |
| 255 | case 'native_prepare_project': { |
| 256 | const setup = prepareProjectSetup(input.path, local('stdio')) |
| 257 | const id = randomUUID() |
| 258 | projects.clear() |
| 259 | projects.set(id, setup) |
| 260 | return { id, replacing: setup.replacing } |
| 261 | } |
| 262 | case 'native_write_project': { |
| 263 | const setup = projects.get(input.id) |
| 264 | if (!setup) throw new AppError('INVALID_CONFIG', 'Choose the working folder again.') |
| 265 | projects.delete(input.id) |
| 266 | return writeProjectSetup(setup) |
| 267 | } |
| 268 | case 'native_cancel_restore': |
| 269 | discardMigration() |
| 270 | return {} |
| 271 | case 'native_preview_electron': { |
| 272 | // SQLite's online backup API includes committed WAL data without changing the source. |
| 273 | discardMigration() |
| 274 | const sourcePath = path.join(path.dirname(folder), 'OpenTalon Prototype', 'opentalon.sqlite') |
| 275 | if (path.resolve(sourcePath) === path.resolve(store.file)) |
| 276 | throw new AppError('INVALID_BACKUP', 'Choose a different workspace to copy.') |
| 277 | if (!fs.existsSync(sourcePath)) |
| 278 | throw new AppError('NO_ELECTRON_WORKSPACE', 'No existing Electron workspace was found.') |
| 279 | migrationFolder = fs.mkdtempSync(path.join(folder, '.native-import-')) |
| 280 | const destination = path.join(migrationFolder, 'previous.sqlite') |
| 281 | try { |
| 282 | const source = new DatabaseSync(sourcePath, { readOnly: true }) |
| 283 | try { |
| 284 | await backup(source, destination) |
| 285 | } finally { |
| 286 | source.close() |
| 287 | } |
| 288 | return await dispatch('preview_destructive_action', { action: 'restore_backup', path: destination }) |
| 289 | } catch (error) { |
| 290 | discardMigration() |
| 291 | throw error |
| 292 | } |
| 293 | } |
| 294 | default: return dispatch(name, input, input.requestKey?.startsWith('phone:') ? 'You · mobile' : 'You · Mac') |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | async function main() { |
| 299 | if (!path.isAbsolute(folder) || !path.isAbsolute(executable)) throw new Error('Invalid app profile.') |
| 300 | store = new Store(folder, { |
| 301 | version, changed, |
| 302 | agentReadiness: (settings, requestedAgent) => { |
| 303 | const runtimes = runner.status() |
| 304 | const available = Object.keys(runtimes).filter((agent) => runtimes[agent].installed) |
| 305 | const agent = requestedAgent || (available.length === 1 ? available[0] : settings.defaultAgent) |
| 306 | assertAgentReady({ ...settings, defaultAgent: agent }, runtimes, connector.status()) |
| 307 | return agent |
| 308 | }, |
| 309 | }) |
| 310 | connector = new Connector({ |
| 311 | folder, executable, stdioCommand: process.execPath, version, changed, call: dispatch, |
| 312 | }) |
| 313 | runner = new AgentRunner({ |
| 314 | store, connector, openExternal: (url) => runFile('/usr/bin/open', [url]), |
| 315 | }) |
| 316 | try { |
| 317 | await connector.start() |
| 318 | } catch (error) { |
| 319 | console.error('OpenTalon MCP startup:', error.message) |
| 320 | } |
| 321 | await runner.start() |
| 322 | const archiveTimer = store.scheduleAutoArchive() |
| 323 | daily = new DailyBackup(store, { changed: () => send({ event: 'backup-changed' }) }) |
| 324 | const dailyTimer = setInterval(() => void daily.run().catch(() => {}), 5 * 60 * 1000) |
| 325 | send({ event: 'ready' }) |
| 326 | void daily.run().catch(() => {}) |
| 327 | const lines = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }) |
| 328 | let queue = Promise.resolve() |
| 329 | let drafting |
| 330 | let chatting |
| 331 | for await (const line of lines) { |
| 332 | const handle = async () => { |
| 333 | let id |
| 334 | try { |
| 335 | if (Buffer.byteLength(line) > maxRequest) |
| 336 | throw new AppError('INVALID_ARGUMENT', 'This request is too large.') |
| 337 | const request = JSON.parse(line) |
| 338 | id = request.id |
| 339 | if (request.name === 'native_agent_chat') { |
| 340 | if (chatting) throw new AppError('BUSY', 'Wait for the current reply to finish.') |
| 341 | chatting = chat(request.input || {}) |
| 342 | .then((data) => send({ id, data })) |
| 343 | .catch((error) => send({ id, error: errorView(error) })) |
| 344 | .finally(() => { chatting = undefined }) |
| 345 | return |
| 346 | } |
| 347 | if (request.name === 'native_draft_task') { |
| 348 | if (!connector.status().enabled || !connector.status().running) |
| 349 | throw new AppError('MCP_DISABLED', 'Connect MCP in Settings to draft with an agent.') |
| 350 | const idea = request.input?.idea |
| 351 | if (typeof idea !== 'string' || !idea.trim() || idea.length > 2000) |
| 352 | throw new AppError('INVALID_ARGUMENT', 'Enter an idea up to 2,000 characters.') |
| 353 | if (drafting) throw new AppError('BUSY', 'A task is already being drafted.') |
| 354 | // Drafting produces text only. Leave the workspace available while the agent responds. |
| 355 | drafting = (async () => { |
| 356 | try { |
| 357 | if (request.input.boardId !== undefined) store.board(request.input.boardId) |
| 358 | const settings = store.agentSettings(request.input.boardId) |
| 359 | const data = await draftTask(settings.defaultAgent, idea, { |
| 360 | workingFolder: settings.workingFolder, |
| 361 | permissionMode: settings.permissionMode, |
| 362 | model: defaultModel(settings.defaultAgent), |
| 363 | autoProject: request.input.autoProject === true, |
| 364 | projects: request.input.autoProject === true ? store.boards() : [], |
| 365 | priorities: request.input.autoPriority === true ? ['Urgent', 'High', 'Medium', 'Low', 'None'] : [], |
| 366 | }) |
| 367 | send({ id, data }) |
| 368 | } catch (error) { |
| 369 | send({ id, error: errorView(error) }) |
| 370 | } finally { |
| 371 | drafting = undefined |
| 372 | } |
| 373 | })() |
| 374 | return |
| 375 | } |
| 376 | const data = await privateAction(request.name, request.input || {}) |
| 377 | send({ id, data }) |
| 378 | } catch (error) { |
| 379 | send({ id, error: errorView(error) }) |
| 380 | } |
| 381 | } |
| 382 | // Every native request is ordered; MCP requests use the store's own queue. |
| 383 | queue = queue.then(handle) |
| 384 | } |
| 385 | clearInterval(dailyTimer) |
| 386 | clearInterval(archiveTimer) |
| 387 | await queue |
| 388 | chatController?.abort() |
| 389 | await chatting |
| 390 | await drafting |
| 391 | await daily.running?.catch(() => {}) |
| 392 | await runner.close() |
| 393 | await connector.stop() |
| 394 | await store.queue |
| 395 | discardMigration() |
| 396 | store.close() |
| 397 | } |
| 398 | |
| 399 | main().catch((error) => { |
| 400 | send({ event: 'failed', error: errorView(error) }) |
| 401 | process.exitCode = 1 |
| 402 | }) |