loopctl-mcp-server 3.45.0 → 3.46.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.
@@ -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
+ }
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * `webhook_create` / `webhook_list` / `webhook_update` / `webhook_delete` / `webhook_test` /
3
+ * `webhook_deliveries` — `POST /api/v1/webhooks`, `GET /api/v1/webhooks`,
4
+ * `PATCH /api/v1/webhooks/:id`, `DELETE /api/v1/webhooks/:id`, `POST /api/v1/webhooks/:id/test`
5
+ * and `GET /api/v1/webhooks/:id/deliveries` (`WebhookController`), loopctl #872.
6
+ *
7
+ * KEY: the controller has ONE plug, `role: :user` WITH the hierarchy, so an agent or
8
+ * orchestrator key is 403 insufficient_role on every action. They travel on LOOPCTL_USER_KEY
9
+ * verbatim when set (index.js `userKeyApiCall`). Not human-anchored and not custody surface.
10
+ *
11
+ * THE SIGNING SECRET. Create answers the subscription's HMAC signing secret ONCE, and a tool
12
+ * result lands in the session transcript, so the secret NEVER appears in the result: it is
13
+ * written to `secret_file` (an absolute path that must not exist yet, created 0600 BEFORE the
14
+ * request, lib/secret-file.js) and stripped from the answer. A path that exists or a missing
15
+ * directory is refused with nothing created. Only a failure after the create (the write
16
+ * itself) can leave a subscription without its secret, and the result then names it to delete.
17
+ *
18
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
19
+ *
20
+ * - `page` / `page_size`: loopctl drops a non-integer and clamps `page_size` to 1..100 and
21
+ * `page` to at least 1, so an out-of-range value answers a page nobody asked for;
22
+ * - an update with no field, or with `project_id: null`: loopctl drops every nil field and
23
+ * answers 200 with the subscription unchanged (a subscription's project cannot be cleared);
24
+ * - `events` that is not a non-empty list of strings, `active` that is not a boolean;
25
+ * - a non-UUID webhook id, which would not answer the plain 404 a missing subscription does.
26
+ *
27
+ * Unknown event types, a bad URL and a destination the egress guard refuses are loopctl's to
28
+ * judge (422 with the reason), so they are sent.
29
+ */
30
+
31
+ import { isAbsolute } from "node:path";
32
+
33
+ import { uuid } from "./delivery-loop.js";
34
+ import { GATEWAY_STATUSES } from "./holder-journal.js";
35
+ import { createSecretFile } from "./secret-file.js";
36
+
37
+ export const WEBHOOK_MAX_PAGE_SIZE = 100;
38
+
39
+ function refuse(body) {
40
+ return { error: true, status: 0, body };
41
+ }
42
+
43
+ // ONE template literal per builder (see `test/tool-surface.js`).
44
+ export function webhooksPath(query = "") {
45
+ return `/api/v1/webhooks${query}`;
46
+ }
47
+
48
+ export function webhookPath(webhookId) {
49
+ return `/api/v1/webhooks/${encodeURIComponent(webhookId)}`;
50
+ }
51
+
52
+ export function webhookTestPath(webhookId) {
53
+ return `/api/v1/webhooks/${encodeURIComponent(webhookId)}/test`;
54
+ }
55
+
56
+ export function webhookDeliveriesPath(webhookId, query = "") {
57
+ return `/api/v1/webhooks/${encodeURIComponent(webhookId)}/deliveries${query}`;
58
+ }
59
+
60
+ function pageQuery(page, page_size, defaultSize) {
61
+ if (page != null && !(Number.isInteger(page) && page >= 1)) {
62
+ return { bad: refuse("`page` must be a positive integer.") };
63
+ }
64
+
65
+ if (
66
+ page_size != null &&
67
+ !(Number.isInteger(page_size) && page_size >= 1 && page_size <= WEBHOOK_MAX_PAGE_SIZE)
68
+ ) {
69
+ return {
70
+ bad: refuse(
71
+ `\`page_size\` must be an integer from 1 to ${WEBHOOK_MAX_PAGE_SIZE} (default ` +
72
+ `${defaultSize}); loopctl would clamp any other value without saying so.`,
73
+ ),
74
+ };
75
+ }
76
+
77
+ const params = new URLSearchParams();
78
+ if (page != null) params.set("page", String(page));
79
+ if (page_size != null) params.set("page_size", String(page_size));
80
+ const qs = params.toString();
81
+
82
+ return { query: qs === "" ? "" : `?${qs}` };
83
+ }
84
+
85
+ function badEvents(events) {
86
+ if (
87
+ !Array.isArray(events) ||
88
+ events.length === 0 ||
89
+ events.some((e) => typeof e !== "string" || e.trim() === "")
90
+ ) {
91
+ return refuse(
92
+ "`events` must be a non-empty list of event type strings (e.g. story.verified); " +
93
+ "loopctl answers 422 naming any it does not know.",
94
+ );
95
+ }
96
+ return null;
97
+ }
98
+
99
+ function badProjectId(project_id) {
100
+ if (typeof project_id !== "string" || project_id.trim() === "") {
101
+ return refuse(
102
+ "`project_id` must be a project's UUID, slug or repo name. A subscription's project " +
103
+ "cannot be cleared: loopctl drops a null and answers 200 unchanged.",
104
+ );
105
+ }
106
+ return null;
107
+ }
108
+
109
+ /**
110
+ * `deps.apiCall(method, path, body)` is the user-key caller; `deps.openSecret(path)` creates the
111
+ * file and returns `{ writeSecret(text), discardSecret() }` (lib/secret-file.js; injected so a
112
+ * test owns the disk it touches).
113
+ */
114
+ export async function webhookCreate(
115
+ { url, events, project_id, secret_file } = {},
116
+ { apiCall, openSecret = createSecretFile } = {},
117
+ ) {
118
+ if (typeof url !== "string" || url.trim() === "") {
119
+ return refuse("`url` is required: the HTTPS (or HTTP) URL deliveries are POSTed to.");
120
+ }
121
+
122
+ const eventsBad = badEvents(events);
123
+ if (eventsBad) return eventsBad;
124
+
125
+ if (project_id !== undefined) {
126
+ const bad = badProjectId(project_id);
127
+ if (bad) return bad;
128
+ }
129
+
130
+ if (typeof secret_file !== "string" || !isAbsolute(secret_file)) {
131
+ return refuse(
132
+ "`secret_file` must be an absolute path that does not exist yet. The signing secret is " +
133
+ "written there (mode 0600) and never returned, because a tool result lands in the " +
134
+ "transcript.",
135
+ );
136
+ }
137
+
138
+ let sink;
139
+ try {
140
+ sink = openSecret(secret_file);
141
+ } catch (error) {
142
+ return refuse(
143
+ `${secret_file} could not be created (${error.code || error.message}); nothing was ` +
144
+ "created. Pass a path that does not exist yet, in a directory that does.",
145
+ );
146
+ }
147
+
148
+ const body = { url, events };
149
+ if (project_id !== undefined) body.project_id = project_id;
150
+
151
+ let result;
152
+ try {
153
+ result = await apiCall("POST", webhooksPath(), body);
154
+ } catch (error) {
155
+ sink.discardSecret();
156
+ throw error;
157
+ }
158
+
159
+ const created = result && result.webhook;
160
+
161
+ if (!created || typeof created.signing_secret !== "string") {
162
+ sink.discardSecret();
163
+ return transportUnknown(result) ? mayHaveCreated(result, url) : stripSecret(result);
164
+ }
165
+
166
+ const { signing_secret, ...rest } = created;
167
+
168
+ try {
169
+ sink.writeSecret(signing_secret + "\n");
170
+ } catch (error) {
171
+ sink.discardSecret();
172
+ return {
173
+ error: true,
174
+ status: 0,
175
+ body:
176
+ `The webhook ${rest.id} was created but ${secret_file} could not be written ` +
177
+ `(${error.code || error.message}); its signing secret is lost and no delivery can be ` +
178
+ `verified. Delete it (webhook_delete ${rest.id}) and create another with a new ` +
179
+ "secret_file.",
180
+ };
181
+ }
182
+
183
+ return { webhook: rest, secret_file };
184
+ }
185
+
186
+ export async function webhookList({ page, page_size } = {}, { apiCall } = {}) {
187
+ const { bad, query } = pageQuery(page, page_size, 20);
188
+ if (bad) return bad;
189
+
190
+ return apiCall("GET", webhooksPath(query), null);
191
+ }
192
+
193
+ export async function webhookUpdate(
194
+ { webhook_id, url, events, project_id, active } = {},
195
+ { apiCall } = {},
196
+ ) {
197
+ const idBad = uuid(webhook_id, "webhook_id");
198
+ if (idBad) return idBad;
199
+
200
+ const body = {};
201
+
202
+ if (url !== undefined) {
203
+ if (typeof url !== "string" || url.trim() === "") {
204
+ return refuse("`url` must be a non-empty URL string.");
205
+ }
206
+ body.url = url;
207
+ }
208
+
209
+ if (events !== undefined) {
210
+ const bad = badEvents(events);
211
+ if (bad) return bad;
212
+ body.events = events;
213
+ }
214
+
215
+ if (project_id !== undefined) {
216
+ const bad = badProjectId(project_id);
217
+ if (bad) return bad;
218
+ body.project_id = project_id;
219
+ }
220
+
221
+ if (active !== undefined) {
222
+ if (typeof active !== "boolean") return refuse("`active` must be a boolean.");
223
+ body.active = active;
224
+ }
225
+
226
+ if (Object.keys(body).length === 0) {
227
+ return refuse(
228
+ "Name at least one of `url`, `events`, `project_id`, `active`: loopctl would answer 200 " +
229
+ "with the subscription unchanged.",
230
+ );
231
+ }
232
+
233
+ return apiCall("PATCH", webhookPath(webhook_id), body);
234
+ }
235
+
236
+ export async function webhookDelete({ webhook_id } = {}, { apiCall } = {}) {
237
+ return uuid(webhook_id, "webhook_id") ?? apiCall("DELETE", webhookPath(webhook_id), null);
238
+ }
239
+
240
+ export async function webhookTest({ webhook_id } = {}, { apiCall } = {}) {
241
+ return uuid(webhook_id, "webhook_id") ?? apiCall("POST", webhookTestPath(webhook_id), null);
242
+ }
243
+
244
+ export async function webhookDeliveries({ webhook_id, page, page_size } = {}, { apiCall } = {}) {
245
+ const idBad = uuid(webhook_id, "webhook_id");
246
+ if (idBad) return idBad;
247
+
248
+ const { bad, query } = pageQuery(page, page_size, 25);
249
+ if (bad) return bad;
250
+
251
+ return apiCall("GET", webhookDeliveriesPath(webhook_id, query), null);
252
+ }
253
+
254
+ // The outcome is unknown when the answer did not come from loopctl: status 0 is apiCall's
255
+ // transport failure (a timeout, a dropped connection), and a 502/503/504 is the proxy's. Either
256
+ // can follow a committed create. A status-0 refusal marked `not_sent` (no key configured) sent
257
+ // nothing, so it is an ordinary failure.
258
+ function transportUnknown(result) {
259
+ if (!result || !result.error) return false;
260
+ if (result.status === 0) return result.not_sent !== true;
261
+ return GATEWAY_STATUSES.includes(result.status);
262
+ }
263
+
264
+ function mayHaveCreated(result, url) {
265
+ return {
266
+ ...result,
267
+ body:
268
+ `${typeof result.body === "string" ? result.body : JSON.stringify(result.body)}. ` +
269
+ `The request may have created a webhook for ${url} whose signing secret is lost: list ` +
270
+ "the tenant's webhooks (webhook_list) and delete any for that URL before retrying.",
271
+ };
272
+ }
273
+
274
+ // A refusal body never carries the secret, but nothing from this route is passed on unread.
275
+ function stripSecret(result) {
276
+ if (result && result.webhook && "signing_secret" in result.webhook) {
277
+ const { signing_secret: _secret, ...rest } = result.webhook;
278
+ return { ...result, webhook: rest };
279
+ }
280
+ return result;
281
+ }