shapewall 0.3.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +501 -0
- package/README.md +87 -4
- package/THIRD_PARTY.md +15 -0
- package/dist/agent/package-lock.json +594 -2
- package/dist/client/assets/BoardChat-WS8mAIW6.js +27 -0
- package/dist/client/assets/{BuzzDialog-Ix9qJvim.js → BuzzDialog-B-Mlr6wF.js} +1 -1
- package/dist/client/assets/ChecksPanel-Dx1ZLBR6.js +1 -0
- package/dist/client/assets/History-sXhmpcvs.js +1 -0
- package/dist/client/assets/LocalSettings-CtGzz9F3.js +1 -0
- package/dist/client/assets/{Management-NVFDtSZB.js → Management-CGHe8Wt9.js} +1 -1
- package/dist/client/assets/QuickConnect-DEk84E4A.js +1 -0
- package/dist/client/assets/{ShareDialog-By0ETg6n.js → ShareDialog-CGGx-AYK.js} +2 -2
- package/dist/client/assets/{app-update-dialog-RGIw24iZ.js → app-update-dialog-_bVp8hnC.js} +1 -1
- package/dist/client/assets/{circle-x-B6KfScOE.js → circle-x-BWoHA1QY.js} +1 -1
- package/dist/client/assets/index-Bm-Xd3YN.js +37 -0
- package/dist/client/assets/index-C7Ostk3K.css +2 -0
- package/dist/client/assets/play-BzQ3tRTv.js +1 -0
- package/dist/client/assets/{refresh-cw-vkgvCCfR.js → refresh-cw-BYBMyDKT.js} +1 -1
- package/dist/client/assets/{runtime-Bft6x_6E.js → runtime-Bvq10IhH.js} +1 -1
- package/dist/client/assets/ui-CAY6myRA.js +41 -0
- package/dist/client/build-info.json +1 -1
- package/dist/client/index.html +3 -3
- package/dist/client/sw.js +2 -2
- package/dist/console/assets/LocalAccountsApp-CWRguRRL.js +1 -0
- package/dist/console/assets/LocalConsole--I2SaIpr.js +2 -0
- package/dist/console/assets/LocalUsage-BmpCZ36k.js +1 -0
- package/dist/console/assets/app-update-dialog-B8M9plaT.js +1 -0
- package/dist/console/assets/app-version-muKrQqbL.js +1 -0
- package/dist/console/assets/console-CrhTsPbz.css +2 -0
- package/dist/console/assets/console-DxapQ9oS.js +11 -0
- package/dist/console/assets/local-agents-CoqD4dSN.js +6 -0
- package/dist/console/assets/minus-DDQ0ydcM.js +1 -0
- package/dist/console/assets/tailnet-C5Flwl_d.js +2 -0
- package/dist/console/assets/theme-DCd0qh4l.js +1 -0
- package/dist/console/assets/ui-Bry1mnCY.js +41 -0
- package/dist/console/assets/usage-CIPWnHaS.css +1 -0
- package/dist/console/assets/usage-CqVjMb7m.js +5 -0
- package/dist/console/assets/usage-D1G0GgE3.js +56 -0
- package/dist/console/build-info.json +1 -1
- package/dist/console/console.html +8 -2
- package/docs/agent-hardening.md +206 -0
- package/docs/agent-recipes.md +23 -0
- package/docs/agent-workflow.md +5 -0
- package/docs/agents.md +49 -6
- package/docs/architecture.md +10 -4
- package/docs/deployment.md +39 -17
- package/docs/design-system.md +56 -7
- package/docs/hosted.md +1800 -46
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/where-to-run.md +119 -3
- package/package.json +6 -1
- package/src/agent/backends/acp.js +745 -44
- package/src/agent/branch-mode.js +17 -3
- package/src/agent/card-hash.js +65 -0
- package/src/agent/context.js +41 -0
- package/src/agent/exec-paths.js +105 -0
- package/src/agent/routes.js +23 -2
- package/src/agent/run.js +11 -1
- package/src/agent/starter/cli.js +6 -1
- package/src/agent/turn-changes.js +70 -8
- package/src/agent/usage-log.js +251 -0
- package/src/cli/args.js +37 -0
- package/src/cli/commands.js +20 -5
- package/src/cli/help.js +73 -3
- package/src/cli/init.js +2 -1
- package/src/cli/serve.js +20 -5
- package/src/cli.js +8 -0
- package/src/hosted/access-cli.js +99 -1
- package/src/hosted/activity-core.js +232 -0
- package/src/hosted/activity.js +375 -0
- package/src/hosted/admin.js +87 -13
- package/src/hosted/agent-approvals.js +29 -4
- package/src/hosted/agent-link.js +1032 -0
- package/src/hosted/agent-policy.js +10 -3
- package/src/hosted/agent-presence.js +63 -22
- package/src/hosted/agent-routes.js +135 -0
- package/src/hosted/agents.js +1206 -0
- package/src/hosted/app.js +178 -12
- package/src/hosted/auth-routes.js +156 -15
- package/src/hosted/auth.js +123 -20
- package/src/hosted/board-routes.js +129 -5
- package/src/hosted/chat-frames.js +246 -0
- package/src/hosted/chat-job.js +204 -0
- package/src/hosted/chat-permissions.js +203 -0
- package/src/hosted/chat-routes.js +1009 -0
- package/src/hosted/chat-store.js +477 -0
- package/src/hosted/comment-files.js +11 -1
- package/src/hosted/comments.js +1 -1
- package/src/hosted/console-routes.js +122 -34
- package/src/hosted/db.js +295 -0
- package/src/hosted/device-routes.js +88 -10
- package/src/hosted/device.js +54 -4
- package/src/hosted/events.js +3 -3
- package/src/hosted/guards.js +337 -27
- package/src/hosted/http.js +6 -3
- package/src/hosted/membership.js +22 -3
- package/src/hosted/operator-access.js +418 -0
- package/src/hosted/operator.js +106 -2
- package/src/hosted/ops-cli.js +238 -3
- package/src/hosted/pages.js +4 -0
- package/src/hosted/passkey-policy.js +75 -0
- package/src/hosted/permissions.js +52 -6
- package/src/hosted/presence.js +31 -2
- package/src/hosted/projects.js +30 -2
- package/src/hosted/public.js +4 -4
- package/src/hosted/ratelimit.js +14 -0
- package/src/hosted/retention.js +18 -2
- package/src/hosted/server.js +123 -11
- package/src/hosted/shares.js +2 -2
- package/src/hosted/step-up-settings.js +68 -0
- package/src/hosted/step-up.js +135 -0
- package/src/hosted/tailnet-identity.js +24 -0
- package/src/hosted/tailnet-routes.js +342 -0
- package/src/hosted/tailnet.js +220 -0
- package/src/hosted/tailscale.js +75 -9
- package/src/hosted/tenancy.js +66 -1
- package/src/hosted/token-api.js +119 -20
- package/src/hosted/token-events.js +5 -3
- package/src/hosted/tokens.js +29 -6
- package/src/hosted/turn-hub.js +152 -0
- package/src/hosted/usage-core.js +624 -0
- package/src/hosted/usage-layout.js +724 -0
- package/src/hosted/usage-routes.js +375 -0
- package/src/hosted/usage-shape.js +256 -0
- package/src/hosted/usage.js +641 -0
- package/src/remote/agent-connect.js +469 -0
- package/src/remote/agent-fix.js +611 -0
- package/src/remote/agent-job.js +216 -0
- package/src/remote/agent-link.js +906 -0
- package/src/remote/agent-policy-file.js +242 -0
- package/src/remote/credentials.js +35 -1
- package/src/remote/login.js +44 -9
- package/src/remote/share.js +1 -1
- package/src/remote/tailnet-cli.js +547 -0
- package/src/server/app.js +15 -0
- package/src/server/pairing-routes.js +34 -5
- package/src/server/tailscale.js +97 -4
- package/src/tailnet-proof.js +766 -0
- package/dist/client/assets/BoardChat-DxehB761.js +0 -27
- package/dist/client/assets/ChecksPanel-pA_ueIaJ.js +0 -1
- package/dist/client/assets/History-C9N32kCv.js +0 -1
- package/dist/client/assets/LocalSettings-DawtKnvi.js +0 -1
- package/dist/client/assets/QuickConnect-DO1TjS1t.js +0 -1
- package/dist/client/assets/index-CsqLdqGx.css +0 -2
- package/dist/client/assets/index-DnZarJ3U.js +0 -37
- package/dist/client/assets/shield-check-QzwGhz0t.js +0 -1
- package/dist/client/assets/ui-DI-FGWWK.js +0 -41
- package/dist/console/assets/LocalAccountsApp-VOCZg8dg.js +0 -1
- package/dist/console/assets/LocalConsole-CMwAW-mF.js +0 -1
- package/dist/console/assets/app-update-dialog-Cw6UDqNP.js +0 -1
- package/dist/console/assets/console-DgfWmUEx.js +0 -55
- package/dist/console/assets/console-Lis0vvdL.css +0 -2
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
// Agents on a hosted server. A project API token that may take work (the
|
|
2
|
+
// claim scope) is an agent: something a board lists by name, with a face,
|
|
3
|
+
// a state, and rules about who may send it work. The row in `agents`
|
|
4
|
+
// (migration 12) hangs that on the token; the token keeps the secret, the
|
|
5
|
+
// scopes, the name and revocation, exactly as before.
|
|
6
|
+
//
|
|
7
|
+
// state online (heard from in the last 90 seconds; a connected
|
|
8
|
+
// agent: while its link is open), busy (online and holding a
|
|
9
|
+
// comment it took, or answering in a chat), offline, revoked
|
|
10
|
+
// (its token was revoked, expired, or its maker is no longer an
|
|
11
|
+
// admin)
|
|
12
|
+
// connected an agent whose token has the "agent" scope: a machine runs
|
|
13
|
+
// `shapewall agent connect` for it and holds a link
|
|
14
|
+
// (src/hosted/agent-link.js). It says what it is and can do
|
|
15
|
+
// when the link opens (hello): its kind, its machine, whether it
|
|
16
|
+
// chats, and what its own machine allows. That is display and a
|
|
17
|
+
// narrowing only: the server never widens anything from it.
|
|
18
|
+
// audience who may send it work: "owner" (the person who connected it,
|
|
19
|
+
// the default for a new agent), "members" (the owner and named
|
|
20
|
+
// members) or "trusted" (everyone the project's agent policy
|
|
21
|
+
// trusts; what tokens from before 0.4.0 keep). The agent policy
|
|
22
|
+
// still decides who may send work to an agent at all: an
|
|
23
|
+
// audience only narrows that.
|
|
24
|
+
// routing a comment is addressed to one agent or to none ("any agent").
|
|
25
|
+
// Only the addressed agent's token may take it, and an agent
|
|
26
|
+
// only takes comments sent by someone in its audience.
|
|
27
|
+
//
|
|
28
|
+
// One function per setting. setIdentity, setDefault, setAudience,
|
|
29
|
+
// setApprovalRule and revoke below are the only code that changes those
|
|
30
|
+
// settings: each checks the role (src/hosted/permissions.js), validates,
|
|
31
|
+
// writes, and records an audit event with before and after. The console
|
|
32
|
+
// routes (src/hosted/agent-routes.js) are thin callers, so a CLI command or
|
|
33
|
+
// an admin tool can call the same functions later. `actor` is who asks:
|
|
34
|
+
// { userId, role, audit(action, target, detail) }.
|
|
35
|
+
//
|
|
36
|
+
// Every query goes through the tenant handle `t` (src/hosted/tenancy.js).
|
|
37
|
+
|
|
38
|
+
import { logoForAgent } from '../agent/agent-logos.js'
|
|
39
|
+
import { cleanAgentName, isAgentTint, isBuiltInIcon } from '../agent/identity.js'
|
|
40
|
+
import { agentPolicy, trustedMember } from './agent-policy.js'
|
|
41
|
+
import { newId } from './crypto.js'
|
|
42
|
+
import { RUN_DURATION } from './usage-shape.js'
|
|
43
|
+
import { HttpError } from './http.js'
|
|
44
|
+
import {
|
|
45
|
+
AGENT_AUDIENCES,
|
|
46
|
+
APPROVAL_ROLES,
|
|
47
|
+
APPROVAL_RULES,
|
|
48
|
+
approvalAutoAvailable,
|
|
49
|
+
approvalRuleFor,
|
|
50
|
+
canAnswerApproval,
|
|
51
|
+
canChangeApprovalRoles,
|
|
52
|
+
canChangeApprovalRule,
|
|
53
|
+
canManageAgents,
|
|
54
|
+
effectiveApprovalRule,
|
|
55
|
+
roleAtLeast,
|
|
56
|
+
tokenCreatorOk,
|
|
57
|
+
} from './permissions.js'
|
|
58
|
+
|
|
59
|
+
// What runs behind an agent, as far as the server was told. "watcher" is a
|
|
60
|
+
// `shapewall watch --remote` (or MCP client) whose command is unknown; the
|
|
61
|
+
// known ones show their product mark (src/agent/agent-logos.js).
|
|
62
|
+
export const AGENT_KINDS = ['watcher', 'claude', 'codex', 'goose', 'gemini', 'custom']
|
|
63
|
+
// What a connected agent may say it is (hello): never "watcher".
|
|
64
|
+
export const LINK_KINDS = ['claude', 'codex', 'goose', 'gemini', 'custom']
|
|
65
|
+
export const LINK_TURNS_MAX = 4
|
|
66
|
+
export const AUDIENCE_USERS_MAX = 50
|
|
67
|
+
export const AGENT_ID_RE = /^ag_[a-f0-9]{24}$/
|
|
68
|
+
// On a comment as the server hands it around (src/hosted/app.js
|
|
69
|
+
// dispatchView): { agent_id, dispatch_by }, what claimCheck goes by. A
|
|
70
|
+
// symbol key, so it never reaches JSON.
|
|
71
|
+
export const COMMENT_ROUTING = Symbol('commentRouting')
|
|
72
|
+
|
|
73
|
+
const SELECT = `SELECT a.*, k.name AS name, k.prefix AS token_prefix, k.scopes AS token_scopes, k.revoked_at AS token_revoked_at,
|
|
74
|
+
k.expires_at AS token_expires_at, k.created_by AS token_created_by, k.last_used_at AS token_last_used_at,
|
|
75
|
+
p.name AS project_name, u.handle AS creator_handle, u.display_name AS creator_name, m.role AS creator_role
|
|
76
|
+
FROM agents a JOIN api_tokens k ON k.id = a.token_id AND k.workspace_id = a.workspace_id
|
|
77
|
+
JOIN projects p ON p.id = a.project_id AND p.workspace_id = a.workspace_id
|
|
78
|
+
LEFT JOIN users u ON u.id = k.created_by
|
|
79
|
+
LEFT JOIN memberships m ON m.user_id = k.created_by AND m.workspace_id = a.workspace_id
|
|
80
|
+
WHERE a.workspace_id = :ws`
|
|
81
|
+
|
|
82
|
+
const parseList = (text) => {
|
|
83
|
+
try {
|
|
84
|
+
const value = JSON.parse(text || '[]')
|
|
85
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []
|
|
86
|
+
} catch {
|
|
87
|
+
return []
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const personName = (person) => person?.displayName || person?.handle || 'someone who left'
|
|
91
|
+
const listNames = (names) => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`)
|
|
92
|
+
|
|
93
|
+
// What a connected agent reported about itself, cleaned: display only.
|
|
94
|
+
const parseCaps = (text) => {
|
|
95
|
+
try {
|
|
96
|
+
const value = JSON.parse(text || '{}')
|
|
97
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
98
|
+
} catch {
|
|
99
|
+
return {}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// `links`: the open links of connected agents (src/hosted/agent-link.js):
|
|
104
|
+
// { of(workspaceId, agentId) -> { connectedAt, streams } | null,
|
|
105
|
+
// turns(workspaceId, agentId) -> how many chat turns it is answering }.
|
|
106
|
+
export function createAgentStore(t, { now = () => new Date(), presence = null, handleFor = () => null, links = null } = {}) {
|
|
107
|
+
const iso = () => now().toISOString()
|
|
108
|
+
// Reads repeat within one request (a list of comments asks per comment);
|
|
109
|
+
// every write starts over.
|
|
110
|
+
let memo = new Map()
|
|
111
|
+
const forget = () => {
|
|
112
|
+
memo = new Map()
|
|
113
|
+
}
|
|
114
|
+
const once = (key, make) => {
|
|
115
|
+
if (!memo.has(key)) memo.set(key, make())
|
|
116
|
+
return memo.get(key)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---- Rows ----
|
|
120
|
+
|
|
121
|
+
// A token with the claim scope that has no agent row yet was made while an
|
|
122
|
+
// older build ran on this database: it becomes an agent the first time it
|
|
123
|
+
// is looked for, with the audience such tokens had (the agent policy's).
|
|
124
|
+
// `audit(action, target, detail)`: hears `agent_first_seen` for each one,
|
|
125
|
+
// whoever's request found it (a token's call, the board, the console).
|
|
126
|
+
// Two requests may find the same token at once: the insert gives way to
|
|
127
|
+
// the row that is already there.
|
|
128
|
+
function ensure(projectId, audit = null) {
|
|
129
|
+
const missing = t.all(
|
|
130
|
+
`SELECT k.id, k.name, k.created_by, k.created_at, k.last_used_at FROM api_tokens k WHERE k.workspace_id = :ws AND k.project_id = :project
|
|
131
|
+
AND k.scopes LIKE '%"claim"%' AND NOT EXISTS (SELECT 1 FROM agents a WHERE a.token_id = k.id)`,
|
|
132
|
+
{ project: projectId },
|
|
133
|
+
)
|
|
134
|
+
let made = 0
|
|
135
|
+
for (const token of missing) {
|
|
136
|
+
const id = insert({ projectId, tokenId: token.id, userId: token.created_by, at: token.created_at, inherited: true })
|
|
137
|
+
if (!id) continue
|
|
138
|
+
made += 1
|
|
139
|
+
audit?.('agent_first_seen', id, { project: projectId, token: token.id, name: token.name, kind: 'watcher' })
|
|
140
|
+
}
|
|
141
|
+
if (missing.length) forget()
|
|
142
|
+
return made
|
|
143
|
+
}
|
|
144
|
+
// Returns the new agent's id, or null when the token already had one.
|
|
145
|
+
function insert({
|
|
146
|
+
projectId,
|
|
147
|
+
tokenId,
|
|
148
|
+
userId,
|
|
149
|
+
at = iso(),
|
|
150
|
+
inherited = false,
|
|
151
|
+
machine = null,
|
|
152
|
+
kind = 'watcher',
|
|
153
|
+
lastSeenAt = null,
|
|
154
|
+
icon = null,
|
|
155
|
+
tint = null,
|
|
156
|
+
}) {
|
|
157
|
+
const id = newId('ag')
|
|
158
|
+
const result = t.run(
|
|
159
|
+
`INSERT INTO agents (workspace_id, project_id, id, token_id, kind, icon, tint, machine, audience, audience_inherited, created_by,
|
|
160
|
+
created_at, approved_by, approved_at, last_seen_at)
|
|
161
|
+
VALUES (:ws, :project, :id, :token, :kind, :icon, :tint, :machine, :audience, :inherited, :user, :at, :user, :at, :seen)
|
|
162
|
+
ON CONFLICT(token_id) DO NOTHING`,
|
|
163
|
+
{
|
|
164
|
+
project: projectId,
|
|
165
|
+
id,
|
|
166
|
+
token: tokenId,
|
|
167
|
+
kind,
|
|
168
|
+
icon,
|
|
169
|
+
tint,
|
|
170
|
+
machine,
|
|
171
|
+
audience: inherited ? 'trusted' : 'owner',
|
|
172
|
+
inherited: inherited ? 1 : 0,
|
|
173
|
+
user: userId || null,
|
|
174
|
+
at,
|
|
175
|
+
seen: lastSeenAt,
|
|
176
|
+
},
|
|
177
|
+
)
|
|
178
|
+
forget()
|
|
179
|
+
return Number(result.changes) ? id : null
|
|
180
|
+
}
|
|
181
|
+
// A new token with the claim scope: its agent, for the person who made it
|
|
182
|
+
// only until they say otherwise. `machine`: the label `shapewall login` sent.
|
|
183
|
+
// Audit entries about an agent carry its name: the log reads without a
|
|
184
|
+
// lookup, and still makes sense after the agent is gone.
|
|
185
|
+
function create(actor, { projectId, tokenId, name = null, machine = null, kind = 'watcher', icon = null, tint = null }) {
|
|
186
|
+
const label = cleanMachine(machine)
|
|
187
|
+
const id = insert({
|
|
188
|
+
projectId,
|
|
189
|
+
tokenId,
|
|
190
|
+
userId: actor.userId,
|
|
191
|
+
machine: label,
|
|
192
|
+
kind: AGENT_KINDS.includes(kind) ? kind : 'custom',
|
|
193
|
+
icon: isBuiltInIcon(icon) ? icon : null,
|
|
194
|
+
tint: isAgentTint(tint) ? tint : null,
|
|
195
|
+
})
|
|
196
|
+
actor.audit('agent_created', id, {
|
|
197
|
+
project: projectId,
|
|
198
|
+
token: tokenId,
|
|
199
|
+
name,
|
|
200
|
+
kind,
|
|
201
|
+
audience: 'owner',
|
|
202
|
+
...(label ? { machine: label } : {}),
|
|
203
|
+
})
|
|
204
|
+
return id
|
|
205
|
+
}
|
|
206
|
+
const rows = (projectId = null) =>
|
|
207
|
+
once(`rows:${projectId || ''}`, () =>
|
|
208
|
+
projectId
|
|
209
|
+
? t.all(`${SELECT} AND a.project_id = :project ORDER BY a.created_at, a.id`, { project: projectId })
|
|
210
|
+
: t.all(`${SELECT} ORDER BY a.created_at, a.id`),
|
|
211
|
+
)
|
|
212
|
+
const live = (row, at = iso()) =>
|
|
213
|
+
Boolean(row) &&
|
|
214
|
+
!row.token_revoked_at &&
|
|
215
|
+
!(row.token_expires_at && row.token_expires_at <= at) &&
|
|
216
|
+
Boolean(row.token_created_by) &&
|
|
217
|
+
tokenCreatorOk(row.creator_role)
|
|
218
|
+
const get = (projectId, agentId) =>
|
|
219
|
+
(AGENT_ID_RE.test(String(agentId || '')) ? rows(projectId).find((row) => row.id === agentId) : null) || null
|
|
220
|
+
function need(projectId, agentId) {
|
|
221
|
+
const row = get(projectId, agentId)
|
|
222
|
+
if (!row) throw new HttpError(404, 'unknown_agent', 'No such agent.')
|
|
223
|
+
return row
|
|
224
|
+
}
|
|
225
|
+
// The agent of a token, or null. A claim-scoped token from an older build
|
|
226
|
+
// becomes an agent here, on first sight (`audit` hears of it, see ensure).
|
|
227
|
+
function forToken(projectId, tokenId, { audit = null } = {}) {
|
|
228
|
+
const find = () => rows(projectId).find((row) => row.token_id === tokenId) || null
|
|
229
|
+
const found = find()
|
|
230
|
+
if (found) return found
|
|
231
|
+
ensure(projectId, audit)
|
|
232
|
+
return find()
|
|
233
|
+
}
|
|
234
|
+
// Which agent a token is, for the face on a reply it wrote (revoked or not).
|
|
235
|
+
const idForToken = (projectId, tokenId) => (tokenId ? rows(projectId).find((row) => row.token_id === tokenId)?.id || null : null)
|
|
236
|
+
const defaultId = (projectId) =>
|
|
237
|
+
once(
|
|
238
|
+
`default:${projectId}`,
|
|
239
|
+
() =>
|
|
240
|
+
t.get('SELECT default_agent_id FROM projects WHERE workspace_id = :ws AND id = :project', { project: projectId })
|
|
241
|
+
?.default_agent_id || null,
|
|
242
|
+
)
|
|
243
|
+
// The project's default agent while it can still take work, else null
|
|
244
|
+
// (a revoked default falls back to "any agent").
|
|
245
|
+
function defaultAgent(projectId) {
|
|
246
|
+
const row = get(projectId, defaultId(projectId))
|
|
247
|
+
return live(row) ? row : null
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---- State ----
|
|
251
|
+
|
|
252
|
+
// Which comments each agent holds right now: token id -> [{ board, number }].
|
|
253
|
+
const held = (projectId) =>
|
|
254
|
+
once(`held:${projectId}`, () => {
|
|
255
|
+
const out = new Map()
|
|
256
|
+
for (const claim of t.all(
|
|
257
|
+
`SELECT c.token_id, c.board_id, c.comment_number FROM agent_claims c
|
|
258
|
+
JOIN comments m ON m.workspace_id = c.workspace_id AND m.project_id = c.project_id AND m.board_id = c.board_id AND m.number = c.comment_number
|
|
259
|
+
WHERE c.workspace_id = :ws AND c.project_id = :project AND c.ended_at IS NULL AND m.status = 'open' AND m.agent_status IN ('queued', 'working')
|
|
260
|
+
ORDER BY c.created_at`,
|
|
261
|
+
{ project: projectId },
|
|
262
|
+
)) {
|
|
263
|
+
if (!out.has(claim.token_id)) out.set(claim.token_id, [])
|
|
264
|
+
out.get(claim.token_id).push({ board: claim.board_id, number: claim.comment_number })
|
|
265
|
+
}
|
|
266
|
+
return out
|
|
267
|
+
})
|
|
268
|
+
// Comments sent to an agent (or to any, under '') that nothing took yet:
|
|
269
|
+
// agent id -> [{ board, number }]. Open, vouched for, the run approved.
|
|
270
|
+
const waiting = (projectId) =>
|
|
271
|
+
once(`waiting:${projectId}`, () => {
|
|
272
|
+
const out = new Map()
|
|
273
|
+
const liveIds = new Set(
|
|
274
|
+
rows(projectId)
|
|
275
|
+
.filter((row) => live(row))
|
|
276
|
+
.map((row) => row.id),
|
|
277
|
+
)
|
|
278
|
+
for (const comment of t.all(
|
|
279
|
+
`SELECT board_id, number, agent_id FROM comments WHERE workspace_id = :ws AND project_id = :project AND status = 'open'
|
|
280
|
+
AND agent_status IS NULL AND dispatch_hash IS NOT NULL AND run_approved = 1 ORDER BY dispatch_at, number`,
|
|
281
|
+
{ project: projectId },
|
|
282
|
+
)) {
|
|
283
|
+
const key = comment.agent_id && liveIds.has(comment.agent_id) ? comment.agent_id : ''
|
|
284
|
+
if (!out.has(key)) out.set(key, [])
|
|
285
|
+
out.get(key).push({ board: comment.board_id, number: comment.number })
|
|
286
|
+
}
|
|
287
|
+
return out
|
|
288
|
+
})
|
|
289
|
+
// A connected agent: its token may hold a link.
|
|
290
|
+
const linked = (row) => parseList(row.token_scopes).includes('agent')
|
|
291
|
+
// What it said about itself the last time its link opened (hello).
|
|
292
|
+
const capsOf = (row) => parseCaps(row.capabilities)
|
|
293
|
+
const linkOf = (row) => (linked(row) ? links?.of(t.workspaceId, row.id) || null : null)
|
|
294
|
+
function stateOf(row) {
|
|
295
|
+
if (!live(row)) return { state: 'revoked', lastSeenAt: latestOf(row.last_seen_at, row.token_last_used_at) }
|
|
296
|
+
const heard = presence?.ofAgent(t.workspaceId, row.id) || { online: false, lastSeenAt: null }
|
|
297
|
+
const lastSeenAt = latestOf(heard.lastSeenAt, row.last_seen_at, row.token_last_used_at)
|
|
298
|
+
// A connected agent is online exactly while its link is open: a call to
|
|
299
|
+
// the token API alone does not make it reachable.
|
|
300
|
+
const online = linked(row) ? Boolean(linkOf(row)) : heard.online
|
|
301
|
+
if (!online) return { state: 'offline', lastSeenAt }
|
|
302
|
+
const busy = held(row.project_id).get(row.token_id)?.length || (links?.turns(t.workspaceId, row.id) || 0) > 0
|
|
303
|
+
return { state: busy ? 'busy' : 'online', lastSeenAt }
|
|
304
|
+
}
|
|
305
|
+
// The link opened and the agent said what it is (POST /api/v1/agent/hello):
|
|
306
|
+
// kind, machine and capabilities, validated by the caller. Display, and
|
|
307
|
+
// what the machine's own policy narrows; never a widening.
|
|
308
|
+
function hello(row, { kind, machine, capabilities }) {
|
|
309
|
+
const label = cleanMachine(machine)
|
|
310
|
+
t.run(
|
|
311
|
+
'UPDATE agents SET kind = :kind, machine = :machine, capabilities = :caps, last_seen_at = :at WHERE workspace_id = :ws AND id = :id',
|
|
312
|
+
{
|
|
313
|
+
kind: LINK_KINDS.includes(kind) ? kind : 'custom',
|
|
314
|
+
machine: label || row.machine || null,
|
|
315
|
+
caps: JSON.stringify(capabilities || {}),
|
|
316
|
+
at: iso(),
|
|
317
|
+
id: row.id,
|
|
318
|
+
},
|
|
319
|
+
)
|
|
320
|
+
forget()
|
|
321
|
+
return get(row.project_id, row.id)
|
|
322
|
+
}
|
|
323
|
+
// What the agent's machine said it allows (hello), as the approval rules
|
|
324
|
+
// read it. Nothing here is ever more than the machine said.
|
|
325
|
+
function machinePolicy(row) {
|
|
326
|
+
const policy = linked(row) ? capsOf(row).policy || {} : {}
|
|
327
|
+
const approvals = ['owner', 'admins'].includes(policy.approvals) ? policy.approvals : 'none'
|
|
328
|
+
const commands =
|
|
329
|
+
approvals !== 'none' && Array.isArray(policy.commands) ? policy.commands.filter((item) => typeof item === 'string') : []
|
|
330
|
+
const auto =
|
|
331
|
+
approvals !== 'none' && Array.isArray(policy.auto)
|
|
332
|
+
? policy.auto.filter((kind) => kind === 'edits' || (kind === 'commands' && commands.length > 0))
|
|
333
|
+
: []
|
|
334
|
+
return { audience: policy.audience === 'owner' ? 'owner' : 'server', approvals, commands, auto }
|
|
335
|
+
}
|
|
336
|
+
// On a machine that takes approvals from the person who connected it
|
|
337
|
+
// alone, "allow without asking" counts only when that same person set it:
|
|
338
|
+
// nobody else can take them out of the loop.
|
|
339
|
+
const ownerOnly = (row) => machinePolicy(row).approvals === 'owner'
|
|
340
|
+
const ruleStands = (row) =>
|
|
341
|
+
row.approval_rule !== 'auto' || !ownerOnly(row) || (Boolean(row.created_by) && row.approval_rule_by === row.created_by)
|
|
342
|
+
const approvalOf = (row) => {
|
|
343
|
+
const machine = machinePolicy(row)
|
|
344
|
+
return {
|
|
345
|
+
approvalRule: ruleStands(row) ? row.approval_rule : 'ask',
|
|
346
|
+
approvalChangeRole: row.approval_change_role,
|
|
347
|
+
approvalAnswerRole: row.approval_answer_role,
|
|
348
|
+
machineApprovals: machine.approvals,
|
|
349
|
+
machineAuto: machine.auto,
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// The rule in effect for this agent's requests, per kind: what a fix is told.
|
|
353
|
+
const approvalRules = (row) => ({
|
|
354
|
+
edits: approvalRuleFor(approvalOf(row), 'edits'),
|
|
355
|
+
commands: approvalRuleFor(approvalOf(row), 'commands'),
|
|
356
|
+
// The person who connected the agent set the rule themself (a machine that said "owner" asks for this).
|
|
357
|
+
byOwner: row.approval_rule === 'auto' && Boolean(row.created_by) && row.approval_rule_by === row.created_by,
|
|
358
|
+
})
|
|
359
|
+
// Whether a machine takes edits from the board at all, and how its
|
|
360
|
+
// requests are answered: "none" (reads and answers), "ask" or "auto".
|
|
361
|
+
function editMode(row) {
|
|
362
|
+
const machine = machinePolicy(row)
|
|
363
|
+
if (machine.approvals === 'none') return 'none'
|
|
364
|
+
return approvalRules(row).edits === 'auto' ? 'auto' : 'ask'
|
|
365
|
+
}
|
|
366
|
+
// May this person answer this agent's permission cards, and if not, why
|
|
367
|
+
// (said on the card). Every rule must hold: the agent's answer role, its
|
|
368
|
+
// audience and the project's trust (the same as sending it work), and the
|
|
369
|
+
// level its own machine set ("owner": only the person who connected it).
|
|
370
|
+
function answerCheck(row, { userId, role, boardId = null }) {
|
|
371
|
+
const machine = machinePolicy(row)
|
|
372
|
+
const owner = people().get(row.created_by) || null
|
|
373
|
+
if (!live(row)) return { ok: false, reason: `${row.name} was revoked.` }
|
|
374
|
+
if (machine.approvals === 'none')
|
|
375
|
+
return { ok: false, reason: `${row.name} reads and answers only: its machine takes no approvals from the board.` }
|
|
376
|
+
const who =
|
|
377
|
+
machine.approvals === 'owner'
|
|
378
|
+
? personName(owner)
|
|
379
|
+
: row.approval_answer_role === 'owner'
|
|
380
|
+
? `an owner ${row.name} takes work from`
|
|
381
|
+
: `an admin ${row.name} takes work from`
|
|
382
|
+
const no = { ok: false, reason: `Waiting for ${who} to allow or deny this.` }
|
|
383
|
+
if (!userId || !canAnswerApproval(role, approvalOf(row))) return no
|
|
384
|
+
if (!inAudience(row, userId) || !trusted(row.project_id, boardId, userId)) return no
|
|
385
|
+
if (machine.approvals === 'owner' && row.created_by !== userId) return no
|
|
386
|
+
return { ok: true, reason: null, owner: Boolean(row.created_by) && row.created_by === userId }
|
|
387
|
+
}
|
|
388
|
+
// The link opened (hello): when the machine no longer allows "without
|
|
389
|
+
// asking", a stored "always allow" does not wait for it to come back. It
|
|
390
|
+
// is set to "ask" again, in the open. `audit(action, target, detail)`.
|
|
391
|
+
// Also says, when it changed, what the machine allows now.
|
|
392
|
+
function helloPolicy(before, after, audit) {
|
|
393
|
+
const was = machinePolicy(before)
|
|
394
|
+
const now = machinePolicy(after)
|
|
395
|
+
const shape = (policy) => ({ approvals: policy.approvals, commands: policy.commands.length, auto: policy.auto })
|
|
396
|
+
if (JSON.stringify(shape(was)) !== JSON.stringify(shape(now)))
|
|
397
|
+
audit?.('agent_edit_mode_changed', after.id, {
|
|
398
|
+
project: after.project_id,
|
|
399
|
+
name: after.name,
|
|
400
|
+
before: shape(was),
|
|
401
|
+
after: shape(now),
|
|
402
|
+
by: 'machine',
|
|
403
|
+
})
|
|
404
|
+
if (after.approval_rule === 'auto' && (!ruleStands(after) || !approvalAutoAvailable(approvalOf(after)))) {
|
|
405
|
+
t.run("UPDATE agents SET approval_rule = 'ask' WHERE workspace_id = :ws AND id = :id", { id: after.id })
|
|
406
|
+
audit?.('agent_approval_rule_changed', after.id, {
|
|
407
|
+
project: after.project_id,
|
|
408
|
+
name: after.name,
|
|
409
|
+
before: { rule: 'auto' },
|
|
410
|
+
after: { rule: 'ask' },
|
|
411
|
+
reason: 'the machine no longer allows requests without asking',
|
|
412
|
+
})
|
|
413
|
+
forget()
|
|
414
|
+
}
|
|
415
|
+
return get(after.project_id, after.id)
|
|
416
|
+
}
|
|
417
|
+
// A claim-scoped token was heard from: its agent is online, and its
|
|
418
|
+
// last-seen time is written down at most once a minute.
|
|
419
|
+
function seen(row) {
|
|
420
|
+
if (!row || !presence) return
|
|
421
|
+
const { save } = presence.seen(t.workspaceId, row.project_id, row.id, row.name)
|
|
422
|
+
if (save) t.run('UPDATE agents SET last_seen_at = :at WHERE workspace_id = :ws AND id = :id', { at: iso(), id: row.id })
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ---- Audience ----
|
|
426
|
+
|
|
427
|
+
const people = () =>
|
|
428
|
+
once('people', () => {
|
|
429
|
+
const out = new Map()
|
|
430
|
+
for (const row of t.all(
|
|
431
|
+
'SELECT m.user_id, m.role, u.handle, u.display_name FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.workspace_id = :ws',
|
|
432
|
+
))
|
|
433
|
+
out.set(row.user_id, { userId: row.user_id, role: row.role, handle: row.handle, displayName: row.display_name })
|
|
434
|
+
return out
|
|
435
|
+
})
|
|
436
|
+
// The named members of a "members" audience who are still in the workspace.
|
|
437
|
+
const namedUsers = (row) => parseList(row.audience_users).filter((id) => id !== row.created_by && people().has(id))
|
|
438
|
+
// Whether this person is in the agent's audience. (Whether the agent
|
|
439
|
+
// policy lets them send work to an agent at all is `trusted` below: both
|
|
440
|
+
// must hold.)
|
|
441
|
+
// The agent's own machine said it takes work from its connector only
|
|
442
|
+
// (`shapewall agent connect --audience owner`): the last word, whatever
|
|
443
|
+
// the audience here says.
|
|
444
|
+
const machineOwnerOnly = (row) => linked(row) && capsOf(row).policy?.audience === 'owner'
|
|
445
|
+
function inAudience(row, userId) {
|
|
446
|
+
if (!row || !userId) return false
|
|
447
|
+
if (machineOwnerOnly(row)) return Boolean(row.created_by) && row.created_by === userId
|
|
448
|
+
if (row.audience === 'trusted') return true
|
|
449
|
+
if (row.created_by && row.created_by === userId) return true
|
|
450
|
+
return row.audience === 'members' && namedUsers(row).includes(userId)
|
|
451
|
+
}
|
|
452
|
+
const trusted = (projectId, boardId, userId) => trustedMember({ ...t, handleFor }, agentPolicy(t, projectId, boardId), userId)
|
|
453
|
+
// The audience in words and names, for whoever looks at the agent.
|
|
454
|
+
function audienceOf(row) {
|
|
455
|
+
const owner = people().get(row.created_by) || null
|
|
456
|
+
const named = row.audience === 'members' ? namedUsers(row).map((id) => people().get(id)) : []
|
|
457
|
+
const names = [personName(owner), ...named.map(personName)]
|
|
458
|
+
// Narrowed on the agent's machine: what is in effect, said plainly.
|
|
459
|
+
if (machineOwnerOnly(row) && row.audience !== 'owner')
|
|
460
|
+
return {
|
|
461
|
+
kind: row.audience,
|
|
462
|
+
effective: 'owner',
|
|
463
|
+
inherited: false,
|
|
464
|
+
text: `Only ${personName(owner)} (set on the agent's own machine)`,
|
|
465
|
+
people: owner ? [{ handle: owner.handle, displayName: owner.displayName }] : [],
|
|
466
|
+
}
|
|
467
|
+
return {
|
|
468
|
+
kind: row.audience,
|
|
469
|
+
effective: row.audience,
|
|
470
|
+
// Kept from before 0.4.0, never chosen.
|
|
471
|
+
inherited: Boolean(row.audience_inherited) && row.audience === 'trusted',
|
|
472
|
+
text:
|
|
473
|
+
row.audience === 'trusted'
|
|
474
|
+
? "Everyone this project's agent policy trusts"
|
|
475
|
+
: row.audience === 'owner'
|
|
476
|
+
? `Only ${personName(owner)}`
|
|
477
|
+
: listNames(names),
|
|
478
|
+
people: (row.audience === 'trusted' ? [] : [owner, ...named]).filter(Boolean).map((person) => ({
|
|
479
|
+
handle: person.handle,
|
|
480
|
+
displayName: person.displayName,
|
|
481
|
+
})),
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
// May this person send the agent work, and if not, why (said on the board).
|
|
485
|
+
function sendCheck(row, { userId, role, boardId = null }) {
|
|
486
|
+
if (!roleAtLeast(role, 'member')) return { ok: false, reason: 'Viewers cannot send work to an agent.' }
|
|
487
|
+
if (!live(row)) return { ok: false, reason: `${row.name} was revoked.` }
|
|
488
|
+
if (!trusted(row.project_id, boardId, userId))
|
|
489
|
+
return { ok: false, reason: "This project's agent policy does not let you send work to an agent. Ask an admin." }
|
|
490
|
+
if (inAudience(row, userId)) return { ok: true, reason: null }
|
|
491
|
+
const audience = audienceOf(row)
|
|
492
|
+
return {
|
|
493
|
+
ok: false,
|
|
494
|
+
reason:
|
|
495
|
+
row.audience === 'owner'
|
|
496
|
+
? `${audience.text} can send work to ${row.name}. Ask them, or an admin, to share it.`
|
|
497
|
+
: `${row.name} takes work from ${audience.text} only. Ask an admin to add you.`,
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// May this person chat with the agent right now, and if not, why (said
|
|
502
|
+
// in the picker and under the composer). Chat needs a connected agent
|
|
503
|
+
// that chats, the same rules as sending it work, and an open link.
|
|
504
|
+
function chatCheck(row, { userId, role, boardId = null }) {
|
|
505
|
+
if (!live(row)) return { ok: false, code: 'agent_revoked', reason: `${row.name} was revoked.` }
|
|
506
|
+
if (!linked(row) || capsOf(row).chat !== true)
|
|
507
|
+
return {
|
|
508
|
+
ok: false,
|
|
509
|
+
code: 'no_chat',
|
|
510
|
+
reason: `${row.name} takes comments only. Chat needs an agent connected with "shapewall agent connect".`,
|
|
511
|
+
}
|
|
512
|
+
const send = sendCheck(row, { userId, role, boardId })
|
|
513
|
+
if (!send.ok) return { ok: false, code: 'agent_audience', reason: send.reason.replace(/send work to/g, 'use') }
|
|
514
|
+
if (!linkOf(row)) return { ok: false, code: 'agent_offline', reason: `${row.name} is offline.` }
|
|
515
|
+
return { ok: true, code: null, reason: null }
|
|
516
|
+
}
|
|
517
|
+
// What a connected agent said it can do, for the board and the console.
|
|
518
|
+
function linkView(row) {
|
|
519
|
+
if (!linked(row)) return { connected: false }
|
|
520
|
+
const caps = capsOf(row)
|
|
521
|
+
const link = linkOf(row)
|
|
522
|
+
return {
|
|
523
|
+
connected: true,
|
|
524
|
+
connectedAt: link?.connectedAt || null,
|
|
525
|
+
chats: caps.chat === true,
|
|
526
|
+
version: typeof caps.version === 'string' ? caps.version : null,
|
|
527
|
+
// Read and answer only: the machine refuses edits and commands itself.
|
|
528
|
+
capabilities: {
|
|
529
|
+
chat: caps.chat === true,
|
|
530
|
+
edits: caps.edits === true,
|
|
531
|
+
commands: caps.commands === true,
|
|
532
|
+
images: caps.images === true,
|
|
533
|
+
},
|
|
534
|
+
policy: machinePolicy(row),
|
|
535
|
+
maxTurns: Number.isInteger(caps.maxTurns) ? caps.maxTurns : null,
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
// Edits from the board, as the board says it about this agent: whether
|
|
539
|
+
// its machine takes them, how requests are answered, and whether this
|
|
540
|
+
// person may press Fix and answer its cards (with the reason when not).
|
|
541
|
+
function editsView(row, viewer, { boardId = null } = {}) {
|
|
542
|
+
const mode = editMode(row)
|
|
543
|
+
const machine = machinePolicy(row)
|
|
544
|
+
const answer = mode === 'none' ? { ok: false, reason: null } : answerCheck(row, { ...viewer, boardId })
|
|
545
|
+
const chat = chatCheck(row, { ...viewer, boardId })
|
|
546
|
+
const fix =
|
|
547
|
+
mode === 'none'
|
|
548
|
+
? {
|
|
549
|
+
ok: false,
|
|
550
|
+
reason: `${row.name} reads and answers only. Edits are switched on on its own machine (shapewall agent connect --approvals).`,
|
|
551
|
+
}
|
|
552
|
+
: chat.ok
|
|
553
|
+
? { ok: true, reason: null }
|
|
554
|
+
: { ok: false, reason: chat.reason }
|
|
555
|
+
return {
|
|
556
|
+
mode,
|
|
557
|
+
text:
|
|
558
|
+
mode === 'none'
|
|
559
|
+
? 'Reads and answers'
|
|
560
|
+
: mode === 'auto'
|
|
561
|
+
? 'Edits on a branch, allowed without asking'
|
|
562
|
+
: `Edits on a branch, each allowed by ${machine.approvals === 'owner' ? 'the person who connected it' : row.approval_answer_role === 'owner' ? 'an owner' : 'an admin'}`,
|
|
563
|
+
commands: machine.commands.length,
|
|
564
|
+
answer: { ok: answer.ok, reason: answer.reason },
|
|
565
|
+
fix,
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// ---- Routing ----
|
|
570
|
+
|
|
571
|
+
// The agent a comment is addressed to, while that agent can still take
|
|
572
|
+
// work; null means any agent. A comment addressed to a revoked agent is
|
|
573
|
+
// never stuck: any agent may take it.
|
|
574
|
+
function addressOf(projectId, row) {
|
|
575
|
+
const agent = row?.agent_id ? get(projectId, row.agent_id) : null
|
|
576
|
+
return live(agent) ? agent.id : null
|
|
577
|
+
}
|
|
578
|
+
// Addresses a comment a person just sent (or that was vouched for when it
|
|
579
|
+
// was written). `wanted`: an agent id, null for any agent, or undefined
|
|
580
|
+
// for the project's default agent when this person may use it (any agent
|
|
581
|
+
// otherwise). Throws when the named agent is not theirs to use.
|
|
582
|
+
function address(projectId, boardId, row, { userId, role }, wanted = undefined) {
|
|
583
|
+
let agent = null
|
|
584
|
+
if (wanted === undefined) {
|
|
585
|
+
const candidate = defaultAgent(projectId)
|
|
586
|
+
agent = candidate && inAudience(candidate, userId) ? candidate : null
|
|
587
|
+
} else if (wanted !== null) {
|
|
588
|
+
agent = get(projectId, wanted)
|
|
589
|
+
if (!live(agent)) throw new HttpError(404, 'unknown_agent', 'No such agent in this project. It may have been revoked.')
|
|
590
|
+
const check = sendCheck(agent, { userId, role, boardId })
|
|
591
|
+
if (!check.ok) throw new HttpError(403, 'agent_audience', check.reason)
|
|
592
|
+
}
|
|
593
|
+
t.run(
|
|
594
|
+
'UPDATE comments SET agent_id = :agent WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
|
|
595
|
+
{ project: projectId, board: boardId, number: row.number, agent: agent?.id || null },
|
|
596
|
+
)
|
|
597
|
+
forget()
|
|
598
|
+
return agent?.id || null
|
|
599
|
+
}
|
|
600
|
+
// "Let any agent take it": a comment that waits for one agent goes to
|
|
601
|
+
// whichever agent takes it first. Returns the agent it was waiting for.
|
|
602
|
+
function release(actor, projectId, boardId, row) {
|
|
603
|
+
const from = addressOf(projectId, row)
|
|
604
|
+
if (row.agent_id)
|
|
605
|
+
t.run(
|
|
606
|
+
'UPDATE comments SET agent_id = NULL WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
|
|
607
|
+
{ project: projectId, board: boardId, number: row.number },
|
|
608
|
+
)
|
|
609
|
+
forget()
|
|
610
|
+
if (from)
|
|
611
|
+
actor.audit('agent_queue_released', `${boardId}#${row.number}`, {
|
|
612
|
+
project: projectId,
|
|
613
|
+
from,
|
|
614
|
+
fromName: get(projectId, from)?.name || null,
|
|
615
|
+
to: null,
|
|
616
|
+
})
|
|
617
|
+
return from
|
|
618
|
+
}
|
|
619
|
+
// May this agent take this comment? The two rules a token cannot get
|
|
620
|
+
// around: a comment sent to another agent is not its to take, and it only
|
|
621
|
+
// takes work from people in its audience (the person whose vouch stands on
|
|
622
|
+
// the comment, `dispatch_by`).
|
|
623
|
+
function claimCheck(agent, projectId, row) {
|
|
624
|
+
if (!agent) return { ok: false, code: 'not_an_agent', message: 'This token is not an agent.' }
|
|
625
|
+
const addressed = addressOf(projectId, row)
|
|
626
|
+
if (addressed && addressed !== agent.id)
|
|
627
|
+
return { ok: false, code: 'addressed_elsewhere', message: 'This comment was sent to another agent.' }
|
|
628
|
+
if (!inAudience(agent, row.dispatch_by))
|
|
629
|
+
return { ok: false, code: 'agent_audience', message: "This comment was sent by someone outside this agent's audience." }
|
|
630
|
+
return { ok: true, code: null, message: null }
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Whether this agent's token holds the comment right now (it took it and
|
|
634
|
+
// has not finished). `row`: a comment row, or its COMMENT_ROUTING.
|
|
635
|
+
function holds(agent, projectId, row) {
|
|
636
|
+
if (!agent || !row) return false
|
|
637
|
+
const board = row.board_id
|
|
638
|
+
const number = row.number
|
|
639
|
+
return (held(projectId).get(agent.token_id) || []).some((item) => item.board === board && item.number === number)
|
|
640
|
+
}
|
|
641
|
+
// May this agent's token work on this comment at all (read it, reply, set
|
|
642
|
+
// a status, ask for an approval)? Yes while it holds it, whatever changed
|
|
643
|
+
// since: an audience governs new work, and never strands work under way.
|
|
644
|
+
// Otherwise the rule for taking it (claimCheck).
|
|
645
|
+
function workCheck(agent, projectId, row) {
|
|
646
|
+
if (holds(agent, projectId, row)) return { ok: true, code: null, message: null }
|
|
647
|
+
return claimCheck(agent, projectId, row)
|
|
648
|
+
}
|
|
649
|
+
// May this agent's token read a reply this person wrote? Only people in
|
|
650
|
+
// its audience (the same rule as sending it work): someone the agent
|
|
651
|
+
// policy trusts but this agent does not take work from cannot steer it
|
|
652
|
+
// through a reply. While it holds the comment, the person whose approval
|
|
653
|
+
// stands on it stays readable too.
|
|
654
|
+
function replyVisible(agent, projectId, row, userId) {
|
|
655
|
+
if (!agent || !userId) return false
|
|
656
|
+
return inAudience(agent, userId) || (userId === row?.dispatch_by && holds(agent, projectId, row))
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ---- Agents that are gone ----
|
|
660
|
+
|
|
661
|
+
// Every comment an agent holds, by the newest claim on it: [{ token_id,
|
|
662
|
+
// board, number }] for open comments that read queued or working.
|
|
663
|
+
function heldBy(projectId) {
|
|
664
|
+
const latest = new Map()
|
|
665
|
+
for (const claim of t.all(
|
|
666
|
+
`SELECT c.token_id, c.board_id, c.comment_number FROM agent_claims c
|
|
667
|
+
JOIN comments m ON m.workspace_id = c.workspace_id AND m.project_id = c.project_id AND m.board_id = c.board_id AND m.number = c.comment_number
|
|
668
|
+
WHERE c.workspace_id = :ws AND c.project_id = :project AND m.status = 'open' AND m.agent_status IN ('queued', 'working')
|
|
669
|
+
ORDER BY c.created_at, c.rowid`,
|
|
670
|
+
{ project: projectId },
|
|
671
|
+
))
|
|
672
|
+
latest.set(`${claim.board_id}#${claim.comment_number}`, {
|
|
673
|
+
token_id: claim.token_id,
|
|
674
|
+
board: claim.board_id,
|
|
675
|
+
number: claim.comment_number,
|
|
676
|
+
})
|
|
677
|
+
return [...latest.values()]
|
|
678
|
+
}
|
|
679
|
+
// An agent that can no longer take work lets go of everything: the
|
|
680
|
+
// comments it holds lose their working status and go to any agent (their
|
|
681
|
+
// claims end, their usage records close with the reason), the comments
|
|
682
|
+
// that waited for it go to any agent, and the project loses it as default.
|
|
683
|
+
// `audit` hears one agent_queue_released per comment. Safe to run again.
|
|
684
|
+
function releaseAgent(projectId, agent, { audit = null, reason = 'revoked', holding = null } = {}) {
|
|
685
|
+
const at = iso()
|
|
686
|
+
const where = 'workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number'
|
|
687
|
+
const mine = (holding || heldBy(projectId)).filter((item) => item.token_id === agent.token_id)
|
|
688
|
+
const said = (item, was) =>
|
|
689
|
+
audit?.('agent_queue_released', `${item.board}#${item.number}`, {
|
|
690
|
+
project: projectId,
|
|
691
|
+
from: agent.id,
|
|
692
|
+
fromName: agent.name,
|
|
693
|
+
to: null,
|
|
694
|
+
reason,
|
|
695
|
+
was,
|
|
696
|
+
})
|
|
697
|
+
for (const item of mine) {
|
|
698
|
+
t.run(
|
|
699
|
+
`UPDATE agent_runs SET ended_at = :at, outcome = :reason, ${RUN_DURATION} WHERE workspace_id = :ws AND project_id = :project AND agent_id = :agent AND board_id = :board AND comment_number = :number AND ended_at IS NULL`,
|
|
700
|
+
{ project: projectId, agent: agent.id, board: item.board, number: item.number, at, reason },
|
|
701
|
+
)
|
|
702
|
+
t.run(`UPDATE comments SET agent_status = NULL, agent_status_at = NULL, agent_id = NULL WHERE ${where}`, {
|
|
703
|
+
project: projectId,
|
|
704
|
+
board: item.board,
|
|
705
|
+
number: item.number,
|
|
706
|
+
})
|
|
707
|
+
said(item, 'working')
|
|
708
|
+
}
|
|
709
|
+
t.run(
|
|
710
|
+
'UPDATE agent_claims SET ended_at = :at WHERE workspace_id = :ws AND project_id = :project AND token_id = :token AND ended_at IS NULL',
|
|
711
|
+
{ project: projectId, token: agent.token_id, at },
|
|
712
|
+
)
|
|
713
|
+
const queued = t
|
|
714
|
+
.all(
|
|
715
|
+
"SELECT board_id, number FROM comments WHERE workspace_id = :ws AND project_id = :project AND agent_id = :agent AND status = 'open' AND agent_status IS NULL",
|
|
716
|
+
{ project: projectId, agent: agent.id },
|
|
717
|
+
)
|
|
718
|
+
.map((comment) => ({ board: comment.board_id, number: comment.number }))
|
|
719
|
+
for (const item of queued) {
|
|
720
|
+
t.run(`UPDATE comments SET agent_id = NULL WHERE ${where}`, { project: projectId, board: item.board, number: item.number })
|
|
721
|
+
said(item, 'waiting')
|
|
722
|
+
}
|
|
723
|
+
const wasDefault = defaultId(projectId) === agent.id
|
|
724
|
+
if (wasDefault) {
|
|
725
|
+
t.run('UPDATE projects SET default_agent_id = NULL WHERE workspace_id = :ws AND id = :project', { project: projectId })
|
|
726
|
+
audit?.('agent_default_changed', projectId, { before: agent.id, beforeName: agent.name, after: null, afterName: null, reason })
|
|
727
|
+
}
|
|
728
|
+
presence?.forgetAgent(t.workspaceId, agent.id)
|
|
729
|
+
forget()
|
|
730
|
+
return { comments: queued.length, held: mine.length, wasDefault }
|
|
731
|
+
}
|
|
732
|
+
// The same for every agent of the project that stopped being able to take
|
|
733
|
+
// work by another road: its token expired, was revoked with its maker's
|
|
734
|
+
// other grants, or its maker is no longer an admin. Run where such an
|
|
735
|
+
// agent would be seen (a token's call, the board's list, the console), so
|
|
736
|
+
// nothing reads "working" under an agent that is gone, and a revoked agent
|
|
737
|
+
// is never shown as the default.
|
|
738
|
+
function releaseGone(projectId, audit = null) {
|
|
739
|
+
const gone = rows(projectId).filter((row) => !live(row))
|
|
740
|
+
if (!gone.length) return 0
|
|
741
|
+
const holding = heldBy(projectId)
|
|
742
|
+
const addressed = new Set(
|
|
743
|
+
t
|
|
744
|
+
.all(
|
|
745
|
+
"SELECT DISTINCT agent_id FROM comments WHERE workspace_id = :ws AND project_id = :project AND agent_id IS NOT NULL AND status = 'open' AND agent_status IS NULL",
|
|
746
|
+
{ project: projectId },
|
|
747
|
+
)
|
|
748
|
+
.map((row) => row.agent_id),
|
|
749
|
+
)
|
|
750
|
+
const open = new Set(
|
|
751
|
+
t
|
|
752
|
+
.all('SELECT DISTINCT token_id FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND ended_at IS NULL', {
|
|
753
|
+
project: projectId,
|
|
754
|
+
})
|
|
755
|
+
.map((row) => row.token_id),
|
|
756
|
+
)
|
|
757
|
+
const fallback = defaultId(projectId)
|
|
758
|
+
let released = 0
|
|
759
|
+
for (const agent of gone) {
|
|
760
|
+
const busy = holding.some((item) => item.token_id === agent.token_id)
|
|
761
|
+
if (!busy && !addressed.has(agent.id) && !open.has(agent.token_id) && fallback !== agent.id) continue
|
|
762
|
+
const reason = agent.token_revoked_at ? 'revoked' : agent.token_expires_at && agent.token_expires_at <= iso() ? 'expired' : 'inactive'
|
|
763
|
+
releaseAgent(projectId, agent, { audit, reason, holding })
|
|
764
|
+
released += 1
|
|
765
|
+
}
|
|
766
|
+
return released
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ---- Usage records (the groundwork of the usage dashboard) ----
|
|
770
|
+
|
|
771
|
+
// One row per comment an agent took: who asked, which agent, where, when.
|
|
772
|
+
// No comment text, no answer. The model, effort and token columns stay
|
|
773
|
+
// NULL: a watcher reports none of them.
|
|
774
|
+
function startRun({ projectId, boardId, number, agentId, claimId, askedBy }) {
|
|
775
|
+
t.run(
|
|
776
|
+
`INSERT INTO agent_runs (workspace_id, project_id, id, kind, agent_id, claim_id, board_id, comment_number, asked_by, started_at,
|
|
777
|
+
agent_owner)
|
|
778
|
+
VALUES (:ws, :project, :id, 'fix', :agent, :claim, :board, :number, :asked, :at,
|
|
779
|
+
(SELECT a.created_by FROM agents a WHERE a.id = :agent))`,
|
|
780
|
+
{
|
|
781
|
+
project: projectId,
|
|
782
|
+
id: newId('run'),
|
|
783
|
+
agent: agentId || null,
|
|
784
|
+
claim: claimId,
|
|
785
|
+
board: boardId,
|
|
786
|
+
number,
|
|
787
|
+
asked: askedBy || null,
|
|
788
|
+
at: iso(),
|
|
789
|
+
},
|
|
790
|
+
)
|
|
791
|
+
}
|
|
792
|
+
// Closes the record of every run whose claim ended, with how it ended:
|
|
793
|
+
// the status the agent left (done, needs-human, branch-ready), "resolved"
|
|
794
|
+
// when the comment was resolved meanwhile, "released" when the claim was
|
|
795
|
+
// dropped with nothing to show, "removed" when the comment is gone. A run
|
|
796
|
+
// whose claim was swept away and followed by another claim on the same
|
|
797
|
+
// comment is "stale": what the comment says now is the later run's doing.
|
|
798
|
+
function closeRuns(projectId) {
|
|
799
|
+
const ended = t.all(
|
|
800
|
+
`SELECT r.id, r.claim_id, r.board_id, r.comment_number, c.ended_at FROM agent_runs r
|
|
801
|
+
JOIN agent_claims c ON c.id = r.claim_id AND c.workspace_id = r.workspace_id
|
|
802
|
+
WHERE r.workspace_id = :ws AND r.project_id = :project AND r.ended_at IS NULL AND c.ended_at IS NOT NULL`,
|
|
803
|
+
{ project: projectId },
|
|
804
|
+
)
|
|
805
|
+
for (const run of ended) {
|
|
806
|
+
const comment = t.get(
|
|
807
|
+
'SELECT status, agent_status, resolved_at FROM comments WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND number = :number',
|
|
808
|
+
{ project: projectId, board: run.board_id, number: run.comment_number },
|
|
809
|
+
)
|
|
810
|
+
const newest = t.get(
|
|
811
|
+
'SELECT id FROM agent_claims WHERE workspace_id = :ws AND project_id = :project AND board_id = :board AND comment_number = :number ORDER BY created_at DESC, rowid DESC LIMIT 1',
|
|
812
|
+
{ project: projectId, board: run.board_id, number: run.comment_number },
|
|
813
|
+
)
|
|
814
|
+
const outcome = !comment
|
|
815
|
+
? 'removed'
|
|
816
|
+
: newest && newest.id !== run.claim_id
|
|
817
|
+
? 'stale'
|
|
818
|
+
: comment.status === 'resolved'
|
|
819
|
+
? 'resolved'
|
|
820
|
+
: ['done', 'needs-human', 'branch-ready'].includes(comment.agent_status)
|
|
821
|
+
? comment.agent_status
|
|
822
|
+
: 'released'
|
|
823
|
+
const at =
|
|
824
|
+
comment?.status === 'resolved' && comment.resolved_at && comment.resolved_at < run.ended_at ? comment.resolved_at : run.ended_at
|
|
825
|
+
t.run(`UPDATE agent_runs SET ended_at = :at, outcome = :outcome, ${RUN_DURATION} WHERE workspace_id = :ws AND id = :id`, {
|
|
826
|
+
id: run.id,
|
|
827
|
+
at,
|
|
828
|
+
outcome,
|
|
829
|
+
})
|
|
830
|
+
}
|
|
831
|
+
return ended.length
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// ---- Views ----
|
|
835
|
+
|
|
836
|
+
const face = (row) => ({
|
|
837
|
+
icon: isBuiltInIcon(row.icon) ? row.icon : null,
|
|
838
|
+
tint: isAgentTint(row.tint) ? row.tint : null,
|
|
839
|
+
logo: logoForAgent(row.kind),
|
|
840
|
+
})
|
|
841
|
+
// An agent as a board member sees it. No token id, prefix or scope, and
|
|
842
|
+
// no account id: names, a face, a state, and what this viewer may do.
|
|
843
|
+
function boardView(row, viewer, { boardId = null } = {}) {
|
|
844
|
+
const check = sendCheck(row, { ...viewer, boardId })
|
|
845
|
+
const mine = (list) => (list || []).filter((item) => !boardId || item.board === boardId).map((item) => item.number)
|
|
846
|
+
const working = held(row.project_id).get(row.token_id) || []
|
|
847
|
+
const queued = waiting(row.project_id).get(row.id) || []
|
|
848
|
+
return {
|
|
849
|
+
id: row.id,
|
|
850
|
+
name: row.name,
|
|
851
|
+
kind: row.kind,
|
|
852
|
+
...face(row),
|
|
853
|
+
machine: row.machine || null,
|
|
854
|
+
...stateOf(row),
|
|
855
|
+
isDefault: defaultId(row.project_id) === row.id,
|
|
856
|
+
audience: audienceOf(row),
|
|
857
|
+
canSend: check.ok,
|
|
858
|
+
reason: check.reason,
|
|
859
|
+
// A connected agent: whether it chats, and whether this person may
|
|
860
|
+
// chat with it right now (with the reason when not).
|
|
861
|
+
link: linkView(row),
|
|
862
|
+
edits: editsView(row, viewer, { boardId }),
|
|
863
|
+
chat: (() => {
|
|
864
|
+
const chat = chatCheck(row, { ...viewer, boardId })
|
|
865
|
+
return { ok: chat.ok, code: chat.code, reason: chat.reason }
|
|
866
|
+
})(),
|
|
867
|
+
working: mine(working),
|
|
868
|
+
queued: mine(queued),
|
|
869
|
+
// What it holds on the project's other boards, as counts.
|
|
870
|
+
elsewhere: { working: working.length - mine(working).length, queued: queued.length - mine(queued).length },
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
// The agents of a project for its board: the ones that can take work.
|
|
874
|
+
function boardList(projectId, viewer, { boardId = null, audit = null } = {}) {
|
|
875
|
+
ensure(projectId, audit)
|
|
876
|
+
releaseGone(projectId, audit)
|
|
877
|
+
const agents = rows(projectId)
|
|
878
|
+
.filter((row) => live(row))
|
|
879
|
+
.map((row) => boardView(row, viewer, { boardId }))
|
|
880
|
+
return {
|
|
881
|
+
agents,
|
|
882
|
+
defaultAgentId: defaultAgent(projectId)?.id || null,
|
|
883
|
+
// Whether this person may send work to an agent at all (the agent policy).
|
|
884
|
+
canSend: roleAtLeast(viewer.role, 'member') && trusted(projectId, boardId, viewer.userId),
|
|
885
|
+
// Sent to any agent and not taken yet, on this board.
|
|
886
|
+
unassigned: (waiting(projectId).get('') || []).filter((item) => !boardId || item.board === boardId).map((item) => item.number),
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
// An agent as the console shows it to an admin: everything above plus its
|
|
890
|
+
// settings, its token (what the Tokens page shows of it) and who made it.
|
|
891
|
+
function consoleView(row) {
|
|
892
|
+
const working = held(row.project_id).get(row.token_id) || []
|
|
893
|
+
const queued = waiting(row.project_id).get(row.id) || []
|
|
894
|
+
const audience = audienceOf(row)
|
|
895
|
+
const approval = approvalOf(row)
|
|
896
|
+
const machine = machinePolicy(row)
|
|
897
|
+
return {
|
|
898
|
+
id: row.id,
|
|
899
|
+
name: row.name,
|
|
900
|
+
kind: row.kind,
|
|
901
|
+
...face(row),
|
|
902
|
+
machine: row.machine || null,
|
|
903
|
+
...stateOf(row),
|
|
904
|
+
projectId: row.project_id,
|
|
905
|
+
projectName: row.project_name,
|
|
906
|
+
isDefault: defaultId(row.project_id) === row.id,
|
|
907
|
+
audience: {
|
|
908
|
+
...audience,
|
|
909
|
+
users: row.audience === 'members' ? namedUsers(row).map((id) => ({ userId: id, ...pick(people().get(id)) })) : [],
|
|
910
|
+
},
|
|
911
|
+
approval: {
|
|
912
|
+
rule: row.approval_rule,
|
|
913
|
+
effectiveRule: effectiveApprovalRule(approval),
|
|
914
|
+
autoAvailable: approvalAutoAvailable(approval),
|
|
915
|
+
changeRole: row.approval_change_role,
|
|
916
|
+
answerRole: row.approval_answer_role,
|
|
917
|
+
// What its own machine allows: the ceiling for everything above.
|
|
918
|
+
mode: editMode(row),
|
|
919
|
+
machine: { approvals: machine.approvals, commands: machine.commands, auto: machine.auto },
|
|
920
|
+
rules: { edits: approvalRules(row).edits, commands: approvalRules(row).commands },
|
|
921
|
+
// Who may switch "allow without asking" on: only the person who connected it, when its machine says "owner".
|
|
922
|
+
autoBy: ownerOnly(row) ? 'owner' : 'role',
|
|
923
|
+
},
|
|
924
|
+
counts: { working: working.length, queued: queued.length },
|
|
925
|
+
link: { ...linkView(row), streams: linkOf(row)?.streams || 0 },
|
|
926
|
+
createdAt: row.created_at,
|
|
927
|
+
createdBy: row.created_by
|
|
928
|
+
? { userId: row.created_by, ...pick(people().get(row.created_by)), left: !people().has(row.created_by) }
|
|
929
|
+
: null,
|
|
930
|
+
token: {
|
|
931
|
+
id: row.token_id,
|
|
932
|
+
prefix: row.token_prefix,
|
|
933
|
+
scopes: parseList(row.token_scopes),
|
|
934
|
+
expiresAt: row.token_expires_at,
|
|
935
|
+
revokedAt: row.token_revoked_at,
|
|
936
|
+
},
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
// Every agent of the project (or, without one, of the workspace), live
|
|
940
|
+
// ones first.
|
|
941
|
+
function consoleList(projectId = null, { audit = null } = {}) {
|
|
942
|
+
const projects = projectId ? [projectId] : t.all('SELECT id FROM projects WHERE workspace_id = :ws').map((project) => project.id)
|
|
943
|
+
for (const id of projects) {
|
|
944
|
+
ensure(id, audit)
|
|
945
|
+
releaseGone(id, audit)
|
|
946
|
+
}
|
|
947
|
+
const all = rows(projectId).map(consoleView)
|
|
948
|
+
return [...all.filter((agent) => agent.state !== 'revoked'), ...all.filter((agent) => agent.state === 'revoked')]
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// ---- Settings: one function each ----
|
|
952
|
+
|
|
953
|
+
const mayManage = (actor) => {
|
|
954
|
+
if (!canManageAgents(actor.role)) throw new HttpError(403, 'forbidden', 'Managing agents needs the admin role or higher.')
|
|
955
|
+
}
|
|
956
|
+
const after = (projectId, agentId) => {
|
|
957
|
+
forget()
|
|
958
|
+
return consoleView(need(projectId, agentId))
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// Name, icon, tint and kind: how the agent looks on the board. `changes`
|
|
962
|
+
// holds only what changes. The name is the token's name (what the agent's
|
|
963
|
+
// replies are signed with from now on).
|
|
964
|
+
function setIdentity(actor, projectId, agentId, changes = {}) {
|
|
965
|
+
mayManage(actor)
|
|
966
|
+
const row = need(projectId, agentId)
|
|
967
|
+
if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
|
|
968
|
+
const before = { name: row.name, icon: row.icon || null, tint: row.tint || null, kind: row.kind }
|
|
969
|
+
const next = { ...before }
|
|
970
|
+
if (changes.name !== undefined) {
|
|
971
|
+
const { name, problem } = cleanAgentName(changes.name)
|
|
972
|
+
if (problem || !name) throw new HttpError(400, 'invalid_name', problem ? `Agent ${problem}.` : 'Agent name: 1 to 40 characters.')
|
|
973
|
+
next.name = name
|
|
974
|
+
}
|
|
975
|
+
if (changes.icon !== undefined) {
|
|
976
|
+
if (changes.icon !== null && !isBuiltInIcon(changes.icon))
|
|
977
|
+
throw new HttpError(400, 'invalid_icon', 'Choose one of the built-in icons.')
|
|
978
|
+
next.icon = changes.icon
|
|
979
|
+
}
|
|
980
|
+
if (changes.tint !== undefined) {
|
|
981
|
+
if (changes.tint !== null && !isAgentTint(changes.tint)) throw new HttpError(400, 'invalid_tint', 'Choose one of the tints.')
|
|
982
|
+
next.tint = changes.tint
|
|
983
|
+
}
|
|
984
|
+
if (changes.kind !== undefined) {
|
|
985
|
+
if (!AGENT_KINDS.includes(changes.kind)) throw new HttpError(400, 'invalid_kind', `Kind: ${AGENT_KINDS.join(', ')}.`)
|
|
986
|
+
next.kind = changes.kind
|
|
987
|
+
}
|
|
988
|
+
if (next.name !== before.name) {
|
|
989
|
+
t.run('UPDATE api_tokens SET name = :name WHERE workspace_id = :ws AND project_id = :project AND id = :id', {
|
|
990
|
+
name: next.name,
|
|
991
|
+
project: projectId,
|
|
992
|
+
id: row.token_id,
|
|
993
|
+
})
|
|
994
|
+
actor.audit('agent_renamed', row.id, { project: projectId, from: before.name, to: next.name })
|
|
995
|
+
}
|
|
996
|
+
const look = (value) => ({ icon: value.icon, tint: value.tint, kind: value.kind })
|
|
997
|
+
if (JSON.stringify(look(next)) !== JSON.stringify(look(before))) {
|
|
998
|
+
t.run('UPDATE agents SET icon = :icon, tint = :tint, kind = :kind WHERE workspace_id = :ws AND id = :id', {
|
|
999
|
+
...look(next),
|
|
1000
|
+
id: row.id,
|
|
1001
|
+
})
|
|
1002
|
+
actor.audit('agent_identity_changed', row.id, { project: projectId, name: next.name, before: look(before), after: look(next) })
|
|
1003
|
+
}
|
|
1004
|
+
return after(projectId, agentId)
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// The project's default agent: the one "Send to agent" names, and where a
|
|
1008
|
+
// trusted member's new comment goes. null: any agent.
|
|
1009
|
+
function setDefault(actor, projectId, agentId) {
|
|
1010
|
+
mayManage(actor)
|
|
1011
|
+
const row = agentId === null ? null : need(projectId, agentId)
|
|
1012
|
+
if (row && !live(row)) throw new HttpError(409, 'agent_revoked', 'A revoked agent cannot be the default.')
|
|
1013
|
+
const before = defaultId(projectId)
|
|
1014
|
+
if (before !== (row?.id || null)) {
|
|
1015
|
+
t.run('UPDATE projects SET default_agent_id = :agent WHERE workspace_id = :ws AND id = :project', {
|
|
1016
|
+
project: projectId,
|
|
1017
|
+
agent: row?.id || null,
|
|
1018
|
+
})
|
|
1019
|
+
actor.audit('agent_default_changed', projectId, {
|
|
1020
|
+
before,
|
|
1021
|
+
beforeName: get(projectId, before)?.name || null,
|
|
1022
|
+
after: row?.id || null,
|
|
1023
|
+
afterName: row?.name || null,
|
|
1024
|
+
})
|
|
1025
|
+
forget()
|
|
1026
|
+
}
|
|
1027
|
+
return row?.id || null
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// Who may send the agent work: { audience, users }. `users` (account ids
|
|
1031
|
+
// of workspace members) only with "members"; the person who connected the
|
|
1032
|
+
// agent is always in.
|
|
1033
|
+
function setAudience(actor, projectId, agentId, { audience, users = [] } = {}) {
|
|
1034
|
+
mayManage(actor)
|
|
1035
|
+
const row = need(projectId, agentId)
|
|
1036
|
+
if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
|
|
1037
|
+
if (!AGENT_AUDIENCES.includes(audience)) throw new HttpError(400, 'invalid_audience', `Audience: ${AGENT_AUDIENCES.join(', ')}.`)
|
|
1038
|
+
let named = []
|
|
1039
|
+
if (audience === 'members') {
|
|
1040
|
+
if (!Array.isArray(users) || users.length > AUDIENCE_USERS_MAX || users.some((id) => typeof id !== 'string'))
|
|
1041
|
+
throw new HttpError(400, 'invalid_audience', `Named members: at most ${AUDIENCE_USERS_MAX} people.`)
|
|
1042
|
+
named = [...new Set(users)].filter((id) => id !== row.created_by)
|
|
1043
|
+
const unknown = named.filter((id) => !roleAtLeast(people().get(id)?.role, 'member'))
|
|
1044
|
+
if (unknown.length)
|
|
1045
|
+
throw new HttpError(400, 'invalid_audience', 'Named members must be members of this workspace (viewers cannot send work).')
|
|
1046
|
+
}
|
|
1047
|
+
const shape = (kind, list) => ({ audience: kind, users: [...list].sort() })
|
|
1048
|
+
const before = shape(row.audience, row.audience === 'members' ? namedUsers(row) : [])
|
|
1049
|
+
const next = shape(audience, named)
|
|
1050
|
+
// Saving the same audience still counts as choosing it.
|
|
1051
|
+
if (JSON.stringify(before) !== JSON.stringify(next) || row.audience_inherited) {
|
|
1052
|
+
t.run(
|
|
1053
|
+
'UPDATE agents SET audience = :audience, audience_users = :users, audience_inherited = 0 WHERE workspace_id = :ws AND id = :id',
|
|
1054
|
+
{
|
|
1055
|
+
audience,
|
|
1056
|
+
users: JSON.stringify(next.users),
|
|
1057
|
+
id: row.id,
|
|
1058
|
+
},
|
|
1059
|
+
)
|
|
1060
|
+
actor.audit('agent_audience_changed', row.id, { project: projectId, name: row.name, before, after: next })
|
|
1061
|
+
}
|
|
1062
|
+
return after(projectId, agentId)
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// The approval rule and who may change or answer it: { rule, changeRole,
|
|
1066
|
+
// answerRole }, only what changes. "auto" is refused until the agent's
|
|
1067
|
+
// machine can opt in (permissions.js approvalAutoAvailable).
|
|
1068
|
+
function setApprovalRule(actor, projectId, agentId, changes = {}) {
|
|
1069
|
+
mayManage(actor)
|
|
1070
|
+
const row = need(projectId, agentId)
|
|
1071
|
+
if (!live(row)) throw new HttpError(409, 'agent_revoked', 'This agent was revoked.')
|
|
1072
|
+
const before = { rule: row.approval_rule, changeRole: row.approval_change_role, answerRole: row.approval_answer_role }
|
|
1073
|
+
const next = { ...before }
|
|
1074
|
+
const current = approvalOf(row)
|
|
1075
|
+
if (changes.rule !== undefined && changes.rule !== before.rule) {
|
|
1076
|
+
if (!APPROVAL_RULES.includes(changes.rule))
|
|
1077
|
+
throw new HttpError(400, 'invalid_approval_rule', `Approval rule: ${APPROVAL_RULES.join(', ')}.`)
|
|
1078
|
+
if (!canChangeApprovalRule(actor.role, current))
|
|
1079
|
+
throw new HttpError(403, 'forbidden', `Changing this agent's approval rule needs the ${before.changeRole} role.`)
|
|
1080
|
+
// The machine takes approvals from the person who connected it alone:
|
|
1081
|
+
// then only that person may say "without asking". An admin cannot take them out of the loop.
|
|
1082
|
+
if (changes.rule === 'auto' && ownerOnly(row) && actor.userId !== row.created_by)
|
|
1083
|
+
throw new HttpError(
|
|
1084
|
+
403,
|
|
1085
|
+
'forbidden',
|
|
1086
|
+
`Only ${personName(people().get(row.created_by))} can let ${row.name} edit without asking: its machine takes approvals from the person who connected it alone.`,
|
|
1087
|
+
)
|
|
1088
|
+
if (changes.rule === 'auto' && !approvalAutoAvailable(current))
|
|
1089
|
+
throw new HttpError(
|
|
1090
|
+
409,
|
|
1091
|
+
'approval_auto_unavailable',
|
|
1092
|
+
"Allowing without asking needs the agent's own machine to say so first: shapewall agent connect --approvals owner --auto edits, on that machine.",
|
|
1093
|
+
)
|
|
1094
|
+
next.rule = changes.rule
|
|
1095
|
+
}
|
|
1096
|
+
for (const key of ['changeRole', 'answerRole']) {
|
|
1097
|
+
if (changes[key] === undefined || changes[key] === before[key]) continue
|
|
1098
|
+
if (!APPROVAL_ROLES.includes(changes[key])) throw new HttpError(400, 'invalid_approval_role', `Role: ${APPROVAL_ROLES.join(', ')}.`)
|
|
1099
|
+
if (!canChangeApprovalRoles(actor.role)) throw new HttpError(403, 'forbidden', 'Only an owner changes which role decides approvals.')
|
|
1100
|
+
next[key] = changes[key]
|
|
1101
|
+
}
|
|
1102
|
+
if (JSON.stringify(before) !== JSON.stringify(next)) {
|
|
1103
|
+
t.run(
|
|
1104
|
+
'UPDATE agents SET approval_rule = :rule, approval_change_role = :changeRole, approval_answer_role = :answerRole, approval_rule_by = :by WHERE workspace_id = :ws AND id = :id',
|
|
1105
|
+
{ ...next, id: row.id, by: next.rule !== before.rule ? actor.userId : row.approval_rule_by || null },
|
|
1106
|
+
)
|
|
1107
|
+
actor.audit('agent_approval_rule_changed', row.id, { project: projectId, name: row.name, before, after: next })
|
|
1108
|
+
}
|
|
1109
|
+
return after(projectId, agentId)
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Revokes the agent's token. What it held and what waited for it go to
|
|
1113
|
+
// any agent; it stops being the default.
|
|
1114
|
+
function revoke(actor, projectId, agentId) {
|
|
1115
|
+
mayManage(actor)
|
|
1116
|
+
const row = need(projectId, agentId)
|
|
1117
|
+
const result = t.run(
|
|
1118
|
+
'UPDATE api_tokens SET revoked_at = :at WHERE workspace_id = :ws AND project_id = :project AND id = :id AND revoked_at IS NULL',
|
|
1119
|
+
{ at: iso(), project: projectId, id: row.token_id },
|
|
1120
|
+
)
|
|
1121
|
+
if (!result.changes) throw new HttpError(404, 'unknown_agent', 'This agent was already revoked.')
|
|
1122
|
+
actor.audit('token_revoked', row.token_id)
|
|
1123
|
+
return { ok: true, ...afterRevoke(actor, projectId, row.id) }
|
|
1124
|
+
}
|
|
1125
|
+
// What follows a token's revocation, from here or the Tokens page: the
|
|
1126
|
+
// comments it held and the ones that waited for it go to any agent
|
|
1127
|
+
// (releaseAgent), the project loses it as default, and the audit log says
|
|
1128
|
+
// so. Returns { comments, held, wasDefault }.
|
|
1129
|
+
function afterRevoke(actor, projectId, agentId) {
|
|
1130
|
+
forget()
|
|
1131
|
+
const row = need(projectId, agentId)
|
|
1132
|
+
const released = releaseAgent(projectId, row, { audit: actor.audit, reason: 'revoked' })
|
|
1133
|
+
actor.audit('agent_revoked', row.id, {
|
|
1134
|
+
project: projectId,
|
|
1135
|
+
name: row.name,
|
|
1136
|
+
released: released.comments,
|
|
1137
|
+
held: released.held,
|
|
1138
|
+
wasDefault: released.wasDefault,
|
|
1139
|
+
})
|
|
1140
|
+
return released
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
return {
|
|
1144
|
+
ensure,
|
|
1145
|
+
create,
|
|
1146
|
+
get,
|
|
1147
|
+
forToken,
|
|
1148
|
+
idForToken,
|
|
1149
|
+
live,
|
|
1150
|
+
defaultAgent,
|
|
1151
|
+
stateOf,
|
|
1152
|
+
linked,
|
|
1153
|
+
capsOf,
|
|
1154
|
+
hello,
|
|
1155
|
+
helloPolicy,
|
|
1156
|
+
machinePolicy,
|
|
1157
|
+
approvalRules,
|
|
1158
|
+
editMode,
|
|
1159
|
+
answerCheck,
|
|
1160
|
+
editsView,
|
|
1161
|
+
chatCheck,
|
|
1162
|
+
linkView,
|
|
1163
|
+
seen,
|
|
1164
|
+
inAudience,
|
|
1165
|
+
audienceOf,
|
|
1166
|
+
sendCheck,
|
|
1167
|
+
trusted,
|
|
1168
|
+
addressOf,
|
|
1169
|
+
address,
|
|
1170
|
+
release,
|
|
1171
|
+
claimCheck,
|
|
1172
|
+
holds,
|
|
1173
|
+
workCheck,
|
|
1174
|
+
replyVisible,
|
|
1175
|
+
releaseGone,
|
|
1176
|
+
startRun,
|
|
1177
|
+
closeRuns,
|
|
1178
|
+
boardView,
|
|
1179
|
+
boardList,
|
|
1180
|
+
consoleView,
|
|
1181
|
+
consoleList,
|
|
1182
|
+
setIdentity,
|
|
1183
|
+
setDefault,
|
|
1184
|
+
setAudience,
|
|
1185
|
+
setApprovalRule,
|
|
1186
|
+
revoke,
|
|
1187
|
+
afterRevoke,
|
|
1188
|
+
forget,
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
const pick = (person) => ({ handle: person?.handle || null, displayName: person?.displayName || null })
|
|
1193
|
+
// The later of some ISO times (null when there is none).
|
|
1194
|
+
const latestOf = (...times) => times.filter(Boolean).sort().at(-1) || null
|
|
1195
|
+
// A machine label as `shapewall login` sent it: one short line.
|
|
1196
|
+
function cleanMachine(value) {
|
|
1197
|
+
const text =
|
|
1198
|
+
typeof value === 'string'
|
|
1199
|
+
? value
|
|
1200
|
+
.replace(/[^\w .-]/g, '')
|
|
1201
|
+
.replace(/\s+/g, ' ')
|
|
1202
|
+
.trim()
|
|
1203
|
+
.slice(0, 40)
|
|
1204
|
+
: ''
|
|
1205
|
+
return text || null
|
|
1206
|
+
}
|