heyquilt 0.3.174 → 0.3.176

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 (71) hide show
  1. package/README.md +6 -3
  2. package/RELEASES.md +30 -0
  3. package/bin/quilt.js +1 -75
  4. package/desktop/main.js +22 -9
  5. package/package.json +2 -3
  6. package/src/ai-vm.js +1 -1
  7. package/src/api/memory-store.js +1 -5
  8. package/src/api/server.js +4 -45
  9. package/src/api/supabase-store.js +0 -10
  10. package/src/autowork.js +7 -142
  11. package/src/base-pick.js +125 -12
  12. package/src/branch-view.js +1 -1
  13. package/src/connection.js +12 -37
  14. package/src/control.js +16 -93
  15. package/src/fsutil.js +1 -1
  16. package/src/git-aside.js +70 -0
  17. package/src/github-commit.js +1 -2
  18. package/src/gitstate.js +326 -0
  19. package/src/held.js +12 -53
  20. package/src/history.js +1 -25
  21. package/src/live-merge.js +42 -161
  22. package/src/mcp.js +6 -90
  23. package/src/merge3.js +21 -5
  24. package/src/pathrules.js +1 -1
  25. package/src/protocol.js +6 -11
  26. package/src/read-bases.js +3 -5
  27. package/src/relay-live-write.js +37 -44
  28. package/src/relay-mcp.js +30 -164
  29. package/src/relay-prune.js +3 -6
  30. package/src/relay-turn-sync.js +7 -11
  31. package/src/runner.js +2 -4
  32. package/src/server.js +61 -1717
  33. package/src/session.js +895 -844
  34. package/src/setup.js +11 -3
  35. package/src/status.js +2 -5
  36. package/src/swap-in.js +56 -13
  37. package/src/turn-sync-plan.js +2 -2
  38. package/src/turn-sync.js +1 -1
  39. package/src/ui/agent-guide.js +3 -1
  40. package/src/ui/app.css +4 -96
  41. package/src/ui/app.js +1 -1
  42. package/src/ui/chat.js +2 -6
  43. package/src/ui/cloud-ai-model.js +0 -13
  44. package/src/ui/cloud-ai.js +2 -10
  45. package/src/ui/connections.js +2 -1
  46. package/src/ui/fileview.js +7 -20
  47. package/src/ui/git-rule.js +2 -13
  48. package/src/ui/home.js +2 -8
  49. package/src/ui/session-words.js +27 -0
  50. package/src/ui/session.js +34 -407
  51. package/src/ui-server.js +7 -56
  52. package/src/api/routes/seam-connect.js +0 -103
  53. package/src/api/routes/session-migrate.js +0 -39
  54. package/src/force-date.js +0 -27
  55. package/src/quilt-default.js +0 -84
  56. package/src/quilt-history.js +0 -106
  57. package/src/quilt-remote.js +0 -78
  58. package/src/seam-access.js +0 -97
  59. package/src/seam-url.js +0 -15
  60. package/src/session-follow.js +0 -583
  61. package/src/session-layout3.js +0 -466
  62. package/src/session-migrate.js +0 -123
  63. package/src/session-quilt.js +0 -126
  64. package/src/session-seam.js +0 -312
  65. package/src/source-live/bring-in.js +0 -391
  66. package/src/source-live/land.js +0 -410
  67. package/src/source-live/live-block.js +0 -1166
  68. package/src/source-live/live-square.js +0 -116
  69. package/src/ui/force-words.js +0 -19
  70. package/src/ui/quiltview.js +0 -213
  71. package/src/ui/seam-model.js +0 -309
package/src/ui-server.js CHANGED
@@ -26,7 +26,6 @@ import { effectiveAccess, builtinType } from './session-access.js'
26
26
  import { cleanSessionName, BAD_SESSION_NAME, SESSION_NAME_MAX } from './session-name.js'
27
27
  import { personPasses, personApiAuth } from './pass-source.js'
28
28
  import { INVALID_INVITE, NO_LINK_YET, joinFolderName } from './ui/invite.js'
29
- import { seamResultWords } from './ui/seam-model.js'
30
29
  import { loadIdentity } from './identity.js'
31
30
  import { currentVersion, localReleases, latestRelease, compareVersions, downloadUrl, seenVersion, markSeen, hiddenUpdate, hideUpdate } from './releases.js'
32
31
  import { createReporter } from './report.js'
@@ -47,8 +46,8 @@ const THEMES = ['light', 'dark', 'system']
47
46
  const SAVE_FAILED = "Quilt couldn't save your sign-in on this computer."
48
47
  const SIGNED_OUT_MESSAGE = 'This computer was signed out. Sign in again.'
49
48
  const LOCAL_RELAY_GONE = "This session ran on your computer's own relay, which Quilt no longer supports. Your files are untouched."
50
- // 16's R2: no New session from GitHub. Said to an older window that still offers it.
51
- export const GITHUB_GONE = 'Starting a session from GitHub is gone: start one from a folder (a new session\'s code is committed in Seam from the start), and bring a repository\'s history into Seam with seam github import.'
49
+ // There is no New session from GitHub. Said to an older window that still offers it.
50
+ export const GITHUB_GONE = 'Starting a session from GitHub is gone: clone the repository and start a session from its folder. The session\'s folder is a git folder: commit and push with git as usual.'
52
51
  const STATUS_PUSH_MS = 500 // a session's status goes to the window at most this often when the session changes it
53
52
  // Until this computer is signed in, only these answer.
54
53
  const OPEN_ROUTES = new Set(['GET /api/account', 'POST /api/account/start', 'POST /api/account/signup', 'POST /api/account/signup/confirm', 'POST /api/account/cancel', 'POST /api/account/signout', 'GET /api/events', 'POST /api/shutdown', 'POST /api/report'])
