loopctl-mcp-server 3.45.0 → 3.46.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 +25 -1
- package/index.js +561 -7
- package/lib/anomaly-resolution.js +57 -0
- package/lib/api-keys.js +9 -13
- package/lib/cost-analytics.js +141 -0
- package/lib/secret-file.js +27 -0
- package/lib/token-budgets.js +131 -0
- package/lib/token-usage-admin.js +78 -0
- package/lib/webhooks.js +271 -0
- package/package.json +1 -1
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cost_anomaly_resolve` / `ingestion_anomaly_update` — `PATCH /api/v1/cost-anomalies/:id`
|
|
3
|
+
* (`CostAnomalyController.update`) and `PATCH /api/v1/ingestion-anomalies/:id`
|
|
4
|
+
* (`IngestionAnomalyController.update`), loopctl #872. `get_cost_anomalies` and
|
|
5
|
+
* `get_ingestion_anomalies` read them.
|
|
6
|
+
*
|
|
7
|
+
* KEY: both are `role: :user` with the hierarchy (cost anomaly resolution stays human work), so
|
|
8
|
+
* an agent or orchestrator key is 403 insufficient_role, and both sit behind
|
|
9
|
+
* `RequireHumanAnchor` (403 custody_tier_required on an agent-rooted tenant). They travel on
|
|
10
|
+
* LOOPCTL_USER_KEY verbatim when set (index.js `userKeyApiCall`).
|
|
11
|
+
*
|
|
12
|
+
* The cost route takes no body: it marks the anomaly resolved. The ingestion route's action is
|
|
13
|
+
* its `archived` query parameter: absent resolves, `true` archives (hides it from the default
|
|
14
|
+
* list and suppresses re-detection for a retired source_type), `false` un-archives (restores
|
|
15
|
+
* monitoring). Both answer 404 for an anomaly that is missing or another tenant's.
|
|
16
|
+
*
|
|
17
|
+
* CHECKED HERE: a non-UUID anomaly id, which would not answer the plain 404 a missing anomaly
|
|
18
|
+
* does, and an ingestion `action` outside resolve / archive / unarchive.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { uuid } from "./delivery-loop.js";
|
|
22
|
+
|
|
23
|
+
export const INGESTION_ANOMALY_ACTIONS = ["resolve", "archive", "unarchive"];
|
|
24
|
+
|
|
25
|
+
function refuse(body) {
|
|
26
|
+
return { error: true, status: 0, body };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ONE template literal per builder (see `test/tool-surface.js`).
|
|
30
|
+
export function costAnomalyPath(anomalyId) {
|
|
31
|
+
return `/api/v1/cost-anomalies/${encodeURIComponent(anomalyId)}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function ingestionAnomalyPath(anomalyId, query = "") {
|
|
35
|
+
return `/api/v1/ingestion-anomalies/${encodeURIComponent(anomalyId)}${query}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function costAnomalyResolve({ anomaly_id } = {}, { apiCall } = {}) {
|
|
39
|
+
return uuid(anomaly_id, "anomaly_id") ?? apiCall("PATCH", costAnomalyPath(anomaly_id), null);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function ingestionAnomalyUpdate(
|
|
43
|
+
{ anomaly_id, action = "resolve" } = {},
|
|
44
|
+
{ apiCall } = {},
|
|
45
|
+
) {
|
|
46
|
+
const idBad = uuid(anomaly_id, "anomaly_id");
|
|
47
|
+
if (idBad) return idBad;
|
|
48
|
+
|
|
49
|
+
if (!INGESTION_ANOMALY_ACTIONS.includes(action)) {
|
|
50
|
+
return refuse(`\`action\` is one of: ${INGESTION_ANOMALY_ACTIONS.join(", ")} (default resolve).`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const query =
|
|
54
|
+
action === "archive" ? "?archived=true" : action === "unarchive" ? "?archived=false" : "";
|
|
55
|
+
|
|
56
|
+
return apiCall("PATCH", ingestionAnomalyPath(anomaly_id, query), null);
|
|
57
|
+
}
|
package/lib/api-keys.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
import { isAbsolute } from "node:path";
|
|
16
16
|
|
|
17
17
|
import { uuid } from "./delivery-loop.js";
|
|
18
|
-
import { createSecretFile } from "./secret-file.js";
|
|
18
|
+
import { createSecretFile, secretOutcomeUnknown, unknownOutcomeDetail } from "./secret-file.js";
|
|
19
19
|
|
|
20
20
|
export const API_KEY_ROLES = ["user", "orchestrator", "agent"];
|
|
21
21
|
|
|
@@ -78,7 +78,7 @@ export async function apiKeyCreate(
|
|
|
78
78
|
|
|
79
79
|
if (!created || typeof created.raw_key !== "string") {
|
|
80
80
|
sink.discardSecret();
|
|
81
|
-
return
|
|
81
|
+
return secretOutcomeUnknown(result) ? mayHaveMinted(result, name) : stripRaw(result);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
const { raw_key, ...rest } = created;
|
|
@@ -215,7 +215,7 @@ export async function apiKeyRotate(
|
|
|
215
215
|
|
|
216
216
|
if (!minted || typeof minted.raw_key !== "string") {
|
|
217
217
|
sink.discardSecret();
|
|
218
|
-
return
|
|
218
|
+
return secretOutcomeUnknown(result) ? mayHaveRotated(result, api_key_id) : result;
|
|
219
219
|
}
|
|
220
220
|
|
|
221
221
|
const { raw_key, ...rest } = minted;
|
|
@@ -240,9 +240,10 @@ export async function apiKeyRotate(
|
|
|
240
240
|
|
|
241
241
|
function mayHaveRotated(result, keyId) {
|
|
242
242
|
return {
|
|
243
|
-
|
|
243
|
+
error: true,
|
|
244
|
+
status: result && Number.isInteger(result.status) ? result.status : 0,
|
|
244
245
|
body:
|
|
245
|
-
|
|
246
|
+
`Rotation outcome unknown (${unknownOutcomeDetail(result)}). ` +
|
|
246
247
|
`The request may have rotated ${keyId}, minting a replacement whose raw value is lost, ` +
|
|
247
248
|
`and if it did, ${keyId} now expires when its grace period ends. Before then, list the ` +
|
|
248
249
|
"tenant's keys (api_key_list) and, if a second key by that name appeared, revoke it and " +
|
|
@@ -251,17 +252,12 @@ function mayHaveRotated(result, keyId) {
|
|
|
251
252
|
};
|
|
252
253
|
}
|
|
253
254
|
|
|
254
|
-
// status 0 is apiCall's transport failure (a timeout, a dropped connection): the server may
|
|
255
|
-
// have committed the mint before the answer was lost.
|
|
256
|
-
function transportUnknown(result) {
|
|
257
|
-
return Boolean(result && result.error && result.status === 0);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
255
|
function mayHaveMinted(result, name) {
|
|
261
256
|
return {
|
|
262
|
-
|
|
257
|
+
error: true,
|
|
258
|
+
status: result && Number.isInteger(result.status) ? result.status : 0,
|
|
263
259
|
body:
|
|
264
|
-
|
|
260
|
+
`Mint outcome unknown (${unknownOutcomeDetail(result)}). ` +
|
|
265
261
|
`The request may have minted a key named "${name}" whose raw value is lost: list the ` +
|
|
266
262
|
"tenant's keys (GET /api/v1/api_keys) and revoke any by that name before retrying.",
|
|
267
263
|
};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `cost_trends` / `model_mix` / `agent_model_profile` — `GET /api/v1/analytics/trends`,
|
|
3
|
+
* `GET /api/v1/analytics/model-mix` and `GET /api/v1/analytics/agents/:id/model-profile`
|
|
4
|
+
* (`AnalyticsController`), loopctl #872.
|
|
5
|
+
*
|
|
6
|
+
* KEY: all three are `role: :orchestrator` WITH the hierarchy, so an agent key is 403
|
|
7
|
+
* insufficient_role. They travel on LOOPCTL_ORCH_KEY, else LOOPCTL_USER_KEY, sent verbatim
|
|
8
|
+
* when set (index.js `orchestratorPinnedApiCall`). Read-only; empty data when nothing was
|
|
9
|
+
* reported.
|
|
10
|
+
*
|
|
11
|
+
* `project_id` may be a UUID, a slug or the repo directory name (loopctl resolves it); one that
|
|
12
|
+
* names no project is 422. The model profile answers 404 for an agent that is not this
|
|
13
|
+
* tenant's.
|
|
14
|
+
*
|
|
15
|
+
* CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
|
|
16
|
+
*
|
|
17
|
+
* - `since` / `until` that are not a real `YYYY-MM-DD` date: loopctl DROPS an unparseable
|
|
18
|
+
* date, widening the read to all time;
|
|
19
|
+
* - trends' `granularity` outside daily / weekly: loopctl answers daily for anything else;
|
|
20
|
+
* - trends' `page` / `page_size`: a non-integer is dropped and `page_size` clamped to 1..100;
|
|
21
|
+
* - a non-UUID `agent_id`, which is not a filter loopctl can run (a cast error, not a 422).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { uuid } from "./delivery-loop.js";
|
|
25
|
+
|
|
26
|
+
export const TREND_GRANULARITIES = ["daily", "weekly"];
|
|
27
|
+
|
|
28
|
+
function refuse(body) {
|
|
29
|
+
return { error: true, status: 0, body };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// ONE template literal per builder (see `test/tool-surface.js`).
|
|
33
|
+
export function costTrendsPath(query = "") {
|
|
34
|
+
return `/api/v1/analytics/trends${query}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function modelMixPath(query = "") {
|
|
38
|
+
return `/api/v1/analytics/model-mix${query}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function agentModelProfilePath(agentId, query = "") {
|
|
42
|
+
return `/api/v1/analytics/agents/${encodeURIComponent(agentId)}/model-profile${query}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
46
|
+
|
|
47
|
+
function realDate(value) {
|
|
48
|
+
const m = typeof value === "string" ? DATE_RE.exec(value) : null;
|
|
49
|
+
if (!m) return false;
|
|
50
|
+
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
51
|
+
const date = new Date(Date.UTC(y, mo - 1, d));
|
|
52
|
+
return date.getUTCFullYear() === y && date.getUTCMonth() === mo - 1 && date.getUTCDate() === d;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The shared filters: project, date range. Returns `{ bad }` or `{ params }`.
|
|
56
|
+
function commonFilters({ project_id, since, until }) {
|
|
57
|
+
if (project_id != null && (typeof project_id !== "string" || project_id.trim() === "")) {
|
|
58
|
+
return { bad: refuse("`project_id` must be a project's UUID, slug or repo name.") };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const [field, value] of [
|
|
62
|
+
["since", since],
|
|
63
|
+
["until", until],
|
|
64
|
+
]) {
|
|
65
|
+
if (value != null && !realDate(value)) {
|
|
66
|
+
return {
|
|
67
|
+
bad: refuse(
|
|
68
|
+
`\`${field}\` must be a real date as YYYY-MM-DD. loopctl drops a date it cannot ` +
|
|
69
|
+
"parse and would answer for all time.",
|
|
70
|
+
),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const params = new URLSearchParams();
|
|
76
|
+
if (project_id != null) params.set("project_id", project_id);
|
|
77
|
+
if (since != null) params.set("since", since);
|
|
78
|
+
if (until != null) params.set("until", until);
|
|
79
|
+
|
|
80
|
+
return { params };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function asQuery(params) {
|
|
84
|
+
const qs = params.toString();
|
|
85
|
+
return qs === "" ? "" : `?${qs}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function costTrends(
|
|
89
|
+
{ granularity, project_id, since, until, page, page_size } = {},
|
|
90
|
+
{ apiCall } = {},
|
|
91
|
+
) {
|
|
92
|
+
if (granularity != null && !TREND_GRANULARITIES.includes(granularity)) {
|
|
93
|
+
return refuse(
|
|
94
|
+
`\`granularity\` is one of: ${TREND_GRANULARITIES.join(", ")} (default daily); loopctl ` +
|
|
95
|
+
"would answer daily for any other value.",
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const { bad, params } = commonFilters({ project_id, since, until });
|
|
100
|
+
if (bad) return bad;
|
|
101
|
+
|
|
102
|
+
if (page != null && !(Number.isInteger(page) && page >= 1)) {
|
|
103
|
+
return refuse("`page` must be a positive integer.");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (page_size != null && !(Number.isInteger(page_size) && page_size >= 1 && page_size <= 100)) {
|
|
107
|
+
return refuse("`page_size` must be an integer from 1 to 100 (default 20).");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (granularity != null) params.set("granularity", granularity);
|
|
111
|
+
if (page != null) params.set("page", String(page));
|
|
112
|
+
if (page_size != null) params.set("page_size", String(page_size));
|
|
113
|
+
|
|
114
|
+
return apiCall("GET", costTrendsPath(asQuery(params)), null);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function modelMix({ project_id, agent_id, since, until } = {}, { apiCall } = {}) {
|
|
118
|
+
const { bad, params } = commonFilters({ project_id, since, until });
|
|
119
|
+
if (bad) return bad;
|
|
120
|
+
|
|
121
|
+
if (agent_id != null) {
|
|
122
|
+
const agentBad = uuid(agent_id, "agent_id");
|
|
123
|
+
if (agentBad) return agentBad;
|
|
124
|
+
params.set("agent_id", agent_id);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return apiCall("GET", modelMixPath(asQuery(params)), null);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function agentModelProfile(
|
|
131
|
+
{ agent_id, project_id, since, until } = {},
|
|
132
|
+
{ apiCall } = {},
|
|
133
|
+
) {
|
|
134
|
+
const agentBad = uuid(agent_id, "agent_id");
|
|
135
|
+
if (agentBad) return agentBad;
|
|
136
|
+
|
|
137
|
+
const { bad, params } = commonFilters({ project_id, since, until });
|
|
138
|
+
if (bad) return bad;
|
|
139
|
+
|
|
140
|
+
return apiCall("GET", agentModelProfilePath(agent_id, asQuery(params)), null);
|
|
141
|
+
}
|
package/lib/secret-file.js
CHANGED
|
@@ -12,6 +12,33 @@
|
|
|
12
12
|
|
|
13
13
|
import { closeSync, openSync, unlinkSync, writeSync } from "node:fs";
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Whether a request that should have produced a secret, and did not hand one over, may still
|
|
17
|
+
* have created the record that holds it. Only two answers are certain that nothing was created:
|
|
18
|
+
* a 4xx refusal from loopctl, and a status-0 refusal marked `not_sent` (index.js `sendRequest`,
|
|
19
|
+
* no key configured), which sent nothing. Every other answer may follow a committed create: a
|
|
20
|
+
* transport failure (status 0), a proxy's 502/503/504, a 500 raised after the insert, and a 2xx
|
|
21
|
+
* whose body failed to parse or lacked the secret. Same rule as `lib/runners.js`
|
|
22
|
+
* (`ambiguousEnrollment`): only a 4xx is an unambiguous refusal.
|
|
23
|
+
*/
|
|
24
|
+
export function secretOutcomeUnknown(result) {
|
|
25
|
+
if (result && result.error === true && result.not_sent === true) return false;
|
|
26
|
+
const status = result && Number.isInteger(result.status) ? result.status : undefined;
|
|
27
|
+
return !(result && result.error === true && status >= 400 && status < 500);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* What to say about an unknown outcome without echoing the answer: any body other than a
|
|
32
|
+
* transport error's message may be the created record itself, secret included (a truncated
|
|
33
|
+
* 2xx arrives as `{error: true, status: 201, body: "<raw text>"}`).
|
|
34
|
+
*/
|
|
35
|
+
export function unknownOutcomeDetail(result) {
|
|
36
|
+
const status = result && Number.isInteger(result.status) ? result.status : undefined;
|
|
37
|
+
return status === 0 && typeof result.body === "string"
|
|
38
|
+
? result.body
|
|
39
|
+
: `HTTP ${status ?? "?"}; response body withheld: it may contain the secret`;
|
|
40
|
+
}
|
|
41
|
+
|
|
15
42
|
export function createSecretFile(path) {
|
|
16
43
|
const fd = openSync(path, "wx", 0o600);
|
|
17
44
|
let open = true;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `token_budget_list` / `token_budget_get` / `token_budget_update` / `token_budget_delete` —
|
|
3
|
+
* `GET /api/v1/token-budgets`, `GET /api/v1/token-budgets/:id`,
|
|
4
|
+
* `PATCH /api/v1/token-budgets/:id` and `DELETE /api/v1/token-budgets/:id`
|
|
5
|
+
* (`TokenBudgetController`), loopctl #872. `set_token_budget` creates one.
|
|
6
|
+
*
|
|
7
|
+
* KEYS, from the controller's plugs:
|
|
8
|
+
*
|
|
9
|
+
* - list and show are `role: :agent` with the hierarchy: any key. They travel on the
|
|
10
|
+
* session's own key (index.js `ownKeyApiCall`).
|
|
11
|
+
* - update is `role: :orchestrator` with the hierarchy, so an agent key is 403
|
|
12
|
+
* insufficient_role. It travels on LOOPCTL_ORCH_KEY, else LOOPCTL_USER_KEY, sent verbatim
|
|
13
|
+
* when set (index.js `orchestratorPinnedApiCall`).
|
|
14
|
+
* - delete is `role: :user` with the hierarchy, so an agent or orchestrator key is 403
|
|
15
|
+
* insufficient_role. It travels on LOOPCTL_USER_KEY verbatim when set (`userKeyApiCall`).
|
|
16
|
+
* - update and delete are also behind `RequireHumanAnchor`: 403 custody_tier_required on an
|
|
17
|
+
* agent-rooted tenant.
|
|
18
|
+
*
|
|
19
|
+
* CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
|
|
20
|
+
*
|
|
21
|
+
* - list's `scope_type`: an unknown value answers an EMPTY list, which reads as "no budgets";
|
|
22
|
+
* - list's `scope_id`: a non-UUID is not a filter loopctl can run (a cast error, not a 422);
|
|
23
|
+
* - list's `page` / `page_size`: a non-integer is dropped and `page_size` clamped to 1..100;
|
|
24
|
+
* - an update with no field, or naming `scope_type` / `scope_id`: loopctl casts neither (a
|
|
25
|
+
* budget's scope is fixed) and answers 200 with the budget unchanged;
|
|
26
|
+
* - update's `metadata` when it is not an object;
|
|
27
|
+
* - a non-UUID budget id, which would not answer the plain 404 a missing budget does.
|
|
28
|
+
*
|
|
29
|
+
* Out-of-range amounts (`budget_millicents` not above 0, a token limit below 0, a threshold
|
|
30
|
+
* outside 1..100) are loopctl's to judge: 422 with the field named.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { uuid } from "./delivery-loop.js";
|
|
34
|
+
|
|
35
|
+
export const BUDGET_SCOPE_TYPES = ["project", "epic", "story"];
|
|
36
|
+
export const BUDGET_UPDATE_FIELDS = [
|
|
37
|
+
"budget_millicents",
|
|
38
|
+
"budget_input_tokens",
|
|
39
|
+
"budget_output_tokens",
|
|
40
|
+
"alert_threshold_pct",
|
|
41
|
+
"metadata",
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
function refuse(body) {
|
|
45
|
+
return { error: true, status: 0, body };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ONE template literal per builder (see `test/tool-surface.js`).
|
|
49
|
+
export function tokenBudgetsPath(query = "") {
|
|
50
|
+
return `/api/v1/token-budgets${query}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function tokenBudgetPath(budgetId) {
|
|
54
|
+
return `/api/v1/token-budgets/${encodeURIComponent(budgetId)}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function tokenBudgetList(
|
|
58
|
+
{ scope_type, scope_id, page, page_size } = {},
|
|
59
|
+
{ apiCall } = {},
|
|
60
|
+
) {
|
|
61
|
+
if (scope_type != null && !BUDGET_SCOPE_TYPES.includes(scope_type)) {
|
|
62
|
+
return refuse(
|
|
63
|
+
`\`scope_type\` is one of: ${BUDGET_SCOPE_TYPES.join(", ")}. loopctl would answer an ` +
|
|
64
|
+
"empty list for any other value.",
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (scope_id != null) {
|
|
69
|
+
const bad = uuid(scope_id, "scope_id");
|
|
70
|
+
if (bad) return bad;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (page != null && !(Number.isInteger(page) && page >= 1)) {
|
|
74
|
+
return refuse("`page` must be a positive integer.");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (page_size != null && !(Number.isInteger(page_size) && page_size >= 1 && page_size <= 100)) {
|
|
78
|
+
return refuse("`page_size` must be an integer from 1 to 100 (default 20).");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const params = new URLSearchParams();
|
|
82
|
+
if (scope_type != null) params.set("scope_type", scope_type);
|
|
83
|
+
if (scope_id != null) params.set("scope_id", scope_id);
|
|
84
|
+
if (page != null) params.set("page", String(page));
|
|
85
|
+
if (page_size != null) params.set("page_size", String(page_size));
|
|
86
|
+
const qs = params.toString();
|
|
87
|
+
|
|
88
|
+
return apiCall("GET", tokenBudgetsPath(qs === "" ? "" : `?${qs}`), null);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function tokenBudgetGet({ budget_id } = {}, { apiCall } = {}) {
|
|
92
|
+
return uuid(budget_id, "budget_id") ?? apiCall("GET", tokenBudgetPath(budget_id), null);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function tokenBudgetUpdate(args = {}, { apiCall } = {}) {
|
|
96
|
+
const { budget_id } = args;
|
|
97
|
+
const idBad = uuid(budget_id, "budget_id");
|
|
98
|
+
if (idBad) return idBad;
|
|
99
|
+
|
|
100
|
+
for (const fixed of ["scope_type", "scope_id"]) {
|
|
101
|
+
if (args[fixed] !== undefined) {
|
|
102
|
+
return refuse(
|
|
103
|
+
`\`${fixed}\` cannot change: a budget's scope is fixed, and loopctl would ignore it ` +
|
|
104
|
+
"and answer 200. Delete the budget and create one for the other scope.",
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const { metadata } = args;
|
|
110
|
+
if (metadata !== undefined && (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))) {
|
|
111
|
+
return refuse("`metadata` must be an object.");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const body = {};
|
|
115
|
+
for (const field of BUDGET_UPDATE_FIELDS) {
|
|
116
|
+
if (args[field] !== undefined) body[field] = args[field];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (Object.keys(body).length === 0) {
|
|
120
|
+
return refuse(
|
|
121
|
+
`Name at least one of ${BUDGET_UPDATE_FIELDS.map((f) => `\`${f}\``).join(", ")}: ` +
|
|
122
|
+
"loopctl would answer 200 with the budget unchanged.",
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return apiCall("PATCH", tokenBudgetPath(budget_id), body);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function tokenBudgetDelete({ budget_id } = {}, { apiCall } = {}) {
|
|
130
|
+
return uuid(budget_id, "budget_id") ?? apiCall("DELETE", tokenBudgetPath(budget_id), null);
|
|
131
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `token_usage_delete` / `token_usage_correct` — `DELETE /api/v1/token-usage/:id` and
|
|
3
|
+
* `POST /api/v1/token-usage/:id/correction` (`TokenUsageController`), loopctl #872.
|
|
4
|
+
*
|
|
5
|
+
* KEY: both are `role: :user` with the hierarchy (budget and token corrections stay human
|
|
6
|
+
* work), so an agent or orchestrator key is 403 insufficient_role, and both sit behind
|
|
7
|
+
* `RequireHumanAnchor` (403 custody_tier_required on an agent-rooted tenant). They travel on
|
|
8
|
+
* LOOPCTL_USER_KEY verbatim when set (index.js `userKeyApiCall`).
|
|
9
|
+
*
|
|
10
|
+
* Delete is a SOFT delete (`deleted_at`): the report leaves every total and analytics read, and
|
|
11
|
+
* budget warning flags reset when spend drops back under them. 404 for a report that is
|
|
12
|
+
* missing, another tenant's or already deleted.
|
|
13
|
+
*
|
|
14
|
+
* A correction is a NEW report that references the original and carries signed deltas:
|
|
15
|
+
* negative `input_tokens`, `output_tokens` and `cost_millicents` subtract from the story's
|
|
16
|
+
* totals. 404 for an original that is missing, another tenant's or deleted; 422 when the
|
|
17
|
+
* correction would drive any total below 0, when the original is itself a correction, or for a
|
|
18
|
+
* `skill_version_id` that is not this tenant's.
|
|
19
|
+
*
|
|
20
|
+
* CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
|
|
21
|
+
*
|
|
22
|
+
* - a non-UUID report id, which would not answer the plain 404 a missing report does;
|
|
23
|
+
* - a correction whose three deltas are not integers (all three are required; send 0 for a
|
|
24
|
+
* field that does not change), or whose `metadata` is not an object.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { uuid } from "./delivery-loop.js";
|
|
28
|
+
|
|
29
|
+
export const CORRECTION_DELTAS = ["input_tokens", "output_tokens", "cost_millicents"];
|
|
30
|
+
export const CORRECTION_OPTIONAL = ["model_name", "phase", "session_id", "skill_version_id", "metadata"];
|
|
31
|
+
|
|
32
|
+
function refuse(body) {
|
|
33
|
+
return { error: true, status: 0, body };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ONE template literal per builder (see `test/tool-surface.js`).
|
|
37
|
+
export function tokenUsageReportPath(reportId) {
|
|
38
|
+
return `/api/v1/token-usage/${encodeURIComponent(reportId)}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function tokenUsageCorrectionPath(reportId) {
|
|
42
|
+
return `/api/v1/token-usage/${encodeURIComponent(reportId)}/correction`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function tokenUsageDelete({ report_id } = {}, { apiCall } = {}) {
|
|
46
|
+
return uuid(report_id, "report_id") ?? apiCall("DELETE", tokenUsageReportPath(report_id), null);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function tokenUsageCorrect(args = {}, { apiCall } = {}) {
|
|
50
|
+
const { report_id, metadata } = args;
|
|
51
|
+
const idBad = uuid(report_id, "report_id");
|
|
52
|
+
if (idBad) return idBad;
|
|
53
|
+
|
|
54
|
+
for (const field of CORRECTION_DELTAS) {
|
|
55
|
+
if (!Number.isInteger(args[field])) {
|
|
56
|
+
return refuse(
|
|
57
|
+
`\`${field}\` is required, an integer delta (negative subtracts; 0 for no change). ` +
|
|
58
|
+
`All of ${CORRECTION_DELTAS.map((f) => `\`${f}\``).join(", ")} are required.`,
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (metadata !== undefined && (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))) {
|
|
64
|
+
return refuse("`metadata` must be an object.");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (args.skill_version_id !== undefined) {
|
|
68
|
+
const bad = uuid(args.skill_version_id, "skill_version_id");
|
|
69
|
+
if (bad) return bad;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const body = {};
|
|
73
|
+
for (const field of [...CORRECTION_DELTAS, ...CORRECTION_OPTIONAL]) {
|
|
74
|
+
if (args[field] !== undefined) body[field] = args[field];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return apiCall("POST", tokenUsageCorrectionPath(report_id), body);
|
|
78
|
+
}
|