Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cowork): run the agent loop on the Vercel AI SDK
Akarshan Biswas0692e1cd1000
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex fc9f919bd..9ebbb1656 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -133,7 +133,8 @@ describe('agentTools', () => {{ command: 'ls' },undefined,undefined,- false+ false,+ undefined)useAgentToolsConfig.getState().setBashNetworkEnabled(true)@@ -145,7 +146,8 @@ describe('agentTools', () => {{ command: 'ls' },undefined,undefined,- true+ true,+ undefined)useAgentToolsConfig.getState().setBashNetworkEnabled(false)})@@ -160,7 +162,7 @@ describe('agentTools', () => {/// The thread id scopes the sandbox, so it must reach the plugin on every/// call; without it two conversations would share one scratch directory.- it('scopes execution to the calling thread and passes no project path', async () => {+ it('scopes execution to the calling thread and attaches no folder by default', async () => {executeTool.mockResolvedValue({content: 'hello',diff: null,@@ -177,10 +179,44 @@ describe('agentTools', () => {{ path: 'a.txt' },undefined,undefined,- false+ false,+ undefined)})+ // The workspace UI promises "reads from <folder>", so the folder has to reach+ // the plugin; Rust is what makes it read-only.+ it('forwards an attached folder as the read-only project', async () => {+ vi.mocked(executeTool).mockResolvedValue({+ content: 'ok',+ isError: false,+ diff: null,+ } as never)+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool('read', { path: 'a.txt' }, 'thread-1', '/home/u/repo')+ expect(executeTool).toHaveBeenLastCalledWith(+ '/data',+ 'thread-1',+ 'read',+ { path: 'a.txt' },+ undefined,+ undefined,+ false,+ '/home/u/repo'+ )+ })++ it('sends undefined, not null, when no folder is attached', async () => {+ vi.mocked(executeTool).mockResolvedValue({+ content: 'ok',+ isError: false,+ diff: null,+ } as never)+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool('read', { path: 'a.txt' }, 'thread-1', null)+ expect(vi.mocked(executeTool).mock.calls.at(-1)?.[7]).toBeUndefined()+ })+it('maps a gate refusal to an error rather than content', async () => {executeTool.mockResolvedValue({content: "tool 'write' needs user approval",@@ -220,7 +256,8 @@ describe('agentTools', () => {{},undefined,undefined,- false+ false,+ undefined)})diff --git a/web-app/src/lib/__tests__/coworkAsk.test.ts b/web-app/src/lib/__tests__/coworkAsk.test.tsnew file mode 100644index 000000000..0d5453ea0--- /dev/null+++ b/web-app/src/lib/__tests__/coworkAsk.test.ts@@ -0,0 +1,70 @@+import { describe, it, expect } from 'vitest'+import { parseAskRequest, renderAskResult } from '../coworkAsk'++const q = (over = {}) => ({+ id: 'q1',+ question: 'Which?',+ options: [{ label: 'A' }, { label: 'B' }],+ ...over,+})++describe('parseAskRequest', () => {+ it('accepts a well-formed request', () => {+ const out = parseAskRequest({ questions: [q()] })+ expect(typeof out).not.toBe('string')+ expect((out as { questions: unknown[] }).questions).toHaveLength(1)+ })++ it('keeps multi and recommended when present', () => {+ const out = parseAskRequest({+ questions: [q({ multi: true, recommended: 1 })],+ }) as { questions: Array<{ multi?: boolean; recommended?: number }> }+ expect(out.questions[0].multi).toBe(true)+ expect(out.questions[0].recommended).toBe(1)+ })++ it('drops multi and recommended when absent rather than inventing them', () => {+ const out = parseAskRequest({ questions: [q()] }) as {+ questions: Array<Record<string, unknown>>+ }+ expect('multi' in out.questions[0]).toBe(false)+ expect('recommended' in out.questions[0]).toBe(false)+ })++ // A card the user cannot answer would stall the run forever, so a malformed+ // request has to come back as a tool error the model can correct.+ it('rejects requests that would render an unanswerable card', () => {+ expect(typeof parseAskRequest({})).toBe('string')+ expect(typeof parseAskRequest({ questions: [] })).toBe('string')+ expect(typeof parseAskRequest({ questions: [q({ id: '' })] })).toBe('string')+ expect(typeof parseAskRequest({ questions: [q({ question: '' })] })).toBe(+ 'string'+ )+ expect(+ typeof parseAskRequest({ questions: [q({ options: [{ label: 'only' }] })] })+ ).toBe('string')+ })++ it('rejects a question whose options are unlabelled', () => {+ const out = parseAskRequest({+ questions: [q({ options: [{ description: 'x' }, { description: 'y' }] })],+ })+ expect(typeof out).toBe('string')+ })+})++describe('renderAskResult', () => {+ it('serialises the answers', () => {+ const answers = [{ id: 'q1', selected: ['A'] }]+ expect(JSON.parse(renderAskResult(answers).output)).toEqual(answers)+ })++ // An empty array reads as "the user chose nothing", which is different from+ // "the user never answered" and sends the model down the wrong path.+ it('says plainly when the user did not answer', () => {+ const out = renderAskResult(null)+ expect(out.output).toMatch(/did not answer/)+ expect(out.output).toMatch(/best judgement/)+ expect(out.isError).toBeUndefined()+ })+})diff --git a/web-app/src/lib/__tests__/coworkBudget.test.ts b/web-app/src/lib/__tests__/coworkBudget.test.tsnew file mode 100644index 000000000..2f68e0147--- /dev/null+++ b/web-app/src/lib/__tests__/coworkBudget.test.ts@@ -0,0 +1,53 @@+import { describe, it, expect } from 'vitest'+import {+ budgetExceeded,+ MAX_AGENT_STEPS,+ MAX_SUBAGENT_STEPS,+ MAX_SESSION_TOKENS,+} from '../coworkBudget'++describe('budgetExceeded', () => {+ it('is null while under both caps', () => {+ expect(budgetExceeded({ step: 0, sessionTokens: 0 })).toBeNull()+ expect(+ budgetExceeded({ step: MAX_AGENT_STEPS - 1, sessionTokens: 0 })+ ).toBeNull()+ })++ it('reports the step cap at the boundary, not past it', () => {+ expect(budgetExceeded({ step: MAX_AGENT_STEPS, sessionTokens: 0 })).toBe(+ 'steps'+ )+ })++ it('reports the token cap', () => {+ expect(+ budgetExceeded({ step: 0, sessionTokens: MAX_SESSION_TOKENS })+ ).toBe('tokens')+ })++ // Steps first: it is the cheaper one to explain and the one "Keep going"+ // can actually resolve, whereas the token cap needs a compact or a new+ // session.+ it('reports steps first when both are exceeded', () => {+ expect(+ budgetExceeded({+ step: MAX_AGENT_STEPS,+ sessionTokens: MAX_SESSION_TOKENS,+ })+ ).toBe('steps')+ })++ it('honours a caller-supplied cap, as a subagent uses', () => {+ expect(+ budgetExceeded({ step: MAX_SUBAGENT_STEPS, sessionTokens: 0 }, MAX_SUBAGENT_STEPS)+ ).toBe('steps')+ expect(+ budgetExceeded({ step: MAX_SUBAGENT_STEPS - 1, sessionTokens: 0 }, MAX_SUBAGENT_STEPS)+ ).toBeNull()+ })++ it('keeps a subagent on a tighter leash than the parent', () => {+ expect(MAX_SUBAGENT_STEPS).toBeLessThan(MAX_AGENT_STEPS)+ })+})diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsnew file mode 100644index 000000000..c3ee4d7d7--- /dev/null+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -0,0 +1,94 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { executeAgentTool } = vi.hoisted(() => ({ executeAgentTool: vi.fn() }))+vi.mock('@/lib/agentTools', () => ({ executeAgentTool }))++import { dispatchCoworkTool } from '../coworkDispatch'+import type { PendingToolCall } from '../coworkRunner'++const call = (toolName: string, input: unknown = {}): PendingToolCall => ({+ toolCallId: 'c1',+ toolName,+ input,+})++const ctx = (over = {}) => ({+ sessionId: 's1',+ readOnlyFolder: null,+ planMode: false,+ onTodo: vi.fn(async () => ({ output: 'todo ok' })),+ onAsk: vi.fn(async () => ({ output: 'ask ok' })),+ onTask: vi.fn(async () => ({ output: 'task ok' })),+ ...over,+})++describe('dispatchCoworkTool', () => {+ beforeEach(() => {+ executeAgentTool.mockReset()+ executeAgentTool.mockResolvedValue({ content: 'ok' })+ })++ it('routes built-ins to the Rust plugin with the session as workspace key', async () => {+ const c = ctx()+ await dispatchCoworkTool(call('read', { path: 'a' }), c)+ expect(executeAgentTool).toHaveBeenCalledWith(+ 'read',+ { path: 'a' },+ 's1',+ null+ )+ })++ it('routes the client-only tools to their handlers', async () => {+ const c = ctx()+ expect((await dispatchCoworkTool(call('todo'), c)).output).toBe('todo ok')+ expect((await dispatchCoworkTool(call('ask'), c)).output).toBe('ask ok')+ expect((await dispatchCoworkTool(call('task'), c)).output).toBe('task ok')+ expect(executeAgentTool).not.toHaveBeenCalled()+ })++ // Withholding a tool from the advertised set is not authoritative: a model+ // can still emit a call for one. Without this the run would happily write+ // files in a mode whose entire promise is that it does not.+ it('refuses a mutating tool in plan mode even though it was never advertised', async () => {+ const c = ctx({ planMode: true })+ const out = await dispatchCoworkTool(call('write', { path: 'a' }), c)+ expect(out.isError).toBe(true)+ expect(out.output).toMatch(/disabled in plan mode/)+ expect(executeAgentTool).not.toHaveBeenCalled()+ })++ it('still allows reads in plan mode', async () => {+ await dispatchCoworkTool(call('read'), ctx({ planMode: true }))+ expect(executeAgentTool).toHaveBeenCalled()+ })++ it('passes the attached folder through', async () => {+ await dispatchCoworkTool(call('grep'), ctx({ readOnlyFolder: '/repo' }))+ expect(executeAgentTool).toHaveBeenCalledWith('grep', {}, 's1', '/repo')+ })++ it('carries the display diff without putting it in the output', async () => {+ executeAgentTool.mockResolvedValue({+ content: 'Wrote a.txt',+ diff: '- a\n+ b',+ })+ const out = await dispatchCoworkTool(call('edit'), ctx())+ expect(out.output).toBe('Wrote a.txt')+ expect(out.diff).toBe('- a\n+ b')+ })++ // A rejection would abort the whole run; the model can usually recover if it+ // is simply told what failed.+ it('turns a tool error into a result instead of throwing', async () => {+ executeAgentTool.mockResolvedValue({ error: 'no such file' })+ const out = await dispatchCoworkTool(call('read'), ctx())+ expect(out).toEqual({ output: 'no such file', isError: true })+ })++ it('turns a thrown exception into a result too', async () => {+ executeAgentTool.mockRejectedValue(new Error('ipc died'))+ const out = await dispatchCoworkTool(call('read'), ctx())+ expect(out).toEqual({ output: 'ipc died', isError: true })+ })+})diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.tsnew file mode 100644index 000000000..678d37acd--- /dev/null+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest'+import {+ buildCoworkSystemPrompt,+ PLAN_REVIEW_QUESTION_ID,+} from '../coworkPrompt'++const opts = (over = {}) => ({+ workspacePath: '/data/agent-workspace/sessions/s1',+ readOnlyFolder: null,+ planMode: false,+ bashAvailable: true,+ subagentNames: [],+ ...over,+})++describe('buildCoworkSystemPrompt', () => {+ it('names the workspace as the writable directory', () => {+ const p = buildCoworkSystemPrompt(opts())+ expect(p).toContain('/data/agent-workspace/sessions/s1')+ expect(p).toContain('No project folder is attached')+ })++ // Without this the model retries the same refused write until the step+ // budget runs out — the single most expensive thing it can get wrong here.+ it('spells out that an attached folder is read-only and how to work around it', () => {+ const p = buildCoworkSystemPrompt(opts({ readOnlyFolder: '/home/u/repo' }))+ expect(p).toContain('/home/u/repo')+ expect(p).toContain('READ-ONLY')+ expect(p).toMatch(/copy it into your workspace/i)+ expect(p).toMatch(/Do not\s+retry a refused write/i)+ })++ it('explains a missing shell rather than staying silent about it', () => {+ const p = buildCoworkSystemPrompt(opts({ bashAvailable: false }))+ expect(p).toMatch(/Shell commands are unavailable/i)+ expect(buildCoworkSystemPrompt(opts())).not.toMatch(+ /Shell commands are unavailable/i+ )+ })++ it('carries the plan-review contract the ask card special-cases', () => {+ const p = buildCoworkSystemPrompt(opts({ planMode: true }))+ expect(p).toContain('PLAN MODE (read only)')+ expect(p).toContain(PLAN_REVIEW_QUESTION_ID)+ expect(p).toContain('Execute plan')+ expect(p).toContain('Keep planning')+ expect(p).toContain('Exit plan mode')+ })++ it('describes subagents only when some are available and not planning', () => {+ expect(+ buildCoworkSystemPrompt(opts({ subagentNames: ['researcher'] }))+ ).toContain('researcher')+ expect(+ buildCoworkSystemPrompt(+ opts({ subagentNames: ['researcher'], planMode: true })+ )+ ).not.toContain('# Subagents')+ expect(buildCoworkSystemPrompt(opts())).not.toContain('# Subagents')+ })+})diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.tsnew file mode 100644index 000000000..fb3797a7a--- /dev/null+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts@@ -0,0 +1,274 @@+import { describe, it, expect, vi } from 'vitest'+import type { UIMessage, UIMessageChunk } from 'ai'+import {+ runTurn,+ consumeStep,+ assistantMessageFor,+ turnsFor,+ abortRun,+ answerAsk,+ isRunning,+ __testing,+ type PendingToolCall,+ type StepResult,+ type ToolOutcome,+} from '../coworkRunner'+import { MAX_SESSION_TOKENS } from '../coworkBudget'++const streamOf = (chunks: UIMessageChunk[]): ReadableStream<UIMessageChunk> =>+ new ReadableStream({+ start(c) {+ for (const chunk of chunks) c.enqueue(chunk)+ c.close()+ },+ })++const textStep = (text: string, usageTotal?: number): UIMessageChunk[] => [+ { type: 'text-delta', id: 't', delta: text } as UIMessageChunk,+ ...(usageTotal !== undefined+ ? ([+ {+ type: 'finish',+ messageMetadata: { usage: { totalTokens: usageTotal } },+ },+ ] as unknown as UIMessageChunk[])+ : []),+]++const toolStep = (name: string, id = 'c1'): UIMessageChunk[] => [+ { type: 'tool-input-start', toolCallId: id, toolName: name } as UIMessageChunk,+ {+ type: 'tool-input-available',+ toolCallId: id,+ toolName: name,+ input: { path: 'a.txt' },+ } as UIMessageChunk,+]++const noopSink = () => ({+ onText: vi.fn(),+ onToolStart: vi.fn(),+ onToolArgsDelta: vi.fn(),+ onToolCall: vi.fn(),+})++const deps = (+ steps: UIMessageChunk[][],+ dispatch = vi.fn(async (): Promise<ToolOutcome> => ({ output: 'ok' }))+) => {+ let i = 0+ return {+ sendStep: vi.fn(async () => streamOf(steps[Math.min(i++, steps.length - 1)])),+ dispatch,+ sink: noopSink(),+ onStep: vi.fn(),+ nextMessageId: (() => {+ let n = 0+ return () => `m${n++}`+ })(),+ }+}++const user = (text: string): UIMessage =>+ ({ id: 'u1', role: 'user', parts: [{ type: 'text', text }] }) as UIMessage++describe('consumeStep', () => {+ it('folds text, tool calls and usage out of the chunk stream', async () => {+ const sink = noopSink()+ const r = await consumeStep(+ streamOf([...textStep('hi'), ...toolStep('read'), ...textStep('', 120)]),+ sink+ )+ expect(r.text).toBe('hi')+ expect(r.toolCalls).toEqual([+ { toolCallId: 'c1', toolName: 'read', input: { path: 'a.txt' } },+ ])+ expect(r.usage?.total_tokens).toBe(120)+ expect(sink.onToolStart).toHaveBeenCalledWith('c1', 'read')+ })++ it('surfaces an error chunk without throwing', async () => {+ const r = await consumeStep(+ streamOf([{ type: 'error', errorText: 'boom' } as UIMessageChunk]),+ noopSink()+ )+ expect(r.errorText).toBe('boom')+ })+})++describe('runTurn', () => {+ it('stops when the model answers without asking for tools', async () => {+ const d = deps([textStep('done')])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('done')+ expect(out.steps).toBe(1)+ expect(d.sendStep).toHaveBeenCalledTimes(1)+ })++ it('keeps stepping while the model asks for tools', async () => {+ const d = deps([toolStep('read'), toolStep('read', 'c2'), textStep('done')])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('done')+ expect(out.steps).toBe(3)+ })++ // Routine, not an error: the caller offers "Keep going" rather than a+ // failure banner, so this must return cleanly instead of throwing.+ it('stops cleanly at the step cap', async () => {+ const d = deps([toolStep('read')])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ maxSteps: 3,+ })+ expect(out.stoppedBy).toBe('steps')+ expect(out.steps).toBe(3)+ })++ it('stops on the session token budget, counting tokens spent earlier', async () => {+ const d = deps([toolStep('read'), ...[textStep('x')]])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ sessionTokens: MAX_SESSION_TOKENS,+ })+ expect(out.stoppedBy).toBe('tokens')+ expect(d.sendStep).not.toHaveBeenCalled()+ })++ it('accumulates usage across steps into the session total', async () => {+ const d = deps([+ [...toolStep('read'), ...textStep('', 100)],+ textStep('done', 50),+ ])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.sessionTokens).toBe(150)+ })++ it('marks outstanding calls interrupted when aborted mid-dispatch', async () => {+ const ac = new AbortController()+ const dispatch = vi.fn(async (): Promise<ToolOutcome> => {+ ac.abort()+ return { output: 'ok' }+ })+ const d = deps(+ [+ [+ ...toolStep('read', 'c1'),+ {+ type: 'tool-input-available',+ toolCallId: 'c2',+ toolName: 'read',+ input: {},+ } as UIMessageChunk,+ ],+ ],+ dispatch+ )+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: ac.signal,+ })+ expect(out.stoppedBy).toBe('aborted')+ const parts = (out.messages.at(-1) as { parts: any[] }).parts+ expect(parts.find((p) => p.toolCallId === 'c2').errorText).toBe(+ '(interrupted)'+ )+ })++ it('ends the run on an error chunk instead of looping', async () => {+ const d = deps([[{ type: 'error', errorText: 'boom' } as UIMessageChunk]])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(out.errorText).toBe('boom')+ expect(d.sendStep).toHaveBeenCalledTimes(1)+ })++ it('feeds each step tool results before the next one', async () => {+ const d = deps([toolStep('read'), textStep('done')])+ await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ const secondCall = d.sendStep.mock.calls[1][0] as UIMessage[]+ const parts = (secondCall.at(-1) as { parts: any[] }).parts+ expect(parts[0].state).toBe('output-available')+ expect(parts[0].output).toBe('ok')+ })+})++describe('diff sidecar', () => {+ // A diff is a rendering aid. Sending it to the model doubles the cost of+ // every edit and corrupts the output the tool widget parses.+ it('never reaches the model-facing message', () => {+ const step: StepResult = {+ text: '',+ toolCalls: [+ { toolCallId: 'c1', toolName: 'edit', input: {} } as PendingToolCall,+ ],+ usage: null,+ aborted: false,+ }+ const outcomes = new Map<string, ToolOutcome>([+ ['c1', { output: 'Wrote a.txt', diff: '- old\n+ new' }],+ ])+ const msg = assistantMessageFor('m0', step, outcomes)+ expect(JSON.stringify(msg)).not.toContain('+ new')+ // …but it does reach the transcript row the UI renders.+ expect(turnsFor(step, outcomes)[0].diff).toBe('- old\n+ new')+ })+})++describe('run handles', () => {+ it('aborts the stream, tools, children and pending asks together', () => {+ const h = __testing.createHandle('s1', 'r1')+ const child = new AbortController()+ h.subagents.set('sub1', child)+ const ask = vi.fn()+ h.pendingAsks.set('q1', ask)++ expect(isRunning('s1')).toBe(true)+ abortRun('s1')++ expect(h.outer.signal.aborted).toBe(true)+ expect(h.tools.signal.aborted).toBe(true)+ expect(child.signal.aborted).toBe(true)+ // Resolved as cancelled, not left hanging: the dispatch loop is awaiting it.+ expect(ask).toHaveBeenCalledWith(null)+ expect(isRunning('s1')).toBe(false)+ })++ it('answers a pending ask once and reports an unknown one', () => {+ const h = __testing.createHandle('s2', 'r2')+ const resolve = vi.fn()+ h.pendingAsks.set('q1', resolve)+ expect(answerAsk('s2', 'q1', [{ id: 'q1', selected: ['a'] }])).toBe(true)+ expect(resolve).toHaveBeenCalledOnce()+ expect(answerAsk('s2', 'q1', [])).toBe(false)+ abortRun('s2')+ })++ it('is a no-op for a session that is not running', () => {+ expect(() => abortRun('nope')).not.toThrow()+ })+})diff --git a/web-app/src/lib/__tests__/coworkTodo.test.ts b/web-app/src/lib/__tests__/coworkTodo.test.tsnew file mode 100644index 000000000..3a1b1403e--- /dev/null+++ b/web-app/src/lib/__tests__/coworkTodo.test.ts@@ -0,0 +1,175 @@+import { describe, it, expect } from 'vitest'+import { applyTodoOp, renderTodoResult, todoProgress } from '../coworkTodo'+import type { TodoList } from '@/types/codeSession'++// Ported from `core/agent/todo.rs`'s own tests: the two implementations drive+// the same schema and the same panel, so they have to agree.++const init = (list: Array<{ phase: string; items: string[] }>) =>+ applyTodoOp(undefined, { op: 'init', list }).list++const active = (l: TodoList) =>+ l.phases.flatMap((p) => p.tasks).find((t) => t.status === 'in_progress')+ ?.content++const statusOf = (l: TodoList, content: string) =>+ l.phases.flatMap((p) => p.tasks).find((t) => t.content === content)?.status++describe('init', () => {+ it('promotes the first task', () => {+ const l = init([{ phase: 'Setup', items: ['a', 'b'] }])+ expect(active(l)).toBe('a')+ expect(todoProgress(l)).toEqual({ done: 0, total: 2 })+ })++ it('accepts the flat items form as one unnamed phase', () => {+ const l = applyTodoOp(undefined, { op: 'init', items: ['x', 'y'] }).list+ expect(l.phases).toHaveLength(1)+ expect(l.phases[0].name).toBe('')+ expect(active(l)).toBe('x')+ })++ it('rejects duplicate phases, duplicate tasks, and cross-phase duplicates', () => {+ for (const list of [+ [+ { phase: 'A', items: ['x'] },+ { phase: 'A', items: ['y'] },+ ],+ [{ phase: 'A', items: ['x', 'x'] }],+ [+ { phase: 'A', items: ['x'] },+ { phase: 'B', items: ['x'] },+ ],+ ]) {+ const r = applyTodoOp(undefined, { op: 'init', list })+ expect(r.error).toBeTruthy()+ // Atomic: a rejected init leaves prior state untouched.+ expect(r.list.phases).toEqual([])+ }+ })++ it('rejects empty task content', () => {+ expect(+ applyTodoOp(undefined, { op: 'init', items: [' '] }).error+ ).toMatch(/must not be empty/)+ })+})++describe('start', () => {+ it('accepts only the current task', () => {+ const l = init([{ phase: 'A', items: ['a', 'b'] }])+ expect(applyTodoOp(l, { op: 'start', task: 'a' }).error).toBeUndefined()+ expect(applyTodoOp(l, { op: 'start', task: 'b' }).error).toMatch(+ /cannot start/+ )+ expect(applyTodoOp(l, { op: 'start', task: 'missing' }).error).toMatch(+ /unknown task/+ )+ })++ it('rejects a task after an open earlier phase', () => {+ let l = init([+ { phase: 'Phase 1', items: ['one'] },+ { phase: 'Phase 2', items: ['two'] },+ { phase: 'Phase 5', items: ['five'] },+ ])+ l = applyTodoOp(l, { op: 'done', phase: 'Phase 1' }).list+ expect(applyTodoOp(l, { op: 'start', task: 'five' }).error).toBeTruthy()+ expect(active(l)).toBe('two')+ })+})++describe('done and drop', () => {+ it('promotes the next pending task on completion', () => {+ let l = init([{ phase: 'A', items: ['a', 'b'] }])+ l = applyTodoOp(l, { op: 'done', task: 'a' }).list+ expect(active(l)).toBe('b')+ expect(todoProgress(l)).toEqual({ done: 1, total: 2 })+ })++ it('promotes the next pending task on abandonment too', () => {+ let l = init([{ phase: 'A', items: ['a', 'b'] }])+ l = applyTodoOp(l, { op: 'drop', task: 'a' }).list+ expect(statusOf(l, 'a')).toBe('abandoned')+ expect(active(l)).toBe('b')+ })++ // Completing a phase must not resurrect a task the agent deliberately+ // abandoned — the record of that decision is the point of `drop`.+ it('completing a phase leaves already-terminal tasks alone', () => {+ let l = init([{ phase: 'A', items: ['a', 'b', 'c'] }])+ l = applyTodoOp(l, { op: 'drop', task: 'b' }).list+ l = applyTodoOp(l, { op: 'done', phase: 'A' }).list+ expect(statusOf(l, 'a')).toBe('completed')+ expect(statusOf(l, 'b')).toBe('abandoned')+ expect(statusOf(l, 'c')).toBe('completed')+ })++ it('done all closes everything open', () => {+ let l = init([{ phase: 'A', items: ['a', 'b'] }])+ l = applyTodoOp(l, { op: 'done', all: true }).list+ expect(todoProgress(l)).toEqual({ done: 2, total: 2 })+ })+})++describe('rm', () => {+ it('deletes outright where drop preserves the record', () => {+ let l = init([{ phase: 'A', items: ['a', 'b'] }])+ l = applyTodoOp(l, { op: 'drop', task: 'a' }).list+ expect(statusOf(l, 'a')).toBe('abandoned')+ l = applyTodoOp(l, { op: 'rm', task: 'a' }).list+ expect(statusOf(l, 'a')).toBeUndefined()+ })++ it('reports a missing target without mutating', () => {+ const l = init([{ phase: 'A', items: ['a'] }])+ const before = JSON.stringify(l)+ expect(applyTodoOp(l, { op: 'rm', task: 'missing' }).error).toBeTruthy()+ expect(applyTodoOp(l, { op: 'rm', phase: 'missing' }).error).toBeTruthy()+ expect(JSON.stringify(l)).toBe(before)+ })+})++describe('append', () => {+ it('adds to an existing phase and creates a missing one', () => {+ let l = init([{ phase: 'A', items: ['a'] }])+ l = applyTodoOp(l, { op: 'append', phase: 'A', items: ['a2'] }).list+ l = applyTodoOp(l, { op: 'append', phase: 'B', items: ['b1'] }).list+ expect(l.phases.map((p) => p.name)).toEqual(['A', 'B'])+ expect(l.phases[0].tasks.map((t) => t.content)).toEqual(['a', 'a2'])+ })++ it('rejects duplicates against the list and within the call', () => {+ const l = init([{ phase: 'A', items: ['a'] }])+ expect(+ applyTodoOp(l, { op: 'append', phase: 'A', items: ['a'] }).error+ ).toMatch(/duplicate/)+ expect(+ applyTodoOp(l, { op: 'append', phase: 'A', items: ['z', 'z'] }).error+ ).toMatch(/duplicate/)+ })+})++describe('argument handling', () => {+ it('never throws on malformed input', () => {+ for (const args of [undefined, {}, { op: 'nope' }, { op: 'done' }, 42]) {+ const r = applyTodoOp(undefined, args)+ expect(r.error).toBeTruthy()+ expect(r.list).toBeDefined()+ }+ })++ it('view returns the list unchanged', () => {+ const l = init([{ phase: 'A', items: ['a'] }])+ expect(applyTodoOp(l, { op: 'view' })).toEqual({ list: l })+ })+})++describe('renderTodoResult', () => {+ // The whole snapshot goes back as the tool result so a compacted history can+ // still reconstruct the list from the transcript alone.+ it('serialises the full list', () => {+ const l = init([{ phase: 'A', items: ['a'] }])+ expect(JSON.parse(renderTodoResult(l))).toEqual(l)+ })+})diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsnew file mode 100644index 000000000..63327e32c--- /dev/null+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -0,0 +1,117 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { getAgentToolSchemas } = vi.hoisted(() => ({+ getAgentToolSchemas: vi.fn(),+}))+vi.mock('@/lib/agentTools', () => ({ getAgentToolSchemas }))++import {+ buildCoworkTools,+ coworkToolSignature,+ allowedToolNames,+ PLAN_DENIED_TOOLS,+ TODO_TOOL_NAME,+ ASK_TOOL_NAME,+ TASK_TOOL_NAME,+} from '../coworkTools'++const schema = (name: string) => ({+ type: 'function' as const,+ function: { name, description: name, parameters: { type: 'object' } },+})++const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'bash', 'memory_write']++const opts = (over: Partial<Parameters<typeof buildCoworkTools>[0]> = {}) => ({+ planMode: false,+ subagentNames: ['researcher'],+ allowSubagents: true,+ ...over,+})++describe('buildCoworkTools', () => {+ beforeEach(() => {+ getAgentToolSchemas.mockReset()+ getAgentToolSchemas.mockResolvedValue(ALL.map(schema))+ })++ it('advertises the built-ins plus the client-only tools', async () => {+ const tools = await buildCoworkTools(opts())+ for (const n of ALL) expect(tools[n]).toBeDefined()+ expect(tools[TODO_TOOL_NAME]).toBeDefined()+ expect(tools[ASK_TOOL_NAME]).toBeDefined()+ expect(tools[TASK_TOOL_NAME]).toBeDefined()+ })++ // Plan mode's guarantee is that nothing can mutate. Withholding is only half+ // of it (the dispatcher refuses too), but a leak here would advertise a tool+ // the run is about to refuse, which reads to the model as a broken tool.+ it('withholds every mutating tool in plan mode', async () => {+ const tools = await buildCoworkTools(opts({ planMode: true }))+ for (const denied of PLAN_DENIED_TOOLS) {+ expect(tools[denied]).toBeUndefined()+ }+ expect(tools.read).toBeDefined()+ expect(tools[TODO_TOOL_NAME]).toBeDefined()+ expect(tools[ASK_TOOL_NAME]).toBeDefined()+ })++ it('withholds task when subagents are not allowed', async () => {+ const tools = await buildCoworkTools(opts({ allowSubagents: false }))+ expect(tools[TASK_TOOL_NAME]).toBeUndefined()+ })++ it('names the saved subagents in the task description', async () => {+ const tools = await buildCoworkTools(+ opts({ subagentNames: ['researcher', 'reviewer'] })+ )+ expect(tools[TASK_TOOL_NAME].description).toContain('researcher, reviewer')+ })++ // The todo tool must keep the Rust name: the plan-mode addendum instructs the+ // model to call `todo` by name, so a rename silently breaks plan mode.+ it('keeps the Rust tool names', () => {+ expect(TODO_TOOL_NAME).toBe('todo')+ expect(ASK_TOOL_NAME).toBe('ask')+ })+})++describe('coworkToolSignature', () => {+ it('is stable across repeated calls with the same config', () => {+ expect(coworkToolSignature(opts(), true)).toBe(+ coworkToolSignature(opts(), true)+ )+ })++ it('changes when anything that alters the advertised set changes', () => {+ const base = coworkToolSignature(opts(), true)+ expect(coworkToolSignature(opts({ planMode: true }), true)).not.toBe(base)+ expect(coworkToolSignature(opts(), false)).not.toBe(base)+ expect(+ coworkToolSignature(opts({ subagentNames: ['other'] }), true)+ ).not.toBe(base)+ })++ // Subagent names only reach the prompt when task is advertised, so they must+ // not churn the signature (and discard the KV prefix) when it is not.+ it('ignores subagent names when subagents are off', () => {+ expect(coworkToolSignature(opts({ allowSubagents: false }), true)).toBe(+ coworkToolSignature(+ opts({ allowSubagents: false, subagentNames: ['x', 'y'] }),+ true+ )+ )+ })+})++describe('allowedToolNames', () => {+ it('refuses the same set plan mode withholds', () => {+ const out = allowedToolNames([...ALL, TASK_TOOL_NAME], opts({ planMode: true }))+ expect(out).toEqual(['read', 'ls', 'grep'])+ })++ it('refuses task past the subagent depth cap', () => {+ const out = allowedToolNames(['read', TASK_TOOL_NAME], opts({ allowSubagents: false }))+ expect(out).toEqual(['read'])+ })+})diff --git a/web-app/src/lib/__tests__/coworkTransport.test.ts b/web-app/src/lib/__tests__/coworkTransport.test.tsnew file mode 100644index 000000000..217735af9--- /dev/null+++ b/web-app/src/lib/__tests__/coworkTransport.test.ts@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++const { sandboxEnforces, buildCoworkTools } = vi.hoisted(() => ({+ sandboxEnforces: vi.fn(() => true),+ buildCoworkTools: vi.fn(),+}))+vi.mock('@/lib/agentTools', () => ({ sandboxEnforces }))+vi.mock('@/lib/coworkTools', async (orig) => ({+ ...(await orig<typeof import('../coworkTools')>()),+ buildCoworkTools,+}))++import { CoworkChatTransport } from '../coworkTransport'+import { CHAT_SLOT_ID, COWORK_SLOT_ID } from '@/constants/models'++const config = (over = {}) => ({+ planMode: false,+ subagentNames: ['researcher'],+ allowSubagents: true,+ workspacePath: '/ws/s1',+ readOnlyFolder: null,+ ...over,+})++// Reaching in on purpose: these are protected seams whose whole job is to be+// different from the parent's, and both fail silently in production.+const slotParamsOf = (t: CoworkChatTransport, id: string) =>+ (t as unknown as {+ slotParams: (s?: string) => Record<string, unknown>+ }).slotParams(id)++describe('CoworkChatTransport', () => {+ beforeEach(() => {+ buildCoworkTools.mockReset()+ buildCoworkTools.mockResolvedValue({ read: {} })+ sandboxEnforces.mockReturnValue(true)+ })++ // Sharing slot 0 would have each of an agent turn's many prefills evict the+ // viewed chat thread's KV cache, and vice versa. Nothing surfaces that but a+ // slowdown, so it is asserted.+ it('pins to the Cowork slot, not the chat slot', () => {+ const t = new CoworkChatTransport('s1', config())+ const params = slotParamsOf(t, 's1')+ expect(params.id_slot).toBe(COWORK_SLOT_ID)+ expect(params.id_slot).not.toBe(CHAT_SLOT_ID)+ expect(params.thread_id).toBe('cowork:s1')+ })++ it('namespaces thread_id so a session cannot collide with a chat thread', () => {+ const t = new CoworkChatTransport('abc', config())+ expect(slotParamsOf(t, 'abc').thread_id).toBe('cowork:abc')+ })++ it('builds the tool set once and reuses it for the rest of the run', async () => {+ const t = new CoworkChatTransport('s1', config())+ await t.refreshTools()+ await t.refreshTools()+ await t.refreshTools()+ expect(buildCoworkTools).toHaveBeenCalledTimes(1)+ })++ // A config change must not take effect mid-run: it would change the tool JSON+ // and throw away the prompt prefix on the very next step.+ it('ignores a config change until the freeze is lifted', async () => {+ const t = new CoworkChatTransport('s1', config())+ await t.refreshTools()+ t.setConfig(config({ planMode: true }))+ await t.refreshTools()+ expect(buildCoworkTools).toHaveBeenCalledTimes(1)++ t.unfreezeTools()+ await t.refreshTools()+ expect(buildCoworkTools).toHaveBeenCalledTimes(2)+ expect(buildCoworkTools).toHaveBeenLastCalledWith(+ expect.objectContaining({ planMode: true })+ )+ })++ it('rebuilds when the sandbox appears, since bash joins the set', async () => {+ sandboxEnforces.mockReturnValue(false)+ const t = new CoworkChatTransport('s1', config())+ await t.refreshTools()+ sandboxEnforces.mockReturnValue(true)+ t.unfreezeTools()+ await t.refreshTools()+ expect(buildCoworkTools).toHaveBeenCalledTimes(2)+ })++ // The parent throws when a window has no user turn. That is right for chat,+ // where it means eviction ate the question, and wrong for a long agent run+ // whose recent traffic is all tool results.+ it('does not abort a window whose recent traffic is all tool results', () => {+ const t = new CoworkChatTransport('s1', config())+ expect(() =>+ (t as unknown as { assertSendable: (m: unknown[]) => void }).assertSendable(+ []+ )+ ).not.toThrow()+ })+})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 9546b4522..9a8997972 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -35,6 +35,9 @@ export const AGENT_TOOL_NAMES = new Set(['skill_list','skill_read','skill_write',+ // Renders a local .html/.svg with headless Chrome so the agent can see what+ // it built. Read capability: it writes nothing back.+ 'screenshot',])/**@@ -67,6 +70,18 @@ export function getSandboxStatus(): Promise<SandboxStatus> {let enforcesNow = false+/**+ * Re-probe the sandbox, dropping both caches. Installing a backend (bubblewrap+ * on Linux) cannot take effect otherwise: `statusCache` is module-level, and+ * leaving `schemaCache` behind would keep `bash` withheld even once a backend+ * enforces.+ */+export function refreshSandboxStatus(): Promise<SandboxStatus> {+ statusCache = null+ schemaCache = null+ return getSandboxStatus()+}+/*** Synchronous view of the sandbox, for building the system prompt. `false` until* the probe resolves, which is safe: the prompt is assembled after@@ -120,7 +135,13 @@ const messageOf = (e: unknown): string =>export async function executeAgentTool(toolName: string,input: unknown,- threadId: string+ threadId: string,+ /**+ * A project folder to attach read-only. Rust validates it and refuses one+ * that overlaps the workspace or the Jan data folder, rather than silently+ * dropping it, so an unusable attachment surfaces as a tool error.+ */+ readOnlyProject?: string | null): Promise<AgentToolResult> {try {const dataFolder = await getServiceHub().app().getJanDataFolder()@@ -136,7 +157,8 @@ export async function executeAgentTool(args,undefined,undefined,- useAgentToolsConfig.getState().bashNetworkEnabled+ useAgentToolsConfig.getState().bashNetworkEnabled,+ readOnlyProject ?? undefined)if (result.isError) return { error: result.content }return { content: result.content, diff: result.diff ?? undefined }diff --git a/web-app/src/lib/coworkAsk.ts b/web-app/src/lib/coworkAsk.tsnew file mode 100644index 000000000..bb313192e--- /dev/null+++ b/web-app/src/lib/coworkAsk.ts@@ -0,0 +1,72 @@+import type {+ AskAnswer,+ AskQuestion,+ AskRequestPayload,+} from '@/types/codeSession'+import type { ToolOutcome } from '@/lib/coworkRunner'++/**+ * The `ask` tool: suspend the run until the user answers.+ *+ * Because Cowork dispatches tools after the model stream has terminated, a+ * suspended ask holds no HTTP connection and occupies no llama.cpp slot while+ * the user thinks — unlike the Rust loop, which blocked inside the turn.+ */++/** Reject a malformed request rather than rendering an unanswerable card. */+export function parseAskRequest(input: unknown): AskRequestPayload | string {+ const raw = (input ?? {}) as { questions?: unknown }+ if (!Array.isArray(raw.questions) || raw.questions.length === 0) {+ return '`ask` requires a non-empty `questions` array'+ }+ const questions: AskQuestion[] = []+ for (const entry of raw.questions) {+ const q = entry as Partial<AskQuestion>+ if (typeof q.id !== 'string' || !q.id.trim()) {+ return 'each question requires a non-empty `id`'+ }+ if (typeof q.question !== 'string' || !q.question.trim()) {+ return `question '${q.id}' requires a \`question\` string`+ }+ if (!Array.isArray(q.options) || q.options.length < 2) {+ return `question '${q.id}' requires at least two options`+ }+ const options = q.options+ .map((o) => o as { label?: unknown; description?: unknown })+ .filter((o) => typeof o.label === 'string' && o.label.trim())+ .map((o) => ({+ label: o.label as string,+ ...(typeof o.description === 'string'+ ? { description: o.description }+ : {}),+ }))+ if (options.length < 2) {+ return `question '${q.id}' requires at least two labelled options`+ }+ questions.push({+ id: q.id,+ question: q.question,+ options,+ ...(q.multi === true ? { multi: true } : {}),+ ...(typeof q.recommended === 'number' && q.recommended >= 0+ ? { recommended: q.recommended }+ : {}),+ })+ }+ return { questions }+}++/**+ * The tool result for a settled ask. `null` answers mean the user dismissed the+ * card or the run was aborted; the model is told so plainly rather than being+ * left to infer it from an empty array.+ */+export function renderAskResult(answers: AskAnswer[] | null): ToolOutcome {+ if (answers === null) {+ return {+ output:+ 'The user did not answer. Proceed with your best judgement, and do not ask again unless something new depends on it.',+ }+ }+ return { output: JSON.stringify(answers) }+}diff --git a/web-app/src/lib/coworkBudget.ts b/web-app/src/lib/coworkBudget.tsnew file mode 100644index 000000000..1f5ecafff--- /dev/null+++ b/web-app/src/lib/coworkBudget.ts@@ -0,0 +1,34 @@+/**+ * Bounds on a Cowork run.+ *+ * The AI SDK cannot enforce these for us: Jan's tools are declared without an+ * `execute`, so `streamText` returns after a single step and its `stopWhen`+ * conditions never evaluate. The loop is the runner's, so the caps are too —+ * and without them an agent with real tools has no upper bound at all.+ */++/** Model turns in one user request. Generous: real work runs long. */+export const MAX_AGENT_STEPS = 100++/** Tighter for a nested run, which should be a focused errand. */+export const MAX_SUBAGENT_STEPS = 30++/** Cumulative tokens for a session, matching what the Rust loop enforced. */+export const MAX_SESSION_TOKENS = 200_000++export type BudgetState = {+ step: number+ sessionTokens: number+}++export type BudgetStop = 'steps' | 'tokens' | null++/** Which cap, if any, this run has reached. */+export function budgetExceeded(+ state: BudgetState,+ maxSteps: number = MAX_AGENT_STEPS+): BudgetStop {+ if (state.step >= maxSteps) return 'steps'+ if (state.sessionTokens >= MAX_SESSION_TOKENS) return 'tokens'+ return null+}diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsnew file mode 100644index 000000000..67dce8a51--- /dev/null+++ b/web-app/src/lib/coworkDispatch.ts@@ -0,0 +1,83 @@+import { executeAgentTool } from '@/lib/agentTools'+import {+ ASK_TOOL_NAME,+ PLAN_DENIED_TOOLS,+ TASK_TOOL_NAME,+ TODO_TOOL_NAME,+} from '@/lib/coworkTools'+import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'++export type DispatchContext = {+ sessionId: string+ readOnlyFolder: string | null+ planMode: boolean+ /** Applies one `todo` operation and persists the result. */+ onTodo: (input: unknown) => Promise<ToolOutcome>+ /** Suspends until the user answers, or the run is aborted. */+ onAsk: (toolCallId: string, input: unknown) => Promise<ToolOutcome>+ /** Runs a nested subagent to completion. */+ onTask: (toolCallId: string, input: unknown) => Promise<ToolOutcome>+}++/**+ * Refusal text for a tool plan mode withholds.+ *+ * Withholding alone is not authoritative — a model can emit a call to a tool+ * that was never advertised, and the SDK still surfaces it — so the dispatcher+ * refuses by name too. The wording tells the model what to do instead, or it+ * simply retries.+ */+function planRefusal(toolName: string): ToolOutcome {+ return {+ output:+ `The \`${toolName}\` tool is disabled in plan mode, which is read-only. ` ++ 'Finish investigating, stage the plan with the `todo` tool, then call ' ++ '`ask` for plan review.',+ isError: true,+ }+}++/**+ * Route one tool call. Always resolves: a rejection here would abort the run,+ * where the model can usually recover from being told what went wrong.+ */+export async function dispatchCoworkTool(+ call: PendingToolCall,+ ctx: DispatchContext+): Promise<ToolOutcome> {+ const { toolName } = call++ if (ctx.planMode && PLAN_DENIED_TOOLS.has(toolName)) {+ return planRefusal(toolName)+ }++ try {+ if (toolName === TODO_TOOL_NAME) return await ctx.onTodo(call.input)+ if (toolName === ASK_TOOL_NAME) {+ return await ctx.onAsk(call.toolCallId, call.input)+ }+ if (toolName === TASK_TOOL_NAME) {+ return await ctx.onTask(call.toolCallId, call.input)+ }++ const result = await executeAgentTool(+ toolName,+ call.input,+ ctx.sessionId,+ ctx.readOnlyFolder+ )+ if (result.error) return { output: result.error, isError: true }+ return {+ output:+ typeof result.content === 'string'+ ? result.content+ : JSON.stringify(result.content ?? ''),+ diff: result.diff,+ }+ } catch (e) {+ return {+ output: e instanceof Error ? e.message : String(e),+ isError: true,+ }+ }+}diff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsnew file mode 100644index 000000000..49c3a3e8a--- /dev/null+++ b/web-app/src/lib/coworkPrompt.ts@@ -0,0 +1,103 @@+/**+ * System prompt for a Cowork run.+ *+ * The workspace block is the load-bearing part. The agent writes into a sandbox+ * and may only *read* an attached project folder, which is an arrangement no+ * model assumes — left unsaid, it retries the same denied write until the step+ * budget runs out.+ */++const IDENTITY =+ 'You are Jan, an agent working on the user’s behalf inside the Jan desktop app. ' ++ 'Work autonomously: investigate with your tools before answering, and prefer ' ++ 'acting over asking. Be concise; the user sees your tool calls, so do not narrate them.'++const GUIDELINES = [+ '# Guidelines',+ '',+ '- Read before you write. Never edit a file you have not read in this session.',+ '- Prefer targeted edits over rewriting a whole file.',+ '- Verify your work: run it, or read back what you wrote.',+ '- If a tool fails, read the error and adapt. Do not retry an identical call.',+ '- Use the `todo` tool for any task with more than a couple of steps, and keep it current.',+ '- Use `ask` only when the answer materially changes the work.',+].join('\n')++/** Ported verbatim from `core/agent/plan.rs::plan_mode_prompt_addendum`, whose+ * `plan_review` question id the ask card special-cases. */+const PLAN_ADDENDUM =+ 'PLAN MODE (read only): You are exploring to produce a plan. You may only ' ++ 'read, search, and list files, do web research, and read memory/skills. You ' ++ 'CANNOT edit files, run shell commands, or make any change; those tools are ' ++ 'disabled. Investigate thoroughly, then stage the full phased plan by calling ' ++ 'the `todo` tool with an `init` action listing every task. When the plan is ' ++ 'ready, call `ask` with exactly one question: {"questions": [{"id": ' ++ '"plan_review", "question": "<concise plan summary>", "options": ' ++ '[{"label": "Execute plan"}, {"label": "Keep planning"}, {"label": ' ++ '"Exit plan mode"}]}]}. Do not ask for plan review until the todos are staged.'++export const PLAN_REVIEW_QUESTION_ID = 'plan_review'+export const EXECUTE_PLAN_LABEL = 'Execute plan'+export const KEEP_PLANNING_LABEL = 'Keep planning'+export const EXIT_PLAN_LABEL = 'Exit plan mode'++export type CoworkPromptOptions = {+ /** The sandbox directory: the only writable location. */+ workspacePath: string | null+ /** An attached project folder, readable but never writable. */+ readOnlyFolder: string | null+ planMode: boolean+ /** False when no OS sandbox enforces, in which case `bash` is not offered. */+ bashAvailable: boolean+ subagentNames: string[]+}++function workspaceBlock(opts: CoworkPromptOptions): string {+ const lines = ['# Workspace', '']+ if (opts.workspacePath) {+ lines.push(+ `You have one writable directory, your workspace: \`${opts.workspacePath}\`.`,+ 'Relative paths resolve against it. Everything you create must live here.'+ )+ } else {+ lines.push('You have a private writable workspace. Relative paths resolve against it.')+ }+ if (opts.readOnlyFolder) {+ lines.push(+ '',+ `The user attached a project folder: \`${opts.readOnlyFolder}\`.`,+ 'It is mounted READ-ONLY. You can read, search and list inside it, but every',+ 'write, edit or shell command targeting it will be refused. To work on one of',+ 'its files, copy it into your workspace first and edit the copy there. Do not',+ 'retry a refused write against the original path.'+ )+ } else {+ lines.push('', 'No project folder is attached, so there is nothing outside the workspace to read.')+ }+ if (!opts.bashAvailable) {+ lines.push(+ '',+ 'Shell commands are unavailable on this machine: no OS sandbox is present to',+ 'confine them, so the `bash` tool is not offered. Use the file tools instead.'+ )+ }+ return lines.join('\n')+}++export function buildCoworkSystemPrompt(opts: CoworkPromptOptions): string {+ const blocks = [IDENTITY, GUIDELINES, workspaceBlock(opts)]+ if (opts.subagentNames.length > 0 && !opts.planMode) {+ blocks.push(+ [+ '# Subagents',+ '',+ 'The `task` tool runs a nested agent that does not see this conversation.',+ 'State everything it needs in `description`. Use one for work that is',+ 'self-contained and would otherwise flood your own context.',+ `Available: ${opts.subagentNames.join(', ')}.`,+ ].join('\n')+ )+ }+ if (opts.planMode) blocks.push(PLAN_ADDENDUM)+ return blocks.join('\n\n')+}diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsnew file mode 100644index 000000000..566707b53--- /dev/null+++ b/web-app/src/lib/coworkRunner.ts@@ -0,0 +1,384 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import type { UIMessage, UIMessageChunk } from 'ai'+import type { AskAnswer, CodeTurn, Usage } from '@/types/codeSession'+import {+ MAX_AGENT_STEPS,+ budgetExceeded,+ type BudgetStop,+} from '@/lib/coworkBudget'++/**+ * The Cowork agent loop.+ *+ * Deliberately not `useChat`: that binds one Chat per session through React, and+ * a Cowork run has to survive with no component mounted so a background session+ * keeps streaming while another is viewed. The handle map below lives outside+ * React for the same reason — route unmount must not abort a run.+ *+ * The loop is also ours because the AI SDK cannot own it here: Jan's tools are+ * declared without an `execute`, so `streamText` returns after one step and+ * `stopWhen` never evaluates. Every step boundary, and every cap, is explicit.+ */++/** A tool call the model made, awaiting dispatch. */+export type PendingToolCall = {+ toolCallId: string+ toolName: string+ input: unknown+}++export type ToolOutcome = {+ /** Sent to the model. */+ output: string+ isError?: boolean+ /** Display-only unified diff. Never reaches the model. */+ diff?: string+}++/** One model turn's worth of stream, folded into a shape the loop can act on. */+export type StepResult = {+ text: string+ toolCalls: PendingToolCall[]+ usage: Usage | null+ errorText?: string+ aborted: boolean+}++export type RunHandle = {+ runId: string+ outer: AbortController+ tools: AbortController+ subagents: Map<string, AbortController>+ pendingAsks: Map<string, (answers: AskAnswer[] | null) => void>+}++const handles = new Map<string, RunHandle>()++export function getRunHandle(sid: string): RunHandle | undefined {+ return handles.get(sid)+}++export function isRunning(sid: string): boolean {+ return handles.has(sid)+}++function createHandle(sid: string, runId: string): RunHandle {+ const handle: RunHandle = {+ runId,+ outer: new AbortController(),+ tools: new AbortController(),+ subagents: new Map(),+ pendingAsks: new Map(),+ }+ handles.set(sid, handle)+ return handle+}++/**+ * Stop a session's run: the model stream, the tool dispatch loop, every nested+ * subagent, and any question the user was being asked.+ *+ * An in-flight `bash` cannot be cancelled — `execute_tool` is a plain `invoke`+ * with no cancellation token — so its result is discarded and the process runs+ * to completion.+ */+export function abortRun(sid: string, reason = 'cancelled'): void {+ const handle = handles.get(sid)+ if (!handle) return+ handle.outer.abort(reason)+ handle.tools.abort(reason)+ for (const child of handle.subagents.values()) child.abort(reason)+ handle.subagents.clear()+ // Reject rather than hang: an unanswered ask would otherwise keep its+ // promise, and the dispatch loop awaiting it, alive forever.+ for (const resolve of handle.pendingAsks.values()) resolve(null)+ handle.pendingAsks.clear()+ handles.delete(sid)+}++/** Settle a pending `ask`. Returns false when the request is already gone. */+export function answerAsk(+ sid: string,+ requestId: string,+ answers: AskAnswer[] | null+): boolean {+ const handle = handles.get(sid)+ const resolve = handle?.pendingAsks.get(requestId)+ if (!handle || !resolve) return false+ handle.pendingAsks.delete(requestId)+ resolve(answers)+ return true+}++const usageOf = (meta: unknown): Usage | null => {+ const u = (meta as { usage?: Record<string, unknown> } | undefined)?.usage+ if (!u || typeof u !== 'object') return null+ const num = (v: unknown) => (typeof v === 'number' ? v : undefined)+ return {+ prompt_tokens: num(u.inputTokens ?? u.promptTokens ?? u.prompt_tokens),+ completion_tokens: num(+ u.outputTokens ?? u.completionTokens ?? u.completion_tokens+ ),+ total_tokens: num(u.totalTokens ?? u.total_tokens),+ }+}++export type StreamSink = {+ onText: (delta: string) => void+ onToolStart: (toolCallId: string, toolName: string) => void+ onToolArgsDelta: (toolCallId: string, delta: string) => void+ onToolCall: (call: PendingToolCall) => void+}++/**+ * Fold one `sendMessages` stream into a `StepResult`, reporting progress as it+ * goes. Reading to completion is what makes tool dispatch safe: results land on+ * a finished assistant message, never interleaved with one still streaming.+ */+export async function consumeStep(+ stream: ReadableStream<UIMessageChunk>,+ sink: StreamSink+): Promise<StepResult> {+ const reader = stream.getReader()+ const result: StepResult = {+ text: '',+ toolCalls: [],+ usage: null,+ aborted: false,+ }+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ const chunk = value as any+ switch (chunk.type) {+ case 'text-delta':+ result.text += chunk.delta+ sink.onText(chunk.delta)+ break+ case 'tool-input-start':+ sink.onToolStart(chunk.toolCallId, chunk.toolName)+ break+ case 'tool-input-delta':+ sink.onToolArgsDelta(chunk.toolCallId, chunk.inputTextDelta)+ break+ case 'tool-input-available': {+ const call: PendingToolCall = {+ toolCallId: chunk.toolCallId,+ toolName: chunk.toolName,+ input: chunk.input,+ }+ result.toolCalls.push(call)+ sink.onToolCall(call)+ break+ }+ case 'error':+ result.errorText = chunk.errorText+ break+ case 'abort':+ result.aborted = true+ break+ case 'finish':+ result.usage = usageOf(chunk.messageMetadata) ?? result.usage+ break+ default:+ break+ }+ }+ } finally {+ reader.releaseLock()+ }+ return result+}++/** Assemble the assistant message for a completed step, results included. */+export function assistantMessageFor(+ id: string,+ step: StepResult,+ outcomes: Map<string, ToolOutcome>+): UIMessage {+ const parts: any[] = []+ if (step.text) parts.push({ type: 'text', text: step.text })+ for (const call of step.toolCalls) {+ const outcome = outcomes.get(call.toolCallId)+ const part: any = {+ type: `tool-${call.toolName}`,+ toolCallId: call.toolCallId,+ input: call.input,+ state: outcome+ ? outcome.isError+ ? 'output-error'+ : 'output-available'+ : 'input-available',+ }+ if (outcome) {+ if (outcome.isError) part.errorText = outcome.output+ else part.output = outcome.output+ }+ parts.push(part)+ }+ return { id, role: 'assistant', parts } as UIMessage+}++/** Transcript rows for a completed step, for the Cowork run store. */+export function turnsFor(+ step: StepResult,+ outcomes: Map<string, ToolOutcome>+): CodeTurn[] {+ const turns: CodeTurn[] = []+ if (step.text) turns.push({ role: 'assistant', content: step.text })+ for (const call of step.toolCalls) {+ const outcome = outcomes.get(call.toolCallId)+ turns.push({+ role: 'tool',+ content: '',+ callId: call.toolCallId,+ name: call.toolName,+ args: call.input,+ result: outcome?.output ?? '',+ isError: outcome?.isError,+ diff: outcome?.diff,+ status: outcome ? 'done' : 'running',+ })+ }+ return turns+}++export type RunDeps = {+ /** One model turn. Returns the raw UI message stream. */+ sendStep: (+ messages: UIMessage[],+ signal: AbortSignal+ ) => Promise<ReadableStream<UIMessageChunk>>+ /** Run one tool call. Must resolve, never reject. */+ dispatch: (+ call: PendingToolCall,+ signal: AbortSignal+ ) => Promise<ToolOutcome>+ sink: StreamSink+ /** Called once per completed step with everything that step produced. */+ onStep: (info: {+ step: number+ result: StepResult+ turns: CodeTurn[]+ outcomes: Map<string, ToolOutcome>+ }) => void+ /** Monotonic ids for the assistant messages this run appends. */+ nextMessageId: () => string+}++export type RunOutcome = {+ messages: UIMessage[]+ steps: number+ usage: Usage | null+ sessionTokens: number+ stoppedBy: BudgetStop | 'error' | 'aborted' | 'done'+ errorText?: string+}++/**+ * Drive one user request to completion.+ *+ * Continues while the last step asked for tools, which is the only signal that+ * more work is pending. Stops cleanly on a cap rather than throwing: hitting the+ * step budget is routine on a long task, and the caller offers "Keep going".+ */+export async function runTurn(opts: {+ messages: UIMessage[]+ deps: RunDeps+ signal: AbortSignal+ maxSteps?: number+ /** Tokens already spent by this session, which the caps apply across. */+ sessionTokens?: number+}): Promise<RunOutcome> {+ const { deps, signal } = opts+ const maxSteps = opts.maxSteps ?? MAX_AGENT_STEPS+ const messages = [...opts.messages]+ let step = 0+ let sessionTokens = opts.sessionTokens ?? 0+ let usage: Usage | null = null++ for (;;) {+ if (signal.aborted) {+ return {+ messages,+ steps: step,+ usage,+ sessionTokens,+ stoppedBy: 'aborted',+ }+ }+ const overBudget = budgetExceeded({ step, sessionTokens }, maxSteps)+ if (overBudget) {+ return {+ messages,+ steps: step,+ usage,+ sessionTokens,+ stoppedBy: overBudget,+ }+ }++ // A snapshot, not the live array: the loop pushes to `messages` after the+ // stream is handed over, and the transport rewrites what it is given+ // (trimming, compaction) without expecting it to move underneath.+ const stream = await deps.sendStep([...messages], signal)+ const result = await consumeStep(stream, deps.sink)+ step += 1+ if (result.usage) {+ usage = result.usage+ sessionTokens += result.usage.total_tokens ?? 0+ }++ if (result.errorText) {+ messages.push(assistantMessageFor(deps.nextMessageId(), result, new Map()))+ deps.onStep({+ step,+ result,+ turns: turnsFor(result, new Map()),+ outcomes: new Map(),+ })+ return {+ messages,+ steps: step,+ usage,+ sessionTokens,+ stoppedBy: 'error',+ errorText: result.errorText,+ }+ }++ // Tools run one at a time: they share a workspace, and the progress+ // attribution in the UI assumes a single call in flight.+ const outcomes = new Map<string, ToolOutcome>()+ for (const call of result.toolCalls) {+ if (signal.aborted) {+ outcomes.set(call.toolCallId, {+ output: '(interrupted)',+ isError: true,+ })+ continue+ }+ outcomes.set(call.toolCallId, await deps.dispatch(call, signal))+ }++ messages.push(assistantMessageFor(deps.nextMessageId(), result, outcomes))+ deps.onStep({ step, result, turns: turnsFor(result, outcomes), outcomes })++ if (result.aborted || signal.aborted) {+ return {+ messages,+ steps: step,+ usage,+ sessionTokens,+ stoppedBy: 'aborted',+ }+ }+ // No tool calls means the model answered rather than asked for more work.+ if (result.toolCalls.length === 0) {+ return { messages, steps: step, usage, sessionTokens, stoppedBy: 'done' }+ }+ }+}++export const __testing = { handles, createHandle }diff --git a/web-app/src/lib/coworkTodo.ts b/web-app/src/lib/coworkTodo.tsnew file mode 100644index 000000000..6db6ebdec--- /dev/null+++ b/web-app/src/lib/coworkTodo.ts@@ -0,0 +1,296 @@+import type { TodoItem, TodoList, TodoPhase } from '@/types/codeSession'++/**+ * The `todo` tool's reducer, ported from `core/agent/todo.rs`.+ *+ * Kept behaviourally identical to the Rust version because both drive the same+ * tool schema and the same panel: task content is the stable id, tasks advance+ * in phase then task order, and exactly one task is in progress at a time.+ */++export type TodoOp =+ | 'init'+ | 'start'+ | 'done'+ | 'drop'+ | 'rm'+ | 'append'+ | 'view'++export type TodoArgs = {+ op?: string+ list?: Array<{ phase?: string; items?: string[] }>+ items?: string[]+ task?: string+ phase?: string+ all?: boolean+}++type Target =+ | { kind: 'task'; value: string }+ | { kind: 'phase'; value: string }+ | { kind: 'all' }++export type TodoResult = { list: TodoList; error?: string }++const EMPTY: TodoList = { phases: [] }++const clone = (list: TodoList): TodoList => ({+ phases: list.phases.map((p) => ({+ name: p.name,+ tasks: p.tasks.map((t) => ({ ...t })),+ })),+})++const allTasks = (list: TodoList) => list.phases.flatMap((p) => p.tasks)++const activeTask = (list: TodoList): TodoItem | undefined =>+ allTasks(list).find((t) => t.status === 'in_progress')++const isTerminal = (t: TodoItem) =>+ t.status === 'completed' || t.status === 'abandoned'++/**+ * After a mutation leaves nothing in progress, promote the earliest pending+ * task in phase then task order. This is what makes `done` advance the list+ * without the model having to call `start`.+ */+function promoteNext(list: TodoList): void {+ if (activeTask(list)) return+ for (const phase of list.phases) {+ const next = phase.tasks.find((t) => t.status === 'pending')+ if (next) {+ next.status = 'in_progress'+ return+ }+ }+}++function parseTarget(args: TodoArgs): Target | string {+ if (typeof args.task === 'string') return { kind: 'task', value: args.task }+ if (typeof args.phase === 'string') return { kind: 'phase', value: args.phase }+ if (args.all === true) return { kind: 'all' }+ return 'target requires exactly one of: task, phase, all'+}++function phasesFromArgs(args: TodoArgs): TodoPhase[] | string {+ if (Array.isArray(args.list)) {+ return args.list.map((entry) => ({+ name: entry.phase ?? '',+ tasks: (entry.items ?? []).map((content) => ({+ content,+ status: 'pending' as const,+ })),+ }))+ }+ if (Array.isArray(args.items)) {+ // A flat items array becomes one unnamed phase, matching the Rust form.+ return [+ {+ name: '',+ tasks: args.items.map((content) => ({+ content,+ status: 'pending' as const,+ })),+ },+ ]+ }+ return 'init requires `list` or `items`'+}++function validateInit(phases: TodoPhase[]): string | null {+ const names = new Set<string>()+ const contents = new Set<string>()+ for (const phase of phases) {+ if (names.has(phase.name)) return `duplicate phase name '${phase.name}'`+ names.add(phase.name)+ for (const task of phase.tasks) {+ if (!task.content.trim()) return 'task content must not be empty'+ // Content is the stable id, so a duplicate anywhere is ambiguous.+ if (contents.has(task.content)) {+ return `duplicate task '${task.content}'`+ }+ contents.add(task.content)+ }+ }+ return null+}++/**+ * Confirm a task is in progress. Refuses to jump ahead of open work, so the+ * list reflects the order the agent actually declared.+ */+function start(list: TodoList, content: string): string | null {+ const flat: Array<{ task: TodoItem }> = []+ for (const phase of list.phases) {+ for (const task of phase.tasks) flat.push({ task })+ }+ const index = flat.findIndex((e) => e.task.content === content)+ if (index === -1) return `unknown task '${content}'`++ const target = flat[index].task+ if (target.status === 'in_progress') return null+ if (target.status !== 'pending') return `task '${content}' is not pending`++ for (let i = 0; i < index; i += 1) {+ if (!isTerminal(flat[i].task)) {+ return `cannot start '${content}' before completing or abandoning '${flat[i].task.content}'`+ }+ }+ for (const { task } of flat) {+ if (task.status === 'in_progress') task.status = 'pending'+ }+ target.status = 'in_progress'+ return null+}++function setStatus(+ list: TodoList,+ target: Target,+ status: TodoItem['status']+): string | null {+ if (target.kind === 'task') {+ const task = allTasks(list).find((t) => t.content === target.value)+ if (!task) return `unknown task '${target.value}'`+ task.status = status+ } else if (target.kind === 'phase') {+ const phases = list.phases.filter((p) => p.name === target.value)+ if (phases.length === 0) return `unknown phase '${target.value}'`+ for (const phase of phases) {+ for (const task of phase.tasks) {+ // Already-terminal tasks are left alone rather than resurrected.+ if (!isTerminal(task)) task.status = status+ }+ }+ } else {+ for (const task of allTasks(list)) {+ if (!isTerminal(task)) task.status = status+ }+ }+ promoteNext(list)+ return null+}++function remove(list: TodoList, target: Target): string | null {+ if (target.kind === 'task') {+ if (!allTasks(list).some((t) => t.content === target.value)) {+ return `unknown task '${target.value}'`+ }+ for (const phase of list.phases) {+ phase.tasks = phase.tasks.filter((t) => t.content !== target.value)+ }+ } else if (target.kind === 'phase') {+ if (!list.phases.some((p) => p.name === target.value)) {+ return `unknown phase '${target.value}'`+ }+ list.phases = list.phases.filter((p) => p.name !== target.value)+ } else {+ list.phases = []+ }+ // Drop a phase left both empty and unnamed; a named one stays as a heading.+ list.phases = list.phases.filter((p) => p.tasks.length > 0 || p.name !== '')+ promoteNext(list)+ return null+}++function append(+ list: TodoList,+ phaseName: string,+ items: string[]+): string | null {+ const seen = new Set<string>()+ for (const content of items) {+ if (!content.trim()) return 'task content must not be empty'+ if (allTasks(list).some((t) => t.content === content)) {+ return `duplicate task '${content}'`+ }+ if (seen.has(content)) return `duplicate task '${content}' in append`+ seen.add(content)+ }+ let phase = list.phases.find((p) => p.name === phaseName)+ if (!phase) {+ phase = { name: phaseName, tasks: [] }+ list.phases.push(phase)+ }+ phase.tasks.push(+ ...items.map((content) => ({ content, status: 'pending' as const }))+ )+ promoteNext(list)+ return null+}++/**+ * Apply one operation. Never throws: a bad call comes back as an error string+ * the model can read and correct, alongside the unchanged list.+ */+export function applyTodoOp(+ current: TodoList | undefined,+ rawArgs: unknown+): TodoResult {+ const list = clone(current ?? EMPTY)+ const args = (rawArgs ?? {}) as TodoArgs+ const op = args.op as TodoOp | undefined++ if (!op) return { list, error: 'missing `op`' }+ if (op === 'view') return { list }++ if (op === 'init') {+ const phases = phasesFromArgs(args)+ if (typeof phases === 'string') return { list, error: phases }+ const invalid = validateInit(phases)+ if (invalid) return { list, error: invalid }+ const next: TodoList = { phases }+ promoteNext(next)+ return { list: next }+ }++ if (op === 'append') {+ const items = args.items+ if (!Array.isArray(items) || items.length === 0) {+ return { list, error: 'append requires `items`' }+ }+ const error = append(list, args.phase ?? '', items)+ return error ? { list: clone(current ?? EMPTY), error } : { list }+ }++ if (op === 'start') {+ if (typeof args.task !== 'string') {+ return { list, error: 'start requires `task`' }+ }+ const error = start(list, args.task)+ return error ? { list: clone(current ?? EMPTY), error } : { list }+ }++ const target = parseTarget(args)+ if (typeof target === 'string') return { list, error: target }++ if (op === 'done' || op === 'drop') {+ const error = setStatus(+ list,+ target,+ op === 'done' ? 'completed' : 'abandoned'+ )+ return error ? { list: clone(current ?? EMPTY), error } : { list }+ }++ if (op === 'rm') {+ const error = remove(list, target)+ return error ? { list: clone(current ?? EMPTY), error } : { list }+ }++ return { list, error: `unknown op '${op}'` }+}++/**+ * The tool result body: the whole resulting snapshot, matching+ * `todo.rs::render_result`, so a compacted history can still reconstruct the+ * list from the transcript alone.+ */+export function renderTodoResult(list: TodoList): string {+ return JSON.stringify(list)+}++export function todoProgress(list: TodoList): { done: number; total: number } {+ const tasks = allTasks(list)+ return { done: tasks.filter(isTerminal).length, total: tasks.length }+}diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsnew file mode 100644index 000000000..d4d1cacf1--- /dev/null+++ b/web-app/src/lib/coworkTools.ts@@ -0,0 +1,196 @@+/**+ * The tool set advertised to a Cowork run.+ *+ * Schemas for the built-ins come from Rust (`toolSchemas()`), so there is one+ * source of truth for what they accept. The three client-only tools below are+ * transcribed from their Rust counterparts (`todo.rs`, `interaction.rs`,+ * `subagent.rs`) so the CLI and the desktop advertise the same contract.+ */+import { jsonSchema, type Tool } from 'ai'+import { getAgentToolSchemas } from '@/lib/agentTools'++/** Tools that can mutate something. Withheld, and refused, in plan mode. */+export const PLAN_DENIED_TOOLS = new Set([+ 'write',+ 'edit',+ 'bash',+ 'memory_write',+ 'skill_write',+ 'task',+])++/** Named `todo` to match the Rust tool: the plan-mode addendum instructs the+ * model to call `todo` by name, so renaming it here breaks that prompt. */+export const TODO_TOOL_NAME = 'todo'+export const ASK_TOOL_NAME = 'ask'+export const TASK_TOOL_NAME = 'task'++/** Tools Cowork dispatches itself rather than handing to the Rust plugin. */+export const CLIENT_TOOL_NAMES = new Set([+ TODO_TOOL_NAME,+ ASK_TOOL_NAME,+ TASK_TOOL_NAME,+])++const todoTool: Tool = {+ description:+ 'Manage the canonical session todo list: init/start/done/drop/rm/append/view. One call applies one operation. Tasks advance automatically in phase and task order after done or drop; start only confirms the current task. init takes `list` or `items`, never `phase`/`task` directly.',+ inputSchema: jsonSchema({+ type: 'object',+ properties: {+ op: {+ type: 'string',+ enum: ['init', 'start', 'done', 'drop', 'rm', 'append', 'view'],+ },+ list: {+ type: 'array',+ description: 'For init: [{phase, items}]',+ items: {+ type: 'object',+ properties: {+ phase: { type: 'string' },+ items: { type: 'array', items: { type: 'string' } },+ },+ required: ['phase', 'items'],+ },+ },+ items: {+ type: 'array',+ description: 'For init (flat, single unnamed phase) or append.',+ items: { type: 'string' },+ },+ task: { type: 'string' },+ phase: { type: 'string' },+ all: { type: 'boolean' },+ },+ required: ['op'],+ }),+} as Tool++const askTool: Tool = {+ description:+ 'Ask the user one or more structured questions. Use only when the answer materially changes the work.',+ inputSchema: jsonSchema({+ type: 'object',+ properties: {+ questions: {+ type: 'array',+ minItems: 1,+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ question: { type: 'string' },+ options: {+ type: 'array',+ minItems: 2,+ maxItems: 5,+ items: {+ type: 'object',+ properties: {+ label: { type: 'string' },+ description: { type: 'string' },+ },+ required: ['label'],+ additionalProperties: false,+ },+ },+ multi: { type: 'boolean' },+ recommended: { type: 'integer', minimum: 0 },+ },+ required: ['id', 'question', 'options'],+ additionalProperties: false,+ },+ },+ },+ required: ['questions'],+ additionalProperties: false,+ }),+} as Tool++function taskTool(subagentNames: string[]): Tool {+ const known = subagentNames.length+ ? ` Saved subagents: ${subagentNames.join(', ')}.`+ : ''+ return {+ description:+ 'Run a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Returns its final answer.' ++ known,+ inputSchema: jsonSchema({+ type: 'object',+ properties: {+ subagent_name: { type: 'string' },+ description: { type: 'string' },+ system_prompt: {+ type: 'string',+ description: 'For a one-off subagent with no saved definition.',+ },+ allowed_tools: { type: 'array', items: { type: 'string' } },+ },+ required: ['subagent_name', 'description'],+ additionalProperties: false,+ }),+ } as Tool+}++export type CoworkToolOptions = {+ planMode: boolean+ subagentNames: string[]+ /** Depth 1+ cannot spawn further subagents; mirrors the Rust loop's cap. */+ allowSubagents: boolean+}++/**+ * The signature that must stay stable for the KV prefix to survive a run.+ *+ * Any change to advertised tool JSON changes the prompt prefix, and an agent+ * turn re-prefills 20+ times — so the record is frozen for a run's lifetime and+ * a mode change only takes effect on the next message.+ */+export function coworkToolSignature(+ opts: CoworkToolOptions,+ sandboxEnforces: boolean+): string {+ return [+ opts.planMode ? 'plan' : 'normal',+ sandboxEnforces ? 'jail' : 'nojail',+ opts.allowSubagents ? opts.subagentNames.join(',') : 'nosub',+ ].join('|')+}++/** Filter a name list down to what this mode may call. */+export function allowedToolNames(+ names: string[],+ opts: CoworkToolOptions+): string[] {+ return names.filter((name) => {+ if (opts.planMode && PLAN_DENIED_TOOLS.has(name)) return false+ if (name === TASK_TOOL_NAME && !opts.allowSubagents) return false+ return true+ })+}++export async function buildCoworkTools(+ opts: CoworkToolOptions+): Promise<Record<string, Tool>> {+ const schemas = await getAgentToolSchemas()+ const tools: Record<string, Tool> = {}++ for (const s of schemas) {+ const name = s.function.name+ if (opts.planMode && PLAN_DENIED_TOOLS.has(name)) continue+ tools[name] = {+ description: s.function.description,+ inputSchema: jsonSchema(+ s.function.parameters as Record<string, unknown>+ ),+ } as Tool+ }++ tools[TODO_TOOL_NAME] = todoTool+ tools[ASK_TOOL_NAME] = askTool+ if (opts.allowSubagents && !opts.planMode) {+ tools[TASK_TOOL_NAME] = taskTool(opts.subagentNames)+ }+ return tools+}diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.tsnew file mode 100644index 000000000..c0a201dfd--- /dev/null+++ b/web-app/src/lib/coworkTransport.ts@@ -0,0 +1,109 @@+import type { Tool, UIMessage } from 'ai'+import { CustomChatTransport } from '@/lib/custom-chat-transport'+import { COWORK_SLOT_ID } from '@/constants/models'+import { sandboxEnforces } from '@/lib/agentTools'+import {+ buildCoworkTools,+ coworkToolSignature,+ type CoworkToolOptions,+} from '@/lib/coworkTools'+import { buildCoworkSystemPrompt } from '@/lib/coworkPrompt'++export type CoworkRunConfig = CoworkToolOptions & {+ workspacePath: string | null+ readOnlyFolder: string | null+}++/**+ * The chat transport, re-aimed at an agent run.+ *+ * Everything expensive is inherited: model creation and its abort-during-load+ * unload, the sampling/reasoning merge, attachment encoding, tool-call repair,+ * and the usage metadata. Only four things differ, and each is a seam on the+ * parent.+ */+export class CoworkChatTransport extends CustomChatTransport {+ private config: CoworkRunConfig+ /**+ * The advertised tool set, frozen for a run's lifetime.+ *+ * An agent turn calls `sendMessages` many times, and any change to the tool+ * JSON changes the prompt prefix, discarding the KV cache on every step. A+ * mode change therefore applies at the next message, not mid-run.+ */+ private frozenTools: Record<string, Tool> | null = null+ /** Last set actually built, kept across runs so an unchanged config does not+ * pay for a rebuild at every run boundary. */+ private builtTools: Record<string, Tool> | null = null+ private builtSig = ''++ constructor(sessionId: string, config: CoworkRunConfig) {+ super(undefined, sessionId)+ this.config = config+ }++ /** Applied at the next run: changing it mid-run would invalidate the prefix. */+ setConfig(config: CoworkRunConfig) {+ this.config = config+ }++ /** Drop the freeze so the next run re-reads the config. */+ unfreezeTools() {+ this.frozenTools = null+ }++ /** Cowork gets its own llama.cpp slot: sharing chat's would evict the viewed+ * thread's prefix on every one of this turn's many prefills, and vice versa. */+ protected override slotParams(threadId?: string): Record<string, unknown> {+ return { id_slot: COWORK_SLOT_ID, thread_id: `cowork:${threadId ?? ''}` }+ }++ /**+ * Cowork's own prompt replaces the chat one wholesale — the agent-tools and+ * web-search blurbs are written for a chat that occasionally reaches for a+ * tool, not for a run whose whole purpose is tool use. The attached-files+ * instruction is kept: a pasted document is otherwise never explained.+ */+ protected override buildSystemPrompt(messages: UIMessage[]): string {+ const base = buildCoworkSystemPrompt({+ workspacePath: this.config.workspacePath,+ readOnlyFolder: this.config.readOnlyFolder,+ planMode: this.config.planMode,+ bashAvailable: sandboxEnforces(),+ subagentNames: this.config.allowSubagents ? this.config.subagentNames : [],+ })+ const files = this.buildFilesSystemInstruction(messages)+ return files.trim().length > 0 ? `${base}\n\n${files}` : base+ }++ /**+ * An agent run legitimately reaches a window whose only user turn is far+ * back, and tool results are the recent traffic. The parent's guard exists+ * for chat, where a window with no user turn means eviction ate the question;+ * here it would abort a healthy long run.+ */+ protected override assertSendable(): void {}++ override async refreshTools(): Promise<void> {+ // Frozen means frozen: once a run is under way the advertised set is fixed+ // even if the config changed, because rebuilding it would change the tool+ // JSON and discard the prompt prefix on the next of this turn's many+ // prefills. `unfreezeTools()` at the run boundary is what lets it move.+ if (this.frozenTools) {+ this.tools = this.frozenTools+ return+ }+ const sig = coworkToolSignature(this.config, sandboxEnforces())+ // Between runs, skip the rebuild when nothing that shapes the set changed.+ if (this.builtTools && this.builtSig === sig) {+ this.frozenTools = this.builtTools+ this.tools = this.builtTools+ return+ }+ const tools = await buildCoworkTools(this.config)+ this.builtTools = tools+ this.builtSig = sig+ this.frozenTools = tools+ this.tools = tools+ }+}diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 709be989e..556b66fc9 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -777,7 +777,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {public model: LanguageModel | null = nullprivate routerModel: LanguageModel | null = nullprivate routerModelKey = ''- private tools: Record<string, Tool> = {}+ protected tools: Record<string, Tool> = {}// Smart tool routing selects tools from the latest user message, which would// change the tool set (and thus the cached prompt prefix) every turn. Freeze// the routed set for the thread's lifetime so the prefix stays stable;@@ -788,9 +788,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {private hasDocuments = falseprivate modelSupportsTools = falseprivate ragFeatureAvailable = false- private systemMessage?: string- private serviceHub: ServiceHub | null- private threadId?: string+ protected systemMessage?: string+ protected serviceHub: ServiceHub | null+ protected threadId?: stringprivate continueFromContent: ContinuationContent | null = null/** Latest user message text — used by the MCP orchestrator for tool routing. */private lastUserMessage = ''@@ -863,6 +863,46 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {* Filters out disabled tools based on thread settings* @private*/+ /**+ * llama.cpp slot pin for this surface. Chat reuses one slot per thread so its+ * KV prefix survives across turns; other surfaces override to claim their own+ * and avoid evicting it. See CHAT_SLOT_ID.+ */+ protected slotParams(threadId?: string): Record<string, unknown> {+ return { id_slot: CHAT_SLOT_ID, thread_id: threadId }+ }++ /**+ * The system turn for this surface. Whitespace-only prompts collapse to+ * undefined so we don't send a useless system turn that some chat templates+ * still wrap into special tokens.+ */+ protected buildSystemPrompt(messages: UIMessage[]): string | undefined {+ const raw =+ [+ this.systemMessage,+ this.buildFilesSystemInstruction(messages),+ this.buildWebSearchSystemInstruction(),+ this.buildAgentToolsSystemInstruction(),+ ]+ .filter((s) => typeof s === 'string' && s.trim().length > 0)+ .join('\n\n') || undefined+ return typeof raw === 'string' && raw.trim().length > 0 ? raw : undefined+ }++ /**+ * Many chat templates (Qwen3.5+) reject a window with no genuine user query+ * and throw a cryptic Jinja error. Fail early with a clear message when+ * deletion/eviction has left no real user turn to respond to.+ */+ protected assertSendable(messages: UIMessage[]): void {+ if (!hasGenuineUserQuery(messages)) {+ throw new Error(+ 'This conversation has no user message to respond to. Add a message, or regenerate from a turn that includes your question.'+ )+ }+ }+async refreshTools(abortSignal?: AbortSignal) {if (!this.serviceHub) {this.tools = {}@@ -1257,8 +1297,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// including in a later session. It is stripped before the request// reaches llama.cpp.if (providerId === 'llamacpp') {- mergedParams.id_slot = CHAT_SLOT_ID- mergedParams.thread_id = threadId+ Object.assign(mergedParams, this.slotParams(threadId))}this.model = await this.createModelOrAbort(modelId,@@ -1295,24 +1334,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const selectedModel = useModelProvider.getState().selectedModel- const filesInstruction = this.buildFilesSystemInstruction(messagesToConvert)- const webSearchInstruction = this.buildWebSearchSystemInstruction()- const agentToolsInstruction = this.buildAgentToolsSystemInstruction()- const rawSystem =- [- this.systemMessage,- filesInstruction,- webSearchInstruction,- agentToolsInstruction,- ]- .filter((s) => typeof s === 'string' && s.trim().length > 0)- .join('\n\n') || undefined- // Drop whitespace-only system prompts so we don't send a useless system- // turn that some chat templates still wrap into special tokens.- const effectiveSystem =- typeof rawSystem === 'string' && rawSystem.trim().length > 0- ? rawSystem- : undefined+ const effectiveSystem = this.buildSystemPrompt(messagesToConvert)const maxOutputTokens: number | undefined = (() => {const raw = inferenceParams.max_output_tokens ?? inferenceParams.max_tokens@@ -1396,11 +1418,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// Many chat templates (Qwen3.5+) reject a window with no genuine user query// and throw a cryptic Jinja error. Fail early with a clear message when// deletion/eviction has left no real user turn to respond to.- if (!hasGenuineUserQuery(effectiveMessages)) {- throw new Error(- 'This conversation has no user message to respond to. Add a message, or regenerate from a turn that includes your question.'- )- }+ this.assertSendable(effectiveMessages)const modelSupportsVision =selectedModel?.capabilities?.includes('vision') ?? false