Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): stop truncating long Ask-AI instructions on terminal launches (PRD-7372) (#2692)
serafin-garciaeb6111781b06
diff --git a/.changeset/terminal-transport-prompt-budget.md b/.changeset/terminal-transport-prompt-budget.mdnew file mode 100644index 000000000..5d96af5d7--- /dev/null+++ b/.changeset/terminal-transport-prompt-budget.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Long Ask-AI, Open-with-AI, and Create-with-agent instructions are no longer silently cut to ~1,400-2,200 characters when launched in the docked terminal. The terminal launch previously inherited the web deep-link's URL budget even though it feeds the agent CLI directly through the terminal; it now carries instructions up to ~100 KB, so a long typed prompt reaches Claude, Codex, Cursor, and the other agent CLIs in full. Web deep-link handoffs keep their intentional URL-size budget, and selections continue to travel losslessly on both paths.diff --git a/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.tsnew file mode 100644index 000000000..d50914ede--- /dev/null+++ b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts@@ -0,0 +1,221 @@+/**+ * Transport-budget tests for `composeTerminalLaunchPrompt` — the docked-terminal+ * launch path.+ *+ * A prompt budget is a property of the TRANSPORT the prompt travels over, and+ * the two handoff transports differ by orders of magnitude:+ *+ * - Web deep-link: the dispatched URL is capped at 4096 chars by the server's+ * `/api/handoff` schema (`handoff-dispatch-api.ts`), so the composers+ * shorten an oversized instruction to an encoded budget and append the+ * ` …` truncation marker.+ * - Docked terminal: the prompt is baked into a PTY argv+ * (`buildCliLaunchArgString` → `$SHELL -l -i -c '…'`), whose real limit is+ * the OS ARG_MAX (~1 MB on macOS — the desktop app's only platform).+ *+ * The terminal path must therefore NOT inherit the deep-link URL budget: a+ * long typed instruction survives a terminal launch in full, while the same+ * instruction on the web deep-link path keeps its intentional URL-budget+ * truncation. Selections are never truncated on either transport (locus mode+ * re-reads via MCP).+ *+ * Exercises the real renderer path end-to-end: `buildComposerHandoffInput` →+ * `composeTerminalLaunchPrompt` → `buildCliLaunchArgString` (the composed+ * string is byte-identical to what the PTY receives).+ */++import { describe, expect, test } from 'bun:test';+import {+ assembleHandoffPrompt,+ buildCliLaunchArgString,+ composeAskPrompt,+ composeSelectionPrompt,+ shellSingleQuote,+ TERMINAL_CLI_IDS,+ TERMINAL_INLINE_PROMPT_BUDGET,+} from '@inkeep/open-knowledge-core';+import type { HandoffDispatchInput } from './useHandoffDispatch';++/** The composer's truncation marker (`INSTRUCTION_TRUNCATION_MARKER` in+ * `prompt-composer.ts`) — its presence in a composed prompt is the observable+ * signal that user text was cut. */+const TRUNCATION_MARKER = ' …';++/** macOS ARG_MAX — the terminal transport's real ceiling. The desktop app+ * (the only surface with a docked terminal) is macOS-only. */+const MACOS_ARG_MAX = 1_048_576;++/**+ * Encoded-prompt budget of the web deep-link transport: the 4096-char URL cap+ * minus the 1024-char overhead reserve. Mirrors `INLINE_PROMPT_ENCODED_BUDGET`+ * in `packages/core/src/handoff/prompt-composer.ts` — the two must change+ * together.+ */+const URL_INLINE_PROMPT_ENCODED_BUDGET = 4096 - 1024;++const workspace = { contentDir: '/Users/u/notes', pathSeparator: '/' as const };++/** Realistic single-line prose (spaces + punctuation, no newlines, no `…`),+ * so a full-retention assertion can be a simple substring check against the+ * blockquoted instruction. */+function terminalProse(chars: number): string {+ const unit = 'Please restructure the migration plan, keep the rollback steps, and cite owners. ';+ return unit+ .repeat(Math.ceil(chars / unit.length))+ .slice(0, chars)+ .trimEnd();+}++describe('composeTerminalLaunchPrompt — terminal transport carries long instructions in full', () => {+ test('compose scope: a 40,000-char Ask-AI instruction survives a docked-terminal launch un-truncated for every CLI', async () => {+ const { buildComposerHandoffInput, composeTerminalLaunchPrompt } = await import(+ './useHandoffDispatch'+ );+ const instruction = terminalProse(40_000);+ const input = buildComposerHandoffInput({+ docName: 'plans/migration',+ workspace,+ instruction,+ mentions: [],+ });+ expect(input).not.toBeNull();+ if (input === null) return;+ for (const cli of TERMINAL_CLI_IDS) {+ const prompt = composeTerminalLaunchPrompt(input, cli);+ // The full typed instruction reaches the agent — no loss, no marker.+ expect(prompt).toContain(instruction);+ expect(prompt).not.toContain(TRUNCATION_MARKER);+ // And the resulting PTY argv still fits the transport's real ceiling.+ expect(buildCliLaunchArgString(cli, prompt).length).toBeLessThanOrEqual(MACOS_ARG_MAX);+ }+ });++ test('directive scope: a 40,000-char "Open with AI" instruction survives a terminal launch for claude and cursor', async () => {+ // Cursor is the worst-cased target (its deep-link double-encodes), so it+ // pins that the terminal path must not apply URL-encoding worst-casing at+ // all — the PTY receives raw bytes, not a URL.+ const { composeTerminalLaunchPrompt } = await import('./useHandoffDispatch');+ const instruction = terminalProse(40_000);+ const input: HandoffDispatchInput = {+ docContext: { relativePath: 'plans/migration.md' },+ projectDir: '/proj',+ docPath: '/proj/plans/migration.md',+ instruction,+ };+ for (const cli of ['claude', 'cursor'] as const) {+ const prompt = composeTerminalLaunchPrompt(input, cli);+ expect(prompt).toContain(instruction);+ expect(prompt).not.toContain(TRUNCATION_MARKER);+ }+ });++ test('create scope: a 32,768-char create brief survives a terminal launch un-truncated', async () => {+ const { composeTerminalLaunchPrompt } = await import('./useHandoffDispatch');+ const brief = terminalProse(32_768);+ const input: HandoffDispatchInput = {+ docContext: null,+ createDescription: brief,+ createScenario: 'new-project',+ projectDir: '/proj',+ docPath: '',+ };+ const prompt = composeTerminalLaunchPrompt(input, 'claude');+ expect(prompt).toContain(brief);+ expect(prompt).not.toContain(TRUNCATION_MARKER);+ });++ test('terminal transport stays bounded: a ~950KB instruction is trimmed to TERMINAL_INLINE_PROMPT_BUDGET, marked, and the argv stays under ARG_MAX', async () => {+ // The terminal budget is large but NOT unbounded — an argv over ARG_MAX+ // would make the PTY spawn fail outright. The composer fits the quoted+ // prompt bytes to TERMINAL_INLINE_PROMPT_BUDGET and marks the cut.+ const { buildComposerHandoffInput, composeTerminalLaunchPrompt } = await import(+ './useHandoffDispatch'+ );+ const instruction = terminalProse(950_000);+ const input = buildComposerHandoffInput({+ docName: 'plans/migration',+ workspace,+ instruction,+ mentions: [],+ });+ expect(input).not.toBeNull();+ if (input === null) return;+ const prompt = composeTerminalLaunchPrompt(input, 'claude');+ // The fitted portion (before the funnel-prepended preamble) respects the+ // budget; the launch argv as a whole stays within budget + overhead+ // reserve — far under ARG_MAX.+ expect(new TextEncoder().encode(shellSingleQuote(prompt)).length).toBeLessThanOrEqual(+ TERMINAL_INLINE_PROMPT_BUDGET + 1024,+ );+ expect(buildCliLaunchArgString('claude', prompt).length).toBeLessThanOrEqual(MACOS_ARG_MAX);+ expect(prompt).not.toContain(instruction);+ expect(prompt).toContain(TRUNCATION_MARKER);+ // The trim happened at the terminal budget, not the ~3 KB URL budget.+ expect(prompt.length).toBeGreaterThan(TERMINAL_INLINE_PROMPT_BUDGET - 2_000);+ });+});++describe('web deep-link transport keeps its intentional URL budget', () => {+ test('a 32,768-char instruction on the deep-link ask path is still truncated with the marker, within the encoded budget', () => {+ const instruction = terminalProse(32_768);+ const prompt = composeAskPrompt('plans/migration.md', instruction, true, 'claude-code');+ expect(prompt).toContain(TRUNCATION_MARKER);+ expect(prompt).not.toContain(instruction);+ // Claude single-encodes its `q=` param; the encoded prompt must fit the+ // URL cap minus overhead reserve.+ expect(encodeURIComponent(prompt).length).toBeLessThanOrEqual(URL_INLINE_PROMPT_ENCODED_BUDGET);+ });++ test('a 32,768-char instruction through the deep-link assembler (compose scope, web) is still truncated with the marker', () => {+ const instruction = terminalProse(32_768);+ const prompt = assembleHandoffPrompt({+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ instruction,+ mentions: [],+ autoOpen: true,+ target: 'claude-code',+ });+ expect(prompt).toContain(TRUNCATION_MARKER);+ expect(prompt).not.toContain(instruction);+ expect(encodeURIComponent(prompt).length).toBeLessThanOrEqual(URL_INLINE_PROMPT_ENCODED_BUDGET);+ });+});++describe('selections are never truncated on either transport', () => {+ test('terminal transport: an oversized anchored selection degrades to a locus anchor + MCP re-read directive — no content loss', async () => {+ const { buildComposerHandoffInput, composeTerminalLaunchPrompt } = await import(+ './useHandoffDispatch'+ );+ const selection = terminalProse(40_000);+ const input = buildComposerHandoffInput({+ docName: 'plans/migration',+ workspace,+ instruction: 'tighten this',+ mentions: [],+ selection: { kind: 'anchor', markdown: selection },+ });+ expect(input).not.toBeNull();+ if (input === null) return;+ const prompt = composeTerminalLaunchPrompt(input, 'claude');+ expect(prompt).toContain('The passage begins:');+ expect(prompt).toContain('Read the full passage from');+ // The passage is re-read from the doc, not inlined-and-cut: only the+ // bounded anchor (first 160 chars) rides in the prompt.+ expect(prompt).not.toContain(selection.slice(0, 500));+ expect(prompt).toContain('tighten this');+ });++ test('web transport: an oversized selection degrades to locus mode — no content loss', () => {+ const selection = terminalProse(40_000);+ const prompt = composeSelectionPrompt({+ relativePath: 'plans/migration.md',+ instruction: 'tighten this',+ selectionMarkdown: selection,+ target: 'claude-code',+ });+ expect(prompt).toContain('The passage begins:');+ expect(prompt).toContain('Read the full passage from');+ expect(prompt).not.toContain(selection.slice(0, 500));+ });+});diff --git a/packages/app/src/components/handoff/useHandoffDispatch.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.test.tsindex aae04257e..0d2c0cdd9 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.test.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.test.ts@@ -755,7 +755,7 @@ describe('buildSkillHandoffInput + selectScopedPrompt — skill scope (author-wiworkspace: { contentDir: '/repo', pathSeparator: '/' },});if (!input) throw new Error('expected a non-null skill input');- expect(selectScopedPrompt(input, 'claude-code', true)).toBe(+ expect(selectScopedPrompt(input, 'claude-code', true, 'url')).toBe('Use your open-knowledge-write-skill skill to author the project Open Knowledge skill `commit-helper`. Edit it with the Open Knowledge tools. Open the OK editor in web view.',);});@@ -966,6 +966,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeFilePrompt('notes/today.md', true)));expect(out).toBe(@@ -985,6 +986,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',false,+ 'url',);expect(out).toBe(withSkillPointer("Let's work on `notes/today.md` using OpenKnowledge."));});@@ -1001,6 +1003,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeFolderPrompt('notes', true)));expect(out).toBe(@@ -1021,6 +1024,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',false,+ 'url',);expect(out).toBe(withSkillPointer("Let's work on the `notes` folder using OpenKnowledge."));});@@ -1036,6 +1040,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeEmptySpacePrompt(true)));expect(out).toBe(@@ -1055,6 +1060,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',false,+ 'url',);expect(out).toBe(withSkillPointer("Let's work on this project using OpenKnowledge."));});@@ -1071,6 +1077,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeFilePrompt('notes/today.md', true, 'Tighten the intro')),@@ -1090,6 +1097,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toContain("Let's work on the `notes` folder using OpenKnowledge.");expect(out).toContain('> Review the structure');@@ -1106,6 +1114,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toContain("Let's work on this project using OpenKnowledge.");expect(out).toContain('> Scaffold the wiki');@@ -1127,6 +1136,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toContain('> selection instruction');expect(out).not.toContain('top-level directive instruction');@@ -1149,6 +1159,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toContain('> a worldbuilding wiki');expect(out).not.toContain('top-level directive instruction');@@ -1168,6 +1179,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',false,+ 'url',);expect(out).toContain('> Fix the intro');expect(out).not.toContain('Open the OK editor');@@ -1186,6 +1198,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeCreatePrompt('a worldbuilding wiki', true, 'new-project', [])),@@ -1208,6 +1221,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',false,+ 'url',);expect(out).toBe(withSkillPointer(@@ -1232,6 +1246,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).not.toContain('new OpenKnowledge project');expect(out).toContain('> draft a spec for this codebase');@@ -1244,6 +1259,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () ={ docContext: null, createDescription: 'a wiki', projectDir: '/proj', docPath: '' },'claude-code',false,+ 'url',);expect(out).toBe(withSkillPointer(composeCreatePrompt('a wiki', false, 'new-project', [])));});@@ -1266,6 +1282,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeCreatePrompt('', true, 'new-project', [])));expect(out).not.toBe(withSkillPointer(composeEmptySpacePrompt(true)));@@ -1289,6 +1306,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(withSkillPointer(composeFilePrompt('a.md', true)));});@@ -1310,6 +1328,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'cursor',true,+ 'url',);expect(out).toBe(composeSelectionPrompt({ ...selection, target: 'cursor' }));});@@ -1327,17 +1346,20 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () ={ ...base, docContext: { relativePath: 'a.md' }, docPath: '/proj/a.md' },'claude-code',true,+ 'url',);const folder = selectScopedPrompt({ ...base, docContext: null, folderRelativePath: 'specs' },'claude-code',true,+ 'url',);- const empty = selectScopedPrompt({ ...base, docContext: null }, 'claude-code', true);+ const empty = selectScopedPrompt({ ...base, docContext: null }, 'claude-code', true, 'url');const create = selectScopedPrompt({ ...base, docContext: null, createDescription: 'a wiki' },'claude-code',true,+ 'url',);const selection = selectScopedPrompt({@@ -1347,6 +1369,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);for (const prompt of [file, folder, empty, create]) {@@ -1375,6 +1398,7 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =},'claude-code',true,+ 'url',);expect(out).toBe(composeSelectionPrompt({ ...selection, target: 'claude-code' }));});@@ -1671,15 +1695,15 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +instruction: 'summarize the open questions',};expect(composeTerminalLaunchPrompt(input, 'claude')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false, 'terminal')}`,);expect(composeTerminalLaunchPrompt(input, 'codex')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false, 'terminal')}`,);// Cursor has a distinct handoffTarget ('cursor') + double-encoding; pin it// so a regression in the TERMINAL_CLIS['cursor'] mapping is caught here too.expect(composeTerminalLaunchPrompt(input, 'cursor')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false, 'terminal')}`,);const claudeOut = composeTerminalLaunchPrompt(input, 'claude');// Both present: the surface preamble leads, the user's ask follows (no "stop").@@ -1711,13 +1735,13 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +docPath: '/proj/notes/work-log.md',};expect(composeTerminalLaunchPrompt(input, 'claude')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false, 'terminal')}`,);expect(composeTerminalLaunchPrompt(input, 'codex')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'codex', false, 'terminal')}`,);expect(composeTerminalLaunchPrompt(input, 'cursor')).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'cursor', false, 'terminal')}`,);const claudeOut = composeTerminalLaunchPrompt(input, 'claude');// Both present: the surface preamble leads, the composer's typed ask follows.@@ -1760,7 +1784,7 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +};const out = composeTerminalLaunchPrompt(input, 'claude');expect(out).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false, 'terminal')}`,);expect(out).toContain('a fishing log');expect(out).toContain(OK_TERMINAL_SURFACE_PREAMBLE);@@ -1783,7 +1807,7 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +};const out = composeTerminalLaunchPrompt(input, 'claude');expect(out).toBe(- `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false)}`,+ `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false, 'terminal')}`,);expect(out).not.toBe(composeTerminalBareLaunchPrompt(null));expect(out).toContain(OK_TERMINAL_SURFACE_PREAMBLE);@@ -1802,7 +1826,7 @@ describe('composeTerminalLaunchPrompt — docked-terminal bare launch is load +docPath: '/proj/notes/today.md',};expect(composeTerminalLaunchPrompt(input, 'claude')).not.toContain('Open the OK editor');- expect(selectScopedPrompt(input, 'claude-code', true)).toContain(+ expect(selectScopedPrompt(input, 'claude-code', true, 'url')).toContain('Open the OK editor in web view.',);});@@ -1920,6 +1944,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',true,+ 'url',);expect(out).toBe(composeAskPrompt('notes/today.md', 'condense this doc', true, 'claude-code'));// The typed instruction reaches the composed prompt, blockquoted; the doc is@@ -1939,6 +1964,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',false,+ 'url',);expect(out).toContain('> condense this doc');expect(out).not.toContain('Open the OK editor');@@ -1960,6 +1986,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',true,+ 'url',);expect(out).toContain('condense this doc');expect(out).not.toBe(composeFilePrompt('notes/today.md', true));@@ -1982,6 +2009,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',true,+ 'url',);expect(out).toBe(composeAskPrompt('notes/today.md', 'condense this doc', true, 'claude-code'));});@@ -2004,6 +2032,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',true,+ 'url',);expect(out).toBe(composeSelectionPrompt({ ...selection, target: 'claude-code' }));});@@ -2020,6 +2049,7 @@ describe('selectScopedPrompt — ask scope', () => {},'claude-code',true,+ 'url',);expect(out).toBe(composeAskPrompt('notes/today.md', '', true, 'claude-code'));expect(out).not.toContain('>');@@ -2271,7 +2301,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '/repo/specs/foo/SPEC.md',};- const out = selectScopedPrompt(input, 'cursor', true);+ const out = selectScopedPrompt(input, 'cursor', true, 'url');// Byte-equality with the assembler proves the compose path is the holistic// assembler, NOT a per-composer fit.expect(out).toBe(@@ -2304,7 +2334,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '',};- const out = selectScopedPrompt(input, 'cursor', true);+ const out = selectScopedPrompt(input, 'cursor', true, 'url');expect(out).toBe(assembleHandoffPrompt({scope: 'folder',@@ -2329,7 +2359,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '',};- const out = selectScopedPrompt(input, 'codex', true);+ const out = selectScopedPrompt(input, 'codex', true, 'url');expect(out).toBe(assembleHandoffPrompt({scope: 'project',@@ -2358,7 +2388,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '/repo/notes/today.md',};- const out = selectScopedPrompt(input, 'claude-code', true);+ const out = selectScopedPrompt(input, 'claude-code', true, 'url');expect(out).toBe(assembleHandoffPrompt({scope: 'doc',@@ -2386,7 +2416,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '/repo/a.md',};- const out = selectScopedPrompt(input, 'claude-code', true);+ const out = selectScopedPrompt(input, 'claude-code', true, 'url');expect(out).toBe(assembleHandoffPrompt({scope: 'project',@@ -2406,7 +2436,7 @@ describe('selectScopedPrompt — compose scope (US-002)', () => {projectDir: '/repo',docPath: '',};- const out = selectScopedPrompt(input, 'codex', false);+ const out = selectScopedPrompt(input, 'codex', false, 'url');expect(out).not.toContain('Open the OK editor');});});diff --git a/packages/app/src/components/handoff/useHandoffDispatch.ts b/packages/app/src/components/handoff/useHandoffDispatch.tsindex 5820e3cb2..5568f2a0c 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.ts@@ -33,6 +33,7 @@ import {type HandoffScope,type HandoffTarget,OK_TERMINAL_SURFACE_PREAMBLE,+ type PromptTransport,type SkillScope,type TargetData,TERMINAL_CLIS,@@ -721,6 +722,7 @@ function composeContextToAssembleInput(compose: ComposeContext,target: HandoffTarget,autoOpen: boolean,+ transport: PromptTransport,): AssembleHandoffPromptInput {if (compose.scope === 'doc') {const base = {@@ -730,6 +732,7 @@ function composeContextToAssembleInput(mentions: compose.mentions,target,autoOpen,+ transport,};return compose.selection !== undefined ? { ...base, selection: compose.selection } : base;}@@ -741,6 +744,7 @@ function composeContextToAssembleInput(mentions: compose.mentions,target,autoOpen,+ transport,};}return {@@ -749,6 +753,7 @@ function composeContextToAssembleInput(mentions: compose.mentions,target,autoOpen,+ transport,};}@@ -756,13 +761,21 @@ function composeContextToAssembleInput(* Pick the scope-specific prompt that matches the input's scope. Exported for* direct unit assertions; `runHandoffDispatch` is the only production caller.*- * - `compose` set → compose scope → assembleHandoffPrompt(scope + instruction + mentions[] + selection?, target)- * - `selection` set → selection scope → composeSelectionPrompt(..., target)- * - `ask` set → ask scope → composeAskPrompt(relativePath, instruction, autoOpen, target)- * - `docContext` set → file scope → composeFilePrompt(relativePath, autoOpen, instruction)- * - `folderRelativePath` truthy → folder scope → composeFolderPrompt(..., autoOpen, instruction)- * - `createDescription` set → create scope → composeCreatePrompt(..., autoOpen)- * - none of the above → empty-space scope → composeEmptySpacePrompt(autoOpen, instruction)+ * - `compose` set → compose scope → assembleHandoffPrompt(scope + instruction + mentions[] + selection?, target, transport)+ * - `selection` set → selection scope → composeSelectionPrompt(..., target, transport)+ * - `skill` set → skill scope → composeSkillPrompt(name, scope, autoOpen)+ * - `ask` set → ask scope → composeAskPrompt(relativePath, instruction, autoOpen, target, transport)+ * - `docContext` set → file scope → composeFilePrompt(relativePath, autoOpen, instruction, transport)+ * - `folderRelativePath` truthy → folder scope → composeFolderPrompt(..., autoOpen, instruction, transport)+ * - `createDescription` set → create scope → composeCreatePrompt(..., autoOpen, ..., transport)+ * - none of the above → empty-space scope → composeEmptySpacePrompt(autoOpen, instruction, transport)+ *+ * `transport` is REQUIRED: a prompt budget is a property of the transport the+ * prompt travels over, and this funnel is the single point that knows which+ * one is in use. `'url'` fits to the per-target encoded deep-link budget;+ * `'terminal'` fits to the PTY argv quoted-byte budget (see `PromptTransport`+ * in core's `prompt-composer.ts`). `composeTerminalLaunchPrompt` passes+ * `'terminal'`; the web dispatch (`runHandoffDispatch`) passes `'url'`.** `input.instruction` (the toolbar "Open with AI" prompt box) is threaded into* the file / folder / project directive composers; it is `undefined` for every@@ -788,7 +801,7 @@ function composeContextToAssembleInput(* `folderRelativePath` only; `buildProjectScopedHandoffInput` none). The ordering* is defensive — a caller that hand-constructs the shape with several fields* lands on the most specific scope, matching the implicit- * "compose > selection > ask > file > folder > project" specificity ordering.+ * "compose > selection > skill > ask > file > folder > project" specificity ordering.** `autoOpen` mirrors the user's `appearance.preview.autoOpen` preference and* controls whether each directive composer emits the trailing "Open the OK@@ -800,24 +813,34 @@ export function selectScopedPrompt(input: HandoffDispatchInput,target: HandoffTarget,autoOpen: boolean,+ transport: PromptTransport,): string {if (input.compose) {- return assembleHandoffPrompt(composeContextToAssembleInput(input.compose, target, autoOpen));+ return assembleHandoffPrompt(+ composeContextToAssembleInput(input.compose, target, autoOpen, transport),+ );}// Selection is excluded from the skill pointer: it already ends with an// explicit "read the passage via the OK MCP server" directive and is the most// URL-budget-constrained prompt (see `composeSelectionPrompt`).if (input.selection) {- return composeSelectionPrompt({ ...input.selection, target });+ return composeSelectionPrompt({ ...input.selection, target, transport });}// Skill scope (author-with-AI) carries its own `open-knowledge-write-skill`// directive, so it is excluded from the standing project skill pointer just- // like selection scope.+ // like selection scope. It carries no free-text to fit, so it takes no+ // transport.if (input.skill) {return composeSkillPrompt(input.skill.name, input.skill.scope, autoOpen);}if (input.ask) {- return composeAskPrompt(input.ask.relativePath, input.ask.instruction, autoOpen, target);+ return composeAskPrompt(+ input.ask.relativePath,+ input.ask.instruction,+ autoOpen,+ target,+ transport,+ );}// Every directive launch scope gets the standing skill pointer, applied once// here so the composers stay pure and the wording lives in one place. The@@ -825,17 +848,18 @@ export function selectScopedPrompt(// composers; create scope carries its own free-text and ignores it.const directive =input.docContext !== null- ? composeFilePrompt(input.docContext.relativePath, autoOpen, input.instruction)+ ? composeFilePrompt(input.docContext.relativePath, autoOpen, input.instruction, transport): input.folderRelativePath- ? composeFolderPrompt(input.folderRelativePath, autoOpen, input.instruction)+ ? composeFolderPrompt(input.folderRelativePath, autoOpen, input.instruction, transport): input.createDescription !== undefined? composeCreatePrompt(input.createDescription,autoOpen,input.createScenario ?? 'new-project',input.createMentions ?? [],+ transport,)- : composeEmptySpacePrompt(autoOpen, input.instruction);+ : composeEmptySpacePrompt(autoOpen, input.instruction, transport);return withSkillPointer(directive);}@@ -857,9 +881,10 @@ export function selectScopedPrompt(* `input.instruction`), or the empty-state "Create with <CLI>" brief. These* carry explicit user intent, so they keep the directive composers via* `selectScopedPrompt`, composed against the CLI's handoff target- * (`TERMINAL_CLIS[cli].handoffTarget` — `claude→'claude-code'`,- * `codex→'codex'`, `cursor→'cursor'`) so the instruction / brief threads- * through identically to that target's deep-link. The preview trailer stays+ * (`TERMINAL_CLIS[cli].handoffTarget`) on the `'terminal'` transport, so+ * the instruction / brief keeps the deep-link prompt SHAPE but is fitted+ * to the PTY argv byte budget rather than the far smaller URL budget (a+ * long typed instruction survives the terminal launch in full). The preview trailer stays* suppressed (`autoOpen: false`): the terminal launches alongside an* already-open OK editor, so the "Open the OK editor in web view." directive* would point the agent at a surface the user is already looking at. The web@@ -882,7 +907,7 @@ export function composeTerminalLaunchPrompt(input: HandoffDispatchInput, cli: Te// surface preamble so the launch reads as the same OK handoff the bare// bootstrap establishes — context first, then the user's actual ask. The// bare branch's "Then stop." tail is replaced by that ask.- return `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, TERMINAL_CLIS[cli].handoffTarget, false)}`;+ return `${OK_TERMINAL_SURFACE_PREAMBLE} ${selectScopedPrompt(input, TERMINAL_CLIS[cli].handoffTarget, false, 'terminal')}`;}return composeTerminalBareLaunchPrompt(input.docContext?.relativePath ?? null);}@@ -955,7 +980,7 @@ export async function runHandoffDispatch(// user's `appearance.preview.autoOpen` value, read fresh by the hook at// click time and threaded into directive composers so the receiving// agent's first turn honors the preference.- prompt: selectScopedPrompt(input, target, deps.autoOpen),+ prompt: selectScopedPrompt(input, target, deps.autoOpen, 'url'),};const outcome = await deps.dispatchHandoff(payload);diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.tsindex 883482b7b..a585bbcbd 100644--- a/packages/core/src/handoff/index.ts+++ b/packages/core/src/handoff/index.ts@@ -25,6 +25,8 @@ export {composeTerminalBareLaunchPrompt,OK_PROJECT_SKILL_POINTER,OK_TERMINAL_SURFACE_PREAMBLE,+ type PromptTransport,+ TERMINAL_INLINE_PROMPT_BUDGET,withSkillPointer,} from './prompt-composer.ts';export {diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.tsindex 83af5b9e1..5e1ad52b0 100644--- a/packages/core/src/handoff/prompt-composer.test.ts+++ b/packages/core/src/handoff/prompt-composer.test.ts@@ -15,8 +15,10 @@ import {composeTerminalBareLaunchPrompt,OK_PROJECT_SKILL_POINTER,OK_TERMINAL_SURFACE_PREAMBLE,+ TERMINAL_INLINE_PROMPT_BUDGET,withSkillPointer,} from './prompt-composer.ts';+import { shellSingleQuote } from './terminal-launch.ts';import type { HandoffPayload, HandoffTarget } from './types.ts';// The three composers emit scope-specific directives the receiving agent reads@@ -1427,3 +1429,164 @@ test('assembleHandoffPrompt renders an anchor selection as the locus reference',// Only the opening line is embedded as the landmark, not the whole passage.expect(prompt).not.toContain('and more');});++// --- terminal transport ------------------------------------------------------+//+// A prompt budget is a property of the TRANSPORT: the deep-link URL cap must+// not bind prompts that travel as PTY argv bytes. These pin the terminal+// transport directly at the core composers — measurement is UTF-8 bytes of the+// shell-single-quoted prompt, budget is TERMINAL_INLINE_PROMPT_BUDGET — while+// every unparameterized call keeps the historical URL-budget behavior (pinned+// by the rest of this file).++/** The exact argv-byte measure the terminal fit applies. */+function quotedByteLength(prompt: string): number {+ return new TextEncoder().encode(shellSingleQuote(prompt)).length;+}++/** Realistic single-line prose (no newlines, no apostrophes, no `…`) so+ * full-retention assertions can be simple substring checks. */+function terminalProse(chars: number): string {+ const unit = 'Restructure the migration plan, keep the rollback steps, and cite owners. ';+ return unit+ .repeat(Math.ceil(chars / unit.length))+ .slice(0, chars)+ .trimEnd();+}++test('assembleHandoffPrompt on the terminal transport carries a 40,000-char instruction in full', () => {+ const instruction = terminalProse(40_000);+ const out = assembleHandoffPrompt({+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ instruction,+ mentions: [],+ autoOpen: false,+ target: 'claude-code',+ transport: 'terminal',+ });+ expect(out).toContain(instruction);+ expect(out).not.toContain(' …');+ expect(quotedByteLength(out)).toBeLessThanOrEqual(TERMINAL_INLINE_PROMPT_BUDGET);+});++test('composeFilePrompt on the terminal transport carries a 40,000-char instruction in full', () => {+ // The directive fit worst-cases Cursor double-encoding on the URL transport;+ // the terminal transport measures raw quoted bytes, so no encoding+ // conservatism applies and the instruction survives untouched.+ const instruction = terminalProse(40_000);+ const out = composeFilePrompt('plans/migration.md', false, instruction, 'terminal');+ expect(out).toContain(instruction);+ expect(out).not.toContain(' …');+});++test('composeFolderPrompt on the terminal transport carries a 40,000-char instruction in full', () => {+ const instruction = terminalProse(40_000);+ const out = composeFolderPrompt('specs/notes', false, instruction, 'terminal');+ expect(out).toContain(instruction);+ expect(out).not.toContain(' …');+});++test('composeEmptySpacePrompt on the terminal transport carries a 40,000-char instruction in full', () => {+ const instruction = terminalProse(40_000);+ const out = composeEmptySpacePrompt(false, instruction, 'terminal');+ expect(out).toContain(instruction);+ expect(out).not.toContain(' …');+});++test('composeAskPrompt on the terminal transport carries a 40,000-char instruction in full', () => {+ const instruction = terminalProse(40_000);+ const out = composeAskPrompt('plans/migration.md', instruction, false, 'claude-code', 'terminal');+ expect(out).toContain(instruction);+ expect(out).not.toContain(' …');+});++test('composeCreatePrompt on the terminal transport carries a 32,768-char brief in full', () => {+ const brief = terminalProse(32_768);+ const out = composeCreatePrompt(brief, false, 'new-project', [], 'terminal');+ expect(out).toContain(brief);+ expect(out).not.toContain(' …');+});++test('terminal transport trims a just-over-budget instruction at TERMINAL_INLINE_PROMPT_BUDGET with the marker', () => {+ const instruction = terminalProse(TERMINAL_INLINE_PROMPT_BUDGET + 5_000);+ const out = assembleHandoffPrompt({+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ instruction,+ mentions: [],+ autoOpen: false,+ target: 'claude-code',+ transport: 'terminal',+ });+ expect(out).not.toContain(instruction);+ expect(out).toContain(' …');+ expect(quotedByteLength(out)).toBeLessThanOrEqual(TERMINAL_INLINE_PROMPT_BUDGET);+ // The trim lands at the terminal budget, not the ~3 KB URL budget: nearly+ // the whole budget's worth of instruction is retained (the composed shell+ // overhead around the instruction is far under 2,000 bytes).+ expect(out.length).toBeGreaterThan(TERMINAL_INLINE_PROMPT_BUDGET - 2_000);+});++test('terminal transport measures shell-quoted BYTES — an apostrophe-dense instruction trims by its expanded byte length, not its char count', () => {+ // Each apostrophe in the prompt expands to the 4-byte `'\''` escape once+ // shell-single-quoted. 60,000 chars with 30,000 apostrophes quote to+ // ~150,000 bytes: within the budget by char count, over it by argv bytes.+ // Only the quoted-byte measure catches it.+ const instruction = "y'".repeat(30_000);+ expect(instruction.length).toBeLessThan(TERMINAL_INLINE_PROMPT_BUDGET);+ expect(quotedByteLength(instruction)).toBeGreaterThan(TERMINAL_INLINE_PROMPT_BUDGET);+ const out = assembleHandoffPrompt({+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ instruction,+ mentions: [],+ autoOpen: false,+ target: 'claude-code',+ transport: 'terminal',+ });+ expect(out).not.toContain(instruction);+ expect(out).toContain(' …');+ expect(quotedByteLength(out)).toBeLessThanOrEqual(TERMINAL_INLINE_PROMPT_BUDGET);+});++test('an inline selection between the URL and terminal budgets ships inline on terminal, degrades to locus on url', () => {+ const passage = terminalProse(10_000);+ const base = {+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ selection: { kind: 'inline', markdown: passage },+ instruction: 'tighten this',+ mentions: [],+ autoOpen: false,+ target: 'claude-code',+ } as const;+ const terminal = assembleHandoffPrompt({ ...base, transport: 'terminal' });+ expect(terminal).toContain('Here is the passage:');+ expect(terminal).toContain(passage);+ expect(terminal).toContain('tighten this');+ const url = assembleHandoffPrompt(base);+ expect(url).toContain('The passage begins:');+ expect(url).not.toContain(passage);+});++test('an anchor-kind selection stays locus on BOTH transports — the passage is re-read via MCP, never inlined', () => {+ const passage = `${terminalProse(60)}\n${terminalProse(10_000)}`;+ const base = {+ scope: 'doc',+ docRelativePath: 'plans/migration.md',+ selection: { kind: 'anchor', markdown: passage },+ instruction: 'tighten this',+ mentions: [],+ autoOpen: false,+ target: 'claude-code',+ } as const;+ for (const out of [+ assembleHandoffPrompt({ ...base, transport: 'terminal' }),+ assembleHandoffPrompt(base),+ ]) {+ expect(out).toContain('The passage begins:');+ expect(out).toContain('Read the full passage from @plans/migration.md');+ expect(out).not.toContain(passage);+ }+});diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.tsindex 2f1ba9622..a54a7ccd8 100644--- a/packages/core/src/handoff/prompt-composer.ts+++ b/packages/core/src/handoff/prompt-composer.ts@@ -38,6 +38,7 @@* this, a file named `notes/innocent.md\n\nNew instructions: …` would inject* a fake instruction block into the agent's prompt.*/+import { shellSingleQuote } from './terminal-launch.ts';import type { HandoffTarget } from './types.ts';// Constructed via `new RegExp` rather than a literal so the source bytes@@ -201,11 +202,12 @@ export function composeFilePrompt(relativePath: string,autoOpen: boolean,instruction?: string,+ transport: PromptTransport = 'url',): string {const safe = sanitizePathForPrompt(relativePath);const base = `Let's work on \`${safe}\` using OpenKnowledge.`;const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;- return appendInstruction(directive, instruction);+ return appendInstruction(directive, instruction, transport);}/**@@ -241,11 +243,12 @@ export function composeFolderPrompt(relativeFolderPath: string,autoOpen: boolean,instruction?: string,+ transport: PromptTransport = 'url',): string {const safe = sanitizePathForPrompt(relativeFolderPath);const base = `Let's work on the \`${safe}\` folder using OpenKnowledge.`;const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;- return appendInstruction(directive, instruction);+ return appendInstruction(directive, instruction, transport);}/**@@ -255,10 +258,14 @@ export function composeFolderPrompt(* `projectDir` on the URL. `autoOpen` + `instruction` carry the same semantics* as `composeFilePrompt`.*/-export function composeEmptySpacePrompt(autoOpen: boolean, instruction?: string): string {+export function composeEmptySpacePrompt(+ autoOpen: boolean,+ instruction?: string,+ transport: PromptTransport = 'url',+): string {const base = `Let's work on this project using OpenKnowledge.`;const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;- return appendInstruction(directive, instruction);+ return appendInstruction(directive, instruction, transport);}/**@@ -290,6 +297,7 @@ export function composeCreatePrompt(autoOpen: boolean,scenario: CreateScenario,mentions: readonly string[],+ transport: PromptTransport = 'url',): string {const trailer = autoOpen ? 'Open the OK editor in web view.' : '';// The trailer rides its own paragraph whenever the prompt has a body: the@@ -353,11 +361,13 @@ export function composeCreatePrompt(// budget — target-agnostic, mirroring `fitInstructionForDirective`. The funnel// prepends the skill pointer to this prompt, so the directive budget (which// holds back `POINTER_ENCODED_RESERVE`) is the right cap. Mentions + framing- // are never trimmed.+ // are never trimmed. On the terminal transport the quoted-byte budget applies+ // instead and the URL budget is ignored.const fittedBrief = fitInstruction(build,description.trim(),'cursor',+ transport,DIRECTIVE_INLINE_PROMPT_ENCODED_BUDGET,);return build(fittedBrief);@@ -401,6 +411,86 @@ const POINTER_ENCODED_RESERVE = encodedPromptLength(`${OK_PROJECT_SKILL_POINTER}const DIRECTIVE_INLINE_PROMPT_ENCODED_BUDGET =INLINE_PROMPT_ENCODED_BUDGET - POINTER_ENCODED_RESERVE;+/**+ * Which transport a composed prompt travels over. A prompt budget is a+ * property of the transport, so the transport selects both the measurement+ * and the budget the instruction fit applies:+ *+ * - `url` — the deep-link handoff. The prompt rides a `q=` / `prompt=` /+ * `text=` query param, so length is measured post-URL-encoding (per+ * target; Cursor double-encodes) against the 4096-char URL cap.+ * - `terminal` — the docked-terminal launch. The prompt is baked into a PTY+ * spawn argv (`<bin> [fixed-args…] '<prompt>'` inside `$SHELL -l -i -c`),+ * so length is measured as UTF-8 bytes of the shell-single-quoted prompt+ * against `TERMINAL_INLINE_PROMPT_BUDGET`. No URL encoding happens on an+ * argv, so the per-target encoding (and Cursor's double-encode+ * worst-casing) never applies.+ *+ * Every composer defaults to `'url'` — the historical behavior, keeping all+ * deep-link call sites byte-identical — and the app-layer dispatch funnel+ * states the transport explicitly per launch path.+ */+export type PromptTransport = 'url' | 'terminal';++/**+ * Ceiling on the shell-quoted prompt bytes the docked-terminal launch bakes+ * into its PTY spawn argv. The docked terminal ships only on macOS, whose+ * `ARG_MAX` is 1 MiB; 100 KB also stays under Linux's per-argument+ * `MAX_ARG_STRLEN` (128 KiB) should the surface ever widen (matching the+ * server's git argv threshold in `rename-log.ts`), so an oversized paste+ * degrades to a marked trim instead of a silent `E2BIG` spawn failure.+ * WARNING (hidden constraint): Windows+ * `CreateProcess` caps the whole command line at ~32,767 UTF-16 chars —+ * BELOW this ceiling — so a Windows terminal surface would need a+ * per-platform budget, not this constant.+ */+const MAX_TERMINAL_PROMPT_ARG_BYTES = 100 * 1024;++/**+ * Headroom held back, out of `MAX_TERMINAL_PROMPT_ARG_BYTES`, for every argv+ * byte that is not the quoted prompt itself: the terminal-surface preamble+ * and skill pointer the dispatch funnel prepends after the fit, the CLI+ * binary and its fixed args (including Claude's inline `--settings` JSON),+ * and the `; exec <shell> -l -i` tail of the launch command — measured under+ * ~600 bytes worst case today. Mirrors `URL_OVERHEAD_RESERVE`'s stance:+ * over-reserving only trims a borderline instruction slightly sooner, which+ * is safe degradation; under-reserving risks an oversized argv, which is not.+ */+const TERMINAL_OVERHEAD_RESERVE = 1024;++/**+ * Quoted-prompt byte budget for the terminal transport. Exported so the+ * transport-budget tests pin trims against the real constant.+ */+export const TERMINAL_INLINE_PROMPT_BUDGET =+ MAX_TERMINAL_PROMPT_ARG_BYTES - TERMINAL_OVERHEAD_RESERVE;++const UTF8_ENCODER = new TextEncoder();++/**+ * Transport-specific length of a composed prompt. URL transport measures the+ * per-target URL encoding (Cursor double-encodes); terminal transport+ * measures the UTF-8 bytes of the shell-single-quoted prompt — the exact+ * argv bytes the PTY launch bakes, apostrophes expanding to the `'\''`+ * escape — and ignores `target` (no URL encoding happens on an argv).+ */+function promptTransportLength(+ prompt: string,+ target: HandoffTarget,+ transport: PromptTransport,+): number {+ if (transport === 'terminal') {+ return UTF8_ENCODER.encode(shellSingleQuote(prompt)).length;+ }+ return encodedPromptLength(prompt, target);+}++/** Per-transport budget: the caller's encoded URL budget on `url`; the fixed+ * quoted-byte budget on `terminal` (URL budgets are meaningless there). */+function transportBudget(transport: PromptTransport, urlBudget: number): number {+ return transport === 'terminal' ? TERMINAL_INLINE_PROMPT_BUDGET : urlBudget;+}+/*** Longest locus anchor — the quoted opening of an oversized selection.* Distinctive enough to be a landmark the agent can find in the doc, short@@ -436,6 +526,9 @@ interface SelectionPromptInput {/** Dispatch target — selects the URL encoding. Cursor double-encodes its* prompt param; Claude and Codex single-encode. */readonly target: HandoffTarget;+ /** Transport the prompt travels over — selects measurement + budget (see+ * `PromptTransport`). Defaults to `'url'`. */+ readonly transport?: PromptTransport;}/** Length of the longest unbroken run of backtick characters in `s`. */@@ -525,11 +618,13 @@ function directiveWithInstruction(directive: string, instruction: string): strin}/**- * Longest prefix of `instruction` whose composed prompt stays within the encoded- * URL budget for `target`. Shared by the directive ("Open with AI") and selection- * locus ("Edit with AI") fits — both bound the same unbounded user instruction- * against the same 4096-char server `z.string().max(4096)` cap, differing only in- * how the surrounding prompt is composed (`compose`). Returns the instruction+ * Longest prefix of `instruction` whose composed prompt stays within the+ * budget of the transport in use — the encoded URL budget for `target` on the+ * deep-link transport, the quoted-byte budget on the terminal transport (see+ * `PromptTransport`). Shared by the directive ("Open with AI") and selection+ * locus ("Edit with AI") fits — both bound the same unbounded user+ * instruction, differing only in how the surrounding prompt is composed+ * (`compose`). Returns the instruction* unchanged when it already fits, else a marker-suffixed prefix down to the empty* string.*@@ -543,9 +638,12 @@ function fitInstruction(compose: (instruction: string) => string,instruction: string,target: HandoffTarget,- budget: number = INLINE_PROMPT_ENCODED_BUDGET,+ transport: PromptTransport = 'url',+ urlBudget: number = INLINE_PROMPT_ENCODED_BUDGET,): string {- const fits = (instr: string): boolean => encodedPromptLength(compose(instr), target) <= budget;+ const budget = transportBudget(transport, urlBudget);+ const fits = (instr: string): boolean =>+ promptTransportLength(compose(instr), target, transport) <= budget;if (fits(instruction)) return instruction;const codePoints = Array.from(instruction);let lo = 0;@@ -566,31 +664,45 @@ function fitInstruction(* single-encoded targets (Claude / Codex) too, so the directive composers never* need the dispatch target. Over-reserving (trimming a Claude / Codex* instruction slightly sooner than its own encoding strictly requires) is safe- * degradation; an over-length URL is not.+ * degradation; an over-length URL is not. On the `'terminal'` transport the+ * encoding worst-casing does not apply — the fit measures quoted argv bytes+ * against `TERMINAL_INLINE_PROMPT_BUDGET` instead.*/-function fitInstructionForDirective(directive: string, instruction: string): string {+function fitInstructionForDirective(+ directive: string,+ instruction: string,+ transport: PromptTransport,+): string {return fitInstruction((instr) => directiveWithInstruction(directive, instr),instruction,'cursor',+ transport,// Reserve room for the skill pointer the funnel prepends to directive// prompts (see `POINTER_ENCODED_RESERVE`) so instruction + directive +- // pointer together stay within the URL cap.+ // pointer together stay within the URL cap. On the terminal transport the+ // pointer (and preamble) headroom lives in `TERMINAL_OVERHEAD_RESERVE`+ // instead and this URL budget is ignored.DIRECTIVE_INLINE_PROMPT_ENCODED_BUDGET,);}/*** Append the user's instruction block beneath a directive prompt, shortening an- * oversized instruction so the dispatched URL stays within budget (see- * `fitInstructionForDirective`). An empty / whitespace / absent instruction+ * oversized instruction so the dispatched prompt stays within its transport's+ * budget (see `fitInstructionForDirective` — encoded URL budget on `'url'`,+ * PTY argv byte budget on `'terminal'`). An empty / whitespace / absent instruction* returns the bare directive unchanged, so the no-instruction dispatch path* stays byte-identical to the path-only prompts.*/-function appendInstruction(directive: string, instruction: string | undefined): string {+function appendInstruction(+ directive: string,+ instruction: string | undefined,+ transport: PromptTransport,+): string {return directiveWithInstruction(directive,- fitInstructionForDirective(directive, instruction ?? ''),+ fitInstructionForDirective(directive, instruction ?? '', transport),);}@@ -642,8 +754,9 @@ function fitInstructionToBudget(instruction: string,target: HandoffTarget,compose: (instruction: string) => string,+ transport: PromptTransport = 'url',): string {- return fitInstruction(compose, instruction, target);+ return fitInstruction(compose, instruction, target, transport);}/**@@ -651,7 +764,9 @@ function fitInstructionToBudget(* a prompt naming the doc (as an `@`-mention), the user's instruction (when* one was typed), and the selected passage.*- * The passage travels by a hybrid transport chosen per target:+ * The passage travels by a hybrid transport chosen per target (measured+ * against the encoded URL budget on `'url'`, the PTY argv byte budget on+ * `'terminal'`):** - **Inline** — when the prompt's post-encoding length leaves the URL* within budget, the passage is embedded verbatim in a fenced block whose@@ -673,15 +788,22 @@ export function composeSelectionPrompt(input: SelectionPromptInput): string {// terminated. The other composers wrap in backticks and use the base// sanitizer.const safePath = sanitizePathForAtMention(input.relativePath);+ const transport = input.transport ?? 'url';const inline = composeInline(safePath, input.instruction, input.selectionMarkdown);- if (encodedPromptLength(inline, input.target) <= INLINE_PROMPT_ENCODED_BUDGET) {+ if (+ promptTransportLength(inline, input.target, transport) <=+ transportBudget(transport, INLINE_PROMPT_ENCODED_BUDGET)+ ) {return inline;}// Oversized selection → locus. The anchor is capped and the passage is read// from the doc, so the instruction is the only remaining unbounded input;- // shorten it if needed so the locus URL also stays within budget.- const fittedInstruction = fitInstructionToBudget(input.instruction, input.target, (instr) =>- composeLocus(safePath, instr, input.selectionMarkdown),+ // shorten it if needed so the locus prompt also stays within budget.+ const fittedInstruction = fitInstructionToBudget(+ input.instruction,+ input.target,+ (instr) => composeLocus(safePath, instr, input.selectionMarkdown),+ transport,);return composeLocus(safePath, fittedInstruction, input.selectionMarkdown);}@@ -728,17 +850,24 @@ function composeAskBody(safePath: string, instruction: string, autoOpen: boolean** `autoOpen` carries the same semantics as `composeFilePrompt`. When an* oversized instruction would push the encoded URL over the per-target budget- * it is shortened (never the path); the URL is never emitted unbounded.+ * it is shortened (never the path); the URL is never emitted unbounded. On the+ * `'terminal'` transport the prompt does not travel as a deep link — the fit+ * applies the PTY argv byte budget instead; the `'url'` default preserves the+ * deep-link behavior described above.*/export function composeAskPrompt(relativePath: string,instruction: string,autoOpen: boolean,target: HandoffTarget,+ transport: PromptTransport = 'url',): string {const safePath = sanitizePathForAtMention(relativePath);- const fitted = fitInstructionToBudget(instruction, target, (instr) =>- composeAskBody(safePath, instr, autoOpen),+ const fitted = fitInstructionToBudget(+ instruction,+ target,+ (instr) => composeAskBody(safePath, instr, autoOpen),+ transport,);return composeAskBody(safePath, fitted, autoOpen);}@@ -786,6 +915,9 @@ interface AssembleDocScopeInput {readonly mentions: readonly string[];readonly autoOpen: boolean;readonly target: HandoffTarget;+ /** Transport the prompt travels over — selects measurement + budget (see+ * `PromptTransport`). Defaults to `'url'`. */+ readonly transport?: PromptTransport;}/**@@ -798,6 +930,9 @@ interface AssembleProjectScopeInput {readonly mentions: readonly string[];readonly autoOpen: boolean;readonly target: HandoffTarget;+ /** Transport the prompt travels over (see `PromptTransport`). Defaults to+ * `'url'`. */+ readonly transport?: PromptTransport;}/**@@ -819,6 +954,9 @@ interface AssembleFolderScopeInput {readonly mentions: readonly string[];readonly autoOpen: boolean;readonly target: HandoffTarget;+ /** Transport the prompt travels over (see `PromptTransport`). Defaults to+ * `'url'`. */+ readonly transport?: PromptTransport;}/**@@ -939,6 +1077,7 @@ function selectionSegmentFor(mentionBlock: string,trailer: string,target: HandoffTarget,+ transport: PromptTransport,): string {if (selection.kind === 'lines') {return linesSelectionSegment(selection.startLine, selection.endLine, safeDocPath);@@ -954,7 +1093,8 @@ function selectionSegmentFor(mentionBlock,trailer,);- return encodedPromptLength(inlineWithoutInstruction, target) <= INLINE_PROMPT_ENCODED_BUDGET+ return promptTransportLength(inlineWithoutInstruction, target, transport) <=+ transportBudget(transport, INLINE_PROMPT_ENCODED_BUDGET)? inlineSegment: locusSelectionSegment(selection.markdown, safeDocPath);}@@ -972,6 +1112,7 @@ function assembleDocSelectionPrompt(trailer: string,): string {const { target } = input;+ const transport = input.transport ?? 'url';const safeDocPath = sanitizePathForAtMention(input.docRelativePath);const lead = `Let's work on @${safeDocPath} using OpenKnowledge.`;const selectionSegment = selectionSegmentFor(@@ -981,9 +1122,13 @@ function assembleDocSelectionPrompt(mentionBlock,trailer,target,+ transport,);- const fittedInstruction = fitInstructionToBudget(input.instruction, target, (instr) =>- composeAssembledBlocks(lead, instr, selectionSegment, mentionBlock, trailer),+ const fittedInstruction = fitInstructionToBudget(+ input.instruction,+ target,+ (instr) => composeAssembledBlocks(lead, instr, selectionSegment, mentionBlock, trailer),+ transport,);return composeAssembledBlocks(lead, fittedInstruction, selectionSegment, mentionBlock, trailer);}@@ -1018,8 +1163,11 @@ export function assembleHandoffPrompt(input: AssembleHandoffPromptInput): string// so the budget accounts for the whole assembled string, not the instruction// alone.const lead = scopeLead(input);- const fittedInstruction = fitInstructionToBudget(input.instruction, target, (instr) =>- composeAssembledBlocks(lead, instr, '', mentionBlock, trailer),+ const fittedInstruction = fitInstructionToBudget(+ input.instruction,+ target,+ (instr) => composeAssembledBlocks(lead, instr, '', mentionBlock, trailer),+ input.transport ?? 'url',);return composeAssembledBlocks(lead, fittedInstruction, '', mentionBlock, trailer);}@@ -1038,6 +1186,14 @@ export function composeAskProjectPrompt(instruction: string,autoOpen: boolean,target: HandoffTarget,+ transport: PromptTransport = 'url',): string {- return assembleHandoffPrompt({ scope: 'project', instruction, mentions: [], autoOpen, target });+ return assembleHandoffPrompt({+ scope: 'project',+ instruction,+ mentions: [],+ autoOpen,+ target,+ transport,+ });}diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.tsindex aebcbdfd6..8bb93f829 100644--- a/packages/core/src/handoff/terminal-launch.ts+++ b/packages/core/src/handoff/terminal-launch.ts@@ -2,11 +2,13 @@* In-app-terminal twin of the Claude Desktop deep-link handoff.** The deep-link path puts the scope-specific prompt in the `q=` URL param and- * opens the target's desktop app. The docked-terminal path takes the SAME- * prompt string and launches one of the supported agent CLIs (`claude`,- * `codex`, `cursor-agent`) with it inside OK's bottom terminal, so the two- * surfaces stay in lockstep — the prompt is composed once by the dispatch hook- * (`selectScopedPrompt`) and threaded into either transport.+ * opens the target's desktop app. The docked-terminal path launches one of the+ * supported agent CLIs (see `TERMINAL_CLIS`) inside OK's bottom+ * terminal with the same scope-specific prompt shape, so the two surfaces stay+ * in lockstep — the prompt is composed once by the dispatch hook+ * (`selectScopedPrompt`), budgeted per transport (URL-encoded budget for the+ * deep link, quoted-argv-byte budget for the PTY — see `PromptTransport` in+ * `prompt-composer.ts`), and threaded into either transport.** This module owns the shell-injection-safe wrapping. The terminal write is a* FIXED `<bin> [<fixed-args>…] '<prompt>'` shape — never an arbitrary command.diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 8298ca6d3..da9b8c940 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -391,10 +391,12 @@ export {OK_GATED_TOOL_NAMES,OK_PROJECT_SKILL_POINTER,OK_TERMINAL_SURFACE_PREAMBLE,+ type PromptTransport,shellSingleQuote,type TargetData,TERMINAL_CLI_IDS,TERMINAL_CLIS,+ TERMINAL_INLINE_PROMPT_BUDGET,type TerminalCli,type TerminalCliInfo,URN_HTTP_ONLY,