@wiro-ai/wiro-mcp 1.8.0 → 1.9.1
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/README.md +54 -7
- package/dist/instructions.js +4 -4
- package/dist/instructions.js.map +1 -1
- package/dist/playbooks.d.ts +1 -1
- package/dist/playbooks.d.ts.map +1 -1
- package/dist/playbooks.js +176 -6
- package/dist/playbooks.js.map +1 -1
- package/dist/tools/check-model-access.d.ts +4 -0
- package/dist/tools/check-model-access.d.ts.map +1 -0
- package/dist/tools/check-model-access.js +281 -0
- package/dist/tools/check-model-access.js.map +1 -0
- package/dist/tools/get-account.d.ts +5 -1
- package/dist/tools/get-account.d.ts.map +1 -1
- package/dist/tools/get-account.js +39 -4
- package/dist/tools/get-account.js.map +1 -1
- package/dist/tools/get-agent-conversation.d.ts.map +1 -1
- package/dist/tools/get-agent-conversation.js +3 -2
- package/dist/tools/get-agent-conversation.js.map +1 -1
- package/dist/tools/get-controls.d.ts +4 -0
- package/dist/tools/get-controls.d.ts.map +1 -0
- package/dist/tools/get-controls.js +365 -0
- package/dist/tools/get-controls.js.map +1 -0
- package/dist/tools/index.d.ts +6 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +22 -8
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/manage-model-access.d.ts +4 -0
- package/dist/tools/manage-model-access.d.ts.map +1 -0
- package/dist/tools/manage-model-access.js +816 -0
- package/dist/tools/manage-model-access.js.map +1 -0
- package/dist/tools/manage-spend-limit.d.ts +4 -0
- package/dist/tools/manage-spend-limit.d.ts.map +1 -0
- package/dist/tools/manage-spend-limit.js +535 -0
- package/dist/tools/manage-spend-limit.js.map +1 -0
- package/dist/tools/resume-workflow-run.d.ts +2 -1
- package/dist/tools/resume-workflow-run.d.ts.map +1 -1
- package/dist/tools/resume-workflow-run.js +4 -4
- package/dist/tools/resume-workflow-run.js.map +1 -1
- package/dist/tools/run-model.d.ts +2 -1
- package/dist/tools/run-model.d.ts.map +1 -1
- package/dist/tools/run-model.js +10 -9
- package/dist/tools/run-model.js.map +1 -1
- package/dist/tools/run-workflow.d.ts +2 -1
- package/dist/tools/run-workflow.d.ts.map +1 -1
- package/dist/tools/run-workflow.js +4 -4
- package/dist/tools/run-workflow.js.map +1 -1
- package/dist/tools/schemas.d.ts.map +1 -1
- package/dist/tools/schemas.js +18 -1
- package/dist/tools/schemas.js.map +1 -1
- package/dist/tools/send-agent-message.d.ts +2 -1
- package/dist/tools/send-agent-message.d.ts.map +1 -1
- package/dist/tools/send-agent-message.js +9 -4
- package/dist/tools/send-agent-message.js.map +1 -1
- package/dist/tools/update-agent.d.ts +2 -1
- package/dist/tools/update-agent.d.ts.map +1 -1
- package/dist/tools/update-agent.js +3 -3
- package/dist/tools/update-agent.js.map +1 -1
- package/dist/utils/agent-catalog.d.ts +1 -1
- package/dist/utils/agent-message.d.ts +6 -0
- package/dist/utils/agent-message.d.ts.map +1 -1
- package/dist/utils/agent-message.js +21 -1
- package/dist/utils/agent-message.js.map +1 -1
- package/dist/utils/agent-targets.d.ts +9 -3
- package/dist/utils/agent-targets.d.ts.map +1 -1
- package/dist/utils/agent-targets.js +41 -12
- package/dist/utils/agent-targets.js.map +1 -1
- package/dist/utils/agent-turns.d.ts +4 -0
- package/dist/utils/agent-turns.d.ts.map +1 -1
- package/dist/utils/agent-turns.js +5 -3
- package/dist/utils/agent-turns.js.map +1 -1
- package/dist/utils/api.d.ts +52 -5
- package/dist/utils/api.d.ts.map +1 -1
- package/dist/utils/api.js +98 -10
- package/dist/utils/api.js.map +1 -1
- package/dist/utils/controls.d.ts +427 -0
- package/dist/utils/controls.d.ts.map +1 -0
- package/dist/utils/controls.js +910 -0
- package/dist/utils/controls.js.map +1 -0
- package/dist/utils/wiro-project.d.ts +2 -0
- package/dist/utils/wiro-project.d.ts.map +1 -1
- package/dist/utils/wiro-project.js +1 -0
- package/dist/utils/wiro-project.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,910 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { WiroApiError } from '../client.js';
|
|
4
|
+
import { ApiResultError, asString, errorText, isOutcomeUnknown, isPlainObject, MODEL_ACCESS_URL, requireApiSuccess, SPEND_LIMITS_URL, toNumber, truncate, } from './api.js';
|
|
5
|
+
import { oneLine, quotedSpan } from './quoted-text.js';
|
|
6
|
+
import { keySafeErrorText, readProjects } from './wiro-project.js';
|
|
7
|
+
import { canonicalStringify } from './workflow-artifacts.js';
|
|
8
|
+
// Controls: a workspace's Spend Limits (caps on what it spends in a month or a
|
|
9
|
+
// day) and Model Access rules (which models it may run). The four controls
|
|
10
|
+
// tools share what is here: reading Wiro's lists, naming a limit's or a rule's
|
|
11
|
+
// target, putting a rule in plain words, and turning a refused or failed change
|
|
12
|
+
// into a sentence that says what happened. Every field shown is rebuilt from an
|
|
13
|
+
// allowlist, and names people wrote stay in code spans.
|
|
14
|
+
export const CONTROL_SCOPES = ['account', 'member', 'project', 'surface', 'agent'];
|
|
15
|
+
export const SURFACES = ['web', 'api', 'mcp', 'llm-gateway', 'extension', 'agent'];
|
|
16
|
+
export const PERIODS = ['month', 'day'];
|
|
17
|
+
export const CATEGORY_KEYS = ['image', 'video', 'audio', 'music', '3d', 'llm', 'utilities'];
|
|
18
|
+
const DEFAULT_CATEGORY_LABELS = {
|
|
19
|
+
image: 'Image Generation',
|
|
20
|
+
video: 'Video Generation',
|
|
21
|
+
audio: 'Audio & Speech',
|
|
22
|
+
music: 'Music Generation',
|
|
23
|
+
'3d': '3D Generation',
|
|
24
|
+
llm: 'LLM & Chat',
|
|
25
|
+
utilities: 'Utilities',
|
|
26
|
+
};
|
|
27
|
+
/** How Wiro names each way in, as its refusals do. */
|
|
28
|
+
export const SURFACE_LABELS = {
|
|
29
|
+
web: 'the dashboard',
|
|
30
|
+
api: 'the API',
|
|
31
|
+
mcp: 'MCP',
|
|
32
|
+
'llm-gateway': 'the LLM gateway',
|
|
33
|
+
extension: 'the browser extensions',
|
|
34
|
+
agent: 'agents',
|
|
35
|
+
};
|
|
36
|
+
/** What each way in covers. A local install of this server sends its calls with an API key, so it counts as api. */
|
|
37
|
+
export const SURFACE_DESCRIPTIONS = {
|
|
38
|
+
web: 'the Wiro dashboard, with Studio and the Workflow Agent used there',
|
|
39
|
+
api: 'calls with an API key, a local install of this server included',
|
|
40
|
+
mcp: 'the hosted MCP server at mcp.wiro.ai',
|
|
41
|
+
'llm-gateway': 'the OpenAI and Anthropic compatible LLM gateway',
|
|
42
|
+
extension: 'the Wiro browser extensions',
|
|
43
|
+
agent: 'deployed agents\' own runs',
|
|
44
|
+
};
|
|
45
|
+
/** Wiro's limit on one rule: it can name at most this many models. */
|
|
46
|
+
export const MAX_RULE_MODELS = 500;
|
|
47
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
48
|
+
const PROJECT_ID = /^[1-9][0-9]{0,17}$/;
|
|
49
|
+
const TEXT_MAX = 200;
|
|
50
|
+
export const NOTHING_CHANGED = 'Nothing was changed.';
|
|
51
|
+
export function isScope(value) {
|
|
52
|
+
return typeof value === 'string' && CONTROL_SCOPES.includes(value);
|
|
53
|
+
}
|
|
54
|
+
export function isSurface(value) {
|
|
55
|
+
return typeof value === 'string' && SURFACES.includes(value);
|
|
56
|
+
}
|
|
57
|
+
function isPeriod(value) {
|
|
58
|
+
return value === 'month' || value === 'day';
|
|
59
|
+
}
|
|
60
|
+
export function isCategory(value) {
|
|
61
|
+
return typeof value === 'string' && CATEGORY_KEYS.includes(value);
|
|
62
|
+
}
|
|
63
|
+
function isAccess(value) {
|
|
64
|
+
return value === 'allow' || value === 'block';
|
|
65
|
+
}
|
|
66
|
+
function textValue(value, max = TEXT_MAX) {
|
|
67
|
+
const text = asString(value);
|
|
68
|
+
return text?.trim() ? truncate(oneLine(text), max) : undefined;
|
|
69
|
+
}
|
|
70
|
+
function unixValue(value) {
|
|
71
|
+
const seconds = toNumber(value);
|
|
72
|
+
return seconds !== null && seconds > 0 ? Math.trunc(seconds) : undefined;
|
|
73
|
+
}
|
|
74
|
+
export function cents(value) {
|
|
75
|
+
return Math.round(value * 100) / 100;
|
|
76
|
+
}
|
|
77
|
+
/** An amount in USD with cents, such as $248.70. */
|
|
78
|
+
export function usd(value) {
|
|
79
|
+
return `$${cents(value).toFixed(2)}`;
|
|
80
|
+
}
|
|
81
|
+
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
|
82
|
+
/** A time in plain words, in UTC, as Wiro's refusals give it: "December 1, 2026 at 00:00 UTC". */
|
|
83
|
+
export function utcText(unixSeconds) {
|
|
84
|
+
const date = new Date(unixSeconds * 1000);
|
|
85
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
86
|
+
return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()} at `
|
|
87
|
+
+ `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())} UTC`;
|
|
88
|
+
}
|
|
89
|
+
export function isoTime(unixSeconds) {
|
|
90
|
+
return unixSeconds ? new Date(unixSeconds * 1000).toISOString().replace('.000Z', 'Z') : undefined;
|
|
91
|
+
}
|
|
92
|
+
function toWorkspace(value) {
|
|
93
|
+
if (!isPlainObject(value))
|
|
94
|
+
return { kind: 'unknown' };
|
|
95
|
+
const kind = value.type === 'team' ? 'team' : value.type === 'personal' ? 'personal' : 'unknown';
|
|
96
|
+
const teamGuid = textValue(value.teamguid, 64);
|
|
97
|
+
return {
|
|
98
|
+
kind,
|
|
99
|
+
...(kind === 'team' && teamGuid ? { teamGuid } : {}),
|
|
100
|
+
...(typeof value.canmanage === 'boolean' ? { canManage: value.canmanage } : {}),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function toCaller(value) {
|
|
104
|
+
if (!isPlainObject(value))
|
|
105
|
+
return undefined;
|
|
106
|
+
const projectId = asString(value.projectid)?.trim();
|
|
107
|
+
return {
|
|
108
|
+
...(isSurface(value.surface) ? { surface: value.surface } : {}),
|
|
109
|
+
...(projectId && PROJECT_ID.test(projectId) ? { projectId } : {}),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Wiro's label for an organization's owner who is not a member of the team. */
|
|
113
|
+
const ORGANIZATION_OWNER = /^the organization owner$/i;
|
|
114
|
+
export const changedBySchema = z.object({
|
|
115
|
+
useruuid: z.string(),
|
|
116
|
+
name: z.string().optional().describe('Their name or e-mail, or "the organization owner"; absent for someone who is no longer in the team.'),
|
|
117
|
+
}).describe('Who changed it last. Absent when Wiro did not say, or when a change Wiro made itself was the last.');
|
|
118
|
+
/** A row's updatedby: { useruuid, label } of a person, or null for a change Wiro made itself. */
|
|
119
|
+
function toChangedBy(value) {
|
|
120
|
+
if (!isPlainObject(value))
|
|
121
|
+
return undefined;
|
|
122
|
+
const useruuid = textValue(value.useruuid, 64);
|
|
123
|
+
if (!useruuid || !UUID.test(useruuid))
|
|
124
|
+
return undefined;
|
|
125
|
+
const name = textValue(value.label);
|
|
126
|
+
return { useruuid, ...(name ? { name } : {}) };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* "last changed by `Jane Doe` on November 18, 2026 at 14:02 UTC", or undefined when Wiro did not say who. A name
|
|
130
|
+
* people wrote stays in a code span; Wiro's own label for the organization's owner reads as words.
|
|
131
|
+
*/
|
|
132
|
+
export function changedByText(row, kind, caller) {
|
|
133
|
+
const by = row.updatedBy;
|
|
134
|
+
if (!by)
|
|
135
|
+
return undefined;
|
|
136
|
+
const name = by.name
|
|
137
|
+
? ORGANIZATION_OWNER.test(by.name) ? 'the organization\'s owner' : quotedSpan(by.name)
|
|
138
|
+
: kind === 'team' ? `a former team member (user id ${quotedSpan(by.useruuid)})` : `user id ${quotedSpan(by.useruuid)}`;
|
|
139
|
+
const at = row.updatedAt ?? row.createdAt;
|
|
140
|
+
const self = isThisConnection('member', by.useruuid, caller) ? `, the person this connection acts as${at ? ',' : ''}` : '';
|
|
141
|
+
return `last changed by ${name}${self}${at ? ` on ${utcText(at)}` : ''}`;
|
|
142
|
+
}
|
|
143
|
+
/** The parenthesis a list line ends with: a guid and who changed the row last, each when known. */
|
|
144
|
+
function lineTrailer(...parts) {
|
|
145
|
+
const known = parts.filter((part) => Boolean(part));
|
|
146
|
+
return known.length > 0 ? ` (${known.join('; ')})` : '';
|
|
147
|
+
}
|
|
148
|
+
/** Who may change controls, for a sentence after a refusal or in a read. */
|
|
149
|
+
export function whoCanChange(kind) {
|
|
150
|
+
return kind === 'personal' ? 'the account owner' : 'a team admin or the organization\'s owner';
|
|
151
|
+
}
|
|
152
|
+
/** The whole wallet's name, by the kind of workspace. */
|
|
153
|
+
export function wholeWallet(kind) {
|
|
154
|
+
return kind === 'team' ? 'the whole team' : kind === 'personal' ? 'the whole account' : 'the whole wallet';
|
|
155
|
+
}
|
|
156
|
+
/** A limit row of SpendLimit/List, /Preview or /Set, rebuilt from an allowlist. */
|
|
157
|
+
export function toLimitRow(row) {
|
|
158
|
+
const scope = row.scope;
|
|
159
|
+
const period = row.period;
|
|
160
|
+
const amountUsd = toNumber(row.amountusd);
|
|
161
|
+
if (!isScope(scope) || !isPeriod(period) || amountUsd === null)
|
|
162
|
+
return null;
|
|
163
|
+
const guid = textValue(row.guid, 64);
|
|
164
|
+
const target = scope === 'account' ? '' : textValue(row.target) ?? '';
|
|
165
|
+
const targetName = textValue(row.targetlabel);
|
|
166
|
+
const held = toNumber(row.heldusd);
|
|
167
|
+
const alert = toNumber(row.alertpct);
|
|
168
|
+
const periodStart = unixValue(row.periodstart);
|
|
169
|
+
const resetsAt = unixValue(row.resetsat);
|
|
170
|
+
const createdAt = unixValue(row.createdat);
|
|
171
|
+
const updatedAt = unixValue(row.updatedat);
|
|
172
|
+
const updatedBy = toChangedBy(row.updatedby);
|
|
173
|
+
return {
|
|
174
|
+
...(guid ? { guid } : {}),
|
|
175
|
+
scope,
|
|
176
|
+
target,
|
|
177
|
+
...(targetName ? { targetName } : {}),
|
|
178
|
+
period,
|
|
179
|
+
amountUsd: cents(amountUsd),
|
|
180
|
+
spentUsd: cents(Math.max(0, toNumber(row.spentusd) ?? 0)),
|
|
181
|
+
...(held !== null && held > 0 ? { heldUsd: cents(held) } : {}),
|
|
182
|
+
alertPercent: alert === null || alert <= 0 ? null : Math.trunc(alert),
|
|
183
|
+
...(periodStart ? { periodStart } : {}),
|
|
184
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
185
|
+
...(createdAt ? { createdAt } : {}),
|
|
186
|
+
...(updatedAt ? { updatedAt } : {}),
|
|
187
|
+
...(updatedBy ? { updatedBy } : {}),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/** What is left for new work: the amount less what was spent and what running work holds. */
|
|
191
|
+
export function leftOf(row) {
|
|
192
|
+
return Math.max(0, cents(row.amountUsd - row.spentUsd - (row.heldUsd ?? 0)));
|
|
193
|
+
}
|
|
194
|
+
export function isUsedUp(row) {
|
|
195
|
+
return row.spentUsd >= row.amountUsd;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* A row's version, as a change summary records it: its last change, 0 when there is no row. A
|
|
199
|
+
* confirmed change goes ahead only while the row still has the version the user saw.
|
|
200
|
+
*/
|
|
201
|
+
export function versionOf(row) {
|
|
202
|
+
return row ? row.updatedAt ?? row.createdAt ?? 1 : 0;
|
|
203
|
+
}
|
|
204
|
+
export function confirmState(args, version, id) {
|
|
205
|
+
if (!args.confirm)
|
|
206
|
+
return 'summary';
|
|
207
|
+
if (args.updated_at === undefined || args.summary_id === undefined)
|
|
208
|
+
return 'no-summary';
|
|
209
|
+
if (args.updated_at !== version)
|
|
210
|
+
return 'changed';
|
|
211
|
+
return args.summary_id === id ? 'confirmed' : 'differs';
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The id of a change summary: a digest of the exact change it shows and the version of the row it was made from,
|
|
215
|
+
* keyed by this connection's API key. It cannot be made up without the key, and every server of one deployment
|
|
216
|
+
* gives the same id for the same change.
|
|
217
|
+
*/
|
|
218
|
+
export function summaryId(client, change) {
|
|
219
|
+
const identity = client.identity;
|
|
220
|
+
return createHmac('sha256', `wiro-mcp-controls:${typeof identity === 'string' ? identity : ''}`)
|
|
221
|
+
.update(canonicalStringify(change))
|
|
222
|
+
.digest('hex')
|
|
223
|
+
.slice(0, 32);
|
|
224
|
+
}
|
|
225
|
+
/** The sentence a summary opens with when a confirm did not write, by why it did not. */
|
|
226
|
+
export function confirmLead(state, what) {
|
|
227
|
+
switch (state) {
|
|
228
|
+
case 'changed':
|
|
229
|
+
return `The ${what} changed after the summary you showed, so nothing was saved. Show this summary and ask the user again.`;
|
|
230
|
+
case 'no-summary':
|
|
231
|
+
return 'This call did not repeat a change summary\'s nextAction, so nothing was saved. Show this summary and ask the user.';
|
|
232
|
+
case 'differs':
|
|
233
|
+
return 'This call asks for something other than the summary it repeats, so nothing was saved. Show this summary and ask the user.';
|
|
234
|
+
default:
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
export const summaryIdSchema = z.string().trim().min(1).max(64).optional()
|
|
239
|
+
.describe('From the change summary\'s nextAction: the id of the change the user saw. Never set it yourself.');
|
|
240
|
+
export function periodWord(period) {
|
|
241
|
+
return period === 'day' ? 'daily' : 'monthly';
|
|
242
|
+
}
|
|
243
|
+
/** The label of a period's spending so far: "Today so far" or "This month so far". */
|
|
244
|
+
export function soFarLabel(period) {
|
|
245
|
+
return period === 'day' ? 'Today so far' : 'This month so far';
|
|
246
|
+
}
|
|
247
|
+
/** A phrase of this server's text at the start of a sentence. */
|
|
248
|
+
export function capitalized(text) {
|
|
249
|
+
return text ? `${text[0].toUpperCase()}${text.slice(1)}` : text;
|
|
250
|
+
}
|
|
251
|
+
/** "$500.00 a month". */
|
|
252
|
+
export function amountPerPeriod(amountUsd, period) {
|
|
253
|
+
return `${usd(amountUsd)} a ${period}`;
|
|
254
|
+
}
|
|
255
|
+
export function alertText(alertPercent) {
|
|
256
|
+
return alertPercent === null ? 'no alert email' : `alert email at ${alertPercent}%`;
|
|
257
|
+
}
|
|
258
|
+
/** When a period ends, or the time a row gives. */
|
|
259
|
+
export function resetText(row) {
|
|
260
|
+
if (row.resetsAt)
|
|
261
|
+
return `resets ${utcText(row.resetsAt)}`;
|
|
262
|
+
return row.period === 'day' ? 'resets every day at 00:00 UTC' : 'resets on the 1st at 00:00 UTC';
|
|
263
|
+
}
|
|
264
|
+
export function isThisConnection(scope, target, caller) {
|
|
265
|
+
if (!caller)
|
|
266
|
+
return false;
|
|
267
|
+
if (scope === 'project')
|
|
268
|
+
return caller.projectId !== undefined && caller.projectId === target;
|
|
269
|
+
if (scope === 'surface')
|
|
270
|
+
return caller.surface !== undefined && caller.surface === target;
|
|
271
|
+
if (scope === 'member')
|
|
272
|
+
return caller.memberUuid !== undefined && caller.memberUuid.toLowerCase() === target.toLowerCase();
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
/** What a limit or a rule covers, as one phrase of this server's own text. */
|
|
276
|
+
export function targetText(view, kind) {
|
|
277
|
+
const id = view.target ?? '';
|
|
278
|
+
const name = view.targetName;
|
|
279
|
+
let text;
|
|
280
|
+
switch (view.scope) {
|
|
281
|
+
case 'account':
|
|
282
|
+
text = wholeWallet(kind);
|
|
283
|
+
break;
|
|
284
|
+
case 'member':
|
|
285
|
+
text = name ? `team member ${quotedSpan(name)} (user id ${quotedSpan(id)})` : `the team member with user id ${quotedSpan(id)}`;
|
|
286
|
+
break;
|
|
287
|
+
case 'project':
|
|
288
|
+
text = name ? `the API key of project ${quotedSpan(name)} (id ${quotedSpan(id)})` : `the API key of project id ${quotedSpan(id)}`;
|
|
289
|
+
break;
|
|
290
|
+
case 'surface':
|
|
291
|
+
text = isSurface(id) ? `${SURFACE_LABELS[id]} (surface \`${id}\`)` : `surface ${quotedSpan(id)}`;
|
|
292
|
+
break;
|
|
293
|
+
case 'agent':
|
|
294
|
+
text = name ? `agent ${quotedSpan(name)} (guid ${quotedSpan(id)})` : `the agent with guid ${quotedSpan(id)}`;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
if (!view.thisConnection)
|
|
298
|
+
return text;
|
|
299
|
+
if (view.scope === 'project')
|
|
300
|
+
return `${text}, the key this connection uses`;
|
|
301
|
+
if (view.scope === 'member')
|
|
302
|
+
return `${text}, the person this connection acts as`;
|
|
303
|
+
return `${text}, the way in this connection counts as`;
|
|
304
|
+
}
|
|
305
|
+
/** The argument that names a scope's target in the manage tools, or none for the whole wallet. */
|
|
306
|
+
export function targetArgument(scope, target) {
|
|
307
|
+
return scope === 'account' ? {} : { [scope]: target };
|
|
308
|
+
}
|
|
309
|
+
export const limitViewSchema = z.object({
|
|
310
|
+
guid: z.string().optional(),
|
|
311
|
+
scope: z.enum(CONTROL_SCOPES).describe('What the limit caps: the whole wallet (account), one team member, one API key (project), one way in (surface) or one agent.'),
|
|
312
|
+
target: z.string().optional().describe('The member\'s user id, the project id, the surface or the agent guid; absent for the whole wallet.'),
|
|
313
|
+
targetName: z.string().optional(),
|
|
314
|
+
thisConnection: z.boolean().optional().describe('True for the API key this connection uses, the surface it counts as, or in a team the member it acts as.'),
|
|
315
|
+
period: z.enum(PERIODS).describe('A monthly limit runs from the 1st at 00:00 UTC, a daily one from 00:00 UTC.'),
|
|
316
|
+
amountUsd: z.number(),
|
|
317
|
+
spentUsd: z.number().describe('Spent in the current period, including what was spent before the limit was set.'),
|
|
318
|
+
heldUsd: z.number().optional().describe('Held by work that is still running, until it is charged or ends.'),
|
|
319
|
+
leftUsd: z.number().describe('What new work can still use: the amount less what was spent and what is held.'),
|
|
320
|
+
usedUp: z.boolean().describe('True when what was spent reached the amount: new work it covers is refused with error code 93.'),
|
|
321
|
+
alertPercent: z.number().int().nullable().describe('The alert email goes out at this percent of the amount; null for none.'),
|
|
322
|
+
periodStart: z.string().optional(),
|
|
323
|
+
resetsAt: z.string().optional(),
|
|
324
|
+
updatedAt: z.number().int().optional().describe('When the limit last changed, in Unix seconds.'),
|
|
325
|
+
updatedBy: changedBySchema.optional(),
|
|
326
|
+
});
|
|
327
|
+
export function limitView(row, caller) {
|
|
328
|
+
const periodStart = isoTime(row.periodStart);
|
|
329
|
+
const resetsAt = isoTime(row.resetsAt);
|
|
330
|
+
const version = row.updatedAt ?? row.createdAt;
|
|
331
|
+
return {
|
|
332
|
+
...(row.guid ? { guid: row.guid } : {}),
|
|
333
|
+
scope: row.scope,
|
|
334
|
+
...(row.scope !== 'account' ? { target: row.target } : {}),
|
|
335
|
+
...(row.targetName ? { targetName: row.targetName } : {}),
|
|
336
|
+
...(isThisConnection(row.scope, row.target, caller) ? { thisConnection: true } : {}),
|
|
337
|
+
period: row.period,
|
|
338
|
+
amountUsd: row.amountUsd,
|
|
339
|
+
spentUsd: row.spentUsd,
|
|
340
|
+
...(row.heldUsd ? { heldUsd: row.heldUsd } : {}),
|
|
341
|
+
leftUsd: leftOf(row),
|
|
342
|
+
usedUp: isUsedUp(row),
|
|
343
|
+
alertPercent: row.alertPercent,
|
|
344
|
+
...(periodStart ? { periodStart } : {}),
|
|
345
|
+
...(resetsAt ? { resetsAt } : {}),
|
|
346
|
+
...(version ? { updatedAt: version } : {}),
|
|
347
|
+
...(row.updatedBy ? { updatedBy: row.updatedBy } : {}),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/** "$248.70 of $500.00 used, $20.00 held by work still running, $231.30 left". */
|
|
351
|
+
export function spendingText(row) {
|
|
352
|
+
const held = row.heldUsd ? `, ${usd(row.heldUsd)} held by work still running` : '';
|
|
353
|
+
if (isUsedUp(row))
|
|
354
|
+
return `${usd(row.spentUsd)} of ${usd(row.amountUsd)} used${held}: used up, so new work it covers is refused until it resets`;
|
|
355
|
+
const left = leftOf(row);
|
|
356
|
+
const state = left === 0 ? `, nothing left until running work ends` : `, ${usd(left)} left`;
|
|
357
|
+
return `${usd(row.spentUsd)} of ${usd(row.amountUsd)} used${held}${state}`;
|
|
358
|
+
}
|
|
359
|
+
/** One line of a limit list. */
|
|
360
|
+
export function limitLine(row, kind, caller) {
|
|
361
|
+
const view = { scope: row.scope, target: row.target, targetName: row.targetName, thisConnection: isThisConnection(row.scope, row.target, caller) };
|
|
362
|
+
const period = row.period === 'day' ? 'Daily' : 'Monthly';
|
|
363
|
+
const trailer = lineTrailer(row.guid ? `limit_guid ${quotedSpan(row.guid)}` : undefined, changedByText(row, kind, caller));
|
|
364
|
+
return `- ${period} limit for ${targetText(view, kind)}: ${spendingText(row)}, ${alertText(row.alertPercent)}, ${resetText(row)}${trailer}`;
|
|
365
|
+
}
|
|
366
|
+
/** A rule row of ModelAccess/List, /Preview, /Set or /Check, rebuilt from an allowlist. */
|
|
367
|
+
export function toRuleRow(row) {
|
|
368
|
+
const scope = row.scope;
|
|
369
|
+
if (!isScope(scope))
|
|
370
|
+
return null;
|
|
371
|
+
const guid = textValue(row.guid, 64);
|
|
372
|
+
const target = scope === 'account' ? '' : textValue(row.target) ?? '';
|
|
373
|
+
const targetName = textValue(row.targetlabel);
|
|
374
|
+
const categories = {};
|
|
375
|
+
const entries = Array.isArray(row.categories)
|
|
376
|
+
? row.categories.filter(isPlainObject).map(entry => [entry.category, entry.access])
|
|
377
|
+
: isPlainObject(row.categories) ? Object.entries(row.categories) : [];
|
|
378
|
+
for (const [category, access] of entries) {
|
|
379
|
+
if (isCategory(category) && isAccess(access))
|
|
380
|
+
categories[category] = access;
|
|
381
|
+
}
|
|
382
|
+
const models = (Array.isArray(row.models) ? row.models : []).filter(isPlainObject).flatMap(entry => {
|
|
383
|
+
const id = asString(entry.id)?.trim();
|
|
384
|
+
if (!id || !/^\d{1,19}$/.test(id) || !isAccess(entry.access))
|
|
385
|
+
return [];
|
|
386
|
+
const model = textValue(entry.model);
|
|
387
|
+
const title = textValue(entry.title);
|
|
388
|
+
return [{ id, model: model ?? null, ...(title ? { title } : {}), access: entry.access }];
|
|
389
|
+
});
|
|
390
|
+
const createdAt = unixValue(row.createdat);
|
|
391
|
+
const updatedAt = unixValue(row.updatedat);
|
|
392
|
+
const updatedBy = toChangedBy(row.updatedby);
|
|
393
|
+
return {
|
|
394
|
+
...(guid ? { guid } : {}),
|
|
395
|
+
scope,
|
|
396
|
+
target,
|
|
397
|
+
...(targetName ? { targetName } : {}),
|
|
398
|
+
access: row.access === 'block' ? 'block' : 'allow',
|
|
399
|
+
categories,
|
|
400
|
+
models,
|
|
401
|
+
...(createdAt ? { createdAt } : {}),
|
|
402
|
+
...(updatedAt ? { updatedAt } : {}),
|
|
403
|
+
...(updatedBy ? { updatedBy } : {}),
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
/** The category labels a ModelAccess/List answer gives, over the built-in ones. */
|
|
407
|
+
export function toCategoryLabels(value) {
|
|
408
|
+
const labels = { ...DEFAULT_CATEGORY_LABELS };
|
|
409
|
+
if (!Array.isArray(value))
|
|
410
|
+
return labels;
|
|
411
|
+
for (const entry of value.filter(isPlainObject)) {
|
|
412
|
+
const label = textValue(entry.label, 80);
|
|
413
|
+
if (isCategory(entry.category) && label)
|
|
414
|
+
labels[entry.category] = label;
|
|
415
|
+
}
|
|
416
|
+
return labels;
|
|
417
|
+
}
|
|
418
|
+
export function categoryList(labels) {
|
|
419
|
+
return CATEGORY_KEYS.map(category => ({ category, label: labels[category] }));
|
|
420
|
+
}
|
|
421
|
+
/** A model of a rule by its owner/slug, or by its id when it is no longer on Wiro. */
|
|
422
|
+
export function entryName(entry, quote) {
|
|
423
|
+
if (entry.model === null)
|
|
424
|
+
return `model ${entry.id}, no longer on Wiro`;
|
|
425
|
+
return quote ? quotedSpan(entry.model) : entry.model;
|
|
426
|
+
}
|
|
427
|
+
function listText(items) {
|
|
428
|
+
if (items.length <= 1)
|
|
429
|
+
return items.join('');
|
|
430
|
+
return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
|
|
431
|
+
}
|
|
432
|
+
function namesText(categoryNames, models, quote, maxModels) {
|
|
433
|
+
const shown = models.slice(0, maxModels).map(entry => entryName(entry, quote));
|
|
434
|
+
const more = models.length - shown.length;
|
|
435
|
+
return listText([...categoryNames, ...shown, ...(more > 0 ? [`${more} more ${more === 1 ? 'model' : 'models'}`] : [])]);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* A rule in plain words: "Every model except Video Generation; bytedance/seedance-v2-5-flash allowed by name" or
|
|
439
|
+
* "Only Image Generation and openai/gpt-6-2-astra". In a rule that allows every other model an allowed category
|
|
440
|
+
* decides nothing (a block among a model's categories wins), so it is left out.
|
|
441
|
+
*/
|
|
442
|
+
export function ruleSummary(rule, labels, options = {}) {
|
|
443
|
+
const quote = options.quote ?? false;
|
|
444
|
+
const maxModels = options.maxModels ?? Infinity;
|
|
445
|
+
const categories = (access) => CATEGORY_KEYS.filter(key => rule.categories[key] === access).map(key => labels[key]);
|
|
446
|
+
const models = (access) => rule.models.filter(entry => entry.access === access);
|
|
447
|
+
if (rule.access === 'allow') {
|
|
448
|
+
const blockedCategories = categories('block');
|
|
449
|
+
const blockedModels = models('block');
|
|
450
|
+
if (blockedCategories.length === 0 && blockedModels.length === 0)
|
|
451
|
+
return 'Every model: this rule blocks nothing';
|
|
452
|
+
const allowedModels = models('allow');
|
|
453
|
+
const byName = allowedModels.length > 0 ? `; ${namesText([], allowedModels, quote, maxModels)} allowed by name` : '';
|
|
454
|
+
return `Every model except ${namesText(blockedCategories, blockedModels, quote, maxModels)}${byName}`;
|
|
455
|
+
}
|
|
456
|
+
const allowedCategories = categories('allow');
|
|
457
|
+
const allowedModels = models('allow');
|
|
458
|
+
if (allowedCategories.length === 0 && allowedModels.length === 0)
|
|
459
|
+
return 'No model: this rule blocks every model';
|
|
460
|
+
const blockedCategories = categories('block');
|
|
461
|
+
const blockedModels = models('block');
|
|
462
|
+
const except = blockedCategories.length > 0 || blockedModels.length > 0
|
|
463
|
+
? `, except ${namesText(blockedCategories, blockedModels, quote, maxModels)}`
|
|
464
|
+
: '';
|
|
465
|
+
return `Only ${namesText(allowedCategories, allowedModels, quote, maxModels)}${except}`;
|
|
466
|
+
}
|
|
467
|
+
/** Whether a rule blocks anything at all. One that does not changes no decision. */
|
|
468
|
+
export function blocksSomething(rule) {
|
|
469
|
+
return rule.access === 'block'
|
|
470
|
+
|| Object.values(rule.categories).includes('block')
|
|
471
|
+
|| rule.models.some(entry => entry.access === 'block');
|
|
472
|
+
}
|
|
473
|
+
export const ruleViewSchema = z.object({
|
|
474
|
+
guid: z.string().optional(),
|
|
475
|
+
scope: z.enum(CONTROL_SCOPES).describe('Whose runs the rule covers: the whole wallet (account), one team member, one API key (project), one way in (surface) or one agent.'),
|
|
476
|
+
target: z.string().optional().describe('The member\'s user id, the project id, the surface or the agent guid; absent for the whole wallet.'),
|
|
477
|
+
targetName: z.string().optional(),
|
|
478
|
+
thisConnection: z.boolean().optional().describe('True for the API key this connection uses, the surface it counts as, or in a team the member it acts as.'),
|
|
479
|
+
everythingElse: z.enum(['allow', 'block']).describe('What a model the rule names neither by category nor by name gets.'),
|
|
480
|
+
categories: z.array(z.object({
|
|
481
|
+
category: z.enum(CATEGORY_KEYS),
|
|
482
|
+
label: z.string(),
|
|
483
|
+
access: z.enum(['allow', 'block']),
|
|
484
|
+
})),
|
|
485
|
+
models: z.array(z.object({
|
|
486
|
+
id: z.string(),
|
|
487
|
+
model: z.string().nullable().describe('The owner/slug; null for a model that is no longer on Wiro.'),
|
|
488
|
+
title: z.string().optional(),
|
|
489
|
+
access: z.enum(['allow', 'block']),
|
|
490
|
+
})),
|
|
491
|
+
summary: z.string().describe('The rule in plain words.'),
|
|
492
|
+
updatedAt: z.number().int().optional().describe('When the rule last changed, in Unix seconds.'),
|
|
493
|
+
updatedBy: changedBySchema.optional(),
|
|
494
|
+
});
|
|
495
|
+
export function ruleView(rule, labels, caller) {
|
|
496
|
+
const version = rule.updatedAt ?? rule.createdAt;
|
|
497
|
+
return {
|
|
498
|
+
...(rule.guid ? { guid: rule.guid } : {}),
|
|
499
|
+
scope: rule.scope,
|
|
500
|
+
...(rule.scope !== 'account' ? { target: rule.target } : {}),
|
|
501
|
+
...(rule.targetName ? { targetName: rule.targetName } : {}),
|
|
502
|
+
...(isThisConnection(rule.scope, rule.target, caller) ? { thisConnection: true } : {}),
|
|
503
|
+
everythingElse: rule.access,
|
|
504
|
+
categories: CATEGORY_KEYS.flatMap(category => {
|
|
505
|
+
const access = rule.categories[category];
|
|
506
|
+
return access ? [{ category, label: labels[category], access }] : [];
|
|
507
|
+
}),
|
|
508
|
+
models: rule.models.map(entry => ({ id: entry.id, model: entry.model, ...(entry.title ? { title: entry.title } : {}), access: entry.access })),
|
|
509
|
+
summary: ruleSummary(rule, labels),
|
|
510
|
+
...(version ? { updatedAt: version } : {}),
|
|
511
|
+
...(rule.updatedBy ? { updatedBy: rule.updatedBy } : {}),
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/** One line of a rule list: at most ten models are named in the text. */
|
|
515
|
+
export function ruleLine(rule, labels, kind, caller) {
|
|
516
|
+
const view = { scope: rule.scope, target: rule.target, targetName: rule.targetName, thisConnection: isThisConnection(rule.scope, rule.target, caller) };
|
|
517
|
+
const trailer = lineTrailer(rule.guid ? `rule_guid ${quotedSpan(rule.guid)}` : undefined, changedByText(rule, kind, caller));
|
|
518
|
+
return `- Rule for ${targetText(view, kind)}: ${ruleSummary(rule, labels, { quote: true, maxModels: 10 })}${trailer}`;
|
|
519
|
+
}
|
|
520
|
+
/** The model that transcribes the voice notes of an agent that chats on Gemini. It is an LLM & Chat model too. */
|
|
521
|
+
export const GEMINI_VOICE_MODEL = 'google/gemini-3-flash';
|
|
522
|
+
/**
|
|
523
|
+
* What an agent's own rule gives its built-in voice; null for no rule. Its voice models count as Audio & Speech, so the
|
|
524
|
+
* rule's Audio & Speech entry decides them, else what it gives every other model, and allowing LLM & Chat does not
|
|
525
|
+
* open them. An agent that chats on Gemini has its voice notes transcribed by GEMINI_VOICE_MODEL, which has to pass
|
|
526
|
+
* the rule both as an Audio & Speech model and as the LLM & Chat model it is: a rule entry that names it decides
|
|
527
|
+
* both, else Audio & Speech and LLM & Chat must both let it run.
|
|
528
|
+
*/
|
|
529
|
+
export function agentVoice(rule, chatModel) {
|
|
530
|
+
const gemini = chatModel?.trim().toLowerCase().startsWith('google/') === true;
|
|
531
|
+
if (!rule)
|
|
532
|
+
return { gemini, notes: 'allow', notesByName: false, replies: 'allow' };
|
|
533
|
+
const audio = rule.categories.audio ?? rule.access;
|
|
534
|
+
const named = gemini ? rule.models.find(entry => entry.model?.toLowerCase() === GEMINI_VOICE_MODEL) : undefined;
|
|
535
|
+
if (named)
|
|
536
|
+
return { gemini, notes: named.access, notesByName: true, replies: audio };
|
|
537
|
+
const llm = rule.categories.llm ?? rule.access;
|
|
538
|
+
return { gemini, notes: audio === 'block' || (gemini && llm === 'block') ? 'block' : 'allow', notesByName: false, replies: audio };
|
|
539
|
+
}
|
|
540
|
+
/** The rules of a ModelAccess/Check answer that apply to the run, widest first, each with its decision. */
|
|
541
|
+
export function toRuleDecisions(value) {
|
|
542
|
+
return (Array.isArray(value) ? value.filter(isPlainObject) : []).flatMap(entry => {
|
|
543
|
+
const rule = isPlainObject(entry.rule) ? toRuleRow(entry.rule) : null;
|
|
544
|
+
if (!rule)
|
|
545
|
+
return [];
|
|
546
|
+
const decides = entry.access === 'block' ? 'block' : 'allow';
|
|
547
|
+
const by = entry.by === 'model' || entry.by === 'category' ? entry.by : 'default';
|
|
548
|
+
const category = asString(entry.category) ?? null;
|
|
549
|
+
return [{ rule, decides, by, category }];
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
/** check.context of a ModelAccess/Check answer; undefined when the answer has none (an older Wiro API). */
|
|
553
|
+
export function toCheckedRun(value) {
|
|
554
|
+
if (!isPlainObject(value) || !isSurface(value.surface))
|
|
555
|
+
return undefined;
|
|
556
|
+
const member = isPlainObject(value.member) ? value.member : null;
|
|
557
|
+
const project = isPlainObject(value.project) ? value.project : null;
|
|
558
|
+
const agent = isPlainObject(value.agent) ? value.agent : null;
|
|
559
|
+
const memberUuid = member ? textValue(member.useruuid, 64) : undefined;
|
|
560
|
+
const projectId = project ? asString(project.projectid)?.trim() : undefined;
|
|
561
|
+
const agentGuid = agent ? textValue(agent.useragentguid, 64) : undefined;
|
|
562
|
+
const label = (entry) => (entry ? textValue(entry.label) : undefined);
|
|
563
|
+
return {
|
|
564
|
+
surface: value.surface,
|
|
565
|
+
...(memberUuid && UUID.test(memberUuid) ? { member: { uuid: memberUuid, ...(label(member) ? { name: label(member) } : {}) } } : {}),
|
|
566
|
+
...(projectId && PROJECT_ID.test(projectId) ? { project: { id: projectId, ...(label(project) ? { name: label(project) } : {}) } } : {}),
|
|
567
|
+
...(agentGuid && UUID.test(agentGuid) ? { agent: { guid: agentGuid, ...(label(agent) ? { name: label(agent) } : {}) } } : {}),
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
/** Why one rule decides the model as it does, as the end of a sentence about that rule. */
|
|
571
|
+
export function decisionReason(decision, labels) {
|
|
572
|
+
const label = decision.category && isCategory(decision.category) ? labels[decision.category] : decision.category;
|
|
573
|
+
if (decision.by === 'model')
|
|
574
|
+
return decision.decides === 'block' ? 'blocks this model by name' : 'allows this model by name';
|
|
575
|
+
if (decision.by === 'category') {
|
|
576
|
+
return decision.decides === 'block'
|
|
577
|
+
? `blocks ${label}, and this model is in it`
|
|
578
|
+
: `allows ${label}, and this model is in it`;
|
|
579
|
+
}
|
|
580
|
+
return decision.decides === 'block'
|
|
581
|
+
? 'lets only the models it names run, and this model is not one of them'
|
|
582
|
+
: 'does not name this model, and allows every model it does not name';
|
|
583
|
+
}
|
|
584
|
+
function rowsOf(value) {
|
|
585
|
+
return Array.isArray(value) ? value.filter(isPlainObject) : [];
|
|
586
|
+
}
|
|
587
|
+
/** The workspace's spend limits with this period's spending. Throws when they cannot be read. */
|
|
588
|
+
export async function readLimitList(client, signal) {
|
|
589
|
+
const body = requireApiSuccess(await client.post('/SpendLimit/List', {}, signal), 'The spend limits could not be read.');
|
|
590
|
+
const caller = toCaller(body.caller);
|
|
591
|
+
return {
|
|
592
|
+
workspace: toWorkspace(body.workspace),
|
|
593
|
+
...(caller ? { caller } : {}),
|
|
594
|
+
limits: rowsOf(body.limits).map(toLimitRow).filter((row) => row !== null),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
/** The workspace's Model Access rules and the categories a rule can name. Throws when they cannot be read. */
|
|
598
|
+
export async function readRuleList(client, signal) {
|
|
599
|
+
const body = requireApiSuccess(await client.post('/ModelAccess/List', {}, signal), 'The Model Access rules could not be read.');
|
|
600
|
+
const caller = toCaller(body.caller);
|
|
601
|
+
return {
|
|
602
|
+
workspace: toWorkspace(body.workspace),
|
|
603
|
+
...(caller ? { caller } : {}),
|
|
604
|
+
rules: rowsOf(body.rules).map(toRuleRow).filter((row) => row !== null),
|
|
605
|
+
labels: toCategoryLabels(body.categories),
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
const TARGET_FIELDS = ['member', 'project', 'surface', 'agent'];
|
|
609
|
+
/** Checks before any call that the target arguments fit the scope. Throws a sentence. */
|
|
610
|
+
export function checkTargetArguments(args) {
|
|
611
|
+
if (!args.scope) {
|
|
612
|
+
const given = TARGET_FIELDS.filter(field => args[field] !== undefined);
|
|
613
|
+
if (given.length > 0)
|
|
614
|
+
throw new Error(`\`${given[0]}\` names a target, so \`scope\` must say what it is: ${given[0]}.`);
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
for (const field of TARGET_FIELDS) {
|
|
618
|
+
if (args[field] === undefined || field === args.scope)
|
|
619
|
+
continue;
|
|
620
|
+
if (args.scope === 'account') {
|
|
621
|
+
throw new Error(`Scope account covers the whole wallet and takes no \`${field}\`. For one ${field}, use scope ${field}.`);
|
|
622
|
+
}
|
|
623
|
+
throw new Error(`\`${field}\` goes with scope ${field}, and this call has scope ${args.scope}: name its target with \`${args.scope}\`.`);
|
|
624
|
+
}
|
|
625
|
+
if (args.scope === 'member' && !args.member?.trim()) {
|
|
626
|
+
throw new Error('Scope member needs `member`: the team member\'s e-mail or user id.');
|
|
627
|
+
}
|
|
628
|
+
if (args.scope === 'surface' && !args.surface) {
|
|
629
|
+
throw new Error(`Scope surface needs \`surface\`: one of ${SURFACES.join(', ')}.`);
|
|
630
|
+
}
|
|
631
|
+
if (args.scope === 'agent' && !args.agent?.trim()) {
|
|
632
|
+
throw new Error('Scope agent needs `agent`: the agent\'s name or guid, as list_my_agents shows them.');
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
// Studio and the Workflow Agent are shared by every Wiro user, so no workspace has them as an agent of its own.
|
|
636
|
+
const HOUSE_AGENTS = /^(wiro[ -]?)?(studio|workflow[ -]?agent)$/i;
|
|
637
|
+
const HOUSE_AGENT_TEXT = 'Studio and the Workflow Agent are not agents of this workspace, so no limit or rule names them. '
|
|
638
|
+
+ 'Their chat model and the models they run for a person are checked like that person\'s own runs, against the '
|
|
639
|
+
+ 'controls of the whole wallet, the member, the API key the message came with and the surface it came in on. Use one '
|
|
640
|
+
+ 'of those scopes instead.';
|
|
641
|
+
/** This connection's own project: the one Wiro says the calls come with, or the listed project with its key. */
|
|
642
|
+
async function connectionProject(client, caller, signal) {
|
|
643
|
+
if (caller?.projectId)
|
|
644
|
+
return { id: caller.projectId, connected: true };
|
|
645
|
+
let projects;
|
|
646
|
+
try {
|
|
647
|
+
projects = await readProjects(client, signal);
|
|
648
|
+
}
|
|
649
|
+
catch (error) {
|
|
650
|
+
if (signal?.aborted)
|
|
651
|
+
throw error;
|
|
652
|
+
throw new Error(`The projects could not be read: ${keySafeErrorText(error)} Name the key's project with \`project\`.`);
|
|
653
|
+
}
|
|
654
|
+
const own = projects.find(project => project.view.connected);
|
|
655
|
+
if (!own)
|
|
656
|
+
throw new Error('This connection\'s project is not among the projects Wiro lists. Name the key\'s project with `project`.');
|
|
657
|
+
return { id: own.view.id, ...(own.view.name ? { name: own.view.name } : {}), connected: true };
|
|
658
|
+
}
|
|
659
|
+
async function projectByName(client, name, caller, signal) {
|
|
660
|
+
let projects;
|
|
661
|
+
try {
|
|
662
|
+
projects = await readProjects(client, signal);
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
if (signal?.aborted)
|
|
666
|
+
throw error;
|
|
667
|
+
throw new Error(`The projects could not be read: ${keySafeErrorText(error)} Name the project by its id instead.`);
|
|
668
|
+
}
|
|
669
|
+
const wanted = oneLine(name);
|
|
670
|
+
const exact = projects.filter(project => oneLine(project.view.name) === wanted);
|
|
671
|
+
const found = exact.length > 0 ? exact : projects.filter(project => oneLine(project.view.name).toLowerCase() === wanted.toLowerCase());
|
|
672
|
+
if (found.length === 0) {
|
|
673
|
+
throw new Error(`No project named ${quotedSpan(wanted)} is among this workspace's newest 100 projects. Name it by its id, `
|
|
674
|
+
+ 'as the Projects page of the Wiro dashboard shows it.');
|
|
675
|
+
}
|
|
676
|
+
if (found.length > 1) {
|
|
677
|
+
throw new Error(`${found.length} projects are named ${quotedSpan(wanted)}: ids ${found.map(project => quotedSpan(project.view.id)).join(', ')}. `
|
|
678
|
+
+ 'Name the one you mean by its id.');
|
|
679
|
+
}
|
|
680
|
+
const project = found[0];
|
|
681
|
+
return {
|
|
682
|
+
id: project.view.id,
|
|
683
|
+
...(project.view.name ? { name: project.view.name } : {}),
|
|
684
|
+
connected: project.view.connected || caller?.projectId === project.view.id,
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
/** A project named by its id or its exact name; left out, this connection's own. */
|
|
688
|
+
export async function resolveProject(client, value, caller, signal) {
|
|
689
|
+
const text = value?.trim();
|
|
690
|
+
if (!text)
|
|
691
|
+
return connectionProject(client, caller, signal);
|
|
692
|
+
if (PROJECT_ID.test(text))
|
|
693
|
+
return { id: text, connected: caller?.projectId === text };
|
|
694
|
+
return projectByName(client, text, caller, signal);
|
|
695
|
+
}
|
|
696
|
+
/** The active members of a team, in Wiro's order. Throws when they cannot be read. */
|
|
697
|
+
export async function readTeamMembers(client, teamGuid, signal) {
|
|
698
|
+
const body = requireApiSuccess(await client.post('/Team/Member/List', { teamguid: teamGuid }, signal), 'The team\'s members could not be read.');
|
|
699
|
+
return rowsOf(body.member).flatMap(row => {
|
|
700
|
+
const uuid = asString(row.useruuid)?.trim();
|
|
701
|
+
if (!uuid || row.status !== 'active')
|
|
702
|
+
return [];
|
|
703
|
+
const user = isPlainObject(row.user) ? row.user : {};
|
|
704
|
+
const fullName = [asString(user.firstname), asString(user.lastname)].filter(part => part?.trim()).join(' ');
|
|
705
|
+
const name = textValue(fullName);
|
|
706
|
+
const email = textValue(user.email);
|
|
707
|
+
const role = row.role === 'admin' || row.role === 'member' ? row.role : undefined;
|
|
708
|
+
return [{ uuid, ...(name ? { name } : {}), ...(email ? { email } : {}), ...(role ? { role } : {}) }];
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
/** A team member named by e-mail or user id. Only an e-mail needs the team's member list. */
|
|
712
|
+
export async function resolveMember(client, value, workspace, signal) {
|
|
713
|
+
if (workspace.kind === 'personal') {
|
|
714
|
+
throw new Error('Member limits and rules exist only in a team workspace, and the connected project is personal.');
|
|
715
|
+
}
|
|
716
|
+
const text = value.trim();
|
|
717
|
+
if (UUID.test(text))
|
|
718
|
+
return { uuid: text };
|
|
719
|
+
if (!text.includes('@'))
|
|
720
|
+
throw new Error('`member` takes the team member\'s e-mail or user id.');
|
|
721
|
+
if (!workspace.teamGuid)
|
|
722
|
+
throw new Error('The team of this connection is not known, so a member cannot be found by e-mail. Name the member by user id.');
|
|
723
|
+
let members;
|
|
724
|
+
try {
|
|
725
|
+
members = await readTeamMembers(client, workspace.teamGuid, signal);
|
|
726
|
+
}
|
|
727
|
+
catch (error) {
|
|
728
|
+
if (signal?.aborted)
|
|
729
|
+
throw error;
|
|
730
|
+
throw new Error(`The team's members could not be read: ${keySafeErrorText(error)} Name the member by user id instead.`);
|
|
731
|
+
}
|
|
732
|
+
const found = members.filter(member => member.email?.toLowerCase() === text.toLowerCase());
|
|
733
|
+
if (found.length === 0) {
|
|
734
|
+
throw new Error(`No active member of this team has the e-mail ${quotedSpan(text)}. get_controls with members true lists the team's members.`);
|
|
735
|
+
}
|
|
736
|
+
return { uuid: found[0].uuid, ...(found[0].name ? { name: found[0].name } : { name: text }) };
|
|
737
|
+
}
|
|
738
|
+
const AGENT_PAGE = 50;
|
|
739
|
+
const AGENT_PAGES = 4;
|
|
740
|
+
/** An agent of this workspace named by its guid or its exact name. */
|
|
741
|
+
export async function resolveAgent(client, value, signal) {
|
|
742
|
+
const text = oneLine(value);
|
|
743
|
+
if (UUID.test(text))
|
|
744
|
+
return { guid: text };
|
|
745
|
+
const rows = [];
|
|
746
|
+
try {
|
|
747
|
+
for (let page = 0; page < AGENT_PAGES; page += 1) {
|
|
748
|
+
const body = requireApiSuccess(await client.post('/UserAgent/MyAgents', {
|
|
749
|
+
sort: 'id',
|
|
750
|
+
order: 'DESC',
|
|
751
|
+
start: page * AGENT_PAGE,
|
|
752
|
+
limit: AGENT_PAGE,
|
|
753
|
+
}, signal), 'The agents could not be listed.');
|
|
754
|
+
const pageRows = rowsOf(body.useragents);
|
|
755
|
+
rows.push(...pageRows);
|
|
756
|
+
if (pageRows.length < AGENT_PAGE)
|
|
757
|
+
break;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
catch (error) {
|
|
761
|
+
if (signal?.aborted)
|
|
762
|
+
throw error;
|
|
763
|
+
throw new Error(`The agents could not be listed: ${keySafeErrorText(error)} Name the agent by its guid instead.`);
|
|
764
|
+
}
|
|
765
|
+
const agents = rows.flatMap(row => {
|
|
766
|
+
const guid = asString(row.guid);
|
|
767
|
+
return guid ? [{ guid, title: oneLine(asString(row.title) ?? '') }] : [];
|
|
768
|
+
});
|
|
769
|
+
const exact = agents.filter(agent => agent.title === text);
|
|
770
|
+
const found = exact.length > 0 ? exact : agents.filter(agent => agent.title.toLowerCase() === text.toLowerCase());
|
|
771
|
+
if (found.length === 0) {
|
|
772
|
+
// An agent of the workspace may be called Studio; only without one is the name Wiro's own agent.
|
|
773
|
+
if (HOUSE_AGENTS.test(text))
|
|
774
|
+
throw new Error(HOUSE_AGENT_TEXT);
|
|
775
|
+
throw new Error(`No agent named ${quotedSpan(text)} is in this workspace. list_my_agents lists the agents with their guids.`);
|
|
776
|
+
}
|
|
777
|
+
if (found.length > 1) {
|
|
778
|
+
throw new Error(`${found.length} agents are named ${quotedSpan(text)}: guids ${found.map(agent => quotedSpan(agent.guid)).join(', ')}. `
|
|
779
|
+
+ 'Name the one you mean by its guid.');
|
|
780
|
+
}
|
|
781
|
+
return { guid: found[0].guid, ...(found[0].title ? { name: found[0].title } : {}) };
|
|
782
|
+
}
|
|
783
|
+
/** A limit's or a rule's target from the manage tools' arguments: an e-mail, a name or this connection's key become ids. */
|
|
784
|
+
export async function resolveTarget(client, args, context, signal) {
|
|
785
|
+
switch (args.scope) {
|
|
786
|
+
case 'account':
|
|
787
|
+
return { scope: 'account', target: '', thisConnection: false };
|
|
788
|
+
case 'member': {
|
|
789
|
+
const member = await resolveMember(client, args.member ?? '', context.workspace, signal);
|
|
790
|
+
return { scope: 'member', target: member.uuid, ...(member.name ? { targetName: member.name } : {}), thisConnection: false };
|
|
791
|
+
}
|
|
792
|
+
case 'project': {
|
|
793
|
+
const project = await resolveProject(client, args.project, context.caller, signal);
|
|
794
|
+
return { scope: 'project', target: project.id, ...(project.name ? { targetName: project.name } : {}), thisConnection: project.connected };
|
|
795
|
+
}
|
|
796
|
+
case 'surface': {
|
|
797
|
+
const surface = args.surface;
|
|
798
|
+
return { scope: 'surface', target: surface, thisConnection: context.caller?.surface === surface };
|
|
799
|
+
}
|
|
800
|
+
case 'agent': {
|
|
801
|
+
const agent = await resolveAgent(client, args.agent ?? '', signal);
|
|
802
|
+
return { scope: 'agent', target: agent.guid, ...(agent.name ? { targetName: agent.name } : {}), thisConnection: false };
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
// A team guid as the dashboard takes it in a link; a link with any other value would name no workspace.
|
|
807
|
+
const LINKED_TEAM_GUID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
808
|
+
/**
|
|
809
|
+
* A Controls page of the Wiro dashboard, in the workspace it is about: ?workspace=<team guid> for a team, or
|
|
810
|
+
* ?workspace=personal for a personal account, opens the page in that workspace whichever one the browser is on.
|
|
811
|
+
* The page's plain address when the workspace is not known.
|
|
812
|
+
*/
|
|
813
|
+
export function controlsPageUrl(page, workspace) {
|
|
814
|
+
const url = page === 'spend-limits' ? SPEND_LIMITS_URL : MODEL_ACCESS_URL;
|
|
815
|
+
const named = workspace?.kind === 'personal'
|
|
816
|
+
? 'personal'
|
|
817
|
+
: workspace?.kind === 'team' && workspace.teamGuid && LINKED_TEAM_GUID.test(workspace.teamGuid) ? workspace.teamGuid : undefined;
|
|
818
|
+
return named ? `${url}?workspace=${named}` : url;
|
|
819
|
+
}
|
|
820
|
+
function pageText(page, workspace) {
|
|
821
|
+
const url = controlsPageUrl(page, workspace);
|
|
822
|
+
return page === 'spend-limits' ? `the Spend Limits page of the Wiro dashboard: ${url}` : `the Model Access page of the Wiro dashboard: ${url}`;
|
|
823
|
+
}
|
|
824
|
+
/** An older Wiro API has no change summary for controls, so no change goes through this server. */
|
|
825
|
+
export function previewMissingText(page, workspace) {
|
|
826
|
+
return `This change cannot be previewed right now, so it was not made and nothing was changed. It can be made on ${pageText(page, workspace)}.`;
|
|
827
|
+
}
|
|
828
|
+
/** An older Wiro API takes changes to controls only from a signed-in person. */
|
|
829
|
+
function keyRefusedText(page, workspace) {
|
|
830
|
+
return `This change cannot be made through this connection right now, so nothing was changed. It can be made on ${pageText(page, workspace)}.`;
|
|
831
|
+
}
|
|
832
|
+
/** The refusal an older Wiro API gives a change made with an API key. */
|
|
833
|
+
const KEY_CANNOT_CHANGE = /API keys can't manage teams or organizations/i;
|
|
834
|
+
/** Wiro's limit on how many changes API keys may make in an hour. */
|
|
835
|
+
const TOO_MANY_CHANGES = /Too many changes to Spend Limits and Model Access/i;
|
|
836
|
+
/** What Wiro answers for a route it does not have. */
|
|
837
|
+
const UNKNOWN_ROUTE = /^Parsing url error\.?$/i;
|
|
838
|
+
function withPeriod(text) {
|
|
839
|
+
const trimmed = text.trim();
|
|
840
|
+
return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
|
|
841
|
+
}
|
|
842
|
+
/** Wiro's refusal of a change, with what fixes it where that is known. */
|
|
843
|
+
export function refusalText(message) {
|
|
844
|
+
const text = withPeriod(message);
|
|
845
|
+
if (/ is not a model on Wiro\.$| is not a model's owner\/slug or id\.$/i.test(text)) {
|
|
846
|
+
return `${text} search_models finds a model's owner/slug. ${NOTHING_CHANGED}`;
|
|
847
|
+
}
|
|
848
|
+
if (/ is named twice\.$/i.test(text)) {
|
|
849
|
+
return `${text} Name each model once: a model the rule already holds is named as get_controls shows it, or by its id. ${NOTHING_CHANGED}`;
|
|
850
|
+
}
|
|
851
|
+
return `${text} ${NOTHING_CHANGED}`;
|
|
852
|
+
}
|
|
853
|
+
/** Why a read for a change failed, as one sentence that says nothing changed. */
|
|
854
|
+
export function readFailure(what, error) {
|
|
855
|
+
if (error instanceof ApiResultError)
|
|
856
|
+
return new Error(`${withPeriod(error.message)} ${NOTHING_CHANGED}`);
|
|
857
|
+
return new Error(`${what} could not be read (${keySafeErrorText(error)}), so ${NOTHING_CHANGED.toLowerCase()} Try again in a moment.`);
|
|
858
|
+
}
|
|
859
|
+
/** Why a change summary could not be made. A route the API does not have means the change cannot be previewed. */
|
|
860
|
+
export function previewFailure(error, page, workspace) {
|
|
861
|
+
if (error instanceof ApiResultError) {
|
|
862
|
+
return new Error(UNKNOWN_ROUTE.test(error.message.trim()) ? previewMissingText(page, workspace) : refusalText(error.message));
|
|
863
|
+
}
|
|
864
|
+
if (error instanceof WiroApiError && error.status === 404)
|
|
865
|
+
return new Error(previewMissingText(page, workspace));
|
|
866
|
+
const text = errorText(error);
|
|
867
|
+
if (TOO_MANY_CHANGES.test(text))
|
|
868
|
+
return new Error(`${withPeriod(text)} ${NOTHING_CHANGED}`);
|
|
869
|
+
if (error instanceof WiroApiError && error.status === 401 && KEY_CANNOT_CHANGE.test(text))
|
|
870
|
+
return new Error(keyRefusedText(page, workspace));
|
|
871
|
+
if (!isOutcomeUnknown(error))
|
|
872
|
+
return new Error(`${withPeriod(text)} ${NOTHING_CHANGED}`);
|
|
873
|
+
return new Error(`The change summary could not be made (${keySafeErrorText(error)}), so ${NOTHING_CHANGED.toLowerCase()} Try again in a moment.`);
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Why a change failed. A clean refusal changed nothing. Without a clear answer the change may have
|
|
877
|
+
* gone through, so `unknownText` says how to find out.
|
|
878
|
+
*/
|
|
879
|
+
export function changeFailure(error, page, unknownText, workspace) {
|
|
880
|
+
if (error instanceof ApiResultError)
|
|
881
|
+
return new Error(refusalText(error.message));
|
|
882
|
+
const text = errorText(error);
|
|
883
|
+
if (TOO_MANY_CHANGES.test(text))
|
|
884
|
+
return new Error(`${withPeriod(text)} ${NOTHING_CHANGED}`);
|
|
885
|
+
if (error instanceof WiroApiError && error.status === 401 && KEY_CANNOT_CHANGE.test(text))
|
|
886
|
+
return new Error(keyRefusedText(page, workspace));
|
|
887
|
+
if (error instanceof WiroApiError && error.status === 404)
|
|
888
|
+
return new Error(previewMissingText(page, workspace));
|
|
889
|
+
if (!isOutcomeUnknown(error))
|
|
890
|
+
return new Error(`${withPeriod(text)} ${NOTHING_CHANGED}`);
|
|
891
|
+
return new Error(`${keySafeErrorText(error)}\n\n${unknownText}`);
|
|
892
|
+
}
|
|
893
|
+
/** The sentence for a connection that may read controls but not change them. */
|
|
894
|
+
export function cannotChangeText(workspace, what, page) {
|
|
895
|
+
const url = controlsPageUrl(page, workspace);
|
|
896
|
+
if (workspace.kind === 'team') {
|
|
897
|
+
return `Only a team admin or the organization's owner can change this team's ${what}, and this connection acts as a team `
|
|
898
|
+
+ `member without those rights. ${NOTHING_CHANGED} Ask a team admin to do it, with their own connection or at ${url}.`;
|
|
899
|
+
}
|
|
900
|
+
return `This connection cannot change the ${what} of this workspace. ${NOTHING_CHANGED} The account owner can change them at ${url}.`;
|
|
901
|
+
}
|
|
902
|
+
export const dashboardSchema = z.object({
|
|
903
|
+
spendLimits: z.string(),
|
|
904
|
+
modelAccess: z.string(),
|
|
905
|
+
});
|
|
906
|
+
/** The Controls pages of the Wiro dashboard, in the given workspace where it is known. */
|
|
907
|
+
export function dashboardOf(workspace) {
|
|
908
|
+
return { spendLimits: controlsPageUrl('spend-limits', workspace), modelAccess: controlsPageUrl('model-access', workspace) };
|
|
909
|
+
}
|
|
910
|
+
//# sourceMappingURL=controls.js.map
|