astrocms 0.1.0

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 (137) hide show
  1. package/backend/auth.ts +54 -0
  2. package/backend/config.ts +50 -0
  3. package/backend/parsers/collections.ts +279 -0
  4. package/backend/parsers/components.ts +184 -0
  5. package/backend/parsers/frontmatter.ts +67 -0
  6. package/backend/parsers/glob.ts +57 -0
  7. package/backend/root.ts +7 -0
  8. package/backend/routes/auth.ts +42 -0
  9. package/backend/routes/claude.ts +401 -0
  10. package/backend/routes/collections.ts +9 -0
  11. package/backend/routes/components.ts +9 -0
  12. package/backend/routes/config.ts +7 -0
  13. package/backend/routes/file.ts +179 -0
  14. package/backend/routes/git.ts +458 -0
  15. package/backend/routes/tree.ts +100 -0
  16. package/backend/routes/upload.ts +33 -0
  17. package/backend/server.ts +173 -0
  18. package/backend/stubs/astro-content.ts +14 -0
  19. package/backend/stubs/astro-loaders.ts +17 -0
  20. package/bin/astrocms.js +66 -0
  21. package/dist/_cms/apl-B4CMkyY2.js +1 -0
  22. package/dist/_cms/asciiarmor-Df11BRmG.js +1 -0
  23. package/dist/_cms/asn1-EdZsLKOL.js +1 -0
  24. package/dist/_cms/asterisk-B-8jnY81.js +1 -0
  25. package/dist/_cms/brainfuck-C4LP7Hcl.js +1 -0
  26. package/dist/_cms/clike-B9uivgTg.js +1 -0
  27. package/dist/_cms/clojure-BMjYHr_A.js +1 -0
  28. package/dist/_cms/cmake-BQqOBYOt.js +1 -0
  29. package/dist/_cms/cobol-CWcv1MsR.js +1 -0
  30. package/dist/_cms/coffeescript-S37ZYGWr.js +1 -0
  31. package/dist/_cms/commonlisp-DBKNyK5s.js +1 -0
  32. package/dist/_cms/crystal-SjHAIU92.js +1 -0
  33. package/dist/_cms/css-BnMrqG3P.js +1 -0
  34. package/dist/_cms/cypher-C_CwsFkJ.js +1 -0
  35. package/dist/_cms/d-pRatUO7H.js +1 -0
  36. package/dist/_cms/diff-DbItnlRl.js +1 -0
  37. package/dist/_cms/dockerfile-BKs6k2Af.js +1 -0
  38. package/dist/_cms/dtd-DF_7sFjM.js +1 -0
  39. package/dist/_cms/dylan-DwRh75JA.js +1 -0
  40. package/dist/_cms/ebnf-CDyGwa7X.js +1 -0
  41. package/dist/_cms/ecl-Cabwm37j.js +1 -0
  42. package/dist/_cms/eiffel-CnydiIhH.js +1 -0
  43. package/dist/_cms/elm-vLlmbW-K.js +1 -0
  44. package/dist/_cms/erlang-BNw1qcRV.js +1 -0
  45. package/dist/_cms/factor-kuTfRLto.js +1 -0
  46. package/dist/_cms/fcl-Kvtd6kyn.js +1 -0
  47. package/dist/_cms/forth-Ffai-XNe.js +1 -0
  48. package/dist/_cms/fortran-DYz_wnZ1.js +1 -0
  49. package/dist/_cms/gas-Bneqetm1.js +1 -0
  50. package/dist/_cms/gherkin-heZmZLOM.js +1 -0
  51. package/dist/_cms/groovy-D9Dt4D0W.js +1 -0
  52. package/dist/_cms/haskell-Cw1EW3IL.js +1 -0
  53. package/dist/_cms/haxe-H-WmDvRZ.js +1 -0
  54. package/dist/_cms/http-DBlCnlav.js +1 -0
  55. package/dist/_cms/idl-BEugSyMb.js +1 -0
  56. package/dist/_cms/index-7Pc6H4sv.js +1 -0
  57. package/dist/_cms/index-893Rzaov.js +1 -0
  58. package/dist/_cms/index-9o-llXDY.js +508 -0
  59. package/dist/_cms/index-BdC39RoS.js +1 -0
  60. package/dist/_cms/index-BdChuKfE.js +7 -0
  61. package/dist/_cms/index-Bpfn86Of.js +1 -0
  62. package/dist/_cms/index-Bvz8WTJL.js +1 -0
  63. package/dist/_cms/index-C2vDuCBy.js +1 -0
  64. package/dist/_cms/index-C9zUJLja.css +1 -0
  65. package/dist/_cms/index-Cdwq3Ev5.js +1 -0
  66. package/dist/_cms/index-Ce64khPN.js +3 -0
  67. package/dist/_cms/index-CoIA6zkf.js +1 -0
  68. package/dist/_cms/index-DAAZmIPw.js +1 -0
  69. package/dist/_cms/index-DM5GktYD.js +1 -0
  70. package/dist/_cms/index-DQf5bTbe.js +1 -0
  71. package/dist/_cms/index-M4bKZFGh.js +1 -0
  72. package/dist/_cms/index-NwHME3i3.js +1 -0
  73. package/dist/_cms/index-enNvjuOI.js +2 -0
  74. package/dist/_cms/index-wHleENT0.js +1 -0
  75. package/dist/_cms/javascript-iXu5QeM3.js +1 -0
  76. package/dist/_cms/julia-DuME0IfC.js +1 -0
  77. package/dist/_cms/livescript-BwQOo05w.js +1 -0
  78. package/dist/_cms/lua-BgMRiT3U.js +1 -0
  79. package/dist/_cms/mathematica-DTrFuWx2.js +1 -0
  80. package/dist/_cms/mbox-CNhZ1qSd.js +1 -0
  81. package/dist/_cms/mirc-CjQqDB4T.js +1 -0
  82. package/dist/_cms/mllike-CXdrOF99.js +1 -0
  83. package/dist/_cms/modelica-Dc1JOy9r.js +1 -0
  84. package/dist/_cms/mscgen-BA5vi2Kp.js +1 -0
  85. package/dist/_cms/mumps-BT43cFF4.js +1 -0
  86. package/dist/_cms/nginx-DdIZxoE0.js +1 -0
  87. package/dist/_cms/nsis-LdVXkNf5.js +1 -0
  88. package/dist/_cms/ntriples-BfvgReVJ.js +1 -0
  89. package/dist/_cms/octave-Ck1zUtKM.js +1 -0
  90. package/dist/_cms/oz-BzwKVEFT.js +1 -0
  91. package/dist/_cms/pascal--L3eBynH.js +1 -0
  92. package/dist/_cms/perl-CdXCOZ3F.js +1 -0
  93. package/dist/_cms/pig-CevX1Tat.js +1 -0
  94. package/dist/_cms/powershell-CFHJl5sT.js +1 -0
  95. package/dist/_cms/properties-C78fOPTZ.js +1 -0
  96. package/dist/_cms/protobuf-ChK-085T.js +1 -0
  97. package/dist/_cms/pug-DeIclll2.js +1 -0
  98. package/dist/_cms/puppet-DMA9R1ak.js +1 -0
  99. package/dist/_cms/python-BuPzkPfP.js +1 -0
  100. package/dist/_cms/q-pXgVlZs6.js +1 -0
  101. package/dist/_cms/r-B6wPVr8A.js +1 -0
  102. package/dist/_cms/rpm-CTu-6PCP.js +1 -0
  103. package/dist/_cms/ruby-B2Rjki9n.js +1 -0
  104. package/dist/_cms/sas-B4kiWyti.js +1 -0
  105. package/dist/_cms/scheme-C41bIUwD.js +1 -0
  106. package/dist/_cms/shell-CjFT_Tl9.js +1 -0
  107. package/dist/_cms/sieve-C3Gn_uJK.js +1 -0
  108. package/dist/_cms/simple-mode-GW_nhZxv.js +1 -0
  109. package/dist/_cms/smalltalk-CnHTOXQT.js +1 -0
  110. package/dist/_cms/solr-DehyRSwq.js +1 -0
  111. package/dist/_cms/sparql-DkYu6x3z.js +1 -0
  112. package/dist/_cms/spreadsheet-BCZA_wO0.js +1 -0
  113. package/dist/_cms/sql-D0XecflT.js +1 -0
  114. package/dist/_cms/stex-C3f8Ysf7.js +1 -0
  115. package/dist/_cms/stylus-B533Al4x.js +1 -0
  116. package/dist/_cms/swift-BzpIVaGY.js +1 -0
  117. package/dist/_cms/tcl-DVfN8rqt.js +1 -0
  118. package/dist/_cms/textile-CnDTJFAw.js +1 -0
  119. package/dist/_cms/tiddlywiki-DO-Gjzrf.js +1 -0
  120. package/dist/_cms/tiki-DGYXhP31.js +1 -0
  121. package/dist/_cms/toml-Bm5Em-hy.js +1 -0
  122. package/dist/_cms/troff-wAsdV37c.js +1 -0
  123. package/dist/_cms/ttcn-CfJYG6tj.js +1 -0
  124. package/dist/_cms/ttcn-cfg-B9xdYoR4.js +1 -0
  125. package/dist/_cms/turtle-B1tBg_DP.js +1 -0
  126. package/dist/_cms/vb-CmGdzxic.js +1 -0
  127. package/dist/_cms/vbscript-BuJXcnF6.js +1 -0
  128. package/dist/_cms/velocity-D8B20fx6.js +1 -0
  129. package/dist/_cms/verilog-C6RDOZhf.js +1 -0
  130. package/dist/_cms/vhdl-lSbBsy5d.js +1 -0
  131. package/dist/_cms/webidl-ZXfAyPTL.js +1 -0
  132. package/dist/_cms/xquery-DzFWVndE.js +1 -0
  133. package/dist/_cms/yacas-BJ4BC0dw.js +1 -0
  134. package/dist/_cms/z80-Hz9HOZM7.js +1 -0
  135. package/dist/index.html +13 -0
  136. package/package.json +77 -0
  137. package/patches/hast-util-to-estree+3.1.3.patch +14 -0