@@ -116,11 +115,6 @@ function updateProfile (b) {
116
115
  patch.autoModel = m || undefined
117
116
  }
118
117
  if ('autoFiles' in b) patch.autoFiles = b.autoFiles ? true : undefined
119
- // Whether a run of the person's AI may merge a square under its line's policy (Seam, 12): never unless they say so.
120
- if ('autoMerge' in b) {
121
- if (!['never', 'policy'].includes(b.autoMerge)) throw httpError(400, 'Pick Never, or When the line\'s rules allow it.')
122
- patch.autoMerge = b.autoMerge === 'policy' ? 'policy' : undefined
123
- }
124
118
  if ('autoCap' in b) {
125
119
  const n = b.autoCap === '' || b.autoCap === null ? 0 : Number(b.autoCap)
126
120
  if (!Number.isInteger(n) || n < 0 || n > 1e9) throw httpError(400, 'The daily limit is a whole number of tokens (0 for none).')
@@ -182,7 +176,6 @@ export const STATIC = {
182
176
  '/changes.js': ['changes.js', 'text/javascript; charset=utf-8'],
183
177
  '/changes-seen.js': ['changes-seen.js', 'text/javascript; charset=utf-8'],
184
178
  '/diffview.js': ['diffview.js', 'text/javascript; charset=utf-8'],
185
- '/quiltview.js': ['quiltview.js', 'text/javascript; charset=utf-8'],
186
179
  '/boxes.js': ['boxes.js', 'text/javascript; charset=utf-8'],
187
180
  '/releases.js': ['releases.js', 'text/javascript; charset=utf-8'],
188
181
  '/feed-convs.js': ['feed-convs.js', 'text/javascript; charset=utf-8'],
@@ -207,8 +200,7 @@ export const STATIC = {
207
200
  '/preview-model.js': ['preview-model.js', 'text/javascript; charset=utf-8'],
208
201
  '/sounds.js': ['sounds.js', 'text/javascript; charset=utf-8'],
209
202
  '/git-rule.js': ['git-rule.js', 'text/javascript; charset=utf-8'],
210
- '/seam-model.js': ['seam-model.js', 'text/javascript; charset=utf-8'],
211
- '/force-words.js': ['force-words.js', 'text/javascript; charset=utf-8'],
203
+ '/session-words.js': ['session-words.js', 'text/javascript; charset=utf-8'],
212
204
  '/cloud-ai.js': ['cloud-ai.js', 'text/javascript; charset=utf-8'],
213
205
  '/cloud-ai-model.js': ['cloud-ai-model.js', 'text/javascript; charset=utf-8'],
214
206
  '/sandbox-keys.js': ['sandbox-keys.js', 'text/javascript; charset=utf-8'],
@@ -454,7 +446,7 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
454
446
  }
455
447
 
456
448
  async function start ({ mode, dir, tool, invite, room, name, prefer, workspace }) {
457
- // New session from GitHub went in 16's R2: new sessions are quilts (quilt-default.js), and a repository's history comes into Seam by its import.
449
+ // An older window may still ask for a session from GitHub: it is told to start from a folder.
458
450
  if (mode === 'github') throw httpError(410, GITHUB_GONE)
459
451
  const me = profile()
460
452
  // Every session signs in to the relay as this computer's account.
@@ -525,8 +517,6 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
525
517
  apiAuth: personApiAuth,
526
518
  // A new session is named after its folder (the owner can rename it later).
527
519
  startName: mode === 'create' ? cleanSessionName([...path.basename(dir)].slice(0, SESSION_NAME_MAX).join('')) || '' : '',
528
- // A new session is a quilt from the start when the API says so (quilt-default.js).
529
- newSession: mode === 'create',
530
520
  workspace: workspace || '',
531
521
  onLog: log,
532
522
  onFatal: async (err) => {
@@ -554,8 +544,6 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
554
544
  const s = entry.run.session
555
545
  s.on('status-changed', () => pushSoon(id))
556
546
  s.on('access', () => pushSoon(id))
557
- s.on('quilt', () => pushSoon(id))
558
- s.on('quilt-shadow', () => pushSoon(id))
559
547
  s.on('message', (m) => broadcast('message', { id, message: m }))
560
548
  s.on('agent-feed', (entries) => broadcast('feed', { id, entries }))
561
549
  s.on('file-changed', (e) => broadcast('file-changed', { id, ...e }))
@@ -578,7 +566,6 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
578
566
  if (workspace && mode === 'create') {
579
567
  // Put the new room in its workspace before anyone else connects. A failure is logged, never
580
568
  // fatal, and the session is outside any workspace here too, as it is on the API.
581
- // A new session from a folder (New session from GitHub went in 16's R2).
582
569
  const linked = await asAccount((token) => setSessionWorkspace({ token, id: workspace, room: conn.room })).then(() => true, (err) => {
583
570
  log(`could not add this session to its workspace: ${err.message}`)
584
571
  forgetWorkspace(entry.run.dir)
@@ -1215,21 +1202,11 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
1215
1202
  'GET /api/sessions/:id/changes': (b, id) => get(id).changes(),
1216
1203
  'POST /api/sessions/:id/catch-up/dismiss': (b, id) => { const r = get(id).dismissCatchUp(); pushStatus(id); return r },
1217
1204
  // One file's changes, newest first, each with its diff (the Changes panel's "What changed").
1218
- // In a session linked to a quilt, its History: the live changes, then the patches from Seam's log.
1219
- 'GET /api/sessions/:id/history': async (b, id, url) => {
1205
+ 'GET /api/sessions/:id/history': (b, id, url) => {
1220
1206
  const file = String(url.searchParams.get('path') || '')
1221
- const s = get(id)
1222
- const linked = s.quiltLink() ? await s.fileHistory(file) : null
1223
- if (linked) return { entries: linked.live, patches: linked.patches, quilt: linked.quilt, ...(linked.note ? { note: linked.note } : {}) }
1224
- const entries = s.history.entries().filter((e) => e.path === file)
1207
+ const entries = get(id).history.entries().filter((e) => e.path === file)
1225
1208
  return { entries: queryHistory(entries, { limit: 100 }).reverse() }
1226
1209
  },
1227
- // A linked session's Blame of a file, one patch of its History, and code search (the relay reads Seam).
1228
- 'GET /api/sessions/:id/blame': (b, id, url) => get(id).quiltBlame(String(url.searchParams.get('path') || '')),
1229
- 'GET /api/sessions/:id/patch': (b, id, url) => get(id).quiltShow(String(url.searchParams.get('commit') || ''), String(url.searchParams.get('path') || '')),
1230
- 'GET /api/sessions/:id/search': (b, id, url) => get(id).quiltSearch(String(url.searchParams.get('q') || '')),
1231
- // In a session that moved into Seam: the square panel's Commit and Merge onto main, as this member (control.js seamTool).
1232
- 'POST /api/sessions/:id/seam': (b, id) => squareTool(get(id), b),
1233
1210
  'GET /api/sessions/:id/file': (b, id, url) => {
1234
1211
  const f = get(id).readShared(url.searchParams.get('path'))
1235
1212
  if (!f) throw httpError(404, 'That file is not in this session.')
@@ -1262,8 +1239,6 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
1262
1239
  return { on: r.run.session.setSummarize(b.on ? r.run.summarizer() : null) }
1263
1240
  },
1264
1241
  'POST /api/sessions/:id/sharing': (b, id) => ({ on: get(id).setAgentSharing(b.on !== false) }),
1265
- // The owner's stale_write_minutes (held.js): how long a write may not remove lines someone else added (0: off).
1266
- 'POST /api/sessions/:id/stale-write': (b, id) => owned(id).setStaleWrite(b.minutes),
1267
1242
  'POST /api/recent/forget': (b) => {
1268
1243
  const dir = path.resolve(expandHome(String(b.dir || '')))
1269
1244
  const room = readConfig(dir)?.room
@@ -1310,12 +1285,10 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
1310
1285
  reporter.record({ kind: 'error', name: String(b.name || 'renderer').slice(0, 80), outcome: 'error', message: String(b.message || '').slice(0, 500), context: typeof b.context === 'object' && b.context ? b.context : {} })
1311
1286
  return { ok: true }
1312
1287
  },
1313
- // New session from GitHub's lists, gone in 16's R2: an older window that asks is told why.
1288
+ // New session from GitHub's lists are gone: an older window that asks is told why.
1314
1289
  'GET /api/github/status': () => { throw httpError(410, GITHUB_GONE) },
1315
1290
  'GET /api/github/repos': () => { throw httpError(410, GITHUB_GONE) },
1316
1291
  'GET /api/github/branches': () => { throw httpError(410, GITHUB_GONE) },
1317
- // "Make this a quilt" (Seam's plans 16, flag 9): the owner's button. The relay makes the session a quilt and moves it into its squares, as the owner.
1318
- 'POST /api/sessions/:id/quilt-make': async (b, id) => { try { return await get(id).quiltMake(process.env.SEAM_TOKEN || (readAccount() || {}).token) } finally { pushStatus(id) } },
1319
1292
  'GET /api/fs': (b, id, url) => listDir(url.searchParams.get('path') || os.homedir()),
1320
1293
  // Reply first, then shut down, so the page hears back before we exit.
1321
1294
  'POST /api/shutdown': () => {
@@ -1647,28 +1620,6 @@ export function underJoinDir (joinDir, name, message = INVALID_INVITE) {
1647
1620
  return dir
1648
1621
  }
1649
1622
 
1650
- /**
1651
- * The square panel's buttons (layout 3): seam_commit with a message, or seam_merge (a message for what it
1652
- * commits first), as this member through Seam's own tools; or open_square, for a folder whose branch has
1653
- * none (Session.openSquareHere). The answer as { text }, a refusal as a 400.
1654
- */
1655
- export async function squareTool (s, b) {
1656
- const tool = String((b && b.tool) || '')
1657
- if (tool === 'open_square') {
1658
- if (!s.openSquareHere) throw httpError(409, 'This session\'s code is not in Seam.')
1659
- try { return { text: (await s.openSquareHere()).text } } catch (err) { throw httpError(400, err.message) }
1660
- }
1661
- if (tool !== 'seam_commit' && tool !== 'seam_merge') throw httpError(400, 'The app commits or merges the square, or opens one: seam_commit, seam_merge or open_square.')
1662
- if (!s.seamTool) throw httpError(409, 'This session\'s code is not in Seam.')
1663
- const message = b.args && typeof b.args.message === 'string' ? b.args.message.trim().slice(0, 2000) : ''
1664
- if (tool === 'seam_commit' && !message) throw httpError(400, 'Say what the commit is.')
1665
- const r = await s.seamTool({ tool, args: message ? { message } : {} })
1666
- const text = ((r && r.content) || []).map((c) => c.text || '').join('\n').trim()
1667
- if (r && r.isError) throw httpError(400, text || 'Seam refused.')
1668
- // Plain words for a person (seam-model.js), not the tool's text an AI reads.
1669
- return { text: seamResultWords(tool, { structuredContent: r && r.structuredContent, text }) || 'Done.' }
1670
- }
1671
-
1672
1623
  function httpError (status, message) {
1673
1624
  return Object.assign(new Error(message), { status })
1674
1625
  }
@@ -1,103 +0,0 @@
1
- // "Connect Seam": a Quilt person links their own Seam account to Quilt, the way any app connects
2
- // to Seam (Seam's OAuth 2, authorization code with PKCE). Quilt never shares accounts with Seam:
3
- // it keeps the person's Seam token and calls Seam's HTTP API with it. Off unless Quilt is
4
- // registered as a Seam app (seamClientId, env QUILT_SEAM_CLIENT_ID).
5
- //
6
- // The PKCE verifier is never stored: `state` carries who asked and until when, signed with
7
- // Quilt's secret, and the verifier is an HMAC of the state, so any API machine can finish it.
8
- import crypto from 'node:crypto'
9
- import { HttpError, Raw } from '../http.js'
10
-
11
- export const CONNECT_MS = 10 * 60_000
12
- const REFRESH_EARLY_MS = 60_000
13
-
14
- const b64 = (b) => Buffer.from(b).toString('base64url')
15
- const mac = (secret, text) => crypto.createHmac('sha256', secret).update(text).digest('base64url')
16
- const same = (a, b) => a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
17
- const page = (status, title, text) => new Raw(status, `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font:16px system-ui;margin:4em auto;max-width:32em"><h1>${title}</h1><p>${text}</p></body>`, 'text/html; charset=utf-8')
18
-
19
- export function seamConnectRoutes ({ store, person, now = Date.now, apiUrl, seamUrl, seamSiteUrl = 'https://seam.heyquilt.com', clientId, secret, fetch = globalThis.fetch, log = () => {} }) {
20
- if (!clientId || !secret || !seamUrl || !store.seamLink) return []
21
- const seam = String(seamUrl).replace(/\/+$/, '')
22
- const site = String(seamSiteUrl).replace(/\/+$/, '')
23
- const redirectUri = `${String(apiUrl).replace(/\/+$/, '')}/v1/seam/connect/callback`
24
- const verifierOf = (state) => mac(secret, `seam-pkce\0${state}`)
25
- const userOf = (p) => p.userId || p.id
26
-
27
- function makeState (userId) {
28
- const body = b64(JSON.stringify({ u: userId, e: now() + CONNECT_MS, n: crypto.randomBytes(12).toString('base64url') }))
29
- return `${body}.${mac(secret, `seam-state\0${body}`)}`
30
- }
31
- function readState (state) {
32
- const [body, sig] = String(state || '').split('.')
33
- if (!body || !sig || !same(sig, mac(secret, `seam-state\0${body}`))) return null
34
- try {
35
- const s = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'))
36
- return s && s.e > now() ? s : null
37
- } catch { return null }
38
- }
39
-
40
- async function tokenCall (form) {
41
- let res
42
- try { res = await fetch(`${seam}/oauth/token`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, body: new URLSearchParams({ client_id: clientId, ...form }).toString(), signal: AbortSignal.timeout(10_000) }) } catch { throw new HttpError(503, 'Seam could not be reached; try again') }
43
- const data = await res.json().catch(() => null)
44
- if (!res.ok || !data?.access_token) return { error: data?.error || `seam_${res.status}`, detail: data?.error_description || '' }
45
- return { access: data.access_token, refresh: data.refresh_token, scope: data.scope || '', expiresAt: now() + Number(data.expires_in || 3600) * 1000 }
46
- }
47
-
48
- /** The person's Seam access token, refreshed when it is about to end; null when not connected. */
49
- async function freshToken (userId) {
50
- const link = await store.seamLink(userId)
51
- if (!link) return null
52
- if (link.expiresAt - REFRESH_EARLY_MS > now()) return link
53
- const t = await tokenCall({ grant_type: 'refresh_token', refresh_token: link.refresh })
54
- if (t.error) {
55
- // Seam ended the grant (revoked on seam.heyquilt.com, or the token was reused): connect again.
56
- if (t.error === 'invalid_grant' || t.error === 'invalid_client') { await store.deleteSeamLink(userId); return null }
57
- throw new HttpError(503, 'Seam could not refresh your connection; try again')
58
- }
59
- return store.putSeamLink(userId, { ...t, connectedAt: link.connectedAt })
60
- }
61
-
62
- return [
63
- // { scope? } → { url }: the page on Seam's site where the person allows Quilt.
64
- ['POST', /^\/v1\/seam\/connect$/, async (req, body) => {
65
- const p = await person(req)
66
- const scope = String(body?.scope || 'quilts:write').trim()
67
- const state = makeState(userOf(p))
68
- const challenge = crypto.createHash('sha256').update(verifierOf(state)).digest('base64url')
69
- const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: 'code', scope, state, code_challenge: challenge, code_challenge_method: 'S256' })
70
- return { url: `${site}/oauth/authorize?${q}` }
71
- }],
72
- // Seam sends the browser back here with a code (or error=access_denied).
73
- ['GET', /^\/v1\/seam\/connect\/callback$/, async (req) => {
74
- const q = new URL(req.url, 'http://x').searchParams
75
- const s = readState(q.get('state'))
76
- if (!s) return page(400, 'Seam was not connected', 'This link expired or was not made by Quilt. Start again from Quilt.')
77
- if (q.get('error')) return page(200, 'Seam was not connected', 'You chose not to connect Seam. You can connect it from Quilt any time.')
78
- const t = await tokenCall({ grant_type: 'authorization_code', code: q.get('code') || '', redirect_uri: redirectUri, code_verifier: verifierOf(q.get('state')) })
79
- if (t.error) { log(`seam connect: ${t.error} ${t.detail}`); return page(400, 'Seam was not connected', 'Seam did not accept this sign-in. Start again from Quilt.') }
80
- await store.putSeamLink(s.u, { ...t, connectedAt: now() })
81
- return page(200, 'Seam is connected', 'Quilt can now use Seam as you. You can close this tab.')
82
- }],
83
- ['GET', /^\/v1\/seam\/connection$/, async (req) => {
84
- const link = await store.seamLink(userOf(await person(req)))
85
- return link ? { connected: true, scope: link.scope, connectedAt: link.connectedAt } : { connected: false }
86
- }],
87
- // The person's own Seam token, for their app to call Seam's API with.
88
- ['GET', /^\/v1\/seam\/token$/, async (req) => {
89
- const link = await freshToken(userOf(await person(req)))
90
- if (!link) throw new HttpError(404, 'Seam is not connected: connect it first')
91
- return { access_token: link.access, token_type: 'Bearer', expires_at: link.expiresAt, scope: link.scope, seam_url: seam }
92
- }],
93
- ['DELETE', /^\/v1\/seam\/connection$/, async (req) => {
94
- const userId = userOf(await person(req))
95
- const link = await store.seamLink(userId)
96
- if (link) {
97
- await fetch(`${seam}/oauth/revoke`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token: link.refresh }).toString(), signal: AbortSignal.timeout(10_000) }).catch(() => {})
98
- await store.deleteSeamLink(userId)
99
- }
100
- return { connected: false }
101
- }]
102
- ]
103
- }
@@ -1,39 +0,0 @@
1
- // Making a session a quilt (Seam's plans/quilt-source-control/16, "How a session becomes a quilt"):
2
- // POST /v1/sessions/:room/migrate { dry_run, token, step }. The session's owner, signed in, asks here
3
- // (step 'make' is "Make this a quilt": made and moved into its squares in one go; 'switch' moves the session's files into its squares, layout 3; 'unswitch' goes back;
4
- // 'shadow' links a session with a git remote to the quilt its import fills, 16 step 1);
5
- // the relay machine holding the room does the work (POST /quilt/migrate, with the relay secret),
6
- // so this is the same operation as the MCP tool and `quilt session migrate`. Seam is called as the
7
- // owner: with `token` (their Seam sign-in) when given, else the sign-in they used here. The relay
8
- // refuses while Seam is off for it (QUILT_SOURCE_URL), so nothing changes until that flag is set.
9
- import { HttpError } from '../http.js'
10
-
11
- const ROOM = /^[A-Za-z0-9_-]{1,64}$/
12
- const NO_SESSION = 'no such session'
13
- const MIGRATE_TIMEOUT_MS = 5 * 60 * 1000 // a large session's patch 1 and squares take a while
14
-
15
- export function sessionMigrateRoutes ({ store, person, bearer, relaySecret, cluster }) {
16
- return [
17
- ['POST', /^\/v1\/sessions\/([^/]+)\/migrate$/, async (req, body, [room]) => {
18
- const account = `person:${(await person(req)).userId}`
19
- if (!ROOM.test(room)) throw new HttpError(404, NO_SESSION)
20
- const session = await store.sessionByRoom(room).catch(() => null)
21
- if (!session) throw new HttpError(404, NO_SESSION)
22
- if (session.ownerAccount !== account) throw new HttpError(403, 'Only the session owner can make it a quilt.')
23
- if (!relaySecret) throw new HttpError(503, 'the relay is not set up on this server')
24
- const dry = body && body.dry_run === true
25
- const token = body && typeof body.token === 'string' && body.token ? body.token : bearer(req)
26
- const where = await store.relayRoom(room).catch(() => null)
27
- const step = body && (body.step === 'make' || body.step === 'switch' || body.step === 'unswitch' || body.step === 'shadow') ? body.step : null
28
- // step 'shadow' (16 step 1): `quilt` names the quilt an import of the session's git remote fills; null unlinks.
29
- const quilt = step === 'shadow' && typeof body.quilt === 'string' && body.quilt ? body.quilt.slice(0, 200) : null
30
- const ask = { room, account, ...(dry ? { dry_run: true } : { token }), ...(step && !dry ? { step } : {}), ...(step === 'shadow' && !dry ? { quilt } : {}), ...(step === 'unswitch' && !dry && Array.isArray(body.carried) ? { carried: body.carried.filter((x) => typeof x === 'string').slice(0, 200) } : {}) }
31
- try {
32
- return await cluster.callRelay((where && where.machineId) || '', 'POST', '/quilt/migrate', ask, { timeoutMs: MIGRATE_TIMEOUT_MS })
33
- } catch (err) {
34
- const said = String(err.message).replace(/^relay .*? answered \d+: /, '')
35
- throw new HttpError(err.status && err.status < 500 ? err.status : 502, said)
36
- }
37
- }]
38
- ]
39
- }
package/src/force-date.js DELETED
@@ -1,27 +0,0 @@
1
- // The forced date (Seam's plans/quilt-source-control/16, flag 9): QUILT_SOURCE_FORCE_AT=<date> on the
2
- // relay. Unset (or not a date), nothing happens. From the date on, a session still in git mode is
3
- // moved on without anyone losing work: one with no git remote becomes a quilt without history on its
4
- // owner's next open; one with a git remote that has not cut over keeps chat, tasks, the agent feed and
5
- // the audit trail, and its live file sync stops for good (git, its remote, clones and CI untouched).
6
- // Pure: no I/O (test/unit/force-date.test.js). The words are in ui/force-words.js, which the app loads too.
7
- export { syncStoppedWords, forceAheadWords } from './ui/force-words.js'
8
-
9
- /** The date as ms, or null when unset or not a date. */
10
- export function forceAtMs (env = process.env) {
11
- const v = String(env.QUILT_SOURCE_FORCE_AT || '').trim()
12
- if (!v) return null
13
- const ms = Date.parse(v)
14
- return Number.isFinite(ms) ? ms : null
15
- }
16
-
17
- /**
18
- * What the date means for a session now: null (no date, not yet, or already a quilt in its squares),
19
- * 'stop' (a git remote, not cut over: live sync stops), or 'migrate' (no git remote: its owner's next
20
- * open makes it a quilt without history).
21
- */
22
- export function forcedAction ({ at, now = Date.now(), layout = 2, remote = false, stopped = false }) {
23
- if (stopped) return 'stop'
24
- if (at == null || now < at || layout === 3) return null
25
- return remote ? 'stop' : 'migrate'
26
- }
27
-
@@ -1,84 +0,0 @@
1
- // New sessions are quilts from the start (Seam's plans/quilt-source-control/16, flags order 8,
2
- // QUILT_SOURCE_DEFAULT=1 on the accounts API): the app that starts a session (the desktop app,
3
- // `quilt start`, or an AI's quilt_start_session; every tool goes through the same Session) makes it
4
- // a quilt without history as soon as the folder's files have reached the relay: patch 1 holds them
5
- // (binaries and modes too), and the room moves to layout 3 with a square for the folder.
6
- //
7
- // Nothing is lost when it can't: a folder with a git remote is not made a quilt here (16: a room
8
- // with a git remote becomes a quilt only with its history, which flag 9's "Make this a quilt"
9
- // starts), and any failure leaves the session a working git-mode session, with the reason said to
10
- // the owner and their AIs and `quilt session migrate` to try again by hand.
11
- import { execFileSync } from 'node:child_process'
12
- import { apiUrl } from './account.js'
13
-
14
- const FEATURES_TIMEOUT_MS = 5000
15
- const SYNC_TRIES = 20
16
- const SYNC_WAIT_MS = 500
17
-
18
- /** Whether the accounts API at `api` has new sessions start as quilts (GET /v1/features `quilt_source_default`). False when it can't say. */
19
- export async function quiltDefaultOn ({ api = apiUrl(), fetch: fetchImpl = globalThis.fetch } = {}) {
20
- try {
21
- const res = await fetchImpl(`${String(api).replace(/\/+$/, '')}/v1/features`, { signal: AbortSignal.timeout(FEATURES_TIMEOUT_MS) })
22
- if (!res.ok) return false
23
- const f = await res.json()
24
- return !!(f && f.quilt_source_default === true)
25
- } catch { return false }
26
- }
27
-
28
- /** Whether the folder at `root` is a git repository with a remote (its history belongs in the quilt: 16 "With history"). */
29
- export function folderHasGitRemote (root) {
30
- try {
31
- return execFileSync('git', ['--no-optional-locks', 'remote'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }).trim().length > 0
32
- } catch { return false }
33
- }
34
-
35
- const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
36
-
37
- /**
38
- * Makes the new session `session` a quilt (migrate, then the layout-3 switch) as its owner, once.
39
- * Resolves to { done: true, quilt } or { done: false, why }; never throws.
40
- */
41
- export async function startAsQuilt (session, { flagOn = quiltDefaultOn, credential, hasRemote = folderHasGitRemote, syncTries = SYNC_TRIES, syncWaitMs = SYNC_WAIT_MS } = {}) {
42
- const skip = (why) => ({ done: false, why })
43
- try {
44
- if (!(await flagOn())) return skip('off')
45
- if (session.stopped) return skip('stopped')
46
- if (session.quilt) return skip('already a quilt')
47
- if (session.root && hasRemote(session.root)) {
48
- session.log('🧵 this folder has a git remote, so the new session stays on git: it becomes a quilt with its history later (Make this a quilt).')
49
- return skip('git remote')
50
- }
51
- if (session.branchForm === 'diff') return skip('diff branch')
52
- // The folder's files are its patch 1: they must all be on the relay first.
53
- let synced = false
54
- for (let i = 0; i < syncTries && !synced && !session.stopped; i++) {
55
- if (session.ready && !session.seeding) {
56
- try { session.flushPending?.() } catch {}
57
- try { await session.conn.confirmBranch(); synced = true; break } catch {}
58
- }
59
- await wait(syncWaitMs)
60
- }
61
- if (session.stopped) return skip('stopped')
62
- if (!synced) throw new Error("the folder's files had not all reached the relay")
63
- if (session.quilt) return skip('already a quilt')
64
- const token = await credential()
65
- if (!token) throw new Error('no sign-in to reach Seam with')
66
- const m = await session.quiltMigrate(token)
67
- await session.quiltSwitch(token)
68
- // The folder equals patch 1, so the switch opened no square for it: one is opened now, as the
69
- // owner, and the folder follows it (16: a square for the session's first folder). Should that
70
- // fail, the session is a quilt still, and the folder's first edit asks for its square (readOnly).
71
- for (let i = 0; i < syncTries * 4 && !session.stopped && !(session.quilt && session.quilt.layout === 3); i++) await wait(syncWaitMs / 4)
72
- const branch = typeof session.branchKey === 'function' ? session.branchKey() : session.branch
73
- if (session.quilt && session.quilt.layout === 3 && !(session.quilt.live || {})[branch]) {
74
- try { await session.openBranchSquare(branch, { quiet: false, token }) } catch (err) { session.log(`🧵 couldn't open a square for this folder yet (${err.message}); its first edit asks again.`) }
75
- }
76
- session.log(`🧵 new session: its code is in Seam from the start (quilt ${(m.quilt && m.quilt.slug) || ''}, patch 1).`)
77
- return { done: true, quilt: m.quilt }
78
- } catch (err) {
79
- const why = String((err && err.message) || err)
80
- session.log(`🧵 this new session's code could not go into Seam (${why}); the session works as before, on git. The owner can try again with: quilt session migrate`)
81
- if (session.notice) { try { session.notice(`This new session's code could not go into Seam (${why}), so it stays on git for now. The session owner can try again with \`quilt session migrate\`.`) } catch {} }
82
- return skip(why)
83
- }
84
- }
@@ -1,106 +0,0 @@
1
- // quilt_history in a session linked to a quilt (Seam's plans/quilt-source-control/16, step 1
2
- // "Shadow", and after the session became a quilt): the chronology is Seam's log (the commits and
3
- // patches, imported from git or made in Seam) plus the session's own live record of changes not
4
- // committed yet (the branch document's `history`, history.js), oldest first, newest kept.
5
- //
6
- // Quilt reads Seam over its HTTP API (a client with the @heyquilt/seam quiltClient shape: `log`,
7
- // `show`), as the member (Session.seamMember) or, on the relay, with the room's read token. When
8
- // Seam can't be read, the session's own record is shown with a note, never an error: the tool
9
- // worked before the link and keeps working without Seam. The same for every AI tool: this runs
10
- // behind quilt_history in both MCP servers (mcp.js through the folder's daemon, relay-mcp.js).
11
- import { MAX_DIFF_CHARS, queryHistory } from './history.js'
12
-
13
- /**
14
- * The quilt a room's chronology reads from: `{ id, slug, at?, shadow? }`, or null. A quilt the
15
- * session became (meta.quilt_id), or the quilt it shadows while git is still the authority
16
- * (meta.quiltShadow, 16 step 1: an import following the session's git remote). Only with Seam
17
- * on (QUILT_SOURCE_URL), so every other session reads its own record exactly as before.
18
- */
19
- export function historyQuilt (meta, env = process.env) {
20
- if (!env || !env.QUILT_SOURCE_URL || !meta) return null
21
- if (typeof meta.quilt_id === 'string' && meta.quilt_id) {
22
- const q = meta.quilt || {}
23
- return { id: meta.quilt_id, slug: q.slug || '', ...(q.at ? { at: q.at } : {}) }
24
- }
25
- const s = meta.quiltShadow
26
- if (s && typeof s.id === 'string' && s.id) return { id: s.id, slug: s.slug || '', shadow: true }
27
- return null
28
- }
29
-
30
- /** The part of a path or glob Seam's log can filter by: a file, or the folder before the first wildcard. */
31
- export function seamPathOf (p) {
32
- const s = String(p || '').replace(/\\/g, '/').replace(/^\.\//, '')
33
- if (!s) return ''
34
- const wild = s.search(/[*?[{]/)
35
- if (wild < 0) return s.replace(/\/+$/, '')
36
- const dir = s.slice(0, wild)
37
- return dir.includes('/') ? dir.slice(0, dir.lastIndexOf('/')) : ''
38
- }
39
-
40
- const MAX_SHOWN = 10 // commits whose diffs are read when asked for them
41
-
42
- /**
43
- * The quilt's log as chronology entries, oldest first: one per commit, `{ seam: true, commit,
44
- * short, patch, by, ts, message, files, task, diff }`. `since` is a timestamp. Throws what Seam
45
- * said when it can't be read.
46
- */
47
- export async function seamHistory (seam, quilt, { path = '', by, since, task, limit = 30, withDiff = false, rev = 'main' } = {}) {
48
- const p = seamPathOf(path)
49
- const r = await seam.log(quilt, { rev, limit: Math.min(Number(limit) || 30, 200), ...(p ? { paths: [p] } : {}), ...(by ? { author: by } : {}), ...(typeof since === 'number' ? { since: String(Math.floor(since)) } : {}), ...(task ? { task } : {}) })
50
- const out = []
51
- for (const c of (r && r.commits) || []) {
52
- if (!c || !c.id) continue
53
- const a = c.author || {}
54
- out.push({
55
- id: `seam:${c.id}`,
56
- seam: true,
57
- commit: c.id,
58
- short: c.short || c.id.slice(0, 12),
59
- ...(c.patch && c.patch.patch_no != null ? { patch: { line: c.patch.line || rev, no: c.patch.patch_no } } : {}),
60
- by: String(a.name || a.member_id || ''),
61
- ts: Number(c.at ?? c.authored_at) || 0,
62
- message: String(c.message || '').split('\n')[0].slice(0, 200),
63
- files: Number(c.files) || (Array.isArray(c.changes) ? c.changes.length : 0),
64
- task: c.task_id ? { id: String(c.task_id), title: '' } : null,
65
- path: p,
66
- diff: ''
67
- })
68
- }
69
- if (withDiff) {
70
- for (const e of out.slice(0, MAX_SHOWN)) {
71
- try {
72
- const s = await seam.show(quilt, e.commit, { format: 'unified', ...(p ? { paths: [p] } : {}) })
73
- const text = ((s && s.diff && s.diff.files) || []).map((f) => f.patch || (f.binary ? `${f.path}: binary` : '')).filter(Boolean).join('\n')
74
- e.diff = text.length > MAX_DIFF_CHARS ? `${text.slice(0, MAX_DIFF_CHARS)}\n… (diff truncated)` : text
75
- } catch { e.diff = '' }
76
- }
77
- }
78
- return out.sort((x, y) => x.ts - y.ts)
79
- }
80
-
81
- /**
82
- * The chronology of a linked session: the quilt's log (`seam`, a client) and the session's own
83
- * record (`entries`, history.js), filtered by `query` (path, by, since timestamp, task, limit,
84
- * withDiff), oldest first, the newest `limit` kept. A change git pulled into the session is the
85
- * log's (an imported patch) and is left out of the session's record when the log answered, so it
86
- * is not counted twice (16: "entries with `pulled` or `seed` are dropped", here only `pulled`:
87
- * a seed is the session's first copy, which the log has no entry for). Returns { list, note }:
88
- * `note` says why the log is missing, when it is.
89
- */
90
- export async function linkedHistory ({ seam, quilt, entries = [], query = {} }) {
91
- const { path = '', by, since, task, limit = 30, withDiff = false } = query
92
- let fromSeam = []
93
- let note = ''
94
- if (!seam) note = `Seam's log for ${quilt.slug || quilt.id} was not read: the session has no read token for it (its owner links it again); this is the session's own record.`
95
- else {
96
- try { fromSeam = await seamHistory(seam, quilt.id, { path, by, since, task, limit, withDiff }) } catch (err) { note = `Seam's log for ${quilt.slug || quilt.id} could not be read (${String(err.message || err).slice(0, 200)}); this is the session's own record.` }
97
- }
98
- return { list: mergeLinked(entries, fromSeam, { ...query, logRead: !note }), note }
99
- }
100
-
101
- /** The session's own entries (filtered by `query`; git's pulls left out when `logRead`) with the log's, oldest first, the newest `limit`. */
102
- export function mergeLinked (entries, fromSeam, { path = '', by, since, task, limit = 30, logRead = true } = {}) {
103
- const own = queryHistory(logRead ? entries.filter((e) => !(e && e.pulled)) : entries, { path, by, since, task, limit: 0 })
104
- const list = [...own, ...(fromSeam || [])].sort((a, b) => a.ts - b.ts)
105
- return limit && list.length > limit ? list.slice(-limit) : list
106
- }
@@ -1,78 +0,0 @@
1
- // "Make this a quilt" for a session with a git remote (Seam's plans/quilt-source-control/16, flag 9, and
2
- // "An opt-in team's migration"): the steps the owner's one button runs, in order, each time it is
3
- // clicked, from where the session stands. Pure: no I/O (test/unit/quilt-remote.test.js).
4
- //
5
- // 1. import Seam imports the GitHub repository and follows it (the owner's Seam GitHub App
6
- // installation is the read credential; 16 step 1). The session stays git-mode.
7
- // 2. link Once the import follows, the session reads the quilt's log (the shadow link).
8
- // 3. cut-over In the owner's sitting: main must take pushes from Seam's export only (a ruleset only
9
- // the repository's GitHub owner can add: plain steps), then the import is cut over
10
- // with export to the same remote on, then the session moves in with its history.
11
-
12
- export const SEAM_APP = { id: 5475977, slug: 'seam-by-heyquilt' }
13
-
14
- /** owner/name of the session's GitHub remote, from its upstreams (the default branch's first), or null. */
15
- export function githubRepoOf (upstreams, defaultKey) {
16
- const all = Object.entries(upstreams || {})
17
- const pick = all.find(([k]) => k === defaultKey) || all[0]
18
- const m = pick && /^github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(\.git)?$/.exec(String((pick[1] && pick[1].repo) || ''))
19
- return m ? m[1] : null
20
- }
21
-
22
- /** Which of the owner's Seam GitHub installations reaches `repo`, or null. */
23
- export function installationFor (gh, repo) {
24
- const want = String(repo).toLowerCase()
25
- return ((gh && gh.installations) || []).find((i) => (i.repos || []).some((r) => String(r.full_name || '').toLowerCase() === want)) || null
26
- }
27
-
28
- /** The step the session is at: 'import' (nothing yet), 'link' (importing), 'cutover' (linked to the quilt that follows). */
29
- export function remoteStage ({ quiltImport = null, quiltShadow = null }) {
30
- if (quiltShadow) return 'cutover'
31
- if (quiltImport) return 'link'
32
- return 'import'
33
- }
34
-
35
- /** Whether GitHub's rules for main (GET /repos/:o/:r/rules/branches/main) keep everyone but an app from pushing to it. */
36
- export function mainGuarded (rules) {
37
- return Array.isArray(rules) && rules.some((r) => r && r.type === 'update')
38
- }
39
-
40
- /** What the repository's GitHub owner does so only Seam pushes to main (16's cut-over checklist, step 5). */
41
- export function rulesetSteps (repo) {
42
- return [
43
- `On GitHub, open https://github.com/${repo}/settings/rules and choose New ruleset, then New branch ruleset.`,
44
- 'Name it "Seam is the authority on main" and set Enforcement status to Active.',
45
- `Under Bypass list, add the app ${SEAM_APP.slug} (Seam), set to Always allow.`,
46
- 'Under Target branches, add the default branch and the pattern release/**.',
47
- 'Turn on Restrict updates, Restrict deletions and Block force pushes, then Create.',
48
- 'Ask everyone to stop pushing to main and wait for CI\'s last run there. Then click Move into Seam now.'
49
- ]
50
- }
51
-
52
- /** The ruleset as GitHub's API takes it (for an owner who prefers `gh api -X POST repos/<repo>/rulesets --input`). */
53
- export function rulesetBody () {
54
- return {
55
- name: 'Seam is the authority on main',
56
- target: 'branch',
57
- enforcement: 'active',
58
- bypass_actors: [{ actor_id: SEAM_APP.id, actor_type: 'Integration', bypass_mode: 'always' }],
59
- conditions: { ref_name: { include: ['~DEFAULT_BRANCH', 'refs/heads/release/**'], exclude: [] } },
60
- rules: [{ type: 'update' }, { type: 'deletion' }, { type: 'non_fast_forward' }]
61
- }
62
- }
63
-
64
- /** What the owner does when no Seam GitHub installation of theirs reaches the repository. */
65
- export function installSteps (repo, installUrl = `https://github.com/apps/${SEAM_APP.slug}/installations/new`) {
66
- return [
67
- 'Sign in to Seam at https://seam.heyquilt.com with the same account you use for Quilt.',
68
- `Connect GitHub there and install the Seam app on ${repo} (${installUrl}). Seam reads the repository with it, and later pushes main to it.`,
69
- 'Then click Make this a quilt again.'
70
- ]
71
- }
72
-
73
- /** One error whose message is the plain steps, with the steps alone in `steps` (the app lists them). */
74
- export function stepsError (lead, steps) {
75
- const e = new Error(`${lead}\n${steps.map((s, i) => `${i + 1}. ${s}`).join('\n')}`)
76
- e.steps = steps
77
- return e
78
- }