heyquilt 0.3.147 → 0.3.149

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.
package/RELEASES.md CHANGED
@@ -11,6 +11,20 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
11
11
  Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
12
12
  nothing else is.
13
13
 
14
+ ## 0.3.149 — 2026-11-04
15
+
16
+ - **Agents that run commands can talk in calls.** `quilt voice say <text>` says it out loud in the session's call, `quilt voice join` joins it (or leaves with `--leave`), and `quilt voice transcript` reads what was said: the same as the call tools, for agents that use the command line instead of MCP.
17
+ - **Call transcripts stay in the order you spoke.** A short line could finish being written down before a longer one said just before it, and showed up first. Lines now go in in the order they were said.
18
+ - **Your folder's work reaches main by itself.** Once your folder has been quiet for a minute and a half, Quilt commits what your square holds and merges it onto main, waiting for main's required checks as `seam merge --wait` does; your folder carries on in a new square. Nothing waits for you to commit or merge, however long the work was held. Turn it off with `"autoLand": "off"` in Quilt's settings file.
19
+ - **Your work lands only when the project's fast tests pass.** Before it merges, Quilt runs the project's `test:fast` script in a fresh copy of your folder on your computer. If tests fail, the work stays held and you get one note naming the failing tests; Quilt tries again after your next change. An edit made while the tests run starts them again once the folder is quiet, and a run over 20 minutes counts as failed. Set `"landGate"` in Quilt's settings file (or `QUILT_LAND_GATE`) to another command, or to `off`.
20
+ - **A conflict with main settles without you.** Quilt takes Seam's own merge when it offers one; otherwise your cloud AI, if you connected one, gets a task to settle it (two tries); otherwise main's version stays in the file and yours is kept in a square of its own, titled "Your <file> from <time>, kept when main changed the same lines", and Quilt tells you once in chat. Nothing is lost.
21
+ - **Release notes no longer conflict.** Two people adding bullets to `RELEASES.md` (or any CHANGELOG-style file, or one marked `merge=union`) keep both. Work made on an older copy of a file, which took main's newer lines out and conflicted with the next patch beside them, is now put onto main's copy first.
22
+
23
+ ## 0.3.148 — 2026-11-03
24
+
25
+ - **The call says when an agent can't hear you.** Name an agent that Quilt has no way to wake and the call says so, with its face greyed out, instead of showing it joining forever. A person's cloud AI counts as one that wakes by itself.
26
+ - **Agents' voices start sooner and sound like part of the call.** Speech now plays while it is still being made, starting with the first sentence. The voice hears what was said just before it speaks, so its tone fits the conversation. Each line is made once for everyone in the call instead of once per person.
27
+
14
28
  ## 0.3.147 — 2026-11-03
15
29
 
16
30
  - **Agents join a call when you say their name.** A call starts with only the people in it. Say an agent's name in a transcribed call and it is pinged, with what was said just before: its face shows joining, it joins, says a few words straight away so you know it heard, then answers out loud. An agent that never comes drops out after two minutes. This is still only for Quilt run from source.
package/bin/quilt.js CHANGED
@@ -37,6 +37,9 @@ Usage:
37
37
  quilt say [@name] <message> Message everyone, or one person with @name
38
38
  quilt send <file> [@name] [message] Send a file (not added to the project)
39
39
  quilt inbox --wait [--timeout <sec>] [--json] Wait for your next mention, direct message or task and print it (exit 2: timed out)
40
+ quilt voice say <text> Agents: say it out loud in the session's call (everyone hears it in your voice)
41
+ quilt voice join [--leave] Agents: join the call when someone says your name in it, or leave it
42
+ quilt voice transcript [-n 50] What was said in the session's calls, oldest first
40
43
  quilt wake [webhook|email|command|wait|push|schedule|turns|none] [--url U | --address A | --code C | --command CMD | --every N] How Quilt wakes you (step 2 of joining); no method: the ways that fit you
41
44
  quilt webhook set <url> [--bearer-env VAR] | clear | test | status Your webhook (quilt_webhook_subscribe): the relay POSTs your mentions, DMs and tasks there, even while you sleep
42
45
  quilt messages [--all] [--with name] [--grep text] [--before id] [-n 30]
