agent-canvas 0.9.0-dev.13 → 0.9.0-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +28 -0
  2. package/bin/agent-canvas.ts +8 -1
  3. package/bin/lib/cli-auth.ts +31 -0
  4. package/bin/lib/commands/daemon.ts +2 -1
  5. package/bin/lib/commands/exec.ts +5 -4
  6. package/bin/lib/commands/fetch.ts +4 -4
  7. package/bin/lib/commands/push.ts +3 -2
  8. package/bin/lib/commands/reply.ts +45 -0
  9. package/bin/lib/commands/review.ts +4 -2
  10. package/bin/lib/commands/watch.ts +100 -5
  11. package/bin/lib/helpers.ts +121 -43
  12. package/bin/lib/instructions/component-download.md +28 -0
  13. package/bin/lib/instructions/component-filedrop.md +50 -0
  14. package/bin/lib/instructions/overview.md +41 -1
  15. package/bin/lib/instructions/template-dashboard.md +177 -0
  16. package/bin/lib/instructions/template-slides.md +196 -0
  17. package/bin/lib/instructions/theming.md +25 -0
  18. package/daemon/client/App.tsx +17 -5
  19. package/daemon/client/clientApi.ts +64 -5
  20. package/daemon/client/components/Download.tsx +28 -0
  21. package/daemon/client/components/FileDrop.tsx +164 -0
  22. package/daemon/client/components/index.ts +3 -1
  23. package/daemon/client/threadStore.ts +70 -0
  24. package/daemon/dist/client.css +1 -1
  25. package/daemon/dist/client.js +57 -56
  26. package/daemon/dist/components.js +52 -49
  27. package/daemon/src/admission.ts +102 -0
  28. package/daemon/src/assets.ts +16 -0
  29. package/daemon/src/components.ts +6 -1
  30. package/daemon/src/handlers/api.ts +7 -4
  31. package/daemon/src/handlers/assets.ts +126 -0
  32. package/daemon/src/handlers/files.ts +124 -19
  33. package/daemon/src/handlers/static.ts +65 -1
  34. package/daemon/src/handlers/theme.ts +150 -0
  35. package/daemon/src/handlers/threads.ts +93 -0
  36. package/daemon/src/review/server.ts +1 -1
  37. package/daemon/src/server.ts +81 -47
  38. package/daemon/src/threads.ts +132 -0
  39. package/package.json +4 -4
  40. package/skills/canvas/SKILL.md +5 -0
  41. package/types/bin/lib/cli-auth.d.ts +9 -0
  42. package/types/bin/lib/commands/reply.d.ts +2 -0
  43. package/types/bin/lib/commands/watch.d.ts +3 -1
  44. package/types/bin/lib/helpers.d.ts +102 -0
  45. package/types/daemon/client/clientApi.d.ts +14 -1
  46. package/types/daemon/client/components/Download.d.ts +9 -0
  47. package/types/daemon/client/components/FileDrop.d.ts +12 -0
  48. package/types/daemon/client/components/index.d.ts +2 -0
  49. package/types/daemon/client/threadStore.d.ts +15 -0
  50. package/types/daemon/src/admission.d.ts +24 -0
  51. package/types/daemon/src/assets.d.ts +23 -0
  52. package/types/daemon/src/components.d.ts +3 -1
  53. package/types/daemon/src/handlers/assets.d.ts +14 -0
  54. package/types/daemon/src/handlers/files.d.ts +8 -2
  55. package/types/daemon/src/handlers/static.d.ts +16 -0
  56. package/types/daemon/src/handlers/theme.d.ts +18 -0
  57. package/types/daemon/src/handlers/threads.d.ts +19 -0
  58. package/types/daemon/src/review/model.d.ts +24 -24
  59. package/types/daemon/src/review/remote.d.ts +8 -8
  60. package/types/daemon/src/review/server.d.ts +2 -0
  61. package/types/daemon/src/threads.d.ts +109 -0
