heyquilt 0.3.154 → 0.3.156
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 +20 -0
- package/bin/quilt.js +4 -0
- package/package.json +1 -1
- package/src/api/audit.js +13 -2
- package/src/api/composio.js +173 -0
- package/src/api/memory-store.js +47 -0
- package/src/api/routes/connections.js +344 -0
- package/src/api/routes/sessions.js +9 -1
- package/src/api/routes/workspaces.js +43 -3
- package/src/api/server.js +14 -3
- package/src/api/supabase-store.js +43 -0
- package/src/app-tools.js +107 -0
- package/src/control.js +28 -0
- package/src/dev-servers.js +65 -0
- package/src/mcp.js +7 -0
- package/src/presence.js +2 -1
- package/src/relay-mcp.js +14 -0
- package/src/server.js +37 -2
- package/src/ui/agent-guide.js +4 -0
- package/src/ui/app.css +634 -2
- package/src/ui/app.js +42 -23
- package/src/ui/board.js +17 -7
- package/src/ui/common.js +2 -0
- package/src/ui/connections.js +241 -0
- package/src/ui/feed.js +23 -8
- package/src/ui/files.js +67 -22
- package/src/ui/home-view.js +170 -0
- package/src/ui/home.js +95 -6
- package/src/ui/loom-model.js +11 -8
- package/src/ui/loom.css +182 -2
- package/src/ui/loom.js +132 -55
- package/src/ui/palette.js +75 -0
- package/src/ui/people-view.js +116 -0
- package/src/ui/session.js +1066 -71
- package/src/ui/signin.js +1 -0
- package/src/ui/workspaces.js +7 -1
- package/src/ui-server.js +79 -4
|
@@ -0,0 +1,344 @@
|
|
|
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
|
+
/**
|
|
29
|
+
* A page of the catalog for the Connections page: { apps, total, categories }. A search matches names first, then
|
|
30
|
+
* descriptions and categories; a category narrows to it. `categories`: the biggest ones, with how many apps each.
|
|
31
|
+
*/
|
|
32
|
+
export function pickApps (all, { search = '', category = '', offset = 0, limit = 48 }) {
|
|
33
|
+
const words = String(search).toLowerCase().trim().slice(0, 100).split(/\s+/).filter(Boolean)
|
|
34
|
+
let list = category ? all.filter((a) => a.categories.some((c) => c.id === category)) : all
|
|
35
|
+
if (words.length) {
|
|
36
|
+
const score = (a) => {
|
|
37
|
+
const name = a.name.toLowerCase()
|
|
38
|
+
const rest = `${a.slug} ${a.description} ${a.categories.map((c) => c.name).join(' ')}`.toLowerCase()
|
|
39
|
+
if (!words.every((w) => name.includes(w) || rest.includes(w))) return 0
|
|
40
|
+
return words.every((w) => name.includes(w)) ? (name.startsWith(words[0]) ? 3 : 2) : 1
|
|
41
|
+
}
|
|
42
|
+
list = list.map((a, i) => ({ a, s: score(a), i })).filter((x) => x.s).sort((x, y) => y.s - x.s || x.i - y.i).map((x) => x.a)
|
|
43
|
+
}
|
|
44
|
+
const counts = new Map()
|
|
45
|
+
for (const a of all) for (const c of a.categories) { const k = counts.get(c.id) || { id: c.id, name: c.name, n: 0 }; k.n++; counts.set(c.id, k) }
|
|
46
|
+
const from = Math.max(0, offset)
|
|
47
|
+
const n = Math.min(200, Math.max(1, limit))
|
|
48
|
+
return {
|
|
49
|
+
apps: list.slice(from, from + n),
|
|
50
|
+
total: list.length,
|
|
51
|
+
all: all.length,
|
|
52
|
+
categories: [...counts.values()].filter((c) => c.n >= 5 && !/other|misc/i.test(c.name)).sort((x, y) => y.n - x.n).slice(0, 12)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function argsLine (args, max = 400) {
|
|
57
|
+
const s = JSON.stringify(args || {})
|
|
58
|
+
return s.length > max ? `${s.slice(0, max)}…` : s
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** What is kept of an app's reply: itself when small, else its start. */
|
|
62
|
+
const kept = (data) => {
|
|
63
|
+
const s = JSON.stringify(data ?? null)
|
|
64
|
+
return s.length <= MAX_KEPT ? data : { truncated: true, start: s.slice(0, MAX_KEPT) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function connectionRoutes (ctx) {
|
|
68
|
+
const { store, person, bearer, agentAuth, now = Date.now, log = () => {}, apiUrl = '', composio, callsPerDay = 500, sayInRoom = async () => {}, waitMs = APPROVAL_WAIT_MS } = ctx
|
|
69
|
+
const { caller: reachCaller, reach } = workspaceReach(ctx)
|
|
70
|
+
|
|
71
|
+
const nameOf = async (account) => {
|
|
72
|
+
const [kind, id] = String(account || '').split(':')
|
|
73
|
+
if (kind === 'agent') return (await store.agentById(id).catch(() => null))?.name || 'An agent'
|
|
74
|
+
if (kind === 'person') return (await store.profile(id))?.name || 'Someone'
|
|
75
|
+
return ''
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The person or agent calling, hosted agents with a pass: { account, kind, userId, agent }. */
|
|
79
|
+
async function whoCalls (req) {
|
|
80
|
+
if (/^QuiltPass\s/i.test(String(req.headers.authorization || ''))) {
|
|
81
|
+
const c = await reachCaller(req)
|
|
82
|
+
return c.agent ? { account: c.account, kind: 'agent', userId: null, agent: c.agent } : { account: c.account, kind: 'person', userId: c.userId, agent: null }
|
|
83
|
+
}
|
|
84
|
+
if (isAgentKey(bearer(req))) {
|
|
85
|
+
const { agent } = await agentAuth.agentFromRequest(req)
|
|
86
|
+
return { account: `agent:${agent.id}`, kind: 'agent', userId: null, agent }
|
|
87
|
+
}
|
|
88
|
+
const p = await person(req)
|
|
89
|
+
return { account: `person:${p.userId}`, kind: 'person', userId: p.userId, agent: null }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** One scope as a person reaches it, as for secrets: { type, id, name, levels, canManage, me }. */
|
|
93
|
+
async function scopeOf (req, type, rawId) {
|
|
94
|
+
const me = await whoCalls(req)
|
|
95
|
+
if (me.kind !== 'person') throw new HttpError(403, 'People connect apps; agents use them with quilt_app_call.')
|
|
96
|
+
if (type === 'org') {
|
|
97
|
+
const a = await orgAccess(store, me.userId, rawId)
|
|
98
|
+
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 }
|
|
99
|
+
}
|
|
100
|
+
if (type === 'workspace') {
|
|
101
|
+
const r = await reach(req, needId(rawId, 'workspace'))
|
|
102
|
+
return { type, id: r.ws.id, name: r.ws.name, levels: await workspaceLevels(store, r.ws), canManage: !!r.access.admin, me }
|
|
103
|
+
}
|
|
104
|
+
const room = String(rawId)
|
|
105
|
+
if (!ROOM.test(room)) throw new HttpError(404, 'no such session')
|
|
106
|
+
const found = await roomLevels(store, room)
|
|
107
|
+
if (!found || !(await sessionMember(store, room, me.account))) throw new HttpError(404, 'no such session')
|
|
108
|
+
// Anyone in the session connects apps for it (the owner removes any; others their own).
|
|
109
|
+
return { type, id: room, name: found.session.name || '', levels: found.levels, canManage: true, owner: found.session.ownerAccount === me.account, me, session: found.session }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
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.') }
|
|
113
|
+
const mayChange = (s, c) => s.type !== 'session' ? s.canManage : (s.owner || c.createdBy === s.me.account)
|
|
114
|
+
|
|
115
|
+
/** A connection still pending at Composio: asked again, so one finished without the callback shows. */
|
|
116
|
+
async function settle (c) {
|
|
117
|
+
if (c.status !== 'pending' || !composio.on) return c
|
|
118
|
+
try {
|
|
119
|
+
const a = await composio.account(c.composioId)
|
|
120
|
+
const status = a.status === 'ACTIVE' ? 'active' : ['FAILED', 'EXPIRED', 'INACTIVE', 'REVOKED'].includes(a.status) ? 'failed' : 'pending'
|
|
121
|
+
return status === c.status ? c : (await store.updateAppConnection(c.id, { status })) || c
|
|
122
|
+
} catch (err) { log(`connections: ${c.id}: ${err.message}`); return c }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const view = async (c, level, extra = {}) => ({
|
|
126
|
+
id: c.id, app: c.app, name: c.appName || c.app, logo: c.logo, status: c.status, who: c.who,
|
|
127
|
+
level: level.type, levelName: level.name || '', by: await nameOf(c.createdBy), createdAt: c.createdAt, ...extra
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
/** Every connection a session (or workspace) reaches, nearest level first: [{ connection, level }]. */
|
|
131
|
+
async function reachable (levels) {
|
|
132
|
+
const out = []
|
|
133
|
+
for (const l of levels) for (const c of await store.listAppConnections(l.type, l.id)) out.push({ connection: await settle(c), level: l })
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function scopeView (s) {
|
|
138
|
+
const all = await reachable(s.levels)
|
|
139
|
+
const own = all.filter((x) => x.level.type === s.type && x.level.id === s.id)
|
|
140
|
+
const inherited = all.filter((x) => !own.includes(x))
|
|
141
|
+
return {
|
|
142
|
+
scope: { type: s.type, id: s.id, name: s.name },
|
|
143
|
+
canManage: s.canManage,
|
|
144
|
+
connections: await Promise.all(own.map((x) => view(x.connection, x.level, { mayChange: mayChange(s, x.connection) }))),
|
|
145
|
+
inherited: await Promise.all(inherited.filter((x) => x.connection.status === 'active').map((x) => view(x.connection, x.level))),
|
|
146
|
+
callsPerDay
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The caller, when a member of the session: { me, found }; otherwise 404. */
|
|
151
|
+
async function member (req, room) {
|
|
152
|
+
if (!ROOM.test(room)) throw new HttpError(404, 'no such session')
|
|
153
|
+
const me = await whoCalls(req)
|
|
154
|
+
if (!(await sessionMember(store, room, me.account, { agent: me.agent }))) throw new HttpError(404, 'no such session')
|
|
155
|
+
const found = await roomLevels(store, room)
|
|
156
|
+
if (!found) throw new HttpError(404, 'no such session')
|
|
157
|
+
return { me, found }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The connections the caller may use in the session, nearest level first. */
|
|
161
|
+
async function usable (me, found) {
|
|
162
|
+
return (await reachable(found.levels)).filter(({ connection: c }) => c.status === 'active' && (me.kind === 'person' || c.who === 'all'))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const capKey = (session) => session.workspaceId ? `workspace:${session.workspaceId}` : `session:${session.room || ''}`
|
|
166
|
+
|
|
167
|
+
/** Runs a call's action and keeps the outcome: the call as it ended. */
|
|
168
|
+
async function run (call, connection) {
|
|
169
|
+
let outcome
|
|
170
|
+
try {
|
|
171
|
+
outcome = await composio.execute({ tool: call.tool, user: composioUser(connection.scopeType, connection.scopeId), composioId: connection.composioId, args: call.args })
|
|
172
|
+
} catch (err) { outcome = { ok: false, data: null, error: err.message } }
|
|
173
|
+
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'] })
|
|
174
|
+
return { ...(ended || call), data: outcome.data }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** What an agent is told about a call: { state, approval, app, tool, ok, data, error, decidedBy, message }. */
|
|
178
|
+
async function answer (call, appName) {
|
|
179
|
+
const out = { approval: call.id, state: call.state, app: call.app, tool: call.tool }
|
|
180
|
+
if (call.state === 'ran' || call.state === 'failed') {
|
|
181
|
+
const data = call.data !== undefined ? call.data : call.result
|
|
182
|
+
const s = JSON.stringify(data ?? null)
|
|
183
|
+
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 })
|
|
184
|
+
}
|
|
185
|
+
if (call.decidedBy) out.decidedBy = await nameOf(call.decidedBy)
|
|
186
|
+
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.`
|
|
187
|
+
if (call.state === 'declined') out.message = `${out.decidedBy || 'A person'} declined ${call.tool}: don't run it again unless they ask you to.`
|
|
188
|
+
return out
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// A waiting call holds until a person answers it, or a while passes (other API machines answer too).
|
|
192
|
+
async function waitFor (id) {
|
|
193
|
+
const end = now() + waitMs
|
|
194
|
+
while (true) {
|
|
195
|
+
const call = await store.appCallById(id)
|
|
196
|
+
if (!call || call.state !== 'waiting' || now() >= end) return call
|
|
197
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(LOOK_EVERY_MS, Math.max(0, end - now()))))
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const routes = [
|
|
202
|
+
// The apps one can connect (Composio's catalog), most used first.
|
|
203
|
+
['GET', /^\/v1\/connections\/apps$/, async (req, body, params, url) => {
|
|
204
|
+
await whoCalls(req)
|
|
205
|
+
const u = url || new URL(req.url, 'http://x')
|
|
206
|
+
return pickApps(await composio.catalog(), {
|
|
207
|
+
search: u.searchParams.get('search') || '',
|
|
208
|
+
category: u.searchParams.get('category') || '',
|
|
209
|
+
offset: Number(u.searchParams.get('offset')) || 0,
|
|
210
|
+
limit: Number(u.searchParams.get('limit')) || 48
|
|
211
|
+
})
|
|
212
|
+
}],
|
|
213
|
+
|
|
214
|
+
// Composio sends the browser back here once someone signed in (or gave up).
|
|
215
|
+
['GET', /^\/v1\/connections\/done$/, async (req, body, params, url) => {
|
|
216
|
+
const u = url || new URL(req.url, 'http://x')
|
|
217
|
+
const id = String(u.searchParams.get('connected_account_id') || '').slice(0, 80)
|
|
218
|
+
let c = id ? await store.appConnectionByComposioId(id) : null
|
|
219
|
+
if (c) c = await settle(c)
|
|
220
|
+
const ok = !!c && c.status === 'active'
|
|
221
|
+
const name = c ? (c.appName || c.app) : 'the app'
|
|
222
|
+
const title = ok ? `${name} is connected` : `${name} isn't connected`
|
|
223
|
+
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.'
|
|
224
|
+
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')
|
|
225
|
+
}],
|
|
226
|
+
|
|
227
|
+
['GET', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)$`), async (req, body, [type, id]) => scopeView(await scopeOf(req, type, id))],
|
|
228
|
+
|
|
229
|
+
// Connect an app here: a Composio Connect Link to open in the browser.
|
|
230
|
+
['POST', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)$`), async (req, body, [type, id]) => {
|
|
231
|
+
const s = await scopeOf(req, type, id)
|
|
232
|
+
needManage(s)
|
|
233
|
+
const app = String(body.app || '').toLowerCase()
|
|
234
|
+
if (!APP.test(app)) throw new HttpError(400, 'Say which app to connect.')
|
|
235
|
+
const t = await composio.toolkit(app)
|
|
236
|
+
const l = await composio.link({ user: composioUser(s.type, s.id), app, callbackUrl: `${apiUrl}/v1/connections/done` })
|
|
237
|
+
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 })
|
|
238
|
+
return { url: l.url, connection: await view(c, s.levels[0]) }
|
|
239
|
+
}],
|
|
240
|
+
|
|
241
|
+
// Who may use it: 'all' (people and agents) or 'people'.
|
|
242
|
+
['PATCH', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
|
|
243
|
+
const s = await scopeOf(req, type, id)
|
|
244
|
+
const c = await store.appConnectionById(needId(cid, 'connection'))
|
|
245
|
+
if (!c || c.scopeType !== s.type || c.scopeId !== s.id) throw new HttpError(404, 'no such connection')
|
|
246
|
+
if (!mayChange(s, c)) throw new HttpError(403, 'Only whoever connected it, or the session\'s owner, changes it.')
|
|
247
|
+
if (body.who !== 'all' && body.who !== 'people') throw new HttpError(400, 'who is "all" or "people"')
|
|
248
|
+
return view(await store.updateAppConnection(c.id, { who: body.who }), s.levels[0])
|
|
249
|
+
}],
|
|
250
|
+
|
|
251
|
+
['DELETE', new RegExp(`^/v1/connections/${SCOPE}/([^/]+)/([^/]+)$`), async (req, body, [type, id, cid]) => {
|
|
252
|
+
const s = await scopeOf(req, type, id)
|
|
253
|
+
const c = await store.appConnectionById(needId(cid, 'connection'))
|
|
254
|
+
if (!c || c.scopeType !== s.type || c.scopeId !== s.id) throw new HttpError(404, 'no such connection')
|
|
255
|
+
if (!mayChange(s, c)) throw new HttpError(403, 'Only whoever connected it, or the session\'s owner, removes it.')
|
|
256
|
+
await composio.remove(c.composioId)
|
|
257
|
+
await store.deleteAppConnection(c.id)
|
|
258
|
+
return { ok: true }
|
|
259
|
+
}],
|
|
260
|
+
|
|
261
|
+
// ---------------------------------------------------------------- agents in a session --
|
|
262
|
+
|
|
263
|
+
// The apps the caller may use here (quilt_apps).
|
|
264
|
+
['GET', /^\/v1\/sessions\/([^/]+)\/apps$/, async (req, body, [room]) => {
|
|
265
|
+
const { me, found } = await member(req, room)
|
|
266
|
+
const list = await usable(me, found)
|
|
267
|
+
return { apps: await Promise.all(list.map((x) => view(x.connection, x.level))), canConnect: me.kind === 'person', callsPerDay }
|
|
268
|
+
}],
|
|
269
|
+
|
|
270
|
+
// An app's actions, best match first (quilt_app_tools).
|
|
271
|
+
['GET', /^\/v1\/sessions\/([^/]+)\/apps\/tools$/, async (req, body, [room], url) => {
|
|
272
|
+
const { me, found } = await member(req, room)
|
|
273
|
+
const u = url || new URL(req.url, 'http://x')
|
|
274
|
+
const app = String(u.searchParams.get('app') || '').toLowerCase()
|
|
275
|
+
if (!APP.test(app)) throw new HttpError(400, 'Say which app.')
|
|
276
|
+
const connected = (await usable(me, found)).some((x) => x.connection.app === app)
|
|
277
|
+
return { app, connected, tools: await composio.tools({ app, query: u.searchParams.get('query') || '', limit: Number(u.searchParams.get('limit')) || 15 }) }
|
|
278
|
+
}],
|
|
279
|
+
|
|
280
|
+
// Run an action (quilt_app_call), or ask after one waiting for approval.
|
|
281
|
+
['POST', /^\/v1\/sessions\/([^/]+)\/apps\/call$/, async (req, body, [room]) => {
|
|
282
|
+
const { me, found } = await member(req, room)
|
|
283
|
+
if (body.approval) {
|
|
284
|
+
const call = await store.appCallById(needId(body.approval, 'approval'))
|
|
285
|
+
if (!call || call.room !== room || call.account !== me.account) throw new HttpError(404, 'no such approval')
|
|
286
|
+
const now2 = call.state === 'waiting' ? await waitFor(call.id) : call
|
|
287
|
+
return answer(now2 || call)
|
|
288
|
+
}
|
|
289
|
+
const toolSlug = String(body.tool || '')
|
|
290
|
+
if (!TOOL.test(toolSlug)) throw new HttpError(400, 'Say which action (its slug, from quilt_app_tools).')
|
|
291
|
+
const args = body.args && typeof body.args === 'object' && !Array.isArray(body.args) ? body.args : {}
|
|
292
|
+
if (JSON.stringify(args).length > MAX_ARGS) throw new HttpError(413, 'Those arguments are too long.')
|
|
293
|
+
const t = await composio.tool(toolSlug)
|
|
294
|
+
const options = (await usable(me, found)).filter((x) => x.connection.app === t.app)
|
|
295
|
+
const pick = body.connection ? options.find((x) => x.connection.id === body.connection) : options[0]
|
|
296
|
+
if (!pick) throw new HttpError(400, `No ${t.app} connection you may use in this session. A person connects it in Session settings → Connections.`)
|
|
297
|
+
const session = found.session
|
|
298
|
+
const key = capKey({ ...session, room })
|
|
299
|
+
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.`)
|
|
300
|
+
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 })
|
|
301
|
+
if (t.readOnly) return answer(await run(call, pick.connection))
|
|
302
|
+
const who = await nameOf(me.account)
|
|
303
|
+
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}`))
|
|
304
|
+
return answer(await waitFor(call.id) || call, pick.connection.appName)
|
|
305
|
+
}],
|
|
306
|
+
|
|
307
|
+
// The session's app calls, newest first: what agents did in other apps, and what waits (people only).
|
|
308
|
+
['GET', /^\/v1\/sessions\/([^/]+)\/app-calls$/, async (req, body, [room], url) => {
|
|
309
|
+
const { me } = await member(req, room)
|
|
310
|
+
const u = url || new URL(req.url, 'http://x')
|
|
311
|
+
const waiting = u.searchParams.get('waiting') === '1'
|
|
312
|
+
const calls = await store.listAppCalls(room, { states: waiting ? ['waiting'] : null, limit: 50 })
|
|
313
|
+
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' }
|
|
314
|
+
}],
|
|
315
|
+
|
|
316
|
+
// A person approves (and so runs, once) or declines a waiting call.
|
|
317
|
+
['POST', /^\/v1\/sessions\/([^/]+)\/app-calls\/([^/]+)$/, async (req, body, [room, id]) => {
|
|
318
|
+
const { me, found } = await member(req, room)
|
|
319
|
+
if (me.kind !== 'person') throw new HttpError(403, 'Only a person approves what an agent does in another app.')
|
|
320
|
+
const call = await store.appCallById(needId(id, 'approval'))
|
|
321
|
+
if (!call || call.room !== room) throw new HttpError(404, 'no such approval')
|
|
322
|
+
const allow = body.allow === true
|
|
323
|
+
const decided = await store.updateAppCall(call.id, { state: allow ? 'approved' : 'declined', decidedBy: me.account, decidedAt: now() }, { from: 'waiting' })
|
|
324
|
+
if (!decided) throw new HttpError(409, call.state === 'declined' ? 'Someone already declined it.' : 'Someone already approved it.')
|
|
325
|
+
const me2 = await nameOf(me.account)
|
|
326
|
+
const asker = await nameOf(call.account)
|
|
327
|
+
let ended = decided
|
|
328
|
+
if (allow) {
|
|
329
|
+
const c = call.connectionId ? await store.appConnectionById(call.connectionId) : null
|
|
330
|
+
const still = c && c.status === 'active' && (await usable({ kind: call.account.startsWith('person:') ? 'person' : 'agent' }, found)).some((x) => x.connection.id === c.id)
|
|
331
|
+
ended = still ? await run(decided, c) : (await store.updateAppCall(call.id, { state: 'failed', error: 'That connection was removed.', ranAt: now() }, { from: 'approved' })) || decided
|
|
332
|
+
}
|
|
333
|
+
const what = allow ? (ended.state === 'ran' ? 'ran it' : `it failed: ${String(ended.error || '').slice(0, 200)}`) : 'declined it'
|
|
334
|
+
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}`))
|
|
335
|
+
return { id: call.id, state: ended.state, error: ended.error || null }
|
|
336
|
+
}]
|
|
337
|
+
]
|
|
338
|
+
|
|
339
|
+
// Off until the API has a Composio key (COMPOSIO_API_KEY).
|
|
340
|
+
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) }
|
|
341
|
+
return routes.map(([method, pattern, fn, ...rest]) => [method, pattern, on(fn), ...rest])
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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
|
-
|
|
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
|
}],
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Workspaces: a container owned by a person or an org, holding sessions and members.
|
|
2
2
|
// Behind the QUILT_WORKSPACES flag (startApi({ workspaces })): off, every route answers 404.
|
|
3
|
-
import { HttpError, cleanName } from '../http.js'
|
|
3
|
+
import { HttpError, cleanName, needId } from '../http.js'
|
|
4
4
|
import { orgAccess } from '../org-access.js'
|
|
5
5
|
import { workspaceAccess, cleanColor, cleanDescription, cleanAccess, autoColor } from '../workspace-access.js'
|
|
6
6
|
import { workspaceReach, canSeeFiles } from '../workspace-reach.js'
|
|
@@ -14,6 +14,10 @@ const ROOM = /^[A-Za-z0-9_-]{1,64}$/
|
|
|
14
14
|
const ACCOUNT = /^(person|agent):[A-Za-z0-9_-]{1,64}$/
|
|
15
15
|
const OPEN_MS = 10 * 60 * 1000
|
|
16
16
|
|
|
17
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
18
|
+
const HOUR_MS = 60 * 60 * 1000
|
|
19
|
+
const linkView = (l) => ({ id: l.id, name: l.name, url: l.url, room: l.room || null, note: l.note || '', by: l.createdBy, at: l.createdAt })
|
|
20
|
+
|
|
17
21
|
export function workspaceRoutes (ctx) {
|
|
18
22
|
const { store, now, files: fileStore, workspaces = false, log = () => {}, policyChanged = null } = ctx
|
|
19
23
|
const { caller, grantsIn, reach } = workspaceReach(ctx)
|
|
@@ -133,7 +137,7 @@ export function workspaceRoutes (ctx) {
|
|
|
133
137
|
const sessions = (await store.listWorkspaceSessions(ws.id)).map((s) => sessionView(s, t))
|
|
134
138
|
const files = canSeeFiles(access) ? await listedFiles(store, await store.listWorkspaceFiles(ws.id)) : []
|
|
135
139
|
const agents = await workspaceAgents(store, ws, { admin: access.admin })
|
|
136
|
-
return { workspace: ws, access, canDelete, owner, members, agents, sessions, files, usage: await usageView(store, ws, ctx) }
|
|
140
|
+
return { workspace: ws, access, canDelete, owner, members, agents, sessions, files, usage: await usageView(store, ws, ctx), links: (await store.listWorkspaceLinks(ws.id)).map(linkView) }
|
|
137
141
|
}],
|
|
138
142
|
|
|
139
143
|
['PATCH', /^\/v1\/workspaces\/([^/]+)$/, async (req, body, [id]) => {
|
|
@@ -226,7 +230,43 @@ export function workspaceRoutes (ctx) {
|
|
|
226
230
|
await store.setSessionWorkspace(room, null, { linkedBy: null, at: now() })
|
|
227
231
|
if (policyChanged) policyChanged(room) // the workspace's rule no longer covers it
|
|
228
232
|
return { ok: true }
|
|
229
|
-
}]
|
|
233
|
+
}],
|
|
234
|
+
|
|
235
|
+
// The workspace's home (plans/app-redesign.md): AI time per session, by the hour (each 'ai' action is a
|
|
236
|
+
// minute an AI worked: presence.js), for its charts; the app adds merges from Seam.
|
|
237
|
+
['GET', /^\/v1\/workspaces\/([^/]+)\/insights$/, async (req, body, [id], url) => {
|
|
238
|
+
const { ws } = await reach(req, id)
|
|
239
|
+
const days = Math.min(31, Math.max(1, Number((url || new URL(req.url, 'http://x')).searchParams.get('days')) || 14))
|
|
240
|
+
const t = now()
|
|
241
|
+
const sessions = await store.listWorkspaceSessions(ws.id)
|
|
242
|
+
const minutes = await store.aiMinutes(sessions.map((s) => s.room), t - days * DAY_MS)
|
|
243
|
+
const hours = new Map()
|
|
244
|
+
for (const m of minutes) {
|
|
245
|
+
const k = `${m.room}\n${Math.floor(m.at / HOUR_MS) * HOUR_MS}`
|
|
246
|
+
hours.set(k, (hours.get(k) || 0) + 1)
|
|
247
|
+
}
|
|
248
|
+
return { days, sessions: sessions.map((s) => ({ room: s.room, name: s.name || '' })), aiHours: [...hours].map(([k, n]) => { const [room, at] = k.split('\n'); return { room, at: Number(at), minutes: n } }) }
|
|
249
|
+
}],
|
|
250
|
+
|
|
251
|
+
// Previews: the links a workspace keeps at hand (production, staging, a square's preview, a shared localhost).
|
|
252
|
+
['POST', /^\/v1\/workspaces\/([^/]+)\/links$/, async (req, body, [id]) => {
|
|
253
|
+
const r = await reach(req, id)
|
|
254
|
+
if (r.access.access !== 'edit' && !r.access.admin) throw new HttpError(403, 'Only people who can edit the workspace add its links.')
|
|
255
|
+
const name = String(body.name || '').trim().slice(0, 80)
|
|
256
|
+
const link = String(body.url || '').trim()
|
|
257
|
+
if (!name) throw new HttpError(400, 'Give the link a name.')
|
|
258
|
+
if (!/^https?:\/\/\S{3,490}$/.test(link)) throw new HttpError(400, 'That is not a web address (http:// or https://).')
|
|
259
|
+
const room = typeof body.room === 'string' && body.room ? body.room.slice(0, 64) : null
|
|
260
|
+
if (room && !(await store.listWorkspaceSessions(r.ws.id)).some((s) => s.room === room)) throw new HttpError(400, 'That session is not in this workspace.')
|
|
261
|
+
const who = await caller(req)
|
|
262
|
+
return linkView(await store.addWorkspaceLink({ workspaceId: r.ws.id, room, name, url: link, note: String(body.note || '').slice(0, 200), createdBy: who.account }))
|
|
263
|
+
}],
|
|
264
|
+
['DELETE', /^\/v1\/workspaces\/([^/]+)\/links\/([^/]+)$/, async (req, body, [id, linkId]) => {
|
|
265
|
+
const r = await reach(req, id)
|
|
266
|
+
if (r.access.access !== 'edit' && !r.access.admin) throw new HttpError(403, 'Only people who can edit the workspace remove its links.')
|
|
267
|
+
await store.deleteWorkspaceLink(r.ws.id, needId(linkId, 'link'))
|
|
268
|
+
return { ok: true }
|
|
269
|
+
}],
|
|
230
270
|
]
|
|
231
271
|
return routes.map(([method, pattern, fn, ...options]) => [method, pattern, gated(fn), ...options])
|
|
232
272
|
}
|
package/src/api/server.js
CHANGED
|
@@ -48,6 +48,8 @@ import { routeName, cleanEvent } from './issues.js'
|
|
|
48
48
|
import { secretRoutes } from './routes/secrets.js'
|
|
49
49
|
import { voiceRoutes } from './routes/voice.js'
|
|
50
50
|
import { mailRoutes } from './routes/mail.js'
|
|
51
|
+
import { connectionRoutes } from './routes/connections.js'
|
|
52
|
+
import { composioClient } from './composio.js'
|
|
51
53
|
import { agentWakeRoutes } from './routes/agent-wake.js'
|
|
52
54
|
import { workspaceReach } from './workspace-reach.js'
|
|
53
55
|
import { leader, LEADER_ONLY } from './leader.js'
|
|
@@ -74,7 +76,7 @@ const MCP_TIMEOUT_MS = 30 * 1000
|
|
|
74
76
|
// a change to its grant reaches it as soon as it reaches a connected app.
|
|
75
77
|
const PASS_REUSE_MARGIN_MS = 5 * 60 * 1000
|
|
76
78
|
|
|
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 }) {
|
|
79
|
+
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, composioKey = '', composioFetch = globalThis.fetch, appCallsPerDay = 500, appWaitMs, 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
80
|
// PASS_SIGNING_KEY. A bad one should stop the API at start, not fail every pass later.
|
|
79
81
|
if (passKey) passPublicKey(passKey)
|
|
80
82
|
const site = String(siteUrl || '').replace(/\/+$/, '')
|
|
@@ -224,7 +226,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
224
226
|
|
|
225
227
|
// Which optional parts this API has on, for the app and the MCPs to decide what to show. Public.
|
|
226
228
|
// quilt_source_default (QUILT_SOURCE_DEFAULT, Seam's plans/quilt-source-control/16 flags order 8): apps make the sessions they start quilts from the start.
|
|
227
|
-
['GET', /^\/v1\/features$/, async () => ({ workspaces: !!workspaces, secrets: !!vaultSecret, quilt_source_default: !!quiltSourceDefault })],
|
|
229
|
+
['GET', /^\/v1\/features$/, async () => ({ workspaces: !!workspaces, secrets: !!vaultSecret, connections: !!composioKey, quilt_source_default: !!quiltSourceDefault })],
|
|
228
230
|
|
|
229
231
|
['POST', /^\/v1\/device\/start$/, async (req, body) => {
|
|
230
232
|
limitStarts(req)
|
|
@@ -407,6 +409,15 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
407
409
|
await cluster.tellRelays('/mail/arrived', { room, mail: arrived })
|
|
408
410
|
}
|
|
409
411
|
routes.push(...mailRoutes({ ...ctx, passKey, mail, mailFetch, makeLimiter, tellRoom }))
|
|
412
|
+
// App connections (routes/connections.js): apps connected through Composio, off until COMPOSIO_API_KEY is set.
|
|
413
|
+
// A call waiting for a person, and its outcome, are told in the session's chat by the relay machine holding it.
|
|
414
|
+
const sayInRoom = async (room, said) => {
|
|
415
|
+
if (!relay || !relaySecret) return
|
|
416
|
+
const placed = await store.relayRoom(room).catch(() => null)
|
|
417
|
+
if (placed && placed.machineId) return cluster.callRelay(placed.machineId, 'POST', '/apps/said', { room, ...said })
|
|
418
|
+
await cluster.tellRelays('/apps/said', { room, ...said })
|
|
419
|
+
}
|
|
420
|
+
routes.push(...connectionRoutes({ ...ctx, passKey, composio: composioClient({ apiKey: composioKey, fetch: composioFetch, log }), callsPerDay: appCallsPerDay, sayInRoom, ...(appWaitMs !== undefined ? { waitMs: appWaitMs } : {}) }))
|
|
410
421
|
// How Quilt wakes each agent (routes/agent-wake.js): step 2 of joining.
|
|
411
422
|
routes.push(...agentWakeRoutes({ ...ctx, passKey, mail, mailFetch, makeLimiter }))
|
|
412
423
|
// Seam (src/quilts/, Seam's plans/quilt-source-control/) is its own service at seamUrl. This API is its
|
|
@@ -492,7 +503,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
492
503
|
// A route may take a bigger body than usual (the relay's presence reports): route[3].maxBody.
|
|
493
504
|
// A route may want the bytes as sent (route[3].raw: GitHub's webhooks, signed over the raw body).
|
|
494
505
|
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
|
-
const out = await route[2](req, body, url.pathname.match(route[1]).slice(1).map(decodePart))
|
|
506
|
+
const out = await route[2](req, body, url.pathname.match(route[1]).slice(1).map(decodePart), url)
|
|
496
507
|
if (out instanceof Raw) send(out.status, out.body, out.type)
|
|
497
508
|
else if (out instanceof Stream) {
|
|
498
509
|
res.writeHead(out.status, { 'content-type': out.type, 'cache-control': 'no-store', ...out.headers, ...extra, ...cors(req) })
|
|
@@ -51,6 +51,11 @@ const SECRET_TICKET = 'id, token_hash, scope_type, scope_id, entries, created_by
|
|
|
51
51
|
const SECRET_RUN = 'id, token_hash, room, account, kind, label, created_at, expires_at, revoked_at'
|
|
52
52
|
const SECRET_ASK = 'run_id, secret_id, name, state, asked_at, answered_at'
|
|
53
53
|
const SECRET_USE = 'id, secret_id, run_id, room, account, upstream, at'
|
|
54
|
+
// A workspace's links (20261112100000_workspace_home.sql).
|
|
55
|
+
const WORKSPACE_LINK = 'id, workspace_id, room, name, url, note, created_by, created_at'
|
|
56
|
+
// App connections (20261112000000_app_connections.sql).
|
|
57
|
+
const APP_CONNECTION = 'id, scope_type, scope_id, app, app_name, logo, composio_id, status, who, created_by, created_at, updated_at'
|
|
58
|
+
const APP_CALL = 'id, room, cap_key, connection_id, app, tool, args, read_only, state, account, decided_by, result, error, created_at, decided_at, ran_at'
|
|
54
59
|
// How Quilt wakes each agent (20261025000000_agent_wake.sql).
|
|
55
60
|
const AGENT_WAKE = 'agent_id, method, detail, pending, updated_at'
|
|
56
61
|
// Session email (20261024000000_session_mail.sql).
|
|
@@ -419,6 +424,15 @@ export function createSupabaseStore ({ url, serviceKey, client }) {
|
|
|
419
424
|
// `at` isn't a `*At` column, so it's turned into epoch ms here.
|
|
420
425
|
return (await pages(() => db.rpc('actions_in_room', { p_room: room, p_from: ts(from), p_to: ts(to), p_limit: limit }))).map((r) => ({ ...rowFrom(r), at: ms(r.at) }))
|
|
421
426
|
},
|
|
427
|
+
/** Each minute an AI worked in these rooms since `since` ('ai' actions): [{ room, account, at }]. */
|
|
428
|
+
async aiMinutes (rooms, since) {
|
|
429
|
+
if (!rooms.length) return []
|
|
430
|
+
return (await pages(() => db.from('visit_actions').select('room, account, at').eq('action', 'ai').in('room', rooms).gte('at', ts(since)).order('at'))).map((r) => ({ room: r.room, account: r.account, at: ms(r.at) }))
|
|
431
|
+
},
|
|
432
|
+
// The workspace's links (previews), 20261112100000_workspace_home.sql.
|
|
433
|
+
async listWorkspaceLinks (workspaceId) { return (await one(db.from('workspace_links').select(WORKSPACE_LINK).eq('workspace_id', workspaceId).order('created_at'))).map(rowFrom) },
|
|
434
|
+
async addWorkspaceLink (l) { return rowFrom(await one(db.from('workspace_links').insert(toSnake(l)).select(WORKSPACE_LINK).single())) },
|
|
435
|
+
async deleteWorkspaceLink (workspaceId, id) { await one(db.from('workspace_links').delete().eq('workspace_id', workspaceId).eq('id', id)) },
|
|
422
436
|
async sessionByRoom (room) { return rowFrom(await one(db.from('relay_sessions').select(RELAY_SESSION).eq('room', room).maybeSingle())) },
|
|
423
437
|
async visitsInRooms (rooms) {
|
|
424
438
|
if (!rooms.length) return []
|
|
@@ -935,6 +949,35 @@ export function createSupabaseStore ({ url, serviceKey, client }) {
|
|
|
935
949
|
async listSecretUses (secretIds, { limit = 100 } = {}) {
|
|
936
950
|
if (!secretIds.length) return []
|
|
937
951
|
return (await one(db.from('secret_uses').select(SECRET_USE).in('secret_id', secretIds).order('at', { ascending: false }).limit(limit))).map((r) => ({ ...rowFrom(r), at: ms(r.at) }))
|
|
952
|
+
},
|
|
953
|
+
|
|
954
|
+
// App connections (20261112000000_app_connections.sql): Composio holds the tokens.
|
|
955
|
+
async addAppConnection (c) { return rowFrom(await one(db.from('app_connections').insert(toSnake(c)).select(APP_CONNECTION).single())) },
|
|
956
|
+
async appConnectionById (id) { return rowFrom(await one(db.from('app_connections').select(APP_CONNECTION).eq('id', id).maybeSingle())) },
|
|
957
|
+
async appConnectionByComposioId (composioId) { return rowFrom(await one(db.from('app_connections').select(APP_CONNECTION).eq('composio_id', composioId).maybeSingle())) },
|
|
958
|
+
async listAppConnections (scopeType, scopeId) { return (await one(db.from('app_connections').select(APP_CONNECTION).eq('scope_type', scopeType).eq('scope_id', scopeId).order('created_at'))).map(rowFrom) },
|
|
959
|
+
async updateAppConnection (id, patch) {
|
|
960
|
+
return rowFrom(await one(db.from('app_connections').update(toSnake({ ...patch, updatedAt: ts(Date.now()) })).eq('id', id).select(APP_CONNECTION).maybeSingle()))
|
|
961
|
+
},
|
|
962
|
+
async deleteAppConnection (id) { await one(db.from('app_connections').delete().eq('id', id)) },
|
|
963
|
+
async addAppCall (c) { return rowFrom(await one(db.from('app_calls').insert(toSnake(c)).select(APP_CALL).single())) },
|
|
964
|
+
async appCallById (id) { return rowFrom(await one(db.from('app_calls').select(APP_CALL).eq('id', id).maybeSingle())) },
|
|
965
|
+
/** Changes a call only while it is in `from` (one of them, when a list): null when it moved on. */
|
|
966
|
+
async updateAppCall (id, patch, { from = null } = {}) {
|
|
967
|
+
const row = toSnake({ ...patch, decidedAt: ts(patch.decidedAt), ranAt: ts(patch.ranAt) })
|
|
968
|
+
let q = db.from('app_calls').update(row).eq('id', id)
|
|
969
|
+
if (from) q = q.in('state', [].concat(from))
|
|
970
|
+
return rowFrom(await one(q.select(APP_CALL).maybeSingle()))
|
|
971
|
+
},
|
|
972
|
+
async listAppCalls (room, { states = null, limit = 50 } = {}) {
|
|
973
|
+
let q = db.from('app_calls').select(APP_CALL).eq('room', room)
|
|
974
|
+
if (states) q = q.in('state', states)
|
|
975
|
+
return (await one(q.order('created_at', { ascending: false }).limit(limit))).map(rowFrom)
|
|
976
|
+
},
|
|
977
|
+
async countAppCalls (capKey, since) {
|
|
978
|
+
const { count, error } = await db.from('app_calls').select('id', { count: 'exact', head: true }).eq('cap_key', capKey).gte('created_at', ts(since))
|
|
979
|
+
if (error) throw error
|
|
980
|
+
return count || 0
|
|
938
981
|
}
|
|
939
982
|
}
|
|
940
983
|
}
|