@@ -103,6 +106,7 @@ async function main () {
103
106
  case 'inbox': return argv.includes('--wait') ? inboxWait() : messages()
104
107
  case 'webhook': return webhookCmd()
105
108
  case 'wake': return wakeCmd()
109
+ case 'voice': return voiceCmd()
106
110
  case 'get': return getFile()
107
111
  case 'commit': if (!argv.join(' ').trim()) fail('Usage: quilt commit <message>'); return simple('/square-commit', { message: argv.join(' ') }, (r) => r.text)
108
112
  case 'run': return runCmd()
@@ -663,6 +667,28 @@ function splitRecipient (args) {
663
667
  return { to: undefined, rest: args }
664
668
  }
665
669
 
670
+ // An agent in the session's voice call, from the command line: the same as quilt_voice_say,
671
+ // quilt_voice_join and quilt_voice_transcript, for agents that run commands instead of MCP.
672
+ async function voiceCmd () {
673
+ const [sub, ...rest] = argv
674
+ const usage = 'usage: quilt voice say <text> | quilt voice join [--leave] | quilt voice transcript [-n 50]'
675
+ if (sub === 'say') {
676
+ const text = rest.join(' ').trim()
677
+ if (!text) fail(usage)
678
+ return simple('/voice-say', { text }, () => 'Said in the call: everyone in it hears it in your voice.')
679
+ }
680
+ if (sub === 'join') {
681
+ return simple('/voice-join', { leave: rest.includes('--leave') }, (r) => r.in ? `You are in the call with ${r.people.join(', ')}. Only a line that says your name reaches you; answer out loud with quilt voice say.` : 'You left the call.')
682
+ }
683
+ if (sub === 'transcript') {
684
+ const i = rest.indexOf('-n')
685
+ const limit = i >= 0 ? Number(rest[i + 1]) || 50 : 50
686
+ const { renderLines } = await import('../src/voice.js')
687
+ return simple('/voice-transcript', { limit }, (r) => renderLines(r))
688
+ }
689
+ fail(usage)
690
+ }
691
+
666
692
  async function say () {
667
693
  const flag = (f) => { const i = argv.indexOf(f); if (i === -1) return false; argv.splice(i, 1); return true }
668
694
  const everyone = flag('--everyone')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heyquilt",
3
- "version": "0.3.147",
3
+ "version": "0.3.149",
4
4
  "description": "Real-time, tool-agnostic pair vibe coding: sync a project folder live between collaborators using any AI coding tool.",
5
5
  "author": {
6
6
  "name": "Daniel Carmichael",
package/src/account.js CHANGED
@@ -588,3 +588,22 @@ export async function transcribeVoice ({ token, audio, seconds, api = apiUrl(),
588
588
  export async function speakVoice ({ token, text, by, agent, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
589
589
  return call(fetchImpl, api, 'POST', '/v1/voice/speak', { text, by, ...(agent ? { agent } : {}) }, token)
590
590
  }
591
+
592
+ /** The same line as speech that plays as it renders, with what was said before it (`before`): the API's response, its body PCM. */
593
+ export async function speakVoiceStream ({ token, text, by, agent, before = [], api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
594
+ let res
595
+ try {
596
+ res = await fetchImpl(api + '/v1/voice/speak', {
597
+ method: 'POST',
598
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
599
+ body: JSON.stringify({ text, by, stream: true, before, ...(agent ? { agent } : {}) })
600
+ })
601
+ } catch (err) {
602
+ throw new Error(`Couldn't reach Quilt (${err.cause?.code || err.message}).`)
603
+ }
604
+ if (!res.ok) {
605
+ const data = await res.json().catch(() => null)
606
+ throw Object.assign(new Error(data?.error || `Quilt answered ${res.status}.`), { status: res.status })
607
+ }
608
+ return res
609
+ }
package/src/api/http.js CHANGED
@@ -28,6 +28,11 @@ export function cleanName (value, max, message) {
28
28
  return s
29
29
  }
30
30
 
31
+ /** A reply sent as it is made: `chunks` (an async iterable of Buffers), e.g. speech as it renders. */
32
+ export class Stream {
33
+ constructor (status, chunks, type, headers = {}) { this.status = status; this.chunks = chunks; this.type = type; this.headers = headers }
34
+ }
35
+
31
36
  /** A non-JSON reply, e.g. the plain-text join instructions an AI reads. */
32
37
  export class Raw {
33
38
  constructor (status, body, type = 'text/markdown; charset=utf-8') { this.status = status; this.body = body; this.type = type }
@@ -83,7 +83,9 @@ export function agentWakeRoutes (ctx) {
83
83
  const ids = (Array.isArray(body.accounts) ? body.accounts : []).slice(0, 200).map((a) => String(a).split(':')).filter(([k, id]) => k === 'agent' && /^[0-9a-f-]{36}$/i.test(id || '')).map(([, id]) => id)
84
84
  const rows = await store.agentWakes(ids)
85
85
  const by = new Map(rows.map((r) => [r.agentId, r]))
86
- return { wakes: Object.fromEntries(ids.map((id) => { const w = by.get(id); return [`agent:${id}`, { method: (w && w.method) || null, label: wakeLabel(w) }] })) }
86
+ // A person's cloud AI wakes on its own machine, whatever it chose (relay-ai-vm.js).
87
+ const cloud = new Set((await Promise.all(ids.map(async (id) => (await store.aiVmByAgent(id).catch(() => null)) ? id : null))).filter(Boolean))
88
+ return { wakes: Object.fromEntries(ids.map((id) => { const w = by.get(id); return [`agent:${id}`, cloud.has(id) ? { method: 'cloud', label: 'wakes by itself (a cloud AI)' } : { method: (w && w.method) || null, label: wakeLabel(w) }] })) }
87
89
  }],
88
90
  ['GET', /^\/v1\/agents\/me\/wake$/, async (req) => {
89
91
  const { agent, cli, sandbox } = await agentCalling(req)
@@ -5,7 +5,8 @@
5
5
  // And agents' voices: an agent in a call says a line, and each app in the call has it spoken here
6
6
  // with Fluxions' text-to-speech, under a monthly cap of characters per account.
7
7
  import crypto from 'node:crypto'
8
- import { HttpError } from '../http.js'
8
+ import WebSocket from 'ws'
9
+ import { HttpError, Stream } from '../http.js'
9
10
  import { AGENT_VOICE_NAMES, pickAgentVoice } from '../agent-voices.js'
10
11
 
11
12
  export const STUN = { urls: ['stun:stun.cloudflare.com:3478'] }
@@ -31,6 +32,76 @@ export const FALLBACK_VOICES = AGENT_VOICE_NAMES.map((n) => `${n}.h8ff7e07da`)
31
32
  const VOICES_TTL_MS = 60 * 60 * 1000
32
33
  // A line an agent says (voice.js MAX_LINE).
33
34
  export const MAX_SPOKEN = 2000
35
+ // Fluxions' socket (plans/voice.md): a voice agent's replies, in conversation mode, as they render.
36
+ export const FLUXIONS_WS = 'wss://api.fluxions.ai/vui/v1/tts/ws'
37
+ // What it sends: s16le PCM, mono, 24 kHz.
38
+ export const SPEECH_TYPE = 'audio/L16; rate=24000; channels=1'
39
+ // What was said before a line, as the caller's turn: this many lines, each this long at most.
40
+ const BEFORE_LINES = 8
41
+ const BEFORE_CHARS = 500
42
+ // A rendered line is kept this long, so every app in the call gets the one render.
43
+ const RENDER_KEEP_MS = 10 * 60 * 1000
44
+ const RENDER_KEEP = 40
45
+ const SOCKET_TIMEOUT_MS = 30 * 1000
46
+
47
+ /** A line cut into its sentences: one speak each, so the first is heard while the rest render. */
48
+ export function sentences (text) {
49
+ const got = String(text || '').match(/[^.!?…]+[.!?…]+["'”’)\]]*\s*|[^.!?…]+$/g) || []
50
+ const out = got.map((s) => s.trim()).filter(Boolean)
51
+ return out.length ? out : [String(text || '').trim()].filter(Boolean)
52
+ }
53
+
54
+ /** The PCM in a WAV: what follows its data chunk's header (a plain 44-byte header when there's no data chunk). */
55
+ export function wavPcm (buf) {
56
+ const i = buf.indexOf('data', 12, 'latin1')
57
+ return i >= 0 && i + 8 <= buf.length ? buf.subarray(i + 8) : buf.subarray(Math.min(44, buf.length))
58
+ }
59
+
60
+ /**
61
+ * `text` in `voice`, rendered on Fluxions' socket in conversation mode: what was said just before
62
+ * (`before`) is the caller's turn, so the reply carries on its tone, and each sentence is its own
63
+ * speak. Yields PCM as it arrives.
64
+ */
65
+ export async function * fluxionsConversation ({ key, voice, before = [], text, socket = (url, opts) => new WebSocket(url, opts), timeoutMs = SOCKET_TIMEOUT_MS }) {
66
+ const ws = socket(FLUXIONS_WS, { headers: { authorization: key } })
67
+ const queue = []
68
+ let wake = null
69
+ let ended = false
70
+ let failure = null
71
+ const push = (item) => { queue.push(item); if (wake) { wake(); wake = null } }
72
+ const parts = sentences(text)
73
+ let dones = 0
74
+ const timer = setTimeout(() => push({ error: new Error('the speech service took too long') }), timeoutMs)
75
+ ws.on('open', () => {
76
+ ws.send(JSON.stringify({ type: 'session.update', voice, context: true }))
77
+ const said = before.map((l) => `${l.by}: ${l.text}`).join('\n').trim()
78
+ if (said) ws.send(JSON.stringify({ type: 'user', text: said }))
79
+ for (const p of parts) ws.send(JSON.stringify({ type: 'speak', input: p }))
80
+ })
81
+ ws.on('message', (data, isBinary) => {
82
+ if (isBinary) return push({ chunk: Buffer.from(data) })
83
+ let m
84
+ try { m = JSON.parse(String(data)) } catch { return }
85
+ if (m.type === 'error') push({ error: new Error(`${m.code || 'error'}: ${m.message || ''}`.trim()) })
86
+ else if (m.type === 'done' && ++dones >= parts.length) push({ end: true })
87
+ })
88
+ ws.on('error', (err) => push({ error: err }))
89
+ ws.on('close', () => push({ end: true }))
90
+ try {
91
+ while (!ended) {
92
+ if (!queue.length) await new Promise((resolve) => { wake = resolve })
93
+ const item = queue.shift()
94
+ if (item.error) { failure = item.error; break }
95
+ if (item.end) { ended = true; break }
96
+ yield item.chunk
97
+ }
98
+ if (failure) throw failure
99
+ } finally {
100
+ clearTimeout(timer)
101
+ try { ws.send(JSON.stringify({ type: 'session.close' })) } catch {}
102
+ try { ws.close() } catch {}
103
+ }
104
+ }
34
105
 
35
106
  /** The voice of a speaker with no registered voice (a chat link, a persona): the same one for the same name. */
36
107
  export function voiceFor (name, voices) {
@@ -75,7 +146,7 @@ export function iceList (raw) {
75
146
  return out
76
147
  }
77
148
 
78
- export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, voice = {}, fetch: fetchImpl = globalThis.fetch, makeLimiter }) {
149
+ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, voice = {}, fetch: fetchImpl = globalThis.fetch, socket = null, makeLimiter }) {
79
150
  const { turnKeyId = '', turnToken = '', accountId = '', aiToken = '', capMinutes = 600, fluxionsKey = '', speechCapChars = 300000 } = voice
80
151
  const capSeconds = Math.max(0, Number(capMinutes) || 0) * 60
81
152
  const capChars = Math.max(0, Number(speechCapChars) || 0)
@@ -109,6 +180,46 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
109
180
  return list.find((id) => id.split('.')[0] === name) || ''
110
181
  }
111
182
  // Per person: ICE servers a few times an hour, clips about one every couple of seconds of a long talk.
183
+ // Each line is rendered once (renderKey) however many apps in the call ask for it: the apps that
184
+ // ask while it renders hear it as it comes.
185
+ const renders = new Map() // key -> { chunks, done, error, waiting, at }
186
+ const renderKey = (voice, text, before) => crypto.createHash('sha256').update(JSON.stringify([voice, text, before])).digest('hex')
187
+ function startRender (key, gen) {
188
+ for (const [k, r] of renders) if (r.done && now() - r.at > RENDER_KEEP_MS) renders.delete(k)
189
+ while (renders.size >= RENDER_KEEP) renders.delete(renders.keys().next().value)
190
+ const r = { chunks: [], done: false, error: null, waiting: new Set(), at: now() }
191
+ const tell = () => { for (const f of r.waiting) f(); r.waiting.clear() }
192
+ renders.set(key, r)
193
+ ;(async () => {
194
+ try { for await (const c of gen) { r.chunks.push(c); tell() } } catch (err) { r.error = err } finally { r.done = true; r.at = now(); if (r.error) renders.delete(key); tell() }
195
+ })()
196
+ return r
197
+ }
198
+ async function * readRender (r) {
199
+ let i = 0
200
+ for (;;) {
201
+ while (i < r.chunks.length) yield r.chunks[i++]
202
+ if (r.done) { if (r.error && !i) throw r.error; return }
203
+ await new Promise((resolve) => r.waiting.add(resolve))
204
+ }
205
+ }
206
+ const firstOf = (r) => r.chunks.length || r.done ? Promise.resolve() : new Promise((resolve) => r.waiting.add(resolve))
207
+ // The socket first; if it fails before any sound, the plain render.
208
+ async function * speech (voice, text, before) {
209
+ let heard = false
210
+ try {
211
+ for await (const c of fluxionsConversation({ key: fluxionsKey, voice, before, text, ...(socket ? { socket } : {}) })) { heard = true; yield c }
212
+ if (heard) return
213
+ log('voice speak: Fluxions socket closed with no sound')
214
+ } catch (err) {
215
+ log(`voice speak: Fluxions socket: ${err.message}`)
216
+ if (heard) throw err
217
+ }
218
+ const res = await fetchImpl(`${FLUXIONS}/v1/tts`, { method: 'POST', headers: { authorization: fluxionsKey, 'content-type': 'application/json' }, body: JSON.stringify({ voice, input: text, response_format: 'wav' }) })
219
+ if (!res.ok) throw new Error(`Fluxions answered ${res.status}`)
220
+ yield wavPcm(Buffer.from(await res.arrayBuffer()))
221
+ }
222
+
112
223
  const limitIce = makeLimiter(30, 'too many requests for call servers; try again in a minute', { keyOf: (userId) => userId })
113
224
  const limitClips = makeLimiter(60, 'too much speech at once; slow down', { keyOf: (userId) => userId })
114
225
 
@@ -179,8 +290,10 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
179
290
  return { text, seconds: billed, used: total, cap: capSeconds }
180
291
  }, { maxBody: MAX_CLIP_BODY + 4096 }],
181
292
 
182
- // A line an agent said in a call, as speech: { text, by, agent? } in, a WAV out (base64), in the
293
+ // A line an agent said in a call, as speech: { text, by, agent?, stream?, before? } in, in the
183
294
  // agent's voice: the one it was given when it registered (`agent`, its id), else one from its name.
295
+ // `stream`: PCM as it renders, with what was said before (`before`: [{ by, text }]) as context;
296
+ // without it, a WAV (base64) in JSON, for apps from before 0.3.148.
184
297
  ['POST', /^\/v1\/voice\/speak$/, async (req, body) => {
185
298
  const { userId } = await person(req)
186
299
  if (!fluxionsKey) throw new HttpError(503, "Agents' voices are not set up on this server.")
@@ -194,6 +307,21 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
194
307
  if (used >= capChars) throw new HttpError(429, "You've heard this month's share of agents speaking. Their lines still show in the call; their voices start again next month.")
195
308
  const list = await voiceList()
196
309
  const voice = (await registeredVoice(body.agent, list)) || voiceFor(by, list)
310
+ if (body.stream === true) {
311
+ const before = (Array.isArray(body.before) ? body.before : []).slice(-BEFORE_LINES)
312
+ .map((l) => ({ by: String(l?.by || '').slice(0, 80), text: String(l?.text || '').replace(/\s+/g, ' ').trim().slice(0, BEFORE_CHARS) }))
313
+ .filter((l) => l.by && l.text)
314
+ const key = renderKey(voice, text, before)
315
+ let r = renders.get(key)
316
+ // Only the first ask renders, and counts.
317
+ if (!r) { r = startRender(key, speech(voice, text, before)); await store.addVoiceSpeechChars(userId, month, text.length) }
318
+ await firstOf(r)
319
+ if (r.error && !r.chunks.length) {
320
+ log(`voice speak: ${r.error.message}`)
321
+ throw new HttpError(502, 'The speech service turned this line down.')
322
+ }
323
+ return new Stream(200, readRender(r), SPEECH_TYPE, { 'x-quilt-voice': voice })
324
+ }
197
325
  let res
198
326
  try {
199
327
  res = await fetchImpl(`${FLUXIONS}/v1/tts`, {
package/src/api/server.js CHANGED
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url'
10
10
  import { newToken, hashToken, newUserCode, normalizeUserCode } from './tokens.js'
11
11
  import { parsePublicKey, verifyDeviceLink, verifyDeviceResume } from '../identity.js'
12
12
  import { signPass, passPublicKey, PASS_VERSION, PASS_TTL_MS } from '../passes.js'
13
- import { HttpError, Raw } from './http.js'
13
+ import { HttpError, Raw, Stream } from './http.js'
14
14
  import { DiskStore } from './file-store.js'
15
15
  import { contentDisposition } from './file-paths.js'
16
16
  import { orgRoutes } from './routes/orgs.js'
@@ -74,7 +74,7 @@ const MCP_TIMEOUT_MS = 30 * 1000
74
74
  // a change to its grant reaches it as soon as it reaches a connected app.
75
75
  const PASS_REUSE_MARGIN_MS = 5 * 60 * 1000
76
76
 
77
- export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, quiltSourceDefault = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, mail = {}, mailFetch = globalThis.fetch, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, seamUrl = 'https://api.seam.heyquilt.com', seamFetch = globalThis.fetch, seamClientId = '', seamSiteUrl = 'https://seam.heyquilt.com', seamConnectSecret = '', notifyEveryMs = NOTIFY_EVERY_MS }) {
77
+ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, quiltSourceDefault = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, voiceSocket, mail = {}, mailFetch = globalThis.fetch, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, seamUrl = 'https://api.seam.heyquilt.com', seamFetch = globalThis.fetch, seamClientId = '', seamSiteUrl = 'https://seam.heyquilt.com', seamConnectSecret = '', notifyEveryMs = NOTIFY_EVERY_MS }) {
78
78
  // PASS_SIGNING_KEY. A bad one should stop the API at start, not fail every pass later.
79
79
  if (passKey) passPublicKey(passKey)
80
80
  const site = String(siteUrl || '').replace(/\/+$/, '')
@@ -397,7 +397,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
397
397
  // Secrets (routes/secrets.js): off until the vault is set up (QUILT_VAULT_SECRET).
398
398
  routes.push(...secretRoutes({ ...ctx, passKey, vaultSecret, vaultUrl, allowLocalUpstreams, ...(secretWaitMs ? { waitMs: secretWaitMs } : {}) }))
399
399
  // Voice (routes/voice.js): call servers for everyone; transcripts once Workers AI is set up.
400
- routes.push(...voiceRoutes({ ...ctx, voice, fetch: voiceFetch, makeLimiter }))
400
+ routes.push(...voiceRoutes({ ...ctx, voice, fetch: voiceFetch, socket: voiceSocket, makeLimiter }))
401
401
  // Email for every session (routes/mail.js): mail that arrives is told to the relay machine
402
402
  // holding the session, which writes it into the chat and wakes the session's email agents.
403
403
  const tellRoom = async (room, arrived) => {
@@ -494,7 +494,12 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
494
494
  const body = route[3]?.raw ? await readRaw(req, route[3]?.maxBody || MAX_BODY) : ['POST', 'PUT', 'PATCH'].includes(req.method) ? await readJson(req, route[3]?.maxBody || MAX_BODY) : {}
495
495
  const out = await route[2](req, body, url.pathname.match(route[1]).slice(1).map(decodePart))
496
496
  if (out instanceof Raw) send(out.status, out.body, out.type)
497
- else if (Array.isArray(out)) send(out[0], out[1])
497
+ else if (out instanceof Stream) {
498
+ res.writeHead(out.status, { 'content-type': out.type, 'cache-control': 'no-store', ...out.headers, ...extra, ...cors(req) })
499
+ try { for await (const chunk of out.chunks) res.write(chunk) } catch (err) { log(`${pathname}: stream stopped: ${err.message}`) }
500
+ res.end()
501
+ recordOwn({ method: req.method, pathname, status: out.status, startedAt })
502
+ } else if (Array.isArray(out)) send(out[0], out[1])
498
503
  else send(200, out)
499
504
  } catch (err) {
500
505
  // A unique index said no. Agents share one index on their public key; everything
package/src/inbox.js CHANGED
@@ -196,8 +196,8 @@ export function describeEvent (e) {
196
196
  if (e.kind === 'mention') return `${who} ${e.follows ? 'wrote again in chat after mentioning you' : 'mentioned you in chat'}${idOf(e)}: ${e.text}`
197
197
  if (e.kind === 'voice') {
198
198
  const before = Array.isArray(e.said) && e.said.length ? ` Just before, in the call: ${e.said.map((l) => `${l.by}: "${clip(l.text, 300)}"`).join(' / ')}.` : ''
199
- const join = e.joined ? '' : ' You are not in the call yet: if it is for you, join it with quilt_voice_join (quilt_voice_transcript reads more of what was said).'
200
- return `${who} said your name in the voice call: "${e.text}".${before}${join} If it is for you, first say a few words at once with quilt_voice_say that fit what was asked, so people know you heard (in your own words, never a stock phrase); then answer out loud once you have it (no reply in chat needed). Stay quiet if it is not for you.`
199
+ const join = e.joined ? '' : ' You are not in the call yet: if it is for you, join it with quilt_voice_join (`quilt voice join` on the command line; quilt_voice_transcript reads more of what was said).'
200
+ return `${who} said your name in the voice call: "${e.text}".${before}${join} If it is for you, first say a few words at once with quilt_voice_say (\`quilt voice say <text>\`) that fit what was asked, so people know you heard (in your own words, never a stock phrase); then answer out loud the same way once you have it, not in chat. Stay quiet if it is not for you.`
201
201
  }
202
202
  if (e.kind === 'email') return `New email for the session (no reply needed in chat)${idOf(e)}: ${e.text}${e.mail ? ` Read it with quilt_mail (read: "${e.mail}"); answer by email with quilt_mail_send (reply_to: "${e.mail}") if it needs one.` : ''}`
203
203
  if (e.kind === 'task') {
package/src/runner.js CHANGED
@@ -167,6 +167,8 @@ export async function runSession ({ dir, conn, name, tool, color = null, shareBy
167
167
  // listens before the session starts: what was written to their cloud AI while it was away arrives
168
168
  // as the session syncs, before start() returns, and is its work.
169
169
  autowork().attach(session)
170
+ // Whether this person connected a cloud AI, as the API last said (land.js asks it to settle conflicts in their square).
171
+ session.cloudAiKnown = () => { try { return !!autowork().cloudAi() } catch { return false } }
170
172
  try {
171
173
  await session.start({ waitTimeoutMs: 15000 })
172
174
  } catch (err) {
package/src/server.js CHANGED
@@ -36,7 +36,7 @@ import {
36
36
  syncStep1Message, updateMessage, awarenessMessage, bytesMessage, jsonMessage
37
37
  } from './protocol.js'
38
38
  import { isLiveKey, liveRequest, liveKey, liveMaps, liveHead, overlay, seal, entryId, startHead } from './source-live/live-square.js'
39
- import { conflictsAhead, commitAhead, staleAhead, standHead, moveLive, lateEdits, sideReader, HOLDER_WAIT_MS } from './source-live/bring-in.js'
39
+ import { conflictsAhead, commitAhead, staleAhead, olderCopiesAhead, unionMarked, standHead, moveLive, lateEdits, sideReader, HOLDER_WAIT_MS } from './source-live/bring-in.js'
40
40
  import { blobId } from '@heyquilt/seam/lib/quilts/records.js'
41
41
  import { planSessionQuilt, quiltPlanRefusal, describeQuiltPlan, fileHash } from './session-quilt.js'
42
42
  import { makeQuiltWithoutHistory, termsFor } from './session-migrate.js'
@@ -2417,18 +2417,38 @@ class Room {
2417
2417
  standHead(doc, stale, liveHead(doc))
2418
2418
  this.log(`[${this.name}] square ${squareShort(id)}: ${stale.length} live file(s) were older copies of main's, not edits; main's stand (${stale.slice(0, 5).join(', ')}${stale.length > 5 ? ', …' : ''})`)
2419
2419
  }
2420
- const ahead = await conflictsAhead(seam, q, sq, doc, sq.line || 'main')
2420
+ // Work edited on an older copy of main's file is put onto the square's copy first: main's newer lines are nobody's deletion.
2421
+ // Files the project marks merge=union (its .gitattributes) combine like RELEASES.md: both sides stay.
2422
+ const marked = await unionMarked(seam, q, sq.line || 'main')
2423
+ const older = await olderCopiesAhead(seam, q, sq, doc, sq.line || 'main', { marked }).catch((err) => { this.log(`[${this.name}] could not look for work made on older copies of main's files in square ${squareShort(id)}: ${err.message}`); return [] })
2424
+ if (older.length) this.log(`[${this.name}] square ${squareShort(id)}: ${older.length} live file(s) were edited on an older copy of main's; their edits were put onto the square's copy (${older.slice(0, 5).join(', ')}${older.length > 5 ? ', …' : ''})`)
2425
+ const ahead = await conflictsAhead(seam, q, sq, doc, sq.line || 'main', { marked })
2421
2426
  const head = ahead.length ? await commitAhead(seam, q, sq, doc, ahead, by) : sq.head
2422
2427
  const r = await seam.rebase(q, id, { expect_head: head || null })
2423
2428
  if (r.noop || !r.square) { this.catchUps.delete(id); return done() }
2424
2429
  const to = r.square.head || r.square.base
2425
2430
  const terms = [...new Set([...(r.terms || []).map((t) => t.path), ...ahead])]
2426
- const m = await this.moveSquareLive(seam, q, lk, doc, { prev: head || sq.base, head: to, base: !r.square.head, by, brought: { patches: sq.behind_by, conflicts: terms, ...(stale.length ? { stale: stale.slice(0, 50) } : {}) } })
2431
+ const m = await this.moveSquareLive(seam, q, lk, doc, { prev: head || sq.base, head: to, base: !r.square.head, by, marked, brought: { patches: sq.behind_by, conflicts: terms, ...(stale.length ? { stale: stale.slice(0, 50) } : {}) } })
2427
2432
  this.catchUps.delete(id)
2428
2433
  this.log(`[${this.name}] brought ${sq.behind_by} patch(es) of ${sq.line || 'main'} into square ${squareShort(id)} as ${by || 'a member'}${m.combined.length ? `, combining ${m.combined.length} live file(s)` : ''}${terms.length ? `; ${terms.length} conflict(s) kept in the square` : ''}`)
2429
2434
  return done({ brought: { patches: sq.behind_by, combined: m.combined, conflicts: [...new Set([...terms, ...m.conflicts])], ...(stale.length ? { stale: stale.slice(0, 50) } : {}) }, ...(r.square.conflicted_paths ? { conflicted: r.square.conflicted_paths } : {}) })
2430
2435
  }
2431
2436
 
2437
+ /**
2438
+ * A member's app tells its own person something Quilt did with their square's work by itself
2439
+ * (session-follow.js: their version of a file kept in a square of its own when main's change won
2440
+ * the same lines): a note from Quilt in chat, to them alone. Nobody else is told.
2441
+ */
2442
+ quiltNote (ws, req) {
2443
+ const a = this.access.get(ws)
2444
+ const name = this.names.get(ws)
2445
+ if (!a || a.role === 'viewer' || (a.state && a.state !== 'approved') || !name) throw new Error('only a member who may change files is told about their square')
2446
+ const text = String(req.text || '').trim().slice(0, 1000)
2447
+ if (!text) throw new Error('a note needs its words')
2448
+ const m = this.postChat({ by: 'Quilt', to: name, text, kind: 'note' })
2449
+ return { ok: true, message: m.id }
2450
+ }
2451
+
2432
2452
  /** A square's live document moved onto `head` (bring-in.js moveLive), late edits made on the old head combined after (lateEdits). */
2433
2453
  async moveSquareLive (reader, q, lk, doc, opts) {
2434
2454
  const r = await moveLive(reader, q, doc, opts)
@@ -3743,7 +3763,7 @@ class Room {
3743
3763
  read.then(answer, (err) => answer({ ok: false, error: err.message }))
3744
3764
  return
3745
3765
  }
3746
- reply = { id: req.id, op: req.op, ...this.branchRequest(ws, req) }
3766
+ reply = { id: req.id, op: req.op, ...(req.op === 'quilt-note' ? this.quiltNote(ws, req) : this.branchRequest(ws, req)) }
3747
3767
  } catch (err) {
3748
3768
  reply = { id: req.id, op: req.op, ok: false, error: err.message }
3749
3769
  }
@@ -23,8 +23,11 @@ import * as Y from 'yjs'
23
23
  import { FEATURES } from './protocol.js'
24
24
  import { openLiveBlock } from './source-live/live-block.js'
25
25
  import { appSeamUrl } from './seam-url.js'
26
- import { lastWriters } from './source-live/live-square.js'
26
+ import { lastWriters, liveMaps } from './source-live/live-square.js'
27
27
  import { broughtOf } from './source-live/bring-in.js'
28
+ import { Lander, landOn } from './source-live/land.js'
29
+ import { gateCommand, runGate } from './source-live/land-gate.js'
30
+ import { getSettings } from './settings.js'
28
31
  import { catchUpWords } from './ui/seam-model.js'
29
32
  import { QUILT_MOVE_TIMEOUT_MS } from './connection.js'
30
33
  import { squareShort } from '@heyquilt/seam/lib/quilts/errors.js'
@@ -396,6 +399,7 @@ export class SquareFollower {
396
399
  if (block.doc && block.doc.getMap) block.doc.getMap('live').observe(() => { if (this.here === here) this.catchUpSoon() })
397
400
  here.catchUpTimer = setInterval(() => this.catchUp().catch(() => {}), this.catchUpMs)
398
401
  here.catchUpTimer.unref?.()
402
+ here.lander = this.landerFor(here, block, at, quilt)
399
403
  this.catchUp().catch(() => {})
400
404
  } catch (err) {
401
405
  if (this.here !== here) return
@@ -430,6 +434,55 @@ export class SquareFollower {
430
434
  await this.openHere(at, quilt, { fresh: true })
431
435
  }
432
436
 
437
+ /**
438
+ * The folder's held work lands by itself (source-live/land.js): a person's folder only (an agent's
439
+ * own square has its AI; a cloud AI's folder works for its person, who lands), with Seam on and
440
+ * landing not turned off. Every edit on the square (anyone's) starts its quiet again.
441
+ */
442
+ landerFor (here, block, at, quilt) {
443
+ const s = this.session
444
+ if (!this.landing || s.kind === 'agent' || s.aiOf || !s.seamClientNow || !s.conn) return null
445
+ const branch = s.squareBranchKey ? s.squareBranchKey() : s.branchKey()
446
+ const lander = new Lander({
447
+ quilt: quilt.id,
448
+ square: at.square,
449
+ line: 'main',
450
+ block,
451
+ ...(this.landOpts || {}),
452
+ client: async () => { const c = await s.seamClientNow(); if (c) block.client = c; return c },
453
+ next: async () => { const { token } = await s.seamMember().client(quilt.id, [at.square]); return s.conn.branchRequest({ op: 'quilt-next', token, branch }, { timeoutMs: QUILT_MOVE_TIMEOUT_MS }) },
454
+ catchUp: () => this.catchUp(),
455
+ hasAi: () => !!(s.hasCloudAi && s.hasCloudAi()),
456
+ person: s.name,
457
+ board: { list: () => s.taskList(), add: (f) => s.addTask(f), comment: (id, text) => s.commentTask({ id, text }), move: (id, column) => s.updateTask({ id, column }) },
458
+ // The project's fast tests in a fresh copy of the folder before anything lands (land-gate.js).
459
+ gate: async ({ signal }) => {
460
+ let settings = {}
461
+ try { settings = getSettings() } catch {}
462
+ const g = gateCommand(s.root, { settings })
463
+ if (g.off || g.missing) return g
464
+ if (s.log && this.here === here) s.log(`🧵 running ${g.command} in a copy of this folder before its held work lands`)
465
+ return { ...(await runGate({ dir: s.root, command: g.command, signal })), command: g.command }
466
+ },
467
+ notify: (text) => { if (s.noteToSelf) s.noteToSelf(text) },
468
+ log: (m) => { if (this.here === here && s.log) s.log(`🧵 ${m}`) }
469
+ })
470
+ if (block.doc && block.doc.getMap) {
471
+ const m = liveMaps(block.doc)
472
+ const edited = () => { if (this.here === here) lander.edited() }
473
+ for (const k of ['files', 'blobs', 'gone']) m[k].observeDeep(edited)
474
+ }
475
+ lander.soon(lander.quietMs + 50)
476
+ return lander
477
+ }
478
+
479
+ /** Whether held work lands by itself here (land.js landOn), read each time a block opens. */
480
+ get landing () {
481
+ let settings = {}
482
+ try { settings = getSettings() } catch {}
483
+ return landOn({ settings })
484
+ }
485
+
433
486
  /** catchUp in a moment: the relay says something of the quilt in bursts, and one ask answers them all. */
434
487
  catchUpSoon () {
435
488
  if (!this.here || !this.here.block || this.catchUpTimer) return
@@ -458,8 +511,10 @@ export class SquareFollower {
458
511
  // Main waits for a folder on the square too old to follow its base moving (server.js outdatedOn): whose.
459
512
  h.outdated = Array.isArray(r.outdated) ? r.outdated.map(String).slice(0, 10) : []
460
513
  h.catchUpProblem = ''
461
- if (r.brought && s.log) s.log(`🧵 ${catchUpWords({ brought: { ...r.brought, at: Date.now() } }).join(' ')}`)
514
+ if (r.brought && s.log) s.log(`🧵 ${catchUpWords({ brought: { ...r.brought, at: Date.now() }, lands: !!h.lander }).join(' ')}`)
462
515
  if (s.scheduleStatusWrite) s.scheduleStatusWrite()
516
+ // A look at landing the held work too (a square with commits and nothing typed lands this way).
517
+ if (h.lander && !h.lander.busy) setTimeout(() => { if (this.here === h && h.lander) h.lander.tick().then(() => { if (s.scheduleStatusWrite) s.scheduleStatusWrite() }).catch(() => {}) }, 0).unref?.()
463
518
  return r
464
519
  } catch (err) {
465
520
  if (this.here === h && h.catchUpProblem !== err.message) {
@@ -483,6 +538,9 @@ export class SquareFollower {
483
538
  const b = h.block ? broughtOf(h.block.doc) : null
484
539
  const brought = b ? { at: b.at, by: b.by || '', patches: b.patches || 0, combined: b.combined || [], conflicts: b.conflicts || [], ...(Array.isArray(b.stale) && b.stale.length ? { stale: b.stale } : {}) } : null
485
540
  const catching = { ...(h.behind ? { behind: h.behind } : {}), ...(h.behind && h.outdated && h.outdated.length ? { outdated: h.outdated } : {}), ...(h.conflicted !== undefined ? { conflicted: h.conflicted } : {}), ...(brought ? { brought } : {}) }
541
+ // What landing the held work did last (land.js): landed, kept aside, asked the person's AI, waiting.
542
+ if (h.lander) catching.lands = true
543
+ if (h.lander && h.lander.state) catching.landing = h.lander.state
486
544
  const words = h.block ? catchUpWords(catching).join(' ') : ''
487
545
  return { square: h.square, short: squareShort(h.square).slice(3), quilt, ...(h.opening ? { opening: true } : {}), ...(problem ? { problem } : {}), ...(work ? { work } : {}), ...catching, line: squareLine({ square: h.square, quilt, problem: h.problem, opening: h.opening }) + (h.block && h.block.problem ? ` ${h.block.problem}.` : '') + (h.block && h.block.outOfStep ? ` ${h.block.outOfStep}.` : '') + (words ? ` ${words}` : '') }
488
546
  }
@@ -509,6 +567,7 @@ export class SquareFollower {
509
567
  clearTimeout(this.catchUpTimer)
510
568
  this.catchUpTimer = null
511
569
  if (h) clearInterval(h.catchUpTimer)
570
+ if (h && h.lander) h.lander.stop()
512
571
  if (this.session.unfollowSquareDoc) this.session.unfollowSquareDoc()
513
572
  if (h && h.block && h.block.close) await h.block.close().catch(() => {})
514
573
  // Still opening (waiting for the relay, say): stopped where it is, or its connection outlives the folder's square.
package/src/session.js CHANGED
@@ -4028,6 +4028,29 @@ export class Session extends EventEmitter {
4028
4028
  return false
4029
4029
  }
4030
4030
 
4031
+ /**
4032
+ * Whether this person has a cloud AI to hand work to (land.js asks it to settle a conflict in their
4033
+ * square): in the session now, or connected to their account as the app last heard (cloudAiKnown,
4034
+ * set by runner.js from the API's answer). Never their AI sessions on a computer: those are them.
4035
+ */
4036
+ hasCloudAi () {
4037
+ if (this.aiOf || this.kind === 'agent') return false
4038
+ return !!(this.cloudAiLive() || (this.cloudAiKnown && this.cloudAiKnown()))
4039
+ }
4040
+
4041
+ /**
4042
+ * One note to this person about their own work (land.js: their version of a file kept aside when
4043
+ * main's change won the same lines): from Quilt in chat, to them alone (the relay's quilt-note), and
4044
+ * told to their AI sessions at their next call. A relay too old for it leaves the log line only.
4045
+ */
4046
+ noteToSelf (text) {
4047
+ const t = String(text || '').slice(0, 1000)
4048
+ if (!t) return
4049
+ this.log(`🧵 ${t}`)
4050
+ this.notice(t)
4051
+ if (this.conn && this.conn.connected) this.conn.branchRequest({ op: 'quilt-note', text: t }).catch(() => {})
4052
+ }
4053
+
4031
4054
  /** Who an action from this AI session is by: its own name, or this member's. */
4032
4055
  actorName (via) { const p = this.persona(via); return p ? p.name : this.name }
4033
4056