@@ -0,0 +1,150 @@
1
+ import type { SessionManager } from '@fabrika/canvas-kernel/server'
2
+ import { jsonResponse, type Route } from '@fabrika/daemon-kit'
3
+ import { existsSync, readFileSync, realpathSync, statSync } from 'fs'
4
+ import { isAbsolute, join, relative, sep } from 'path'
5
+
6
+ /**
7
+ * A project's brand for its canvases: `<projectRoot>/.agent-canvas/theme.css`, served after the base theme. Only
8
+ * `--color-*` and `--font-*` custom properties on `:root` or a `[data-theme]` mode are accepted, and the daemon serves
9
+ * its own rebuild of them, never the file's text, so a theme cannot load a URL, import a stylesheet or style the page.
10
+ */
11
+
12
+ export const PROJECT_THEME_PATH = join('.agent-canvas', 'theme.css')
13
+ const MAX_THEME_BYTES = 64 * 1024
14
+ const MAX_VALUE_LENGTH = 200
15
+
16
+ const SELECTORS = new Map([
17
+ [':root', ':root'],
18
+ ['[data-theme="light"]', '[data-theme="light"]'],
19
+ ["[data-theme='light']", '[data-theme="light"]'],
20
+ ['[data-theme=light]', '[data-theme="light"]'],
21
+ ['[data-theme="dark"]', '[data-theme="dark"]'],
22
+ ["[data-theme='dark']", '[data-theme="dark"]'],
23
+ ['[data-theme=dark]', '[data-theme="dark"]'],
24
+ ])
25
+ const PROPERTY_RE = /^--(?:color|font)-[a-z0-9]+(?:-[a-z0-9]+)*$/
26
+ // Colours and font stacks need no more; no `;`, braces, backslash escapes or `@`.
27
+ const VALUE_RE = /^[A-Za-z0-9#%.,()'" +\-/]+$/
28
+ // Functions that fetch or embed a resource.
29
+ const FETCHING_RE = /\b(?:url|image|image-set|cross-fade|element|src)\s*\(/i
30
+ // No quantifier here can match the same text as another, so a failed match stays linear.
31
+ const RULE_RE = /([^{}]*)\{([^{}]*)\}/y
32
+ const WHITESPACE_RE = /\s*/y
33
+
34
+ export type ThemeResult = { ok: true; css: string } | { ok: false; error: string }
35
+
36
+ /** Parentheses nest and close, and a quote closes before any parenthesis around it does. */
37
+ function balanced(value: string): boolean {
38
+ const open: string[] = []
39
+ for (const char of value) {
40
+ const top = open.at(-1)
41
+ if (top === "'" || top === '"') {
42
+ if (char === top) open.pop()
43
+ } else if (char === '(' || char === "'" || char === '"') {
44
+ open.push(char)
45
+ } else if (char === ')') {
46
+ if (open.pop() !== '(') return false
47
+ }
48
+ }
49
+ return open.length === 0
50
+ }
51
+
52
+ /** Comments as spaces of the same length, so offsets still point into the file; null for an unclosed one. */
53
+ function blankComments(source: string): string | null {
54
+ let text = ''
55
+ let position = 0
56
+ for (;;) {
57
+ const start = source.indexOf('/*', position)
58
+ if (start < 0) return text + source.slice(position)
59
+ const end = source.indexOf('*/', start + 2)
60
+ if (end < 0) return null
61
+ text += source.slice(position, start) + source.slice(start, end + 2).replace(/[^\n]/g, ' ')
62
+ position = end + 2
63
+ }
64
+ }
65
+
66
+ /** The project theme as the daemon serves it, or why it is refused. A refused theme is not served at all. */
67
+ export function parseProjectTheme(source: string): ThemeResult {
68
+ const text = blankComments(source)
69
+ if (text === null) return { ok: false, error: 'a comment is not closed' }
70
+ // Errors name a line and at most an accepted property name, never a value: the reason reaches the page and the log.
71
+ const lineAt = (offset: number) => text.slice(0, offset).split('\n').length
72
+ const rules: string[] = []
73
+ let position = 0
74
+ for (;;) {
75
+ WHITESPACE_RE.lastIndex = position
76
+ WHITESPACE_RE.exec(text)
77
+ position = WHITESPACE_RE.lastIndex
78
+ if (position >= text.length) break
79
+ RULE_RE.lastIndex = position
80
+ const match = RULE_RE.exec(text)
81
+ if (match === null) return { ok: false, error: `line ${lineAt(position)}: only rules of the form "selector { --color-…: value; }" are allowed` }
82
+ const [, selectorList = '', body = ''] = match
83
+ const selectors: string[] = []
84
+ for (const raw of selectorList.split(',')) {
85
+ const selector = SELECTORS.get(raw.trim().replace(/\s+/g, ''))
86
+ if (selector === undefined) {
87
+ return { ok: false, error: `line ${lineAt(position)}: only :root and [data-theme="light"|"dark"] selectors are allowed` }
88
+ }
89
+ selectors.push(selector)
90
+ }
91
+ const bodyStart = match.index + selectorList.length + 1
92
+ const declarations: string[] = []
93
+ let offset = bodyStart
94
+ for (const raw of body.split(';')) {
95
+ const at = offset + raw.length - raw.trimStart().length
96
+ offset += raw.length + 1
97
+ if (raw.trim() === '') continue
98
+ const colon = raw.indexOf(':')
99
+ const property = raw.slice(0, colon).trim()
100
+ const value = raw.slice(colon + 1).trim()
101
+ if (colon < 0 || !PROPERTY_RE.test(property)) return { ok: false, error: `line ${lineAt(at)}: only --color-* and --font-* properties are allowed` }
102
+ if (value === '' || value.length > MAX_VALUE_LENGTH || !VALUE_RE.test(value) || FETCHING_RE.test(value) || !balanced(value)) {
103
+ return { ok: false, error: `line ${lineAt(at)}: the value of ${property} is not a plain colour or font list` }
104
+ }
105
+ declarations.push(` ${property}: ${value};`)
106
+ }
107
+ rules.push(`${selectors.join(', ')} {\n${declarations.join('\n')}\n}`)
108
+ position = RULE_RE.lastIndex
109
+ }
110
+ return { ok: true, css: rules.length === 0 ? '' : `${rules.join('\n')}\n` }
111
+ }
112
+
113
+ export function createThemeHandlers(sessionManager: SessionManager): Route[] {
114
+ function handleTheme(_req: Request, _url: URL, match: URLPatternResult): Response {
115
+ const session = sessionManager.get(match.pathname.groups['id'] ?? '')
116
+ if (!session) return jsonResponse({ error: 'Session not found' }, 404)
117
+ const path = join(session.projectRoot, PROJECT_THEME_PATH)
118
+ // No project theme: the base theme stands.
119
+ if (!existsSync(path)) return css('')
120
+ let source: string
121
+ try {
122
+ // A symlink may not lead out of the project, e.g. into the daemon's own state.
123
+ const real = relative(realpathSync(session.projectRoot), realpathSync(path))
124
+ if (real === '..' || real.startsWith(`..${sep}`) || isAbsolute(real)) {
125
+ return jsonResponse({ error: `${PROJECT_THEME_PATH} leads outside the project` }, 422)
126
+ }
127
+ const stat = statSync(path)
128
+ if (!stat.isFile()) return jsonResponse({ error: `${PROJECT_THEME_PATH} is not a file` }, 422)
129
+ if (stat.size > MAX_THEME_BYTES) return jsonResponse({ error: `${PROJECT_THEME_PATH} is larger than ${MAX_THEME_BYTES / 1024} KB` }, 422)
130
+ source = readFileSync(path, 'utf-8')
131
+ } catch (error) {
132
+ console.error(`[agent-canvas] cannot read ${path}:`, error)
133
+ return jsonResponse({ error: `${PROJECT_THEME_PATH} could not be read` }, 500)
134
+ }
135
+ const theme = parseProjectTheme(source)
136
+ if (!theme.ok) {
137
+ console.error(`[agent-canvas] ${path} refused: ${theme.error}`)
138
+ return jsonResponse({ error: `${PROJECT_THEME_PATH}: ${theme.error}` }, 422)
139
+ }
140
+ return css(theme.css)
141
+ }
142
+
143
+ return [{ method: 'GET', pattern: new URLPattern({ pathname: '/api/session/:id/theme.css' }), handler: handleTheme }]
144
+ }
145
+
146
+ function css(body: string): Response {
147
+ return new Response(body, {
148
+ headers: { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
149
+ })
150
+ }
@@ -0,0 +1,93 @@
1
+ import { jsonResponse, type Route } from '@fabrika/daemon-kit'
2
+ import { errorMessage } from '../../client/errorMessage'
3
+ import { parseBody } from '../review/server'
4
+ import { ReviewError } from '../review/threads'
5
+ import { agentReplyBodySchema, type CanvasThreadStore, resolvedBodySchema, threadRepliesMarkdown, userReplyBodySchema } from '../threads'
6
+
7
+ export interface ThreadRoutesContext {
8
+ store: CanvasThreadStore
9
+ /** Sends the session's threads to its browsers. */
10
+ broadcast: (sessionId: string, frame: { type: 'threads'; threads: unknown }) => void
11
+ /** Tells the session's waiting CLI that the user answered a thread. */
12
+ notifyWaiters: (sessionId: string, frame: { type: 'thread-queued' }) => void
13
+ }
14
+
15
+ /**
16
+ * Threads on submitted annotations. `reply` and `claim` are the CLI's (admission requires its capability); the
17
+ * browser lists threads, answers them and resolves them.
18
+ */
19
+ export function createThreadHandlers(ctx: ThreadRoutesContext): Route[] {
20
+ const { store } = ctx
21
+
22
+ function publish(sessionId: string): void {
23
+ ctx.broadcast(sessionId, { type: 'threads', threads: store.list(sessionId) })
24
+ }
25
+
26
+ async function answer(work: () => Response | Promise<Response>): Promise<Response> {
27
+ try {
28
+ return await work()
29
+ } catch (error) {
30
+ if (error instanceof ReviewError) return jsonResponse({ error: error.message }, error.status)
31
+ return jsonResponse({ error: errorMessage(error) }, 500)
32
+ }
33
+ }
34
+
35
+ const sessionOf = (match: URLPatternResult) => match.pathname.groups['id'] ?? ''
36
+ const threadOf = (match: URLPatternResult) => match.pathname.groups['thread'] ?? ''
37
+
38
+ return [
39
+ {
40
+ method: 'GET',
41
+ pattern: new URLPattern({ pathname: '/api/session/:id/threads' }),
42
+ handler: (_req, _url, match) => answer(() => jsonResponse({ threads: store.list(sessionOf(match)) })),
43
+ },
44
+ {
45
+ method: 'POST',
46
+ pattern: new URLPattern({ pathname: '/api/session/:id/threads/claim' }),
47
+ handler: (_req, _url, match) =>
48
+ answer(() => {
49
+ const sessionId = sessionOf(match)
50
+ const claimed = store.claimQueued(sessionId)
51
+ if (claimed.length > 0) publish(sessionId)
52
+ return jsonResponse({ markdown: claimed.length > 0 ? threadRepliesMarkdown(claimed) : null })
53
+ }),
54
+ },
55
+ {
56
+ method: 'POST',
57
+ pattern: new URLPattern({ pathname: '/api/session/:id/threads/:thread/reply' }),
58
+ handler: (req, _url, match) =>
59
+ answer(async () => {
60
+ const sessionId = sessionOf(match)
61
+ const body = await parseBody(req, agentReplyBodySchema)
62
+ const thread = store.agentReply(sessionId, threadOf(match), body.body, body.resolve)
63
+ publish(sessionId)
64
+ return jsonResponse({ thread })
65
+ }),
66
+ },
67
+ {
68
+ method: 'POST',
69
+ pattern: new URLPattern({ pathname: '/api/session/:id/threads/:thread/comments' }),
70
+ handler: (req, _url, match) =>
71
+ answer(async () => {
72
+ const sessionId = sessionOf(match)
73
+ const body = await parseBody(req, userReplyBodySchema)
74
+ const thread = store.userReply(sessionId, threadOf(match), body.body)
75
+ publish(sessionId)
76
+ ctx.notifyWaiters(sessionId, { type: 'thread-queued' })
77
+ return jsonResponse({ thread })
78
+ }),
79
+ },
80
+ {
81
+ method: 'POST',
82
+ pattern: new URLPattern({ pathname: '/api/session/:id/threads/:thread/resolved' }),
83
+ handler: (req, _url, match) =>
84
+ answer(async () => {
85
+ const sessionId = sessionOf(match)
86
+ const body = await parseBody(req, resolvedBodySchema)
87
+ const thread = store.setResolved(sessionId, threadOf(match), body.resolved)
88
+ publish(sessionId)
89
+ return jsonResponse({ thread })
90
+ }),
91
+ },
92
+ ]
93
+ }
@@ -34,7 +34,7 @@ function corsHeaders(origin: string): Record<string, string> {
34
34
  }
35
35
  }
36
36
 
37
- async function parseBody<T extends z.ZodTypeAny>(req: Request, schema: T): Promise<z.infer<T>> {
37
+ export async function parseBody<T extends z.ZodTypeAny>(req: Request, schema: T): Promise<z.infer<T>> {
38
38
  let body: unknown
39
39
  try {
40
40
  body = await req.json()
@@ -3,15 +3,20 @@ import { corsHeaders, dispatch, jsonResponse } from '@fabrika/daemon-kit'
3
3
  import { randomBytes } from 'crypto'
4
4
  import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
5
5
  import { dirname, join } from 'path'
6
+ import { admitRequest } from './admission'
6
7
  import { createApiHandlers } from './handlers/api'
8
+ import { createAssetHandlers } from './handlers/assets'
7
9
  import { createFileHandlers } from './handlers/files'
8
- import { createStaticHandlers } from './handlers/static'
10
+ import { createStaticHandlers, serveErrorOptions, withDefaultCsp } from './handlers/static'
11
+ import { createThemeHandlers } from './handlers/theme'
12
+ import { createThreadHandlers } from './handlers/threads'
9
13
  import { createUploadHandlers } from './handlers/uploads'
10
- import { CLI_AUTH_FILE, PID_FILE, REVIEWS_DIR, SESSIONS_DIR, TEMP_DIR } from './paths'
14
+ import { CLI_AUTH_FILE, DATA_DIR, PID_FILE, REVIEWS_DIR, SESSIONS_DIR, TEMP_DIR } from './paths'
11
15
  import { startRemoteFeedbackPoller } from './remote-feedback'
12
16
  import { ReviewProxies } from './review/proxy'
13
17
  import { createReviewServer, type ReviewSocketData } from './review/server'
14
18
  import { ReviewStore } from './review/store'
19
+ import { CanvasThreadStore } from './threads'
15
20
 
16
21
  const PORT = parseInt(process.env.CANVAS_PORT || '19400', 10)
17
22
  const VERSION = JSON.parse(readFileSync(join(dirname(import.meta.dir), '..', 'package.json'), 'utf-8')).version as string
@@ -50,58 +55,78 @@ const routes = [
50
55
  version: VERSION,
51
56
  cliAuthToken,
52
57
  }),
53
- ...createFileHandlers(sessionManager),
58
+ // The file routes never return the daemon's own state, the CLI capability included.
59
+ ...createFileHandlers(sessionManager, { deniedRoots: [TEMP_DIR, DATA_DIR] }),
54
60
  ...createUploadHandlers(sessionManager),
61
+ ...createAssetHandlers(sessionManager),
62
+ ...createThreadHandlers({
63
+ store: new CanvasThreadStore(sessionManager),
64
+ broadcast: wsManager.broadcast,
65
+ notifyWaiters: wsManager.notifyWaiters,
66
+ }),
67
+ ...createThemeHandlers(sessionManager),
55
68
  ...createStaticHandlers(),
56
69
  ]
57
70
 
71
+ type Upgrader = { upgrade(req: Request, options: { data: SocketData }): boolean }
72
+
73
+ function handle(req: Request, server: Upgrader): Response | Promise<Response> | undefined {
74
+ const url = new URL(req.url)
75
+
76
+ const refusal = admitRequest(req, url, { port: PORT, cliAuthToken })
77
+ if (refusal !== null) return refusal
78
+
79
+ // Review mode answers its own preflights: the application under review runs on another port.
80
+ const reviewResponse = review.fetch(req, url, server)
81
+ if (reviewResponse === 'upgraded') return undefined
82
+ if (reviewResponse !== null) return reviewResponse
83
+
84
+ // CORS preflight
85
+ if (req.method === 'OPTIONS') {
86
+ return new Response(null, { status: 204, headers: corsHeaders(PORT) })
87
+ }
88
+
89
+ // WebSocket upgrade: /ws/session/:id
90
+ const wsBrowserMatch = url.pathname.match(/^\/ws\/session\/([^/]+)$/)
91
+ if (wsBrowserMatch) {
92
+ const upgraded = server.upgrade(req, { data: { type: 'browser', sessionId: wsBrowserMatch[1] } })
93
+ if (!upgraded) return new Response('WebSocket upgrade failed', { status: 400 })
94
+ return undefined
95
+ }
96
+
97
+ // WebSocket upgrade: /ws/wait/:id
98
+ const wsWaitMatch = url.pathname.match(/^\/ws\/wait\/([^/]+)$/)
99
+ if (wsWaitMatch) {
100
+ const upgraded = server.upgrade(req, { data: { type: 'wait', sessionId: wsWaitMatch[1] } })
101
+ if (!upgraded) return new Response('WebSocket upgrade failed', { status: 400 })
102
+ return undefined
103
+ }
104
+
105
+ // Route dispatch
106
+ const response = dispatch(routes, req, url)
107
+ if (response) return response
108
+
109
+ // Root redirect
110
+ if (url.pathname === '/' && req.method === 'GET') {
111
+ const sessions = sessionManager.list()
112
+ if (sessions.length > 0) {
113
+ const latest = sessions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0]
114
+ return Response.redirect(`/s/${latest.id}`, 302)
115
+ }
116
+ return jsonResponse({ message: 'No active sessions', sessions: [] })
117
+ }
118
+
119
+ return jsonResponse({ error: 'Not found' }, 404)
120
+ }
121
+
58
122
  const server = Bun.serve<SocketData>({
59
123
  port: PORT,
60
124
  hostname: 'localhost',
125
+ ...serveErrorOptions,
61
126
  fetch(req, server) {
62
- const url = new URL(req.url)
63
-
64
- // Review mode answers its own preflights: the application under review runs on another port.
65
- const reviewResponse = review.fetch(req, url, server)
66
- if (reviewResponse === 'upgraded') return undefined
67
- if (reviewResponse !== null) return reviewResponse
68
-
69
- // CORS preflight
70
- if (req.method === 'OPTIONS') {
71
- return new Response(null, { status: 204, headers: corsHeaders(PORT) })
72
- }
73
-
74
- // WebSocket upgrade: /ws/session/:id
75
- const wsBrowserMatch = url.pathname.match(/^\/ws\/session\/([^/]+)$/)
76
- if (wsBrowserMatch) {
77
- const upgraded = server.upgrade(req, { data: { type: 'browser', sessionId: wsBrowserMatch[1] } })
78
- if (!upgraded) return new Response('WebSocket upgrade failed', { status: 400 })
79
- return undefined
80
- }
81
-
82
- // WebSocket upgrade: /ws/wait/:id
83
- const wsWaitMatch = url.pathname.match(/^\/ws\/wait\/([^/]+)$/)
84
- if (wsWaitMatch) {
85
- const upgraded = server.upgrade(req, { data: { type: 'wait', sessionId: wsWaitMatch[1] } })
86
- if (!upgraded) return new Response('WebSocket upgrade failed', { status: 400 })
87
- return undefined
88
- }
89
-
90
- // Route dispatch
91
- const response = dispatch(routes, req, url)
92
- if (response) return response
93
-
94
- // Root redirect
95
- if (url.pathname === '/' && req.method === 'GET') {
96
- const sessions = sessionManager.list()
97
- if (sessions.length > 0) {
98
- const latest = sessions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0]
99
- return Response.redirect(`/s/${latest.id}`, 302)
100
- }
101
- return jsonResponse({ message: 'No active sessions', sessions: [] })
102
- }
103
-
104
- return jsonResponse({ error: 'Not found' }, 404)
127
+ const response = handle(req, server)
128
+ if (response === undefined) return undefined
129
+ return response instanceof Promise ? response.then(withDefaultCsp) : withDefaultCsp(response)
105
130
  },
106
131
 
107
132
  websocket: {
@@ -129,7 +154,16 @@ export const broadcastPlanUpdate = wsManager.broadcastPlanUpdate
129
154
 
130
155
  // Start polling for remote feedback from shared canvases.
131
156
  // No-ops if CANVAS_SHARE_ENDPOINT is not set.
132
- startRemoteFeedbackPoller(sessionManager, wsManager.broadcastRemoteFeedback, VERSION)
157
+ startRemoteFeedbackPoller(sessionManager, (sessionId, revision, entries) => {
158
+ wsManager.broadcastRemoteFeedback(sessionId, revision, entries)
159
+ // Only that it arrived: what reviewers wrote reaches the agent when the user includes it in a submit.
160
+ wsManager.notifyWaiters(sessionId, {
161
+ type: 'remote-feedback-arrived',
162
+ revision,
163
+ count: entries.reduce((sum, entry) => sum + entry.annotations.length + (entry.generalNote?.trim() ? 1 : 0), 0),
164
+ reviewers: [...new Set(entries.map((entry) => entry.author.name))],
165
+ })
166
+ }, VERSION)
133
167
 
134
168
  reviewProxies.restore()
135
169
 
@@ -0,0 +1,132 @@
1
+ import type { SessionManager } from '@fabrika/canvas-kernel/server'
2
+ import { z } from 'zod'
3
+ import { reviewCommentSchema, reviewThreadStateSchema } from './review/model'
4
+ import type { ReviewAuthor, ReviewComment } from './review/model'
5
+ import { agentReplied, claimed, resolvedAs, ReviewError, userCommented } from './review/threads'
6
+
7
+ /**
8
+ * Threads on a canvas session's submitted annotations. The agent opens one by answering an annotation; the user
9
+ * answers back from the sidebar. The lifecycle is review mode's (`review/threads.ts`); a thread's id is the
10
+ * annotation's, and it lives at session level so it outlives the revision it was submitted on.
11
+ */
12
+
13
+ export const canvasThreadSchema = z.object({
14
+ id: z.string(),
15
+ state: reviewThreadStateSchema,
16
+ revision: z.number().int(),
17
+ snippet: z.string(),
18
+ canvasFile: z.string().optional(),
19
+ filePath: z.string().optional(),
20
+ comments: z.array(reviewCommentSchema),
21
+ createdAt: z.string(),
22
+ updatedAt: z.string(),
23
+ })
24
+ export type CanvasThread = z.infer<typeof canvasThreadSchema>
25
+
26
+ const threadsRecordSchema = z.object({ threads: z.array(canvasThreadSchema) })
27
+
28
+ const commentBody = z.string().trim().min(1).max(20_000)
29
+ export const agentReplyBodySchema = z.object({ body: commentBody, resolve: z.boolean() })
30
+ export const userReplyBodySchema = z.object({ body: commentBody })
31
+ export const resolvedBodySchema = z.object({ resolved: z.boolean() })
32
+
33
+ export class CanvasThreadStore {
34
+ constructor(private readonly sessions: SessionManager, private readonly now: () => Date = () => new Date()) {}
35
+
36
+ list(sessionId: string): readonly CanvasThread[] {
37
+ this.requireSession(sessionId)
38
+ const record = this.sessions.getThreads(sessionId)
39
+ return record === null ? [] : threadsRecordSchema.parse(record).threads
40
+ }
41
+
42
+ /** The agent's answer, which opens the thread on its first reply. Without `resolve` it goes back to the user. */
43
+ agentReply(sessionId: string, annotationId: string, body: string, resolve: boolean): CanvasThread {
44
+ const threads = this.list(sessionId)
45
+ const existing = threads.find((thread) => thread.id === annotationId)
46
+ // Answering over an unread answer would hand the thread back to the user and the answer would never be claimed.
47
+ if (existing?.state === 'queued') {
48
+ throw new ReviewError(`The user answered ${annotationId} since you last read it; read the answer with watch first`, 409)
49
+ }
50
+ const thread = existing ?? this.opened(sessionId, annotationId)
51
+ const next = agentReplied(thread, this.comment('agent', body), resolve)
52
+ this.save(sessionId, existing ? threads.map((candidate) => (candidate.id === annotationId ? next : candidate)) : [...threads, next])
53
+ return next
54
+ }
55
+
56
+ /** The user's answer goes to the agent and reopens a resolved thread. */
57
+ userReply(sessionId: string, threadId: string, body: string): CanvasThread {
58
+ return this.update(sessionId, threadId, (thread) => userCommented(thread, this.comment('user', body), true))
59
+ }
60
+
61
+ setResolved(sessionId: string, threadId: string, resolved: boolean): CanvasThread {
62
+ return this.update(sessionId, threadId, (thread) => resolvedAs(thread, resolved, this.timestamp()))
63
+ }
64
+
65
+ /** Hands every thread the user answered to the agent, once. A session the daemon does not know has none. */
66
+ claimQueued(sessionId: string): readonly CanvasThread[] {
67
+ if (!this.sessions.get(sessionId)) return []
68
+ const result = claimed(this.list(sessionId), this.timestamp())
69
+ if (result.claimed.length > 0) this.save(sessionId, result.threads)
70
+ return result.claimed
71
+ }
72
+
73
+ private opened(sessionId: string, annotationId: string): CanvasThread {
74
+ const submitted = this.sessions.findSubmittedAnnotation(sessionId, annotationId)
75
+ if (submitted === null) throw new ReviewError(`No submitted annotation ${annotationId} in this session`, 404)
76
+ const { annotation, revision } = submitted
77
+ const createdAt = this.timestamp()
78
+ const note = annotation.note.trim()
79
+ return {
80
+ id: annotation.id,
81
+ // Delivered with the submit, so the agent already has it.
82
+ state: 'working',
83
+ revision,
84
+ snippet: annotation.snippet,
85
+ ...(annotation.canvasFile === undefined ? {} : { canvasFile: annotation.canvasFile }),
86
+ ...(annotation.filePath === undefined ? {} : { filePath: annotation.filePath }),
87
+ comments: note === '' ? [] : [{ id: Bun.randomUUIDv7(), author: 'user', body: note, createdAt }],
88
+ createdAt,
89
+ updatedAt: createdAt,
90
+ }
91
+ }
92
+
93
+ private update(sessionId: string, threadId: string, change: (thread: CanvasThread) => CanvasThread): CanvasThread {
94
+ const threads = this.list(sessionId)
95
+ const current = threads.find((thread) => thread.id === threadId)
96
+ if (current === undefined) throw new ReviewError(`No thread ${threadId}`, 404)
97
+ const next = change(current)
98
+ this.save(sessionId, threads.map((thread) => (thread.id === threadId ? next : thread)))
99
+ return next
100
+ }
101
+
102
+ private save(sessionId: string, threads: readonly CanvasThread[]): void {
103
+ this.sessions.saveThreads(sessionId, { threads })
104
+ }
105
+
106
+ private requireSession(sessionId: string): void {
107
+ if (!this.sessions.get(sessionId)) throw new ReviewError('Session not found', 404)
108
+ }
109
+
110
+ private comment(author: ReviewAuthor, body: string): ReviewComment {
111
+ return { id: Bun.randomUUIDv7(), author, body, createdAt: this.timestamp() }
112
+ }
113
+
114
+ private timestamp(): string {
115
+ return this.now().toISOString()
116
+ }
117
+ }
118
+
119
+ /** Threads the user answered, as the agent reads them: the annotation, the conversation, and how to reply. */
120
+ export function threadRepliesMarkdown(threads: readonly CanvasThread[]): string {
121
+ const parts = ['## Thread replies', '']
122
+ for (const thread of threads) {
123
+ const where = thread.filePath ?? thread.canvasFile
124
+ parts.push(`### Annotation \`${thread.id}\`${where ? ` in ${where}` : ''} (revision ${thread.revision})`, '')
125
+ if (thread.snippet.trim()) parts.push(`> ${thread.snippet.trim().split('\n').join('\n> ')}`, '')
126
+ for (const comment of thread.comments) {
127
+ parts.push(`**${comment.author === 'agent' ? 'Agent' : 'User'}:** ${comment.body}`, '')
128
+ }
129
+ }
130
+ parts.push('Answer each with `agent-canvas reply <annotation-id> "<text>"`; add `--resolve` when it is done.')
131
+ return `${parts.join('\n')}\n`
132
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-canvas",
3
- "version": "0.9.0-dev.13",
3
+ "version": "0.9.0-dev.14",
4
4
  "description": "Interactive visual canvas for Claude Code — rich annotatable documents in the browser",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -59,9 +59,9 @@
59
59
  "test": "bun test"
60
60
  },
61
61
  "dependencies": {
62
- "@fabrika/annotations": "0.9.0-dev.13",
63
- "@fabrika/canvas-kernel": "0.9.0-dev.13",
64
- "@fabrika/daemon-kit": "0.9.0-dev.13",
62
+ "@fabrika/annotations": "0.9.0-dev.14",
63
+ "@fabrika/canvas-kernel": "0.9.0-dev.14",
64
+ "@fabrika/daemon-kit": "0.9.0-dev.14",
65
65
  "@jridgewell/trace-mapping": "^0.3.31",
66
66
  "marked": "^17.0.4",
67
67
  "mermaid-parser-bundle": "^0.1.2",
@@ -31,6 +31,11 @@ fresh, so the variable will not survive between commands.
31
31
  Always use absolute filesystem paths for local file references in canvas components
32
32
  (such as `FilePreview`), and verify that the referenced files exist. Resolve them
33
33
  against the user's project directory, not the temporary directory containing the JSX.
34
+ Write each path as a string literal (`path="/abs/file.ts"`): the daemon serves a file outside
35
+ the project root only when a canvas names it that way.
36
+ Canvas JavaScript may connect only to the daemon: `fetch` or a WebSocket to another host,
37
+ an `<iframe>` and scripts from other origins are blocked. Images, fonts, stylesheets, audio
38
+ and video may come from any https URL.
34
39
 
35
40
  Run these commands from the user's project root before using Canvas:
36
41
 
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The capability the running daemon wrote for its owner's CLI, or undefined when no daemon wrote one. Read on every
3
+ * request: a restarted daemon writes a new one.
4
+ */
5
+ export declare function readCliAuthToken(): string | undefined;
6
+ /** Headers that authenticate a CLI request to the daemon; empty when no capability is available. */
7
+ export declare function cliAuthHeaders(): Record<string, string>;
8
+ /** A daemon WebSocket URL that authenticates the CLI; the DOM `WebSocket` constructor the CLI is typed against takes no headers. */
9
+ export declare function cliSocketUrl(url: string): string;
@@ -0,0 +1,2 @@
1
+ /** Answers one submitted annotation; the user sees the reply under it in the sidebar. */
2
+ export declare function handleReply(args: string[]): Promise<void>;
@@ -1 +1,3 @@
1
- export declare function handleWatch(args: string[]): Promise<void>;
1
+ export declare function handleWatch(args: string[]): Promise<undefined>;
2
+ /** A name a reviewer typed, as a quoted label that cannot pass for anything else in the agent's output. */
3
+ export declare function reviewerLabel(name: string): string;