Connects Claude Code sessions in Para Code terminals to Para Code and Para Code Mobile (conversation, live text, questions, approvals, sending, slash commands).

Para Code は、AI コーディングエージェント(Claude Code・Codex など)と一緒に開発することを前提に作られたエディタです。Visual Studio Code を fork し、複数リポジトリの並行作業・常駐ターミナル・エージェントセッション管理・内蔵ブラウザ連携・SSH リモート開発・モバイルからの遠隔操作といった機能を継ぎ足してあります。
このリポジトリは microsoft/vscode を fork した独自エディタです。エディタ本体の土台は本家 VS Code のままで、今後も定期的に upstream の新しいリリースを取り込み続けます。そのうえに、複数のエージェントを並行して走らせながら開発する働き方に合わせた機能を追加しています。
<img alt="Para Code" src=".github/readme/screenshot.png">
各バージョンで実際に何が変わったかは、アプリ内の歯車メニュー →「更新履歴」から確認できます。
Para Code は本家 VS Code のソースをベースにしているため、ビルド・デバッグの基本的な流れは How to Contribute や Coding Guidelines がそのまま参考になります。そのうえで、この fork 特有の実装ルール(新機能の置き場所・既存ファイルへのパッチ方針・upstream 取り込み手順など)は CLAUDE.md と NOTES.md にまとめてあるので、変更を加える前に一読してください。
Para Code は microsoft/vscode を upstream として fetch し続けている fork です。エディタのコア機能(言語サポート、デバッグ、拡張機能 API など)は本家の開発にそのまま追従し、Para Code 独自の機能はなるべく新規ファイル・薄いフックポイントだけで完結させる方針で実装しています。本家の関連プロジェクト一覧は Related Projects を参照してください。
extensions フォルダには、多言語対応の文法・スニペットなどを提供する組み込み拡張機能が含まれます(本家由来)。加えて Para Code では、Open VSX に未公開のいくつかのサードパーティ拡張機能を VSIX として同梱し、起動時に自動インストールする仕組みを備えています。拡張機能の取得元は Open VSX Registry です。
このリポジトリには Visual Studio Code Dev Containers / GitHub Codespaces 用の開発コンテナ設定が含まれています。
フルビルドには最低でも 4 コア・6 GB の RAM(推奨 8 GB) が必要です。詳細は development container README を参照してください。
このプロジェクトに参加するすべての人は、互いに敬意を持って接してください。攻撃的な言動やハラスメントは認められません。問題があれば Issue で報告してください。
Copyright (c) 2015 - present Microsoft Corporation. Para Code による追加・変更部分も含め、MIT ライセンスの下で公開されています。
hooks/register.ts 914 lines1/*---------------------------------------------------------------------------------------------
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt in the project root for license information.
4 *--------------------------------------------------------------------------------------------*/
5// allow-any-unicode-comment-file
6// PARA-CODE: fork-owned file (Para Code) — not present in upstream microsoft/vscode. See CLAUDE.md.
7
8// The Para Code mod for Claude Code (Claude Mods, function hooks).
9//
10// Para Code loads this folder into the Claude Code sessions it starts in its own terminals
11// (CLAUDE_CODE_PLUGIN_DIRS, see src/vs/paradis/contrib/claudeMod). It talks to the Para Code
12// shared process over the same loopback port and pane token the settings hooks use
13// (PARA_CODE_MCP_PORT_FILE / PARA_CODE_TERMINAL_PANE_ID), under /claude-mod/v1/<op>.
14//
15// It never changes what Claude Code does on its own: every hook passes through, and the only
16// answers it gives are the ones the person gave on Para Code Mobile (a question's answers, an
17// approval). The settings hooks, the transcript and the key injection keep working beside it,
18// so a session where this mod is not loaded (or Para Code cannot be reached) behaves as before.
19//
20// Rules for this file:
21// - Never wait on a promise of our own inside a hook: only `next` and `$` calls, whose time the
22// 10 second budget does not count. Background work runs from the session.start engine.
23// - Every request that fails is dropped quietly: Para Code may be restarting or gone.
24
25import type { EngineInterface, Register } from 'claude-code';
26
27type Engine = EngineInterface;
28type Json = Record<string, unknown>;
29
30const MOD_PROTOCOL = '1';
31const MOD_VERSION = '1.4.3';
32/**
33 * What this mod can do beyond the first version, sent with every wait for commands (Para Code may have
34 * restarted since hello): `commands.list` answers `commandList` with `$.command.list()`, `command.run` runs a
35 * slash command for Para Code Mobile with `$.command.run`, `prompt.dialog` answers `dialogCheck` (whether a
36 * screen such as `/config` holds the keys), `draft.fill` answers `draftFill` (replaces the prompt box's text: Para Code clears
37 * a draft before it types a setting and puts it back after; it learns the box's text from draft.ts).
38 */
39const MOD_FEATURES = ['commands.list', 'command.run', 'prompt.dialog', 'draft.fill'];
40/** Para Code never asks to put back more than this (draft.ts marks longer text as cut). */
41const MAX_DRAFT_FILL_CHARS = 20_000;
42/** How long a slash command may take before Para Code is told it was taken (a panel holds `$.command.run` open). */
43const COMMAND_RUN_EARLY_MS = 1_500;
44/**
45 * Commands sent back for `commandList` at most (Claude Code lists hundreds with many skills). The built-ins come
46 * last in the typeahead's order, so they keep their places first and the rest fill what is left, in order.
47 */
48const MAX_LISTED_COMMANDS = 2_000;
49/** How long the port read from the port file is trusted before it is read again. */
50const ENDPOINT_TTL_MS = 30_000;
51/** Text chunks of a response are sent at most this often. */
52const STEP_FLUSH_MS = 150;
53/** Events waiting to be sent; beyond this new ones are dropped (Para Code is not answering). */
54const MAX_QUEUED_EVENTS = 512;
55/** Rows larger than this are left to the transcript reader. */
56const MAX_ROW_CHARS = 256 * 1024;
57/** One wait asks again at most this many times (each wait is held by Para Code for about 25 s). */
58const MAX_WAIT_ROUNDS = 1_000;
59/** Tool calls remembered from tool.check to pair with the PermissionRequest that follows. */
60const MAX_REMEMBERED_ASKS = 64;
61
62interface IEndpoint {
63 readonly url: string;
64 readonly token: string;
65 readonly at: number;
66}
67
68interface IReply {
69 readonly status: number;
70 readonly json: Json | undefined;
71}
72
73let endpoint: IEndpoint | undefined;
74/** `$.http.fetch` was refused (an administrator's policy) while curl reached Para Code. */
75let useCurl = false;
76/** This module is connected to an interactive session in a Para Code terminal. */
77let active = false;
78let mainBusy = false;
79let pumpGeneration = 0;
80/** Events waiting to be sent, each with the session it happened in (taken when it happened, see emit). */
81let queue: { readonly event: Json; readonly session: Promise<string | undefined> }[] = [];
82let flushing = false;
83/** Approvals waiting for Para Code Mobile: Para Code's id -> the call they belong to. */
84const pendingPermissions = new Map<string, { readonly toolUseId: string | undefined; readonly toolName: string }>();
85/** tool.check answered `ask`: `tool\0input` -> tool_use_ids, oldest first. */
86const askedCalls = new Map<string, string[]>();
87/**
88 * What tool.check told about an asked call (Claude Code 2.1.304 and later), by tool_use_id: `personOnly` when the
89 * verdict carries `decider: 'person'` (only the terminal's dialog can approve it; a PermissionRequest hook may only
90 * refuse), `readOnly` when `e.isReadOnly` is set. Older versions send neither, and nothing is kept.
91 */
92const askedTraits = new Map<string, { readonly personOnly: boolean; readonly readOnly: boolean }>();
93/**
94 * A prompt from Para Code Mobile is being submitted. Only one at a time: another one handed over meanwhile is
95 * refused at once (ack ok: false, reason: 'busy') and Para Code sends it with keys once the first one is
96 * taken, so this mod never sends it. Every other refusal carries a reason (`stale`: the session moved on,
97 * `panel-open`: a screen such as /config holds the keys, `refused`), and Para Code then answers the phone instead
98 * of typing the text.
99 */
100let submitting = false;
101/** Counts the sends, so one that finishes after a new session started does not clear the flag of a later send. */
102let submitGeneration = 0;
103/** A prompt submitted for Para Code, waiting for its row to learn the row's uuid. */
104let submitWatch: { readonly id: string; readonly text: string; uuid?: string } | undefined;
105
106function str(value: unknown): string | undefined {
107 return typeof value === 'string' && value.length > 0 ? value : undefined;
108}
109
110function rec(value: unknown): Json | undefined {
111 return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Json : undefined;
112}
113
114function stableJson(value: unknown): string {
115 if (Array.isArray(value)) {
116 return `[${value.map(stableJson).join(',')}]`;
117 }
118 const record = rec(value);
119 if (record !== undefined) {
120 return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(',')}}`;
121 }
122 return JSON.stringify(value) ?? 'null';
123}
124
125function curlQuote(value: string): string {
126 return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\r/g, '\\r').replace(/\n/g, '\\n')}"`;
127}
128
129async function resolveEndpoint($: Engine, refresh = false): Promise<IEndpoint | undefined> {
130 const now = Date.now();
131 if (!refresh && endpoint !== undefined && now - endpoint.at < ENDPOINT_TTL_MS) {
132 return endpoint;
133 }
134 const token = await $.env.get('PARA_CODE_TERMINAL_PANE_ID');
135 const portFile = await $.env.get('PARA_CODE_MCP_PORT_FILE');
136 if (token === undefined || token.length === 0 || portFile === undefined || portFile.length === 0) {
137 endpoint = undefined;
138 return undefined;
139 }
140 let port: unknown;
141 try {
142 port = rec(JSON.parse(String(await $.fs.read(portFile))))?.port;
143 } catch {
144 endpoint = undefined;
145 return undefined;
146 }
147 if (typeof port !== 'number' || !Number.isInteger(port) || port <= 0 || port > 65_535) {
148 endpoint = undefined;
149 return undefined;
150 }
151 endpoint = { url: `http://127.0.0.1:${port}/claude-mod/v1`, token, at: now };
152 return endpoint;
153}
154
155function parseReply(status: number, text: string): IReply {
156 let json: Json | undefined;
157 try {
158 json = rec(JSON.parse(text));
159 } catch {
160 json = undefined;
161 }
162 return { status, json };
163}
164
165async function viaFetch($: Engine, target: IEndpoint, op: string, body: string): Promise<IReply> {
166 const response = await $.http.fetch(`${target.url}/${op}`, {
167 method: 'POST',
168 headers: {
169 'authorization': `Bearer ${target.token}`,
170 'content-type': 'application/json',
171 'x-para-code-mod': MOD_PROTOCOL,
172 },
173 body,
174 });
175 return parseReply(response.status, response.text);
176}
177
178/** The same request through curl: the token and the body go on stdin, never on the command line. */
179async function viaCurl($: Engine, target: IEndpoint, op: string, body: string): Promise<IReply> {
180 const config = [
181 `url = ${curlQuote(`${target.url}/${op}`)}`,
182 'request = "POST"',
183 `header = ${curlQuote(`Authorization: Bearer ${target.token}`)}`,
184 'header = "Content-Type: application/json"',
185 `header = ${curlQuote(`X-Para-Code-Mod: ${MOD_PROTOCOL}`)}`,
186 `data-binary = ${curlQuote(body)}`,
187 'silent',
188 'max-time = 60',
189 'write-out = "\\n%{http_code}"',
190 '',
191 ].join('\n');
192 const result = await $.process.run(['curl', '--config', '-'], { stdin: config, timeoutMs: 70_000 });
193 const newline = result.stdout.lastIndexOf('\n');
194 const status = Number.parseInt(result.stdout.slice(newline + 1), 10);
195 if (result.exitCode !== 0 || !Number.isInteger(status) || status === 0) {
196 throw new Error('curl did not reach Para Code');
197 }
198 return parseReply(status, result.stdout.slice(0, Math.max(0, newline)));
199}
200
201async function request($: Engine, op: string, payload: Json): Promise<IReply | undefined> {
202 const target = await resolveEndpoint($);
203 if (target === undefined) {
204 return undefined;
205 }
206 const body = JSON.stringify(payload);
207 if (useCurl) {
208 try {
209 return await viaCurl($, target, op, body);
210 } catch {
211 endpoint = undefined;
212 return undefined;
213 }
214 }
215 try {
216 return await viaFetch($, target, op, body);
217 } catch {
218 endpoint = undefined;
219 }
220 // The fetch failed. Para Code may have restarted on another port: read the port file again and
221 // fetch once more. Only when that fetch fails too while curl gets through was the fetch refused
222 // (an administrator's policy, not Para Code being away): keep using curl from here on.
223 const retry = await resolveEndpoint($, true);
224 if (retry === undefined) {
225 return undefined;
226 }
227 try {
228 return await viaFetch($, retry, op, body);
229 } catch {
230 // fall through to curl
231 }
232 try {
233 const reply = await viaCurl($, retry, op, body);
234 useCurl = true;
235 return reply;
236 } catch {
237 endpoint = undefined;
238 return undefined;
239 }
240}
241
242/**
243 * Queues an event for Para Code; sent in order and in batches. The session is taken when the event
244 * happens (a /clear starts a new one while older events may still be waiting to be sent).
245 */
246function emit($: Engine, event: Json, sessionId?: string): void {
247 if (!active || queue.length >= MAX_QUEUED_EVENTS) {
248 return;
249 }
250 const session = sessionId !== undefined ? Promise.resolve(sessionId) : $.session.id().then(value => value, () => undefined);
251 queue.push({ event: { ...event, at: Date.now() }, session });
252 if (!flushing) {
253 flushing = true;
254 void flush($);
255 }
256}
257
258async function flush($: Engine): Promise<void> {
259 try {
260 while (queue.length > 0) {
261 const waiting = queue;
262 queue = [];
263 // One request per run of events from the same session, in the order they happened
264 let batch: Json[] = [];
265 let batchSession: string | undefined;
266 for (const item of waiting) {
267 const sessionId = await item.session;
268 if (sessionId === undefined) {
269 continue;
270 }
271 if (batchSession !== undefined && sessionId !== batchSession && batch.length > 0) {
272 await request($, 'event', { sessionId: batchSession, events: batch });
273 batch = [];
274 }
275 batchSession = sessionId;
276 batch.push(item.event);
277 }
278 if (batchSession !== undefined && batch.length > 0) {
279 await request($, 'event', { sessionId: batchSession, events: batch });
280 }
281 }
282 } catch {
283 // Dropped: Para Code reads the transcript and the settings hooks as before.
284 } finally {
285 flushing = false;
286 if (queue.length > 0) {
287 flushing = true;
288 void flush($);
289 }
290 }
291}
292
293/** Asks Para Code until the item `id` is answered, settled or expired; undefined when Para Code is away. */
294async function waitFor($: Engine, sessionId: string, id: string, stop: () => boolean): Promise<Json | undefined> {
295 for (let round = 0; round < MAX_WAIT_ROUNDS && !stop(); round++) {
296 const reply = await request($, 'wait', { sessionId, id });
297 if (reply === undefined || reply.status !== 200 || reply.json === undefined) {
298 return undefined;
299 }
300 if (reply.json.state !== 'pending') {
301 return reply.json;
302 }
303 }
304 return undefined;
305}
306
307function settle($: Engine, sessionId: string, ids: readonly string[]): void {
308 if (ids.length > 0) {
309 void request($, 'settle', { sessionId, ids }).catch(() => undefined);
310 }
311}
312
313/** The approvals this tool call answers (the call only starts once its approval was given). */
314function settleForCall($: Engine, sessionId: string, toolUseId: string | undefined, toolName: string): void {
315 const ids: string[] = [];
316 for (const [id, call] of pendingPermissions) {
317 if ((call.toolUseId !== undefined && call.toolUseId === toolUseId) || (call.toolUseId === undefined && call.toolName === toolName)) {
318 ids.push(id);
319 pendingPermissions.delete(id);
320 }
321 }
322 settle($, sessionId, ids);
323}
324
325function rememberAsk(tool: string, input: unknown, toolUseId: string): void {
326 const key = `${tool}\0${stableJson(input)}`;
327 const ids = askedCalls.get(key) ?? [];
328 ids.push(toolUseId);
329 askedCalls.delete(key);
330 askedCalls.set(key, ids.slice(-8));
331 while (askedCalls.size > MAX_REMEMBERED_ASKS) {
332 const oldest = askedCalls.keys().next();
333 if (oldest.done === true) {
334 break;
335 }
336 askedCalls.delete(oldest.value);
337 }
338}
339
340function rememberTraits(toolUseId: string, personOnly: boolean, readOnly: boolean): void {
341 if (!personOnly && !readOnly) {
342 return;
343 }
344 askedTraits.set(toolUseId, { personOnly, readOnly });
345 while (askedTraits.size > MAX_REMEMBERED_ASKS) {
346 const oldest = askedTraits.keys().next();
347 if (oldest.done === true) {
348 break;
349 }
350 askedTraits.delete(oldest.value);
351 }
352}
353
354/** The tool_use_id of the call a PermissionRequest is about (it does not carry one itself). */
355function takeAskedCall(tool: string, input: unknown): string | undefined {
356 const key = `${tool}\0${stableJson(input)}`;
357 const exact = askedCalls.get(key);
358 if (exact !== undefined && exact.length > 0) {
359 const id = exact.shift();
360 if (exact.length === 0) {
361 askedCalls.delete(key);
362 }
363 return id;
364 }
365 // The input may be spelled differently between the two events: accept a single open call of the tool.
366 const sameTool = [...askedCalls.entries()].filter(([candidate, ids]) => candidate.startsWith(`${tool}\0`) && ids.length > 0);
367 const only = sameTool.length === 1 ? sameTool[0] : undefined;
368 if (only !== undefined && only[1].length === 1) {
369 askedCalls.delete(only[0]);
370 return only[1][0];
371 }
372 return undefined;
373}
374
375function contentBlocks(message: unknown): Json[] {
376 const content = rec(message)?.content;
377 return Array.isArray(content) ? content.map(rec).filter((block): block is Json => block !== undefined) : [];
378}
379
380function textOf(blocks: readonly Json[]): string {
381 return blocks.filter(block => block.type === 'text').map(block => str(block.text) ?? '').join('\n');
382}
383
384function observeRow($: Engine, e: { readonly message: unknown; readonly door: string; readonly origin: unknown; readonly uuid: string; readonly agentId?: string }): void {
385 const blocks = contentBlocks(e.message);
386 const results = blocks.filter(block => block.type === 'tool_result');
387 if (results.length > 0) {
388 const ids = results.map(block => str(block.tool_use_id)).filter((id): id is string => id !== undefined);
389 const errorIds = results.filter(block => block.is_error === true).map(block => str(block.tool_use_id)).filter((id): id is string => id !== undefined);
390 emit($, { type: 'tool-results', ids, errorIds, ...(e.agentId !== undefined ? { agentId: e.agentId } : {}) });
391 }
392 const originKind = str(rec(e.origin)?.kind);
393 if (e.agentId === undefined && e.door === 'prompt' && originKind === 'plugin' && submitWatch !== undefined && submitWatch.uuid === undefined
394 && textOf(blocks).trim() === submitWatch.text.trim()) {
395 submitWatch.uuid = e.uuid;
396 }
397 // Only the main conversation's prompts and responses: the transcript reader keeps the rest
398 // (tool results carry structured records, attachments and media are read from the file).
399 if (e.agentId !== undefined || (e.door !== 'prompt' && e.door !== 'response')) {
400 return;
401 }
402 if (blocks.some(block => block.type === 'image' || block.type === 'document')) {
403 return;
404 }
405 const message = rec(e.message) ?? {};
406 const content = typeof message.content === 'string'
407 ? message.content
408 : blocks.map(block => block.type === 'thinking' || block.type === 'redacted_thinking' ? { type: block.type, thinking: block.thinking } : block);
409 const row: Json = {
410 type: 'row', uuid: e.uuid, door: e.door,
411 ...(originKind !== undefined ? { origin: originKind } : {}),
412 message: {
413 type: message.type,
414 ...(message.role !== undefined ? { role: message.role } : {}),
415 ...(message.isMeta === true ? { isMeta: true } : {}),
416 ...(message.name !== undefined ? { name: message.name } : {}),
417 content,
418 },
419 };
420 if (JSON.stringify(row).length <= MAX_ROW_CHARS) {
421 emit($, row);
422 }
423}
424
425/**
426 * Stops a background task (a shell started with run_in_background) for Para Code Mobile. TaskStop asks no
427 * permission and the call leaves nothing in the transcript, so the ack is how Para Code learns the outcome.
428 */
429async function stopTask($: Engine, sessionId: string, id: string, taskId: string): Promise<void> {
430 let ok = false;
431 let message: string | undefined;
432 try {
433 const reply = await $.tool.call({ tool: 'TaskStop', task_id: taskId }) as unknown as Json;
434 const deny = str(reply.deny);
435 ok = deny === undefined && reply.isError !== true && rec(reply.result) !== undefined;
436 message = deny ?? str(rec(reply.result)?.message) ?? str(reply.text);
437 } catch (error) {
438 message = error instanceof Error ? error.message : undefined;
439 }
440 await request($, 'ack', { sessionId, id, ok, ...(message !== undefined ? { message: message.slice(0, 500) } : {}) });
441}
442
443/** The slash commands the person can run now, for Para Code's list on Para Code Mobile (in the typeahead's order). */
444async function listCommands($: Engine, sessionId: string, id: string): Promise<void> {
445 try {
446 const listed = await $.command.list();
447 const builtIns = listed.filter(command => command.source === 'builtin').length;
448 let others = Math.max(0, MAX_LISTED_COMMANDS - builtIns);
449 const kept = listed.length <= MAX_LISTED_COMMANDS ? listed : listed.filter(command => command.source === 'builtin' || others-- > 0);
450 const commands = kept.slice(0, MAX_LISTED_COMMANDS).map(command => ({
451 name: command.name,
452 description: typeof command.description === 'string' ? command.description.slice(0, 300) : '',
453 source: command.source,
454 ...(typeof command.plugin === 'string' ? { plugin: command.plugin.slice(0, 100) } : {}),
455 }));
456 await request($, 'ack', { sessionId, id, ok: true, commands });
457 } catch (error) {
458 await request($, 'ack', { sessionId, id, ok: false, ...(error instanceof Error ? { message: error.message.slice(0, 500) } : {}) });
459 }
460}
461
462/**
463 * Whether a screen holds the keys (`/config`, `/rewind`, `/model`'s picker, and also an approval or a question):
464 * an empty append to the prompt box is refused with `dialog` then, and leaves the draft as it is otherwise.
465 * Telling an approval or a question apart is Para Code's: it asks only while it sees none waiting.
466 */
467async function panelOpen($: Engine): Promise<boolean> {
468 try {
469 const filled = await $.prompt.fill({ text: '', mode: 'append' });
470 return !filled.isFilled && filled.refusal === 'dialog';
471 } catch {
472 return false;
473 }
474}
475
476async function checkDialog($: Engine, sessionId: string, id: string): Promise<void> {
477 await request($, 'ack', { sessionId, id, ok: true, dialog: await panelOpen($) });
478}
479
480function errorText(error: unknown): string | undefined {
481 return error instanceof Error ? error.message.slice(0, 500) : typeof error === 'string' ? error.slice(0, 500) : undefined;
482}
483
484/**
485 * Runs a slash command sent from Para Code Mobile (`$.prompt.submit` refuses a text that begins with `/`).
486 * An unknown name is refused at once, and that refusal goes back to the phone. A command that opens a panel
487 * holds `$.command.run` open until the panel closes: past {@link COMMAND_RUN_EARLY_MS} Para Code is told it
488 * was taken, and the outcome follows in a second ack.
489 */
490async function runSlashCommand($: Engine, sessionId: string, id: string, name: string, args: string, generation: number): Promise<void> {
491 if (name.startsWith('__')) {
492 // Claude Code's own internal commands are not run for the phone.
493 await request($, 'ack', { sessionId, id, ok: false, reason: 'refused', message: `/${name} is internal to Claude Code` });
494 return;
495 }
496 if (submitting) {
497 await request($, 'ack', { sessionId, id, ok: false, reason: 'busy' });
498 return;
499 }
500 submitting = true;
501 const mine = ++submitGeneration;
502 try {
503 if (generation !== pumpGeneration || !active || await $.session.id() !== sessionId) {
504 await request($, 'ack', { sessionId, id, ok: false, reason: 'stale' });
505 return;
506 }
507 if (await panelOpen($)) {
508 // A screen holds the keys: the command would only queue behind it, and Para Code must not type either.
509 await request($, 'ack', { sessionId, id, ok: false, reason: 'panel-open' });
510 return;
511 }
512 const running = $.command.run({ command: name, args }).then(
513 () => ({ ok: true }),
514 (error: unknown) => ({ ok: false, reason: 'refused', ...(errorText(error) !== undefined ? { message: errorText(error) } : {}) }),
515 );
516 const early = await Promise.race([
517 running,
518 new Promise<undefined>(resolve => $.clock.after(COMMAND_RUN_EARLY_MS, () => resolve(undefined))),
519 ]);
520 if (early !== undefined) {
521 await request($, 'ack', { sessionId, id, ...early });
522 return;
523 }
524 // Still running (a screen it opened, or a long command such as /compact): tell Para Code it was taken, then how it ended.
525 await request($, 'ack', { sessionId, id, received: true });
526 await request($, 'ack', { sessionId, id, ...await running });
527 } finally {
528 if (submitGeneration === mine) {
529 submitting = false;
530 }
531 }
532}
533
534/**
535 * The commands Para Code hands over: prompts and slash commands sent from Para Code Mobile while the session
536 * is idle, background tasks to stop, and the list of slash commands.
537 */
538async function runCommand($: Engine, sessionId: string, command: Json, generation: number): Promise<void> {
539 const id = str(command.id);
540 if (id !== undefined && command.kind === 'taskStop') {
541 const taskId = str(command.taskId);
542 if (taskId !== undefined && /^[A-Za-z0-9_-]{1,64}$/.test(taskId)) {
543 await stopTask($, sessionId, id, taskId);
544 }
545 return;
546 }
547 if (id !== undefined && command.kind === 'dialogCheck') {
548 await checkDialog($, sessionId, id);
549 return;
550 }
551 if (id !== undefined && command.kind === 'commandList') {
552 await listCommands($, sessionId, id);
553 return;
554 }
555 if (id !== undefined && command.kind === 'draftFill') {
556 if (typeof command.text === 'string' && command.text.length <= MAX_DRAFT_FILL_CHARS) {
557 // `append` puts a draft back without removing what the person typed in the meantime
558 await fillDraft($, sessionId, id, command.text, command.mode === 'append' ? 'append' : 'replace', generation);
559 }
560 return;
561 }
562 if (id !== undefined && command.kind === 'commandRun') {
563 const name = str(command.command);
564 const args = typeof command.args === 'string' ? command.args : '';
565 if (name !== undefined) {
566 await runSlashCommand($, sessionId, id, name, args, generation);
567 }
568 return;
569 }
570 const text = str(command.text);
571 if (id === undefined || command.kind !== 'submit' || text === undefined) {
572 return;
573 }
574 if (submitting) {
575 // `reason: 'busy'`: Para Code waits for the first prompt to be taken before it types this one with keys.
576 await request($, 'ack', { sessionId, id, ok: false, reason: 'busy' });
577 return;
578 }
579 // Taken before any await, so a second prompt of the same batch sees it.
580 submitting = true;
581 const mine = ++submitGeneration;
582 try {
583 // The session moved on (a new session.start, /clear) since this prompt was handed over: it was for the old one.
584 if (generation !== pumpGeneration || !active || await $.session.id() !== sessionId) {
585 await request($, 'ack', { sessionId, id, ok: false, reason: 'stale' });
586 return;
587 }
588 if (await panelOpen($)) {
589 // A screen such as /config holds the keys: the prompt would wait behind it.
590 await request($, 'ack', { sessionId, id, ok: false, reason: 'panel-open' });
591 return;
592 }
593 submitWatch = { id, text };
594 // Tell Para Code first that the prompt is ours now: if a turn started meanwhile, $.prompt.submit
595 // only resolves once that turn ends, and Para Code must not send the same text again with keys.
596 await request($, 'ack', { sessionId, id, received: true });
597 let ok = false;
598 let message: string | undefined;
599 try {
600 await $.prompt.submit({ text, asUser: true });
601 ok = true;
602 } catch (error) {
603 ok = false;
604 message = errorText(error);
605 }
606 const uuid = submitWatch?.id === id ? submitWatch.uuid : undefined;
607 submitWatch = undefined;
608 await request($, 'ack', { sessionId, id, ok, ...(ok ? {} : { reason: 'refused' }), ...(message !== undefined ? { message } : {}), ...(uuid !== undefined ? { uuid } : {}) });
609 } finally {
610 if (submitGeneration === mine) {
611 submitting = false;
612 }
613 }
614}
615
616/**
617 * Replaces (or appends to) the prompt box's text for Para Code. Para Code only asks while it knows the box's text (draft.ts
618 * tells it on Claude Code 2.1.300 and later), so this never guesses what is in the box.
619 */
620async function fillDraft($: Engine, sessionId: string, id: string, text: string, mode: 'replace' | 'append', generation: number): Promise<void> {
621 try {
622 // The session moved on (a new session.start, /clear) since this was handed over: the text was for the old
623 // session's box, and writing it would replace the new session's draft.
624 if (generation !== pumpGeneration || !active || await $.session.id() !== sessionId) {
625 await request($, 'ack', { sessionId, id, ok: false, reason: 'stale' });
626 return;
627 }
628 const filled = await $.prompt.fill({ text, mode });
629 await request($, 'ack', { sessionId, id, ok: filled.isFilled, ...(filled.isFilled ? {} : { reason: filled.refusal === 'dialog' ? 'panel-open' : 'refused' }) });
630 } catch (error) {
631 await request($, 'ack', { sessionId, id, ok: false, reason: 'refused', ...(errorText(error) !== undefined ? { message: errorText(error) } : {}) });
632 }
633}
634
635function schedulePump($: Engine, generation: number, delayMs: number): void {
636 $.clock.after(delayMs, () => {
637 void pumpOnce($, generation);
638 });
639}
640
641/** Holds one request open with Para Code for commands, then asks again. */
642async function pumpOnce($: Engine, generation: number): Promise<void> {
643 if (generation !== pumpGeneration || !active) {
644 return;
645 }
646 let delayMs = 1;
647 try {
648 const sessionId = await $.session.id();
649 const reply = await request($, 'commands', { sessionId, busy: mainBusy, features: MOD_FEATURES });
650 if (reply === undefined || reply.status !== 200) {
651 delayMs = 5_000;
652 } else {
653 const commands = Array.isArray(reply.json?.commands) ? reply.json.commands : [];
654 for (const command of commands.slice(0, 8)) {
655 const record = rec(command);
656 if (record === undefined) {
657 continue;
658 }
659 // Never hold the loop on a command: a prompt's `$.prompt.submit` only resolves once a running turn
660 // ends, and a stop must still reach the task meanwhile. A prompt that comes while another is being
661 // submitted is refused (runCommand), never queued.
662 void runCommand($, sessionId, record, generation).catch(() => undefined);
663 }
664 }
665 } catch {
666 delayMs = 5_000;
667 }
668 if (generation === pumpGeneration && active) {
669 schedulePump($, generation, delayMs);
670 }
671}
672
673export const register: Register = on => {
674 on('session.start', async ($, e, next) => {
675 const started = await next(e);
676 active = false;
677 pumpGeneration++;
678 // A new session (or a reload of this module) starts with nothing being sent and no panel of ours open.
679 submitting = false;
680 submitGeneration++;
681 if (e.isInteractive && await resolveEndpoint($, true) !== undefined) {
682 active = true;
683 mainBusy = false;
684 emit($, { type: 'hello', version: MOD_VERSION });
685 schedulePump($, pumpGeneration, 1);
686 }
687 return started;
688 });
689
690 on('session.end', ($, e, next) => {
691 if (active) {
692 emit($, { type: 'bye', reason: e.reason });
693 }
694 return next(e);
695 });
696
697 on('session.append', ($, e, next) => {
698 if (active) {
699 try {
700 observeRow($, e);
701 } catch {
702 // Observing never stands in the way of the row.
703 }
704 }
705 return next(e);
706 });
707
708 on('turn.start', ($, e, next) => {
709 // Since Claude Code 2.1.299 a subagent's or a teammate's turn starts here too, with its agentId. Only the main
710 // loop's turn makes the session busy (turn.complete and turn.step skip them the same way).
711 if (active && e.agentId === undefined) {
712 mainBusy = true;
713 emit($, { type: 'turn.start', turnId: e.turnId });
714 }
715 return next(e);
716 });
717
718 on('turn.complete', ($, e, next) => {
719 if (active) {
720 if (e.agentId === undefined) {
721 mainBusy = false;
722 }
723 emit($, { type: 'turn.complete', turnId: e.turnId, reason: e.reason, aborted: e.isAborted, ...(e.agentId !== undefined ? { agentId: e.agentId } : {}) });
724 }
725 return next(e);
726 });
727
728 // The context window as the status line shows it (Para Code Mobile's session ring). Older Claude Code has no
729 // session.measure; registering it must not cost the other hooks.
730 try {
731 on('session.measure', ($, e, next) => {
732 if (active && e.changed.includes('context')) {
733 const { tokens, window, percent } = e.context;
734 emit($, { type: 'measure', context: { window, ...(tokens !== undefined ? { tokens } : {}), ...(percent !== undefined ? { percent } : {}) } });
735 }
736 return next(e);
737 });
738 } catch {
739 // This Claude Code does not measure sessions: Para Code reads the transcript's usage instead.
740 }
741
742 on('turn.step', async function* ($, e, next) {
743 const stream = next(e);
744 if (!active || e.agentId !== undefined) {
745 return yield* stream;
746 }
747 let chunks: { index: number; text: string }[] = [];
748 let sentAt = Date.now();
749 const send = (end: boolean) => {
750 if (chunks.length > 0 || end) {
751 emit($, { type: 'step', turnId: e.turnId, step: e.index, chunks, end });
752 chunks = [];
753 sentAt = Date.now();
754 }
755 };
756 for await (const chunk of stream) {
757 if (chunk.kind === 'text' && chunk.text.length > 0) {
758 const last = chunks[chunks.length - 1];
759 if (last !== undefined && last.index === chunk.index) {
760 last.text += chunk.text;
761 } else {
762 chunks.push({ index: chunk.index, text: chunk.text });
763 }
764 if (Date.now() - sentAt >= STEP_FLUSH_MS) {
765 send(false);
766 }
767 }
768 yield chunk;
769 }
770 send(true);
771 return await stream.result;
772 });
773
774 on('tool.check', async ($, e, next) => {
775 const verdict = await next(e);
776 if (active && verdict.decision === 'ask' && e.tool_use_id !== undefined) {
777 rememberAsk(e.tool, e.input, e.tool_use_id);
778 rememberTraits(e.tool_use_id, (verdict as { decider?: unknown }).decider === 'person', (e as { isReadOnly?: unknown }).isReadOnly === true);
779 emit($, { type: 'tool.check', toolUseId: e.tool_use_id, tool: e.tool });
780 }
781 return verdict;
782 });
783
784 on('classic.SubagentStart', ($, e, next) => {
785 if (active) {
786 emit($, { type: 'subagent.resume', agentId: e.agent_id, ...(str(e.agent_type) !== undefined ? { agentType: e.agent_type } : {}) }, e.session_id);
787 }
788 return next(e);
789 });
790
791 on('tool.call', async ($, e, next) => {
792 if (!active) {
793 return next(e);
794 }
795 const toolName = String(e.tool);
796 if (pendingPermissions.size > 0) {
797 settleForCall($, await $.session.id(), e.tool_use_id, toolName);
798 }
799 if (e.tool === 'AskUserQuestion') {
800 const sessionId = await $.session.id();
801 const asked = rec(e.answers);
802 if (asked !== undefined && Object.keys(asked).length > 0) {
803 return next(e);
804 }
805 const registered = await request($, 'question', {
806 sessionId, questions: e.questions,
807 ...(e.tool_use_id !== undefined ? { toolUseId: e.tool_use_id } : {}),
808 ...(e.agentId !== undefined ? { agentId: e.agentId } : {}),
809 });
810 const id = str(registered?.json?.id);
811 if (registered?.status !== 200 || id === undefined || registered.json?.wait !== true) {
812 return next(e);
813 }
814 // Race the terminal's own dialog with Para Code Mobile: the first answer is the answer.
815 let finished = false;
816 const fromTerminal = next(e).then(result => ({ kind: 'terminal' as const, result }));
817 const fromMobile = waitFor($, sessionId, id, () => finished).then(reply => ({ kind: 'mobile' as const, reply }));
818 const first = await Promise.race([fromTerminal, fromMobile]);
819 finished = true;
820 if (first.kind === 'mobile') {
821 const answers = rec(first.reply?.answers);
822 if (first.reply?.state === 'answer' && answers !== undefined) {
823 const annotations = rec(first.reply?.annotations);
824 return { result: { questions: e.questions, answers, ...(annotations !== undefined ? { annotations } : {}) } };
825 }
826 // "Chat about this" from the phone: every question is withdrawn. With a message the model
827 // reads "The user responded: …"; without one it gets the same refusal the terminal's own
828 // "Chat about this" writes (Para Code builds the text, with the partial answers and notes).
829 if (first.reply?.state === 'clarify') {
830 const response = str(first.reply.response);
831 if (response !== undefined && response.trim().length > 0) {
832 return { result: { questions: e.questions, answers: {}, response } };
833 }
834 const deny = str(first.reply.deny);
835 if (deny !== undefined && deny.length > 0) {
836 return { deny };
837 }
838 }
839 // Nothing came from the phone (it went away, or Para Code did): the dialog decides.
840 return (await fromTerminal).result;
841 }
842 settle($, sessionId, [id]);
843 return first.result;
844 }
845 if (toolName === 'Agent' || toolName === 'Task') {
846 const started = await next(e);
847 const result = rec(started.result);
848 const agentId = str(result?.agentId) ?? str(result?.agent_id);
849 if (agentId !== undefined) {
850 const input = e as unknown as Json;
851 emit($, {
852 type: 'subagent.start', agentId,
853 ...(e.tool_use_id !== undefined ? { toolUseId: e.tool_use_id } : {}),
854 ...(str(input.subagent_type) !== undefined ? { subagentType: input.subagent_type } : {}),
855 ...(str(input.description) !== undefined ? { description: input.description } : {}),
856 ...(str(input.name) !== undefined ? { name: input.name } : {}),
857 });
858 }
859 return started;
860 }
861 return next(e);
862 });
863
864 on('classic.PermissionRequest', async ($, e, next) => {
865 // The settings hooks (Para Code's own notification among them) run first, as without this mod.
866 const decided = await next(e);
867 if (!active || decided.decision !== undefined || decided.block !== undefined || e.tool_name === 'AskUserQuestion') {
868 return decided;
869 }
870 const sessionId = e.session_id;
871 const toolUseId = takeAskedCall(e.tool_name, e.tool_input);
872 const suggestions = Array.isArray(e.permission_suggestions) ? e.permission_suggestions : [];
873 const traits = toolUseId !== undefined ? askedTraits.get(toolUseId) : undefined;
874 if (toolUseId !== undefined) {
875 askedTraits.delete(toolUseId);
876 }
877 // denyMessage: this mod hands the refusal text Para Code sends back to Claude Code (older mods use a fixed one).
878 // personOnly: an allow from here would not count, so Para Code Mobile shows only the refusal and points to the PC.
879 const registered = await request($, 'permission', {
880 sessionId, toolName: e.tool_name, toolInput: e.tool_input, suggestions, denyMessage: true,
881 ...(traits?.personOnly === true ? { personOnly: true } : {}),
882 ...(traits?.readOnly === true ? { readOnly: true } : {}),
883 ...(toolUseId !== undefined ? { toolUseId } : {}),
884 ...(e.agent_id !== undefined ? { agentId: e.agent_id } : {}),
885 });
886 const id = str(registered?.json?.id);
887 if (registered?.status !== 200 || id === undefined || registered.json?.wait !== true) {
888 return decided;
889 }
890 // The terminal's own permission prompt is up beside this wait. Whichever answers first wins:
891 // an answer in the terminal starts the call (tool.call settles this wait) or writes its
892 // refusal (Para Code settles it from the row).
893 pendingPermissions.set(id, { toolUseId, toolName: e.tool_name });
894 try {
895 const reply = await waitFor($, sessionId, id, () => !pendingPermissions.has(id));
896 if (reply?.state === 'answer' && reply.decision === 'allow') {
897 return {
898 ...decided,
899 decision: { behavior: 'allow', ...(reply.always === true && suggestions.length > 0 ? { updatedPermissions: suggestions } : {}) },
900 };
901 }
902 if (reply?.state === 'answer' && reply.decision === 'deny') {
903 // With an instruction from the phone, Para Code sends the same refusal the terminal's
904 // "No, and tell Claude what to do differently" writes, so the model reads it as the user's.
905 const message = str(reply.message);
906 return { ...decided, decision: { behavior: 'deny', message: message !== undefined && message.length > 0 ? message : 'Denied from Para Code Mobile.' } };
907 }
908 return decided;
909 } finally {
910 pendingPermissions.delete(id);
911 }
912 });
913};
914