@@ -0,0 +1,42 @@
1
+ import { Hono } from 'hono'
2
+ import { deleteCookie, setCookie } from 'hono/cookie'
3
+ import {
4
+ AUTH_COOKIE,
5
+ checkPassword,
6
+ createToken,
7
+ getSessionToken,
8
+ isAuthRequired,
9
+ isValidToken,
10
+ } from '../auth.js'
11
+
12
+ export const authRoutes = new Hono()
13
+
14
+ authRoutes.get('/status', (c) => {
15
+ const required = isAuthRequired()
16
+ const authenticated = !required || isValidToken(getSessionToken(c))
17
+ return c.json({ required, authenticated })
18
+ })
19
+
20
+ authRoutes.post('/login', async (c) => {
21
+ if (!isAuthRequired()) {
22
+ return c.json({ error: 'Auth not configured' }, 400)
23
+ }
24
+ const body = await c.req.json().catch(() => ({}))
25
+ const password = typeof body?.password === 'string' ? body.password : ''
26
+ if (!checkPassword(password)) {
27
+ return c.json({ error: 'Invalid password' }, 401)
28
+ }
29
+ const token = createToken()
30
+ setCookie(c, AUTH_COOKIE, token, {
31
+ httpOnly: true,
32
+ sameSite: 'Lax',
33
+ path: '/',
34
+ maxAge: 60 * 60 * 24 * 30,
35
+ })
36
+ return c.json({ ok: true })
37
+ })
38
+
39
+ authRoutes.post('/logout', (c) => {
40
+ deleteCookie(c, AUTH_COOKIE, { path: '/' })
41
+ return c.json({ ok: true })
42
+ })
@@ -0,0 +1,401 @@
1
+ import { Hono } from 'hono'
2
+ import { streamText, convertToModelMessages } from 'ai'
3
+ import { claudeCode } from 'ai-sdk-provider-claude-code'
4
+ import type { CanUseTool } from 'ai-sdk-provider-claude-code'
5
+ import {
6
+ listSessions,
7
+ getSessionMessages,
8
+ query,
9
+ type Query,
10
+ } from '@anthropic-ai/claude-agent-sdk'
11
+ import { readFile } from 'fs/promises'
12
+ import { join } from 'path'
13
+ import { ROOT_DIR } from '../root.js'
14
+
15
+ export const claudeRoutes = new Hono()
16
+
17
+ // Tools that are auto-allowed (no permission prompt).
18
+ // Bash commands use the Claude Code rule syntax: "Bash(ls:*)" allows any `ls ...`.
19
+ const allowedTools = [
20
+ 'Read',
21
+ 'Edit',
22
+ 'Write',
23
+ 'Grep',
24
+ 'Glob',
25
+ 'Agent',
26
+ 'TodoWrite',
27
+ 'NotebookEdit',
28
+ 'Bash(ls:*)',
29
+ 'Bash(find:*)',
30
+ 'Bash(git:*)',
31
+ 'Bash(mkdir:*)',
32
+ 'Bash(cd * && git commit*)',
33
+ 'Bash(cd * && git push*)',
34
+ ]
35
+
36
+ // --- Permission request handling ---
37
+
38
+ interface PendingPermission {
39
+ id: string
40
+ toolName: string
41
+ input: Record<string, unknown>
42
+ title?: string
43
+ decisionReason?: string
44
+ resolve: (
45
+ result: { behavior: 'allow' } | { behavior: 'deny'; message: string }
46
+ ) => void
47
+ }
48
+
49
+ let pendingPermission: PendingPermission | null = null
50
+ let permissionIdCounter = 0
51
+ // SSE listeners waiting for permission events
52
+ const permissionListeners = new Set<(perm: PendingPermission) => void>()
53
+
54
+ const canUseTool: CanUseTool = async (toolName, input, options) => {
55
+ const id = String(++permissionIdCounter)
56
+ return new Promise((resolve) => {
57
+ const perm: PendingPermission = {
58
+ id,
59
+ toolName,
60
+ input,
61
+ title: options.title,
62
+ decisionReason: options.decisionReason,
63
+ resolve,
64
+ }
65
+ pendingPermission = perm
66
+ // Notify all SSE listeners
67
+ for (const listener of permissionListeners) {
68
+ listener(perm)
69
+ }
70
+ })
71
+ }
72
+
73
+ // Auth status cache
74
+ let statusCache: {
75
+ result: { authenticated: boolean; error?: string; account?: unknown }
76
+ timestamp: number
77
+ } | null = null
78
+ const STATUS_CACHE_TTL = 60_000
79
+
80
+ // Active login query (kept alive during OAuth flow)
81
+ let loginQuery: Query | null = null
82
+ let loginAbortController: AbortController | null = null
83
+
84
+ function cleanupLoginQuery() {
85
+ loginQuery?.close()
86
+ loginQuery = null
87
+ loginAbortController?.abort()
88
+ loginAbortController = null
89
+ }
90
+
91
+ claudeRoutes.get('/status', async (c) => {
92
+ const force = c.req.query('force') === 'true'
93
+ if (
94
+ !force &&
95
+ statusCache &&
96
+ Date.now() - statusCache.timestamp < STATUS_CACHE_TTL
97
+ ) {
98
+ return c.json(
99
+ statusCache.result,
100
+ statusCache.result.authenticated ? 200 : 401
101
+ )
102
+ }
103
+
104
+ const abortController = new AbortController()
105
+ const timeout = setTimeout(() => abortController.abort(), 30_000)
106
+
107
+ try {
108
+ const q = query({
109
+ // Streaming input that never yields — we only want the init phase
110
+ prompt: (async function* () {
111
+ await new Promise(() => {})
112
+ })(),
113
+ options: {
114
+ cwd: ROOT_DIR,
115
+ persistSession: false,
116
+ abortController,
117
+ },
118
+ })
119
+
120
+ const init = await q.initializationResult()
121
+ clearTimeout(timeout)
122
+ q.close()
123
+
124
+ const account = init.account
125
+ // tokenSource "none" means no credentials are configured
126
+ if (!account || account.tokenSource === 'none') {
127
+ const result = {
128
+ authenticated: false as const,
129
+ error: 'Not logged in.',
130
+ account,
131
+ }
132
+ statusCache = { result, timestamp: Date.now() }
133
+ return c.json(result, 401)
134
+ }
135
+
136
+ const result = { authenticated: true as const, account }
137
+ statusCache = { result, timestamp: Date.now() }
138
+ return c.json(result)
139
+ } catch (error) {
140
+ clearTimeout(timeout)
141
+ abortController.abort()
142
+ const message =
143
+ error instanceof Error ? error.message : 'Authentication required'
144
+ const result = { authenticated: false as const, error: message }
145
+ statusCache = { result, timestamp: Date.now() }
146
+ return c.json(result, 401)
147
+ }
148
+ })
149
+
150
+ // Start OAuth login flow — returns URLs to open in browser
151
+ claudeRoutes.post('/login', async (c) => {
152
+ cleanupLoginQuery()
153
+
154
+ loginAbortController = new AbortController()
155
+ const timeout = setTimeout(() => {
156
+ cleanupLoginQuery()
157
+ }, 5 * 60_000) // 5 min timeout for the whole login flow
158
+
159
+ try {
160
+ loginQuery = query({
161
+ prompt: (async function* () {
162
+ await new Promise(() => {})
163
+ })(),
164
+ options: {
165
+ cwd: ROOT_DIR,
166
+ persistSession: false,
167
+ abortController: loginAbortController,
168
+ },
169
+ })
170
+
171
+ await loginQuery.initializationResult()
172
+
173
+ // Start OAuth — returns { manualUrl, automaticUrl }
174
+ const result = await loginQuery.claudeAuthenticate(true)
175
+ clearTimeout(timeout)
176
+ return c.json(result)
177
+ } catch (error) {
178
+ clearTimeout(timeout)
179
+ cleanupLoginQuery()
180
+ const message = error instanceof Error ? error.message : 'Login failed'
181
+ return c.json({ error: message }, 500)
182
+ }
183
+ })
184
+
185
+ // Submit the code+state pasted by the user after authorizing on manualUrl
186
+ claudeRoutes.post('/login/code', async (c) => {
187
+ if (!loginQuery) {
188
+ return c.json({ error: 'No login in progress' }, 400)
189
+ }
190
+
191
+ const body = await c.req.json<{ code?: string; state?: string }>()
192
+ if (!body.code || !body.state) {
193
+ return c.json({ error: 'Missing code or state' }, 400)
194
+ }
195
+
196
+ try {
197
+ const result = await loginQuery.claudeOAuthCallback(body.code, body.state)
198
+ cleanupLoginQuery()
199
+ statusCache = null
200
+ return c.json(result)
201
+ } catch (error) {
202
+ cleanupLoginQuery()
203
+ const message = error instanceof Error ? error.message : 'Login failed'
204
+ return c.json({ error: message }, 500)
205
+ }
206
+ })
207
+
208
+ // AI SDK chat endpoint - compatible with assistant-ui
209
+ claudeRoutes.post('/chat', async (c) => {
210
+ const body = await c.req.json()
211
+ const { messages } = body
212
+ const sessionId = c.req.query('sessionId') || body.sessionId
213
+
214
+ // Clear any stale pending permission from a previous request
215
+ pendingPermission = null
216
+
217
+ const result = streamText({
218
+ model: claudeCode('sonnet', {
219
+ allowedTools,
220
+ canUseTool,
221
+ cwd: ROOT_DIR,
222
+ ...(sessionId ? { resume: sessionId } : {}),
223
+ }),
224
+ messages: await convertToModelMessages(messages),
225
+ })
226
+
227
+ return result.toUIMessageStreamResponse()
228
+ })
229
+
230
+ // SSE stream for permission requests (no polling needed)
231
+ claudeRoutes.get('/permissions/events', (c) => {
232
+ const stream = new ReadableStream({
233
+ start(controller) {
234
+ const encoder = new TextEncoder()
235
+ const send = (perm: PendingPermission) => {
236
+ const data = JSON.stringify({
237
+ id: perm.id,
238
+ toolName: perm.toolName,
239
+ input: perm.input,
240
+ title: perm.title,
241
+ decisionReason: perm.decisionReason,
242
+ })
243
+ controller.enqueue(encoder.encode(`data: ${data}\n\n`))
244
+ }
245
+
246
+ // Send current pending permission if any
247
+ if (pendingPermission) send(pendingPermission)
248
+
249
+ // Listen for future permission requests
250
+ permissionListeners.add(send)
251
+
252
+ // Cleanup when client disconnects
253
+ c.req.raw.signal.addEventListener('abort', () => {
254
+ permissionListeners.delete(send)
255
+ controller.close()
256
+ })
257
+ },
258
+ })
259
+
260
+ return new Response(stream, {
261
+ headers: {
262
+ 'Content-Type': 'text/event-stream',
263
+ 'Cache-Control': 'no-cache',
264
+ Connection: 'keep-alive',
265
+ },
266
+ })
267
+ })
268
+
269
+ // Respond to a permission request
270
+ claudeRoutes.post('/permissions/:id/respond', async (c) => {
271
+ const id = c.req.param('id')
272
+ const { behavior, message, updatedInput } = await c.req.json()
273
+
274
+ if (!pendingPermission || pendingPermission.id !== id) {
275
+ return c.json({ error: 'No matching pending permission' }, 404)
276
+ }
277
+
278
+ const perm = pendingPermission
279
+ pendingPermission = null
280
+
281
+ if (behavior === 'allow') {
282
+ perm.resolve({
283
+ behavior: 'allow',
284
+ updatedInput:
285
+ updatedInput && typeof updatedInput === 'object'
286
+ ? updatedInput
287
+ : perm.input,
288
+ })
289
+ } else {
290
+ perm.resolve({
291
+ behavior: 'deny',
292
+ message: message || 'User denied permission',
293
+ })
294
+ }
295
+
296
+ return c.json({ ok: true })
297
+ })
298
+
299
+ /** Try to read the JSONL transcript for a session, searching known project dirs */
300
+ async function readSessionJsonl(sessionId: string): Promise<string> {
301
+ const home = process.env.HOME || '~'
302
+ const projectsDir = join(home, '.claude', 'projects')
303
+ // The project dir name is the cwd with slashes replaced by dashes, leading dash stripped
304
+ // Sessions may be under ROOT_DIR or its parent depending on the cwd used
305
+ const candidates = [
306
+ ROOT_DIR,
307
+ join(ROOT_DIR, '..'), // parent (e.g. rolebase vs rolebase/website)
308
+ ]
309
+ for (const dir of candidates) {
310
+ const resolved = dir.replace(/\//g, '-')
311
+ const path = join(projectsDir, resolved, `${sessionId}.jsonl`)
312
+ try {
313
+ return await readFile(path, 'utf-8')
314
+ } catch {
315
+ // try next
316
+ }
317
+ }
318
+ throw new Error(`Session JSONL not found for ${sessionId}`)
319
+ }
320
+
321
+ // List recent conversations
322
+ claudeRoutes.get('/conversations', async (c) => {
323
+ const limit = parseInt(c.req.query('limit') || '20')
324
+ try {
325
+ const sessions = await listSessions({ dir: ROOT_DIR, limit })
326
+ return c.json(
327
+ sessions.map((s) => ({
328
+ id: s.sessionId,
329
+ summary: s.summary,
330
+ firstPrompt: s.firstPrompt,
331
+ lastModified: s.lastModified,
332
+ customTitle: s.customTitle,
333
+ }))
334
+ )
335
+ } catch {
336
+ return c.json([])
337
+ }
338
+ })
339
+
340
+ // Get messages for a specific conversation (includes subagent steps)
341
+ claudeRoutes.get('/conversations/:id/messages', async (c) => {
342
+ const sessionId = c.req.param('id')
343
+ try {
344
+ const raw = await readSessionJsonl(sessionId)
345
+ const lines = raw
346
+ .trim()
347
+ .split('\n')
348
+ .map((l) => JSON.parse(l))
349
+
350
+ // Collect progress events grouped by parentToolUseID
351
+ const progressByParent = new Map<string, any[]>()
352
+ for (const line of lines) {
353
+ if (line.type === 'progress' && line.parentToolUseID) {
354
+ const arr = progressByParent.get(line.parentToolUseID) || []
355
+ arr.push(line.data?.message)
356
+ progressByParent.set(line.parentToolUseID, arr)
357
+ }
358
+ }
359
+
360
+ // Build message list: top-level user/assistant + inline subagent steps
361
+ const messages: any[] = []
362
+ for (const line of lines) {
363
+ if (line.type !== 'user' && line.type !== 'assistant') continue
364
+ if (line.isSidechain) continue
365
+
366
+ messages.push(line)
367
+
368
+ // After an assistant message, check if it has Agent tool_use blocks
369
+ if (line.type === 'assistant') {
370
+ const content = line.message?.content
371
+ if (!Array.isArray(content)) continue
372
+ for (const block of content) {
373
+ if (block.type === 'tool_use' && block.name === 'Agent') {
374
+ const subSteps = progressByParent.get(block.id)
375
+ if (subSteps) {
376
+ for (const step of subSteps) {
377
+ if (!step) continue
378
+ messages.push({
379
+ type: step.type === 'user' ? 'user' : 'assistant',
380
+ message: step.message || step,
381
+ parent_tool_use_id: block.id,
382
+ })
383
+ }
384
+ }
385
+ }
386
+ }
387
+ }
388
+ }
389
+
390
+ return c.json(messages)
391
+ } catch (e) {
392
+ console.log(e)
393
+ // Fallback to SDK method
394
+ try {
395
+ const messages = await getSessionMessages(sessionId, { dir: ROOT_DIR })
396
+ return c.json(messages)
397
+ } catch {
398
+ return c.json([])
399
+ }
400
+ }
401
+ })
@@ -0,0 +1,9 @@
1
+ import { Hono } from 'hono'
2
+ import { getCollections } from '../parsers/collections.js'
3
+
4
+ export const collectionsRoutes = new Hono()
5
+
6
+ collectionsRoutes.get('/', async (c) => {
7
+ const { collections, error } = await getCollections()
8
+ return c.json({ collections, error })
9
+ })
@@ -0,0 +1,9 @@
1
+ import { Hono } from 'hono'
2
+ import { scanComponents } from '../parsers/components.js'
3
+
4
+ export const componentsRoutes = new Hono()
5
+
6
+ componentsRoutes.get('/', async (c) => {
7
+ const components = await scanComponents()
8
+ return c.json(components)
9
+ })
@@ -0,0 +1,7 @@
1
+ import { Hono } from 'hono'
2
+
3
+ export const configRoutes = new Hono()
4
+
5
+ configRoutes.get('/', (c) => {
6
+ return c.json({ devServer: !!process.env.ASTROCMS_DEV_CMD })
7
+ })
@@ -0,0 +1,179 @@
1
+ import { Hono } from 'hono'
2
+ import {
3
+ readFile,
4
+ writeFile,
5
+ mkdir,
6
+ rename,
7
+ stat,
8
+ rm,
9
+ access,
10
+ } from 'fs/promises'
11
+ import { join, dirname, relative, resolve } from 'path'
12
+ import { ROOT_DIR } from '../root.js'
13
+ import { loadConfig } from '../config.js'
14
+
15
+ export const fileRoutes = new Hono()
16
+
17
+ // Read a file (path is relative to CONTENT_DIR)
18
+ fileRoutes.get('/', async (c) => {
19
+ const filePath = c.req.query('path')
20
+ if (!filePath) {
21
+ return c.json({ error: 'Missing path parameter' }, 400)
22
+ }
23
+
24
+ if (filePath.includes('..')) {
25
+ return c.json({ error: 'Invalid path' }, 400)
26
+ }
27
+
28
+ const config = await loadConfig()
29
+ const fullPath = join(ROOT_DIR, config.contentDir, filePath)
30
+
31
+ let content: string
32
+ try {
33
+ content = await readFile(fullPath, 'utf-8')
34
+ } catch (err) {
35
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
36
+ return c.json({ error: 'File not found' }, 404)
37
+ }
38
+ console.error('[astrocms] Failed to read file:', fullPath, err)
39
+ return c.json({ error: 'Failed to read file' }, 500)
40
+ }
41
+
42
+ return c.json({ path: filePath, content })
43
+ })
44
+
45
+ // Write a file (path is relative to CONTENT_DIR)
46
+ fileRoutes.post('/', async (c) => {
47
+ const body = await c.req.json<{ path: string; content: string }>()
48
+ if (!body.path || body.content === undefined) {
49
+ return c.json({ error: 'Missing path or content' }, 400)
50
+ }
51
+
52
+ if (body.path.includes('..')) {
53
+ return c.json({ error: 'Invalid path' }, 400)
54
+ }
55
+
56
+ try {
57
+ const config = await loadConfig()
58
+ const fullPath = join(ROOT_DIR, config.contentDir, body.path)
59
+ await mkdir(dirname(fullPath), { recursive: true })
60
+ await writeFile(fullPath, body.content, 'utf-8')
61
+ return c.json({ ok: true, path: body.path })
62
+ } catch (err) {
63
+ return c.json({ error: String(err) }, 500)
64
+ }
65
+ })
66
+
67
+ function isValidRelPath(p: unknown): p is string {
68
+ return typeof p === 'string' && p.length > 0 && !p.includes('..')
69
+ }
70
+
71
+ async function resolveSafe(relPath: string): Promise<string> {
72
+ const config = await loadConfig()
73
+ const base = resolve(ROOT_DIR, config.contentDir)
74
+ const full = resolve(base, relPath)
75
+ const rel = relative(base, full)
76
+ if (rel.startsWith('..') || resolve(base, rel) !== full) {
77
+ throw new Error('Invalid path')
78
+ }
79
+ return full
80
+ }
81
+
82
+ async function pathExists(p: string): Promise<boolean> {
83
+ try {
84
+ await access(p)
85
+ return true
86
+ } catch {
87
+ return false
88
+ }
89
+ }
90
+
91
+ // Create a new file (with default content)
92
+ fileRoutes.post('/create', async (c) => {
93
+ const body = await c.req.json<{ path: string; content?: string }>()
94
+ if (!isValidRelPath(body.path)) {
95
+ return c.json({ error: 'Invalid path' }, 400)
96
+ }
97
+ try {
98
+ const fullPath = await resolveSafe(body.path)
99
+ if (await pathExists(fullPath)) {
100
+ return c.json({ error: 'File already exists' }, 409)
101
+ }
102
+ await mkdir(dirname(fullPath), { recursive: true })
103
+ await writeFile(fullPath, body.content ?? '', 'utf-8')
104
+ return c.json({ ok: true, path: body.path })
105
+ } catch (err) {
106
+ return c.json({ error: String(err) }, 500)
107
+ }
108
+ })
109
+
110
+ // Rename / move a file or folder
111
+ fileRoutes.post('/rename', async (c) => {
112
+ const body = await c.req.json<{ from: string; to: string }>()
113
+ if (!isValidRelPath(body.from) || !isValidRelPath(body.to)) {
114
+ return c.json({ error: 'Invalid path' }, 400)
115
+ }
116
+ try {
117
+ const fromPath = await resolveSafe(body.from)
118
+ const toPath = await resolveSafe(body.to)
119
+ if (!(await pathExists(fromPath))) {
120
+ return c.json({ error: 'Source not found' }, 404)
121
+ }
122
+ if (await pathExists(toPath)) {
123
+ return c.json({ error: 'Destination already exists' }, 409)
124
+ }
125
+ await mkdir(dirname(toPath), { recursive: true })
126
+ await rename(fromPath, toPath)
127
+ return c.json({ ok: true, path: body.to })
128
+ } catch (err) {
129
+ return c.json({ error: String(err) }, 500)
130
+ }
131
+ })
132
+
133
+ // Duplicate a file or folder (recursive copy)
134
+ fileRoutes.post('/duplicate', async (c) => {
135
+ const body = await c.req.json<{ from: string; to: string }>()
136
+ if (!isValidRelPath(body.from) || !isValidRelPath(body.to)) {
137
+ return c.json({ error: 'Invalid path' }, 400)
138
+ }
139
+ try {
140
+ const fromPath = await resolveSafe(body.from)
141
+ const toPath = await resolveSafe(body.to)
142
+ if (!(await pathExists(fromPath))) {
143
+ return c.json({ error: 'Source not found' }, 404)
144
+ }
145
+ if (await pathExists(toPath)) {
146
+ return c.json({ error: 'Destination already exists' }, 409)
147
+ }
148
+ await mkdir(dirname(toPath), { recursive: true })
149
+ const s = await stat(fromPath)
150
+ if (s.isDirectory()) {
151
+ const { cp } = await import('fs/promises')
152
+ await cp(fromPath, toPath, { recursive: true })
153
+ } else {
154
+ const content = await readFile(fromPath)
155
+ await writeFile(toPath, content)
156
+ }
157
+ return c.json({ ok: true, path: body.to })
158
+ } catch (err) {
159
+ return c.json({ error: String(err) }, 500)
160
+ }
161
+ })
162
+
163
+ // Delete a file or folder (recursive)
164
+ fileRoutes.post('/delete', async (c) => {
165
+ const body = await c.req.json<{ path: string }>()
166
+ if (!isValidRelPath(body.path)) {
167
+ return c.json({ error: 'Invalid path' }, 400)
168
+ }
169
+ try {
170
+ const fullPath = await resolveSafe(body.path)
171
+ if (!(await pathExists(fullPath))) {
172
+ return c.json({ error: 'Not found' }, 404)
173
+ }
174
+ await rm(fullPath, { recursive: true, force: true })
175
+ return c.json({ ok: true })
176
+ } catch (err) {
177
+ return c.json({ error: String(err) }, 500)
178
+ }
179
+ })