heyquilt 0.3.152 → 0.3.155

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,23 @@ 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.155 — 2026-11-12
15
+
16
+ A new look: one bar across the top instead of the sidebar, and the session's chat is the loom.
17
+
18
+ - **One bar across the top.** The workspace's name, **Home**, the session you're in (its menu lists every session and who is working in each), **Connections**, **Files**, notifications and the faces of who is working. The sidebar is gone; the rail on the left keeps your workspaces, search and settings. Home, Files, People and Connections are pages of the workspace: click the button again to go back to the session.
19
+ - **Chat is the loom.** A short card for each person at the top of their lane (what they're doing, a cube per thread, a message button with what's unread), what each AI did as cards in the lanes, and messages as lines across them. A message to you has **Reply**: answer right there, with files from your computer or the workspace. The composer says who it writes to, and **+** attaches a file or one of the workspace's files.
20
+ - **Someone's view.** Click a person's card and it becomes their view: their AI's threads as chips, what it did, and **Messages with** them, a thread only the two of you see.
21
+ - **The workspace's Home.** Its sessions with who is working in each, the links that matter (production, staging, a shared localhost) and charts of AI time and merges.
22
+ - **People, Files and ⌘K.** People shows Humans and AI as cards with search; Files shows the workspace's folders as cards; ⌘K (Ctrl+K) finds sessions, people, files and actions from anywhere.
23
+ - **Tasks, Preview and Calls.** The board's cards show who has each task and when their AI is on it; click one for its controls. **Preview** keeps the session's links beside the page itself. **Calls** lists the session's calls with who was in them and opens each transcript.
24
+ - **Connect apps for your agents.** The **Connections** button at the top connects Gmail, Slack, Notion, Linear, HubSpot and thousands more for the whole workspace (or the session, when it isn't in one). You sign in to the app in your browser; Quilt never sees the login. Every agent in that session or workspace can then use it, whatever AI tool it runs in.
25
+ - **Agents ask before they change anything.** An agent reads from a connected app at once. Before it sends, creates, changes or deletes anything there, a card in the session's chat asks a person to **Approve** or **Decline**, and an approved action runs once. Each app call is in the session's audit trail, and Connections lists what agents did.
26
+
27
+ ## 0.3.154 — 2026-11-06
28
+
29
+ - **Your sessions follow your account.** On a new computer, Home now lists the sessions you've been in that aren't on this computer yet. Click **Join here** and choose a folder, or pick the folder you already have the project in. You don't need an invite link: the session lets you back in because you're its owner or one of its members. Once you're in, the session's invite links come to this computer too. Anyone who was never in the session still needs an invite link.
30
+
14
31
  ## 0.3.152 — 2026-11-06
15
32
 
16
33
  - **Agents no longer join calls.** Calls are for people again: saying an agent's name in a call doesn't bring it in or send it anything. Agents can still read what was said in a transcribed call.
package/bin/quilt.js CHANGED
@@ -221,6 +221,9 @@ async function apiCmd () {
221
221
  // Secrets: the vault (quilt-vault) and the secret it calls this API with; off when not set.
222
222
  vaultSecret: env.QUILT_VAULT_SECRET || '',
223
223
  vaultUrl: env.QUILT_VAULT_URL || 'https://vault.heyquilt.com',
224
+ // App connections: Composio's project key (plans/app-connections.md); off when not set.
225
+ composioKey: env.COMPOSIO_API_KEY || '',
226
+ ...(env.QUILT_APP_CALLS_PER_DAY ? { appCallsPerDay: Number(env.QUILT_APP_CALLS_PER_DAY) } : {}),
224
227
  // On Fly, this machine's id: with several API machines, one leads the cloud AI work (src/api/leader.js).
225
228
  machineId: env.FLY_MACHINE_ID || '',
226
229
  // Its own machines through Fly's Machines API (QUILT_API_FLY_TOKEN): more as load climbs, fewer as it drops (src/api/scaler.js).
@@ -263,6 +266,7 @@ async function apiCmd () {
263
266
  if (!env.RELAY_API_SECRET) console.log('RELAY_API_SECRET is not set: the relay cannot report sessions for the dashboard')
264
267
  if (!env.FLY_API_TOKEN || !env.AI_VM_APP || !env.AI_VM_IMAGE) console.log('FLY_API_TOKEN, AI_VM_APP or AI_VM_IMAGE is not set: people cannot connect a cloud AI')
265
268
  if (!env.QUILT_VAULT_SECRET) console.log('QUILT_VAULT_SECRET is not set: secrets are off')
269
+ if (!env.COMPOSIO_API_KEY) console.log('COMPOSIO_API_KEY is not set: app connections are off')
266
270
  if (env.FLY_MACHINE_ID && !env.QUILT_API_FLY_TOKEN) console.log('QUILT_API_FLY_TOKEN is not set: the API grows only within the machines it has')
267
271
  if (!env.CLOUDFLARE_TURN_KEY_ID || !env.CLOUDFLARE_TURN_KEY_TOKEN) console.log('CLOUDFLARE_TURN_KEY_ID or CLOUDFLARE_TURN_KEY_TOKEN is not set: calls connect directly only (STUN)')
268
272
  if (!env.CLOUDFLARE_ACCOUNT_ID || !env.CLOUDFLARE_AI_TOKEN) console.log('CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_AI_TOKEN is not set: call transcripts are off')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heyquilt",
3
- "version": "0.3.152",
3
+ "version": "0.3.155",
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
@@ -149,6 +149,13 @@ export async function fetchMe ({ token, api = apiUrl(), fetch: fetchImpl = globa
149
149
  return (await call(fetchImpl, api, 'GET', '/v1/me', null, token)).profile
150
150
  }
151
151
 
152
+ /** The sessions you've been in, newest first: [{ room, name, owner: { name }, mine, lastActiveAt, live, people, … }]. */
153
+ export async function listMySessions ({ token, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
154
+ const r = await call(fetchImpl, api, 'GET', '/v1/me/sessions', null, token)
155
+ if (!Array.isArray(r.sessions)) throw new Error(BAD_REPLY)
156
+ return r.sessions
157
+ }
158
+
152
159
  /**
153
160
  * The owner renames a session on heyquilt.com: { session: { room, name } }. Throws with
154
161
  * .status: 404 until the relay has reported the session, 403 for anyone but the owner.
package/src/api/audit.js CHANGED
@@ -36,14 +36,25 @@ export function endReasonOf (v, revokedAt) {
36
36
 
37
37
  /**
38
38
  * The trail: visits newest first, each with its actions oldest first.
39
- * `revoked` maps an agent account ('agent:<id>') to when its keys were revoked.
39
+ * `revoked` maps an agent account ('agent:<id>') to when its keys were revoked. `appCalls` (from
40
+ * the accounts API's app_calls) are what agents did in connected apps: each goes with the visit
41
+ * of whoever asked for it, as a 'tool' action ("app GMAIL_SEND_EMAIL on gmail: ran, approved by …").
40
42
  */
41
- export function auditTrail ({ visits, actions, revoked = new Map() }) {
43
+ export function auditTrail ({ visits, actions, revoked = new Map(), appCalls = [] }) {
42
44
  const byVisit = new Map()
43
45
  for (const a of actions) {
46
+ if (a.action === 'ai') continue // a minute of AI work: the workspace's AI time, not something the member did
44
47
  if (!byVisit.has(a.visitStartId)) byVisit.set(a.visitStartId, [])
45
48
  byVisit.get(a.visitStartId).push({ at: a.at, action: a.action, target: a.target || '' })
46
49
  }
50
+ for (const c of appCalls) {
51
+ const v = visits.find((x) => x.account === c.account && x.startedAt <= c.createdAt && (x.endedAt == null || x.endedAt >= c.createdAt))
52
+ if (!v) continue
53
+ if (!byVisit.has(v.eventStartId)) byVisit.set(v.eventStartId, [])
54
+ const list = byVisit.get(v.eventStartId)
55
+ list.push({ at: c.createdAt, action: 'tool', target: `app ${c.tool} on ${c.app}: ${c.state}${c.decidedByName ? `, ${c.state === 'declined' ? 'declined' : 'approved'} by ${c.decidedByName}` : ''}` })
56
+ list.sort((a, b) => a.at - b.at)
57
+ }
47
58
  return [...visits]
48
59
  .sort((a, b) => b.startedAt - a.startedAt)
49
60
  .map((v) => ({
@@ -0,0 +1,139 @@
1
+ // Composio (plans/app-connections.md): the apps agents use, through Composio's REST API with the
2
+ // project key (COMPOSIO_API_KEY), which only this API holds. Composio keeps every app's tokens;
3
+ // Quilt keeps which scope a connection belongs to and who may use it (routes/connections.js).
4
+ // Composio's own OAuth apps sign people in (Composio-managed auth): Quilt registers none.
5
+ import { HttpError } from './http.js'
6
+
7
+ export const COMPOSIO_API = 'https://backend.composio.dev/api/v3.1'
8
+
9
+ // Composio tags each action with what it does; only reads run without a person's approval.
10
+ export const READ_TAG = 'readOnlyHint'
11
+ export const isReadOnly = (tool) => Array.isArray(tool && tool.tags) && tool.tags.includes(READ_TAG) && !tool.tags.includes('destructiveHint')
12
+
13
+ /** Composio's user id for a Quilt scope: one per team, workspace or session. */
14
+ export const composioUser = (type, id) => `quilt:${type}:${id}`
15
+
16
+ /**
17
+ * A client for one Composio project: { on, toolkits, toolkit, tools, tool, link, account, remove, execute }.
18
+ * `fetch` is injectable for tests; every call throws an HttpError with Composio's message.
19
+ */
20
+ export function composioClient ({ apiKey = '', base = COMPOSIO_API, fetch: fetchImpl = globalThis.fetch, log = () => {} } = {}) {
21
+ const at = String(base).replace(/\/+$/, '')
22
+ // Composio-managed auth config per app, made once and remembered (Composio keeps them too).
23
+ const authConfigs = new Map()
24
+
25
+ async function call (method, path, body) {
26
+ if (!apiKey) throw new HttpError(503, 'App connections are not switched on on this server yet.')
27
+ let res
28
+ try {
29
+ res = await fetchImpl(at + path, {
30
+ method,
31
+ headers: { 'x-api-key': apiKey, ...(body ? { 'content-type': 'application/json' } : {}) },
32
+ body: body ? JSON.stringify(body) : undefined,
33
+ signal: AbortSignal.timeout(60_000)
34
+ })
35
+ } catch (err) {
36
+ log(`composio ${method} ${path}: ${err.message}`)
37
+ throw new HttpError(502, 'Couldn\'t reach Composio, which connects apps. Try again in a moment.')
38
+ }
39
+ const data = await res.json().catch(() => null)
40
+ if (!res.ok) {
41
+ const msg = data && data.error && (data.error.message || data.error)
42
+ log(`composio ${method} ${path}: ${res.status} ${typeof msg === 'string' ? msg : ''}`)
43
+ throw new HttpError(res.status === 404 ? 404 : 502, `Composio: ${typeof msg === 'string' ? msg.slice(0, 300) : `answered ${res.status}`}`)
44
+ }
45
+ return data || {}
46
+ }
47
+
48
+ const q = (params) => {
49
+ const s = new URLSearchParams()
50
+ for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== '') s.set(k, String(v))
51
+ const t = s.toString()
52
+ return t ? `?${t}` : ''
53
+ }
54
+
55
+ /** An app as Quilt shows it: { slug, name, logo, managed, noAuth }. */
56
+ const appView = (t) => ({
57
+ slug: t.slug,
58
+ name: t.name || t.slug,
59
+ logo: (t.meta && t.meta.logo) || '',
60
+ description: (t.meta && t.meta.description) || '',
61
+ managed: Array.isArray(t.composio_managed_auth_schemes) && t.composio_managed_auth_schemes.length > 0,
62
+ schemes: Array.isArray(t.auth_schemes) ? t.auth_schemes : [],
63
+ noAuth: !!t.no_auth
64
+ })
65
+
66
+ /** An action as agents see it: { slug, name, description, app, readOnly, input }. */
67
+ const toolView = (t) => ({
68
+ slug: t.slug,
69
+ name: t.name || t.slug,
70
+ description: String(t.description || '').slice(0, 1200),
71
+ app: t.toolkit && t.toolkit.slug,
72
+ readOnly: isReadOnly(t),
73
+ tags: (t.tags || []).filter((x) => /Hint$/.test(x)),
74
+ input: t.input_parameters || {}
75
+ })
76
+
77
+ /** The apps one can connect, most used first: [{ slug, name, logo, … }]. */
78
+ async function toolkits ({ search = '', limit = 60 } = {}) {
79
+ const r = await call('GET', `/toolkits${q({ search: String(search).slice(0, 100), sort_by: 'usage', limit: Math.min(200, Math.max(1, limit)) })}`)
80
+ return (r.items || []).filter((t) => !t.deprecated || !t.deprecated.is_deprecated).map(appView)
81
+ }
82
+
83
+ async function toolkit (slug) {
84
+ return appView(await call('GET', `/toolkits/${encodeURIComponent(slug)}`))
85
+ }
86
+
87
+ /** An app's actions, best match first: [{ slug, name, description, readOnly, input }]. */
88
+ async function tools ({ app, query = '', limit = 20 } = {}) {
89
+ const r = await call('GET', `/tools${q({ toolkit_slug: app, query: String(query).slice(0, 200), limit: Math.min(100, Math.max(1, limit)) })}`)
90
+ return (r.items || []).filter((t) => !t.is_deprecated).map(toolView)
91
+ }
92
+
93
+ async function tool (slug) {
94
+ return toolView(await call('GET', `/tools/${encodeURIComponent(slug)}`))
95
+ }
96
+
97
+ /** The app's auth config: Composio-managed when Composio has one, else one that asks the person for their key. */
98
+ async function authConfigFor (app) {
99
+ if (authConfigs.has(app)) return authConfigs.get(app)
100
+ const found = await call('GET', `/auth_configs${q({ toolkit_slug: app, limit: 50 })}`)
101
+ const usable = (found.items || []).filter((a) => a.status !== 'DISABLED' && !a.is_disabled)
102
+ let id = (usable.find((a) => a.is_composio_managed) || usable[0])?.id
103
+ if (!id) {
104
+ const t = await toolkit(app)
105
+ if (t.noAuth) return null
106
+ const authConfig = t.managed ? { type: 'use_composio_managed_auth' } : { type: 'use_custom_auth', authScheme: t.schemes[0], credentials: {} }
107
+ if (!t.managed && !t.schemes.length) throw new HttpError(400, `${t.name} can't be connected here yet.`)
108
+ id = (await call('POST', '/auth_configs', { toolkit: { slug: app }, auth_config: authConfig })).auth_config.id
109
+ }
110
+ authConfigs.set(app, id)
111
+ return id
112
+ }
113
+
114
+ /** A Connect Link for `user` to sign in to `app`: { url, composioId, expiresAt }. */
115
+ async function link ({ user, app, callbackUrl }) {
116
+ const authConfigId = await authConfigFor(app)
117
+ if (!authConfigId) throw new HttpError(400, 'That app needs no sign-in: agents can use it without connecting it.')
118
+ const r = await call('POST', '/connected_accounts/link', { auth_config_id: authConfigId, user_id: user, callback_url: callbackUrl })
119
+ return { url: r.redirect_url, composioId: r.connected_account_id, expiresAt: r.expires_at ? Date.parse(r.expires_at) : null }
120
+ }
121
+
122
+ /** A connected account's state: { id, app, status } (status: INITIATED, ACTIVE, FAILED, EXPIRED, …). */
123
+ async function account (composioId) {
124
+ const r = await call('GET', `/connected_accounts/${encodeURIComponent(composioId)}`)
125
+ return { id: r.id, app: r.toolkit && r.toolkit.slug, status: r.status }
126
+ }
127
+
128
+ async function remove (composioId) {
129
+ try { await call('DELETE', `/connected_accounts/${encodeURIComponent(composioId)}`) } catch (err) { if (err.status !== 404) throw err }
130
+ }
131
+
132
+ /** Runs one action as `user` with that connected account: { ok, data, error }. */
133
+ async function execute ({ tool: slug, user, composioId, args }) {
134
+ const r = await call('POST', `/tools/execute/${encodeURIComponent(slug)}`, { user_id: user, ...(composioId ? { connected_account_id: composioId } : {}), arguments: args || {} })
135
+ return { ok: r.successful !== false && !r.error, data: r.data ?? null, error: r.error || null }
136
+ }
137
+
138
+ return { on: !!apiKey, toolkits, toolkit, tools, tool, link, account, remove, execute }
139
+ }
@@ -60,6 +60,9 @@ export function createMemoryStore ({ now = Date.now } = {}) {
60
60
  // Secrets (20261018000000_secrets.sql): only what the vault sealed.
61
61
  const seamLinks = new Map(); const secretRows = new Map(); const secretDataKeys = new Map(); const secretSettingsRows = new Map()
62
62
  const secretTickets = new Map(); const secretRuns = new Map(); const secretAsks = new Map(); const secretUses = []
63
+ // App connections (20261112000000_app_connections.sql).
64
+ const appConnections = new Map(); const appCalls = new Map()
65
+ const workspaceLinks = new Map() // 20261112100000_workspace_home.sql
63
66
  const scopeKey = (scopeType, scopeId) => `${scopeType}\n${scopeId}`
64
67
  // A secret as the API's routes see it: never its sealed value (secretSealed reads that, for the vault).
65
68
  const secretMeta = (r) => { if (!r) return null; const { sealedValue, ...rest } = copy(r); return rest }
@@ -577,6 +580,12 @@ export function createMemoryStore ({ now = Date.now } = {}) {
577
580
  },
578
581
  // Mirrors prune_activity.
579
582
  // What was done in a session in [from, to), oldest first, at most `limit` (actions_in_room).
583
+ async aiMinutes (rooms, since) {
584
+ return all(actions, (a) => a.action === 'ai' && rooms.includes(a.room) && a.at >= since).sort((a, b) => a.at - b.at).map((a) => ({ room: a.room, account: a.account, at: a.at }))
585
+ },
586
+ async listWorkspaceLinks (workspaceId) { return all(workspaceLinks, (l) => l.workspaceId === workspaceId).sort((a, b) => a.createdAt - b.createdAt).map(copy) },
587
+ async addWorkspaceLink (l) { const row = { id: uuid(), room: null, note: '', ...copy(l), createdAt: now() }; workspaceLinks.set(row.id, row); return copy(row) },
588
+ async deleteWorkspaceLink (workspaceId, id) { const l = workspaceLinks.get(id); if (l && l.workspaceId === workspaceId) workspaceLinks.delete(id) },
580
589
  async actionsInRoom (room, { from, to, limit }) {
581
590
  return all(actions, (a) => a.room === room && a.at >= from && a.at < to)
582
591
  .sort((a, b) => a.at - b.at).slice(0, limit).map(copy) // stable: ties keep arrival order
@@ -1282,6 +1291,44 @@ export function createMemoryStore ({ now = Date.now } = {}) {
1282
1291
  return secretUses.filter((u) => secretIds.includes(u.secretId)).sort((a, b) => b.at - a.at).slice(0, limit).map(copy)
1283
1292
  },
1284
1293
 
1294
+ // App connections (20261112000000_app_connections.sql): Composio holds the tokens.
1295
+ async addAppConnection (c) {
1296
+ if (all(appConnections, (r) => r.composioId === c.composioId).length) throw duplicate('connection')
1297
+ const row = { id: uuid(), appName: '', logo: '', status: 'pending', who: 'all', ...copy(c), createdAt: now(), updatedAt: now() }
1298
+ appConnections.set(row.id, row)
1299
+ return copy(row)
1300
+ },
1301
+ async appConnectionById (id) { return copy(appConnections.get(id)) },
1302
+ async appConnectionByComposioId (composioId) { return copy(all(appConnections, (r) => r.composioId === composioId)[0]) },
1303
+ async listAppConnections (scopeType, scopeId) { return all(appConnections, (r) => r.scopeType === scopeType && r.scopeId === scopeId).sort((a, b) => a.createdAt - b.createdAt).map(copy) },
1304
+ async updateAppConnection (id, patch) {
1305
+ const r = appConnections.get(id)
1306
+ if (!r) return null
1307
+ Object.assign(r, copy(patch), { updatedAt: now() })
1308
+ return copy(r)
1309
+ },
1310
+ async deleteAppConnection (id) {
1311
+ appConnections.delete(id)
1312
+ for (const c of appCalls.values()) if (c.connectionId === id) c.connectionId = null
1313
+ },
1314
+ async addAppCall (c) {
1315
+ const row = { id: uuid(), args: {}, readOnly: false, decidedBy: null, result: null, error: null, decidedAt: null, ranAt: null, ...copy(c), createdAt: now() }
1316
+ appCalls.set(row.id, row)
1317
+ return copy(row)
1318
+ },
1319
+ async appCallById (id) { return copy(appCalls.get(id)) },
1320
+ /** Changes a call only while it is in `from` (one of them, when a list): null when it moved on. */
1321
+ async updateAppCall (id, patch, { from = null } = {}) {
1322
+ const r = appCalls.get(id)
1323
+ if (!r || (from && ![].concat(from).includes(r.state))) return null
1324
+ Object.assign(r, copy(patch))
1325
+ return copy(r)
1326
+ },
1327
+ async listAppCalls (room, { states = null, limit = 50 } = {}) {
1328
+ return all(appCalls, (c) => c.room === room && (!states || states.includes(c.state))).sort((a, b) => b.createdAt - a.createdAt).slice(0, limit).map(copy)
1329
+ },
1330
+ async countAppCalls (capKey, since) { return all(appCalls, (c) => c.capKey === capKey && c.createdAt >= since).length },
1331
+
1285
1332
  // Test-only views (production reads the tables in the Supabase dashboard).
1286
1333
  listEvents () { return [...events.values()].map(copy) },
1287
1334
  listIssues () { return [...issues.values()].map(copy) },
@@ -0,0 +1,311 @@
1
+ // App connections (plans/app-connections.md): apps a team, workspace or session connected through
2
+ // Composio (composio.js), and the agents' use of them (quilt_apps, quilt_app_tools, quilt_app_call
3
+ // in app-tools.js). People connect at a scope, as with secrets; Composio holds the tokens. An
4
+ // action that only reads runs at once; anything else waits for a person in the session, whose
5
+ // approval runs it once. Every call is kept (app_calls): the approvals, the session's record of
6
+ // what agents did in other apps, and the daily cap.
7
+ import { HttpError, Raw, needId } from '../http.js'
8
+ import { orgAccess } from '../org-access.js'
9
+ import { workspaceReach } from '../workspace-reach.js'
10
+ import { isAgentKey } from '../agent-auth.js'
11
+ import { sessionMember, roomLevels, workspaceLevels, LEVEL_WORDS } from '../secrets-access.js'
12
+ import { composioUser } from '../composio.js'
13
+
14
+ const ROOM = /^[A-Za-z0-9_-]{1,64}$/
15
+ const SCOPE = '(org|workspace|session)'
16
+ const APP = /^[a-z0-9_-]{1,64}$/
17
+ const TOOL = /^[A-Za-z0-9_-]{1,120}$/
18
+ const DAY_MS = 24 * 60 * 60 * 1000
19
+ // How long quilt_app_call holds a call that waits for a person, and how often it looks again.
20
+ export const APPROVAL_WAIT_MS = 15 * 1000
21
+ const LOOK_EVERY_MS = 1000
22
+ // What an answer carries back of an app's reply, and what is kept of it.
23
+ const MAX_ANSWER = 60_000
24
+ const MAX_KEPT = 16_000
25
+ const MAX_ARGS = 32_000
26
+
27
+ /** An action's arguments in a line: what people read on the approval card. */
28
+ export function argsLine (args, max = 400) {
29
+ const s = JSON.stringify(args || {})
30
+ return s.length > max ? `${s.slice(0, max)}…` : s
31
+ }
32
+
33
+ /** What is kept of an app's reply: itself when small, else its start. */
34
+ const kept = (data) => {
35
+ const s = JSON.stringify(data ?? null)
36
+ return s.length <= MAX_KEPT ? data : { truncated: true, start: s.slice(0, MAX_KEPT) }
37
+ }
38
+
39
+ export function connectionRoutes (ctx) {
40
+ const { store, person, bearer, agentAuth, now = Date.now, log = () => {}, apiUrl = '', composio, callsPerDay = 500, sayInRoom = async () => {}, waitMs = APPROVAL_WAIT_MS } = ctx
41
+ const { caller: reachCaller, reach } = workspaceReach(ctx)
42
+
43
+ const nameOf = async (account) => {
44
+ const [kind, id] = String(account || '').split(':')
45
+ if (kind === 'agent') return (await store.agentById(id).catch(() => null))?.name || 'An agent'
46
+ if (kind === 'person') return (await store.profile(id))?.name || 'Someone'
47
+ return ''
48
+ }
49
+
50
+ /** The person or agent calling, hosted agents with a pass: { account, kind, userId, agent }. */
51
+ async function whoCalls (req) {
52
+ if (/^QuiltPass\s/i.test(String(req.headers.authorization || ''))) {
53
+ const c = await reachCaller(req)
54
+ return c.agent ? { account: c.account, kind: 'agent', userId: null, agent: c.agent } : { account: c.account, kind: 'person', userId: c.userId, agent: null }
55
+ }
56
+ if (isAgentKey(bearer(req))) {
57
+ const { agent } = await agentAuth.agentFromRequest(req)
58
+ return { account: `agent:${agent.id}`, kind: 'agent', userId: null, agent }
59
+ }
60
+ const p = await person(req)
61
+ return { account: `person:${p.userId}`, kind: 'person', userId: p.userId, agent: null }
62
+ }
63
+
64
+ /** One scope as a person reaches it, as for secrets: { type, id, name, levels, canManage, me }. */
65
+ async function scopeOf (req, type, rawId) {
66
+ const me = await whoCalls(req)
67
+ if (me.kind !== 'person') throw new HttpError(403, 'People connect apps; agents use them with quilt_app_call.')
68
+ if (type === 'org') {
69
+ const a = await orgAccess(store, me.userId, rawId)
70
+ return { type, id: a.org.id, name: a.org.name, levels: [{ type, id: a.org.id, name: a.org.name }], canManage: a.can('org', 'u'), me }
71
+ }
72
+ if (type === 'workspace') {
73
+ const r = await reach(req, needId(rawId, 'workspace'))
74
+ return { type, id: r.ws.id, name: r.ws.name, levels: await workspaceLevels(store, r.ws), canManage: !!r.access.admin, me }
75
+ }
76
+ const room = String(rawId)
77
+ if (!ROOM.test(room)) throw new HttpError(404, 'no such session')
78
+ const found = await roomLevels(store, room)
79
+ if (!found || !(await sessionMember(store, room, me.account))) throw new HttpError(404, 'no such session')
80
+ // Anyone in the session connects apps for it (the owner removes any; others their own).
81
+ return { type, id: room, name: found.session.name || '', levels: found.levels, canManage: true, owner: found.session.ownerAccount === me.account, me, session: found.session }
82
+ }
83
+
84
+ const needManage = (s) => { if (!s.canManage) throw new HttpError(403, s.type === 'org' ? 'Only the team\'s owner, or a role with Org settings: Update, connects apps for the team.' : 'Only the workspace\'s admins connect apps for it.') }
85
+ const mayChange = (s, c) => s.type !== 'session' ? s.canManage : (s.owner || c.createdBy === s.me.account)
86
+
87
+ /** A connection still pending at Composio: asked again, so one finished without the callback shows. */
88
+ async function settle (c) {
89
+ if (c.status !== 'pending' || !composio.on) return c
90
+ try {
91
+ const a = await composio.account(c.composioId)
92
+ const status = a.status === 'ACTIVE' ? 'active' : ['FAILED', 'EXPIRED', 'INACTIVE', 'REVOKED'].includes(a.status) ? 'failed' : 'pending'
93
+ return status === c.status ? c : (await store.updateAppConnection(c.id, { status })) || c
94
+ } catch (err) { log(`connections: ${c.id}: ${err.message}`); return c }
95
+ }
96
+
97
+ const view = async (c, level, extra = {}) => ({
98
+ id: c.id, app: c.app, name: c.appName || c.app, logo: c.logo, status: c.status, who: c.who,
99
+ level: level.type, levelName: level.name || '', by: await nameOf(c.createdBy), createdAt: c.createdAt, ...extra
100
+ })
101
+
102
+ /** Every connection a session (or workspace) reaches, nearest level first: [{ connection, level }]. */
103
+ async function reachable (levels) {
104
+ const out = []
105
+ for (const l of levels) for (const c of await store.listAppConnections(l.type, l.id)) out.push({ connection: await settle(c), level: l })
106
+ return out
107
+ }
108
+
109
+ async function scopeView (s) {
110
+ const all = await reachable(s.levels)
111
+ const own = all.filter((x) => x.level.type === s.type && x.level.id === s.id)
112
+ const inherited = all.filter((x) => !own.includes(x))
113
+ return {
114
+ scope: { type: s.type, id: s.id, name: s.name },
115
+ canManage: s.canManage,
116
+ connections: await Promise.all(own.map((x) => view(x.connection, x.level, { mayChange: mayChange(s, x.connection) }))),
117
+ inherited: await Promise.all(inherited.filter((x) => x.connection.status === 'active').map((x) => view(x.connection, x.level))),
118
+ callsPerDay
119
+ }
120
+ }
121
+
122
+ /** The caller, when a member of the session: { me, found }; otherwise 404. */
123
+ async function member (req, room) {
124
+ if (!ROOM.test(room)) throw new HttpError(404, 'no such session')
125
+ const me = await whoCalls(req)
126
+ if (!(await sessionMember(store, room, me.account, { agent: me.agent }))) throw new HttpError(404, 'no such session')
127
+ const found = await roomLevels(store, room)
128
+ if (!found) throw new HttpError(404, 'no such session')
129
+ return { me, found }
130
+ }
131
+
132
+ /** The connections the caller may use in the session, nearest level first. */
133
+ async function usable (me, found) {
134
+ return (await reachable(found.levels)).filter(({ connection: c }) => c.status === 'active' && (me.kind === 'person' || c.who === 'all'))
135
+ }
136
+
137
+ const capKey = (session) => session.workspaceId ? `workspace:${session.workspaceId}` : `session:${session.room || ''}`
138
+
139
+ /** Runs a call's action and keeps the outcome: the call as it ended. */
140
+ async function run (call, connection) {
141
+ let outcome
142
+ try {
143
+ outcome = await composio.execute({ tool: call.tool, user: composioUser(connection.scopeType, connection.scopeId), composioId: connection.composioId, args: call.args })
144
+ } catch (err) { outcome = { ok: false, data: null, error: err.message } }
145
+ const ended = await store.updateAppCall(call.id, { state: outcome.ok ? 'ran' : 'failed', result: kept(outcome.data), error: outcome.error ? String(outcome.error).slice(0, 2000) : null, ranAt: now() }, { from: ['waiting', 'approved'] })
146
+ return { ...(ended || call), data: outcome.data }
147
+ }
148
+
149
+ /** What an agent is told about a call: { state, approval, app, tool, ok, data, error, decidedBy, message }. */
150
+ async function answer (call, appName) {
151
+ const out = { approval: call.id, state: call.state, app: call.app, tool: call.tool }
152
+ if (call.state === 'ran' || call.state === 'failed') {
153
+ const data = call.data !== undefined ? call.data : call.result
154
+ const s = JSON.stringify(data ?? null)
155
+ Object.assign(out, { ok: call.state === 'ran', data: s.length > MAX_ANSWER ? { truncated: true, start: s.slice(0, MAX_ANSWER) } : data, error: call.error || null })
156
+ }
157
+ if (call.decidedBy) out.decidedBy = await nameOf(call.decidedBy)
158
+ if (call.state === 'waiting') out.message = `Waiting for a person in the session to approve ${call.tool} on ${appName || call.app}: they see it in the session's chat. Call quilt_app_call again with approval "${call.id}" to get the result.`
159
+ if (call.state === 'declined') out.message = `${out.decidedBy || 'A person'} declined ${call.tool}: don't run it again unless they ask you to.`
160
+ return out
161
+ }
162
+
163
+ // A waiting call holds until a person answers it, or a while passes (other API machines answer too).
164
+ async function waitFor (id) {
165
+ const end = now() + waitMs
166
+ while (true) {
167
+ const call = await store.appCallById(id)
168
+ if (!call || call.state !== 'waiting' || now() >= end) return call
169
+ await new Promise((resolve) => setTimeout(resolve, Math.min(LOOK_EVERY_MS, Math.max(0, end - now()))))
170
+ }
171
+ }
172
+
173
+ const routes = [
174
+ // The apps one can connect (Composio's catalog), most used first.
175
+ ['GET', /^\/v1\/connections\/apps$/, async (req, body, params, url) => {
176
+ await whoCalls(req)
177
+ const u = url || new URL(req.url, 'http://x')
178
+ return { apps: await composio.toolkits({ search: u.searchParams.get('search') || '', limit: Number(u.searchParams.get('limit')) || 60 }) }
179
+ }],
180
+
181
+ // Composio sends the browser back here once someone signed in (or gave up).
182
+ ['GET', /^\/v1\/connections\/done$/, async (req, body, params, url) => {
183
+ const u = url || new URL(req.url, 'http://x')
184
+ const id = String(u.searchParams.get('connected_account_id') || '').slice(0, 80)
185
+ let c = id ? await store.appConnectionByComposioId(id) : null
186
+ if (c) c = await settle(c)
187
+ const ok = !!c && c.status === 'active'
188
+ const name = c ? (c.appName || c.app) : 'the app'
189
+ const title = ok ? `${name} is connected` : `${name} isn't connected`
190
+ const text = ok ? 'You can close this tab and go back to Quilt: agents in that scope can use it now.' : 'Something went wrong signing in. Close this tab and try Connect again in Quilt.'
191
+ return new Raw(200, `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#fcfbf9;color:#1d1b2e;font:15px/1.5 system-ui,sans-serif}main{max-width:420px;padding:24px;text-align:center}h1{font-size:20px;margin:0 0 8px}p{color:#55525f;margin:0}</style></head><body><main><h1>${esc(title)}</h1><p>${esc(text)}</p></main></body></html>`, 'text/html; charset=utf-8')
192
+ }],
193
+
194
+ ['GET', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)$`), async (req, body, [type, id]) => scopeView(await scopeOf(req, type, id))],
195
+
196
+ // Connect an app here: a Composio Connect Link to open in the browser.
197
+ ['POST', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)$`), async (req, body, [type, id]) => {
198
+ const s = await scopeOf(req, type, id)
199
+ needManage(s)
200
+ const app = String(body.app || '').toLowerCase()
201
+ if (!APP.test(app)) throw new HttpError(400, 'Say which app to connect.')
202
+ const t = await composio.toolkit(app)
203
+ const l = await composio.link({ user: composioUser(s.type, s.id), app, callbackUrl: `${apiUrl}/v1/connections/done` })
204
+ const c = await store.addAppConnection({ scopeType: s.type, scopeId: s.id, app, appName: String(t.name || app).slice(0, 120), logo: String(t.logo || '').slice(0, 500), composioId: l.composioId, status: 'pending', who: body.who === 'people' ? 'people' : 'all', createdBy: s.me.account })
205
+ return { url: l.url, connection: await view(c, s.levels[0]) }
206
+ }],
207
+
208
+ // Who may use it: 'all' (people and agents) or 'people'.
209
+ ['PATCH', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
210
+ const s = await scopeOf(req, type, id)
211
+ const c = await store.appConnectionById(needId(cid, 'connection'))
212
+ if (!c || c.scopeType !== s.type || c.scopeId !== s.id) throw new HttpError(404, 'no such connection')
213
+ if (!mayChange(s, c)) throw new HttpError(403, 'Only whoever connected it, or the session\'s owner, changes it.')
214
+ if (body.who !== 'all' && body.who !== 'people') throw new HttpError(400, 'who is "all" or "people"')
215
+ return view(await store.updateAppConnection(c.id, { who: body.who }), s.levels[0])
216
+ }],
217
+
218
+ ['DELETE', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
219
+ const s = await scopeOf(req, type, id)
220
+ const c = await store.appConnectionById(needId(cid, 'connection'))
221
+ if (!c || c.scopeType !== s.type || c.scopeId !== s.id) throw new HttpError(404, 'no such connection')
222
+ if (!mayChange(s, c)) throw new HttpError(403, 'Only whoever connected it, or the session\'s owner, removes it.')
223
+ await composio.remove(c.composioId)
224
+ await store.deleteAppConnection(c.id)
225
+ return { ok: true }
226
+ }],
227
+
228
+ // ---------------------------------------------------------------- agents in a session --
229
+
230
+ // The apps the caller may use here (quilt_apps).
231
+ ['GET', /^\/v1\/sessions\/([^/]+)\/apps$/, async (req, body, [room]) => {
232
+ const { me, found } = await member(req, room)
233
+ const list = await usable(me, found)
234
+ return { apps: await Promise.all(list.map((x) => view(x.connection, x.level))), canConnect: me.kind === 'person', callsPerDay }
235
+ }],
236
+
237
+ // An app's actions, best match first (quilt_app_tools).
238
+ ['GET', /^\/v1\/sessions\/([^/]+)\/apps\/tools$/, async (req, body, [room], url) => {
239
+ const { me, found } = await member(req, room)
240
+ const u = url || new URL(req.url, 'http://x')
241
+ const app = String(u.searchParams.get('app') || '').toLowerCase()
242
+ if (!APP.test(app)) throw new HttpError(400, 'Say which app.')
243
+ const connected = (await usable(me, found)).some((x) => x.connection.app === app)
244
+ return { app, connected, tools: await composio.tools({ app, query: u.searchParams.get('query') || '', limit: Number(u.searchParams.get('limit')) || 15 }) }
245
+ }],
246
+
247
+ // Run an action (quilt_app_call), or ask after one waiting for approval.
248
+ ['POST', /^\/v1\/sessions\/([^/]+)\/apps\/call$/, async (req, body, [room]) => {
249
+ const { me, found } = await member(req, room)
250
+ if (body.approval) {
251
+ const call = await store.appCallById(needId(body.approval, 'approval'))
252
+ if (!call || call.room !== room || call.account !== me.account) throw new HttpError(404, 'no such approval')
253
+ const now2 = call.state === 'waiting' ? await waitFor(call.id) : call
254
+ return answer(now2 || call)
255
+ }
256
+ const toolSlug = String(body.tool || '')
257
+ if (!TOOL.test(toolSlug)) throw new HttpError(400, 'Say which action (its slug, from quilt_app_tools).')
258
+ const args = body.args && typeof body.args === 'object' && !Array.isArray(body.args) ? body.args : {}
259
+ if (JSON.stringify(args).length > MAX_ARGS) throw new HttpError(413, 'Those arguments are too long.')
260
+ const t = await composio.tool(toolSlug)
261
+ const options = (await usable(me, found)).filter((x) => x.connection.app === t.app)
262
+ const pick = body.connection ? options.find((x) => x.connection.id === body.connection) : options[0]
263
+ if (!pick) throw new HttpError(400, `No ${t.app} connection you may use in this session. A person connects it in Session settings → Connections.`)
264
+ const session = found.session
265
+ const key = capKey({ ...session, room })
266
+ if (await store.countAppCalls(key, now() - DAY_MS) >= callsPerDay) throw new HttpError(429, `This ${session.workspaceId ? 'workspace' : 'session'} made its ${callsPerDay} app calls for the last day. Try again later.`)
267
+ const call = await store.addAppCall({ room, capKey: key, connectionId: pick.connection.id, app: t.app, tool: t.slug, args, readOnly: t.readOnly, state: 'waiting', account: me.account })
268
+ if (t.readOnly) return answer(await run(call, pick.connection))
269
+ const who = await nameOf(me.account)
270
+ await sayInRoom(room, { approval: call.id, text: `${who} asks to run ${t.slug} on ${pick.connection.appName || t.app} (${LEVEL_WORDS[pick.level.type].toLowerCase()} connection): ${argsLine(args)}. A person in the session approves or declines it here.` }).catch((err) => log(`connections: tell ${room}: ${err.message}`))
271
+ return answer(await waitFor(call.id) || call, pick.connection.appName)
272
+ }],
273
+
274
+ // The session's app calls, newest first: what agents did in other apps, and what waits (people only).
275
+ ['GET', /^\/v1\/sessions\/([^/]+)\/app-calls$/, async (req, body, [room], url) => {
276
+ const { me } = await member(req, room)
277
+ const u = url || new URL(req.url, 'http://x')
278
+ const waiting = u.searchParams.get('waiting') === '1'
279
+ const calls = await store.listAppCalls(room, { states: waiting ? ['waiting'] : null, limit: 50 })
280
+ return { calls: await Promise.all(calls.map(async (c) => ({ id: c.id, app: c.app, tool: c.tool, args: argsLine(c.args, 2000), readOnly: c.readOnly, state: c.state, by: await nameOf(c.account), decidedBy: c.decidedBy ? await nameOf(c.decidedBy) : null, error: c.error, at: c.createdAt }))), mayDecide: me.kind === 'person' }
281
+ }],
282
+
283
+ // A person approves (and so runs, once) or declines a waiting call.
284
+ ['POST', /^\/v1\/sessions\/([^/]+)\/app-calls\/([^/]+)$/, async (req, body, [room, id]) => {
285
+ const { me, found } = await member(req, room)
286
+ if (me.kind !== 'person') throw new HttpError(403, 'Only a person approves what an agent does in another app.')
287
+ const call = await store.appCallById(needId(id, 'approval'))
288
+ if (!call || call.room !== room) throw new HttpError(404, 'no such approval')
289
+ const allow = body.allow === true
290
+ const decided = await store.updateAppCall(call.id, { state: allow ? 'approved' : 'declined', decidedBy: me.account, decidedAt: now() }, { from: 'waiting' })
291
+ if (!decided) throw new HttpError(409, call.state === 'declined' ? 'Someone already declined it.' : 'Someone already approved it.')
292
+ const me2 = await nameOf(me.account)
293
+ const asker = await nameOf(call.account)
294
+ let ended = decided
295
+ if (allow) {
296
+ const c = call.connectionId ? await store.appConnectionById(call.connectionId) : null
297
+ const still = c && c.status === 'active' && (await usable({ kind: call.account.startsWith('person:') ? 'person' : 'agent' }, found)).some((x) => x.connection.id === c.id)
298
+ ended = still ? await run(decided, c) : (await store.updateAppCall(call.id, { state: 'failed', error: 'That connection was removed.', ranAt: now() }, { from: 'approved' })) || decided
299
+ }
300
+ const what = allow ? (ended.state === 'ran' ? 'ran it' : `it failed: ${String(ended.error || '').slice(0, 200)}`) : 'declined it'
301
+ await sayInRoom(room, { to: asker, text: `${me2} ${allow ? 'approved' : 'declined'} ${call.tool} on ${call.app}${allow ? `: ${what}` : ''}. ${asker}: quilt_app_call with approval "${call.id}" has the result.` }).catch((err) => log(`connections: tell ${room}: ${err.message}`))
302
+ return { id: call.id, state: ended.state, error: ended.error || null }
303
+ }]
304
+ ]
305
+
306
+ // Off until the API has a Composio key (COMPOSIO_API_KEY).
307
+ const on = (fn) => (...a) => { if (!composio || !composio.on) throw new HttpError(503, 'App connections are not switched on on this server yet.'); return fn(...a) }
308
+ return routes.map(([method, pattern, fn, ...rest]) => [method, pattern, on(fn), ...rest])
309
+ }
310
+
311
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
@@ -81,7 +81,15 @@ export function sessionRoutes ({ store, now, person }) {
81
81
  const agent = await store.agentById(acc.slice('agent:'.length)).catch(() => null)
82
82
  if (agent && agent.revokedAt != null) revoked.set(acc, agent.revokedAt)
83
83
  }
84
- const trail = auditTrail({ visits: inWindow, actions: actions.slice(0, MAX_ACTIONS), revoked })
84
+ // What agents did in connected apps (routes/connections.js), with who approved it.
85
+ const calls = (await store.listAppCalls(room, { limit: 500 }).catch(() => [])).filter((c) => c.createdAt >= from && c.createdAt < to)
86
+ const names = new Map()
87
+ for (const acc of new Set(calls.map((c) => c.decidedBy).filter(Boolean))) {
88
+ const [kind, id] = acc.split(':')
89
+ names.set(acc, kind === 'person' ? (await store.profile(id).catch(() => null))?.name || 'someone' : 'an agent')
90
+ }
91
+ const appCalls = calls.map((c) => ({ ...c, decidedByName: c.decidedBy ? names.get(c.decidedBy) : '' }))
92
+ const trail = auditTrail({ visits: inWindow, actions: actions.slice(0, MAX_ACTIONS), revoked, appCalls })
85
93
  if (q.get('format') === 'csv') return new Raw(200, auditCsv(trail), 'text/csv; charset=utf-8')
86
94
  return { session: { room, name: session.name }, from, to, truncated, visits: trail }
87
95
  }],