@jini-ai/devops 0.6.20 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/checks/coverage/disk.js +2 -2
  3. package/dist/checks/coverage/floors.js +2 -2
  4. package/dist/checks/coverage/lcov.d.ts +15 -1
  5. package/dist/checks/coverage/lcov.js +77 -7
  6. package/dist/core/deploy-types.d.ts +15 -0
  7. package/dist/core/export-failure-summary.d.ts +9 -2
  8. package/dist/deploy/config-contracts.d.ts +82 -0
  9. package/dist/deploy/config-contracts.js +7 -0
  10. package/dist/deploy/config-descriptors.d.ts +47 -0
  11. package/dist/deploy/config-descriptors.js +92 -0
  12. package/dist/deploy/index.d.ts +13 -0
  13. package/dist/deploy/index.js +13 -0
  14. package/dist/deploy/ops-contracts.d.ts +168 -0
  15. package/dist/deploy/ops-contracts.js +2 -0
  16. package/dist/deploy/ops-descriptors.d.ts +23 -0
  17. package/dist/deploy/ops-descriptors.js +77 -0
  18. package/dist/deploy/ops-registry.d.ts +7 -0
  19. package/dist/deploy/ops-registry.js +15 -0
  20. package/dist/deploy/ops-runner.d.ts +103 -0
  21. package/dist/deploy/ops-runner.js +343 -0
  22. package/dist/deploy/ops-secret-card.d.ts +13 -0
  23. package/dist/deploy/ops-secret-card.js +62 -0
  24. package/dist/deploy/ops-secrets.d.ts +74 -0
  25. package/dist/deploy/ops-secrets.js +221 -0
  26. package/dist/deploy/ops-tool-contracts.d.ts +223 -0
  27. package/dist/deploy/ops-tool-contracts.js +2 -0
  28. package/dist/deploy/ops-tools.d.ts +8 -0
  29. package/dist/deploy/ops-tools.js +117 -0
  30. package/dist/deploy/publish-jobs.d.ts +72 -0
  31. package/dist/deploy/publish-jobs.js +75 -0
  32. package/dist/deploy/target-contracts.d.ts +231 -0
  33. package/dist/deploy/target-contracts.js +2 -0
  34. package/dist/deploy/target-descriptors.d.ts +23 -0
  35. package/dist/deploy/target-descriptors.js +273 -0
  36. package/dist/local-dev/node-runtime.d.ts +3 -1
  37. package/dist/local-dev/node-runtime.js +4 -4
  38. package/dist/static-export/contracts.d.ts +3 -0
  39. package/dist/static-export/runner.js +2 -1
  40. package/package.json +6 -6
@@ -0,0 +1,343 @@
1
+ // Mechanical extraction provenance is recorded in this package's source-map.md.
2
+ import { nowIso } from '@jini-ai/core/primitives';
3
+ import { ToolInputError } from '@jini-ai/core';
4
+ import { requireDeployPlatform } from './ops-registry.js';
5
+ /** Response text is capped before parsing; the credential layer has already redacted secrets. */
6
+ export const MAX_RESPONSE_CHARS = 256_000;
7
+ /** The daemon applies no default tool timeout; this tool owns its 300s deadline and cancellation. */
8
+ export const MAX_WAIT_SECONDS = 300;
9
+ /** One module pause is short; a module that needs longer must poll, so cancellation stays prompt. */
10
+ export const MAX_MODULE_SLEEP_MS = 5_000;
11
+ const systemClock = {
12
+ now: () => performance.now(),
13
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
14
+ if (signal?.aborted) {
15
+ reject(aborted());
16
+ return;
17
+ }
18
+ const finish = () => { signal?.removeEventListener("abort", onAbort); resolve(); };
19
+ const timer = setTimeout(finish, ms);
20
+ const onAbort = () => { clearTimeout(timer); signal?.removeEventListener("abort", onAbort); reject(aborted()); };
21
+ signal?.addEventListener("abort", onAbort, { once: true });
22
+ }),
23
+ };
24
+ export const aborted = () => new ToolInputError({ message: "Deployment ops wait was aborted." });
25
+ const TIMEOUT = Symbol("deployment ops timeout");
26
+ // Neutral HTTPS origin syntax, independent of any host endpoint.
27
+ const HTTPS_PROTOCOL = "https:";
28
+ const HTTPS_AUTHORITY = `${HTTPS_PROTOCOL}//`;
29
+ /** Internal control signal caught at the registration boundary; tools return the diagnostic. */
30
+ export class DeployCredentialSetupRequired extends ToolInputError {
31
+ credentialSetup;
32
+ constructor({ message, credentialSetup }, _optional = {}) {
33
+ super({ message });
34
+ this.credentialSetup = credentialSetup;
35
+ }
36
+ }
37
+ /** Resolve by explicit label or exactly one saved host match, without decrypting. O(credentials). */
38
+ async function credentialLabel(deps, platform, explicit) {
39
+ const credentials = await deps.credentials.list({}, {});
40
+ if (explicit !== undefined) {
41
+ if (!credentials.some(c => c.label === explicit))
42
+ throw new DeployCredentialSetupRequired(deps.recovery.setupRequired({ label: explicit, baseUrl: `${HTTPS_AUTHORITY}${platform.descriptor.hosts[0]}` }), {});
43
+ return explicit;
44
+ }
45
+ const host = platform.descriptor.hosts[0];
46
+ const matches = credentials.filter(c => c.allowedOrigins.includes(`${HTTPS_AUTHORITY}${host}`));
47
+ if (matches.length === 0)
48
+ throw new DeployCredentialSetupRequired(deps.recovery.setupRequired({ label: platform.descriptor.id, baseUrl: `${HTTPS_AUTHORITY}${host}` }), {});
49
+ if (matches.length !== 1)
50
+ throw new ToolInputError({ message: deps.messages.severalCredentials({ host, labels: matches.map(c => c.label).sort() }) });
51
+ return matches[0].label;
52
+ }
53
+ function requirePlatformUrl({ rawUrl, platform }, _optional = {}) {
54
+ let url;
55
+ try {
56
+ url = new URL(rawUrl);
57
+ }
58
+ catch {
59
+ throw new ToolInputError({ message: "Deployment ops module supplied an invalid URL." });
60
+ }
61
+ const unsafeAuthority = url.username || url.password || url.port;
62
+ if (url.protocol !== "https:" || unsafeAuthority || !platform.descriptor.hosts.includes(url.hostname))
63
+ throw new ToolInputError({ message: `Deployment ops platform '${platform.descriptor.id}' does not allow host '${url.hostname}'.` });
64
+ return url;
65
+ }
66
+ /** Validate both independent host bindings before any credentialed request. */
67
+ async function requireBoundUrl({ rawUrl, platform, deps, workspaceId, label }, _optional = {}) {
68
+ const url = requirePlatformUrl({ rawUrl, platform }, {});
69
+ try {
70
+ await deps.credentials.resolveTarget({ workspaceId, label, url: rawUrl }, {});
71
+ }
72
+ catch (error) {
73
+ const category = deps.credentials.classifyError({ error }, {}).category;
74
+ if (category === "validation")
75
+ throw new ToolInputError({ message: `Credential '${label}' does not allow host '${url.hostname}'. Add that host to the saved credential or choose another credentialLabel.` });
76
+ if (category === "not-found")
77
+ throw new ToolInputError({ message: deps.messages.noSavedCredential({ label }) });
78
+ throw error;
79
+ }
80
+ return url;
81
+ }
82
+ /** Translate only known credential/transport failures without echoing provider payloads. */
83
+ function requestFailure({ deps, error, signal, method, host, label }, _optional = {}) {
84
+ if (signal?.aborted)
85
+ return aborted();
86
+ const category = deps.credentials.classifyError({ error }, {}).category;
87
+ if (category === "egress-refused")
88
+ return new ToolInputError({ message: `Deployment ops host '${host}' was refused by outbound HTTP policy. Use a public HTTPS endpoint allowed by the saved credential.` });
89
+ if (category === "transport")
90
+ return new ToolInputError({ message: method === "GET" ? `Could not reach deployment ops host '${host}' using credential '${label}'. Retry the check.` : `Lost the connection to deployment ops host '${host}' during a ${method}; it may or may not have been accepted. Check ${deps.toolIds.status} before retrying.` });
91
+ if (category === "validation" || category === "not-found")
92
+ return new ToolInputError({ message: `Credential '${label}' changed or no longer allows host '${host}'. Check its saved hosts or choose another credentialLabel.` });
93
+ return error;
94
+ }
95
+ /** Response text is bounded before parsing; clipped JSON must remain text. */
96
+ function normalizeResponse({ deps, response, transportTruncated, host, label }, _optional = {}) {
97
+ if (response.status === 401 || response.status === 403)
98
+ throw new ToolInputError({ message: `Credential '${label}' was rejected (HTTP ${response.status}). Run ${deps.toolIds.credentialVerify} with label '${label}' and check its saved token/scopes.` });
99
+ if (response.status < 200 || response.status >= 300)
100
+ throw new ToolInputError({ message: `Deployment ops host '${host}' returned HTTP ${response.status}. Check the target and retry; redirects are not followed.` });
101
+ const text = response.bodyText.slice(0, MAX_RESPONSE_CHARS);
102
+ const truncated = transportTruncated || response.bodyText.length > MAX_RESPONSE_CHARS;
103
+ let json;
104
+ if (!truncated) {
105
+ try {
106
+ json = JSON.parse(text);
107
+ }
108
+ catch { /* Plain logs are valid text. */ }
109
+ }
110
+ return { status: response.status, ...(json !== undefined ? { json } : {}), text, truncated };
111
+ }
112
+ /**
113
+ * Bound GET/write facade. Both the platform and saved credential must allow the exact HTTPS origin.
114
+ * `allowDelete` is set only by the secret-removal verb, so no other verb's module can send a DELETE.
115
+ */
116
+ /** @agent-note The request port must recheck abort at actual I/O after asynchronous auth-scheme loading. */
117
+ export async function boundContext({ deps, platform, explicit }, { signal, allowDelete } = {}) {
118
+ if (!deps.credentials.available)
119
+ throw new ToolInputError({ message: "Deployment ops HTTP client is unavailable. Restart the site to rebuild its tool dependencies." });
120
+ const label = await credentialLabel(deps, platform, explicit);
121
+ /** One guarded path for every method, so a write can never get a looser binding than a read. */
122
+ const call = async (method, rawUrl, body) => {
123
+ if (signal?.aborted)
124
+ throw aborted();
125
+ const url = await requireBoundUrl({ rawUrl, platform, deps, workspaceId: deps.workspaceId, label }, {});
126
+ if (signal?.aborted)
127
+ throw aborted();
128
+ let response;
129
+ // `content-type` only with a body: some APIs refuse a bodyless DELETE/POST that claims JSON.
130
+ let write = {};
131
+ if (method !== "GET") {
132
+ write = body === undefined ? { headers: { accept: "application/json" } }
133
+ : { headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) };
134
+ }
135
+ try {
136
+ response = await deps.credentials.request({ workspaceId: deps.workspaceId, label, method, url: rawUrl, maxResponseBytes: MAX_RESPONSE_CHARS }, { ...write, signal });
137
+ }
138
+ catch (error) {
139
+ throw requestFailure({ deps, error, signal, method, host: url.hostname, label }, {});
140
+ }
141
+ if (signal?.aborted)
142
+ throw aborted();
143
+ return normalizeResponse({ deps, response, transportTruncated: response.bodyTruncated, host: url.hostname, label }, {});
144
+ };
145
+ return {
146
+ nowIso: () => nowIso({ clock: deps.clock }),
147
+ fail: message => { throw new ToolInputError({ message: message }); },
148
+ sleep: ms => (deps.waitClock ?? systemClock).sleep(Math.min(Math.max(0, Number(ms) || 0), MAX_MODULE_SLEEP_MS), signal),
149
+ get: rawUrl => call("GET", rawUrl),
150
+ send: input => {
151
+ if (![...["POST", "PATCH", "PUT"], ...(allowDelete ? ["DELETE"] : [])].includes(input.method))
152
+ throw new ToolInputError({ message: `Deployment ops module supplied unsupported method '${String(input.method)}'.` });
153
+ return call(input.method, input.url, input.body);
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * Read through a freshly gated installed adapter, passing only a bound GET facade to the module.
159
+ * @param deps - Saved-credential ports, audited HTTP client with redirects disabled, and test seams.
160
+ * @param input - Platform, target, optional credential label and operation-specific selectors.
161
+ * @param operation - Selects the normalized status, logs or target-list result.
162
+ * @param signal - Cancels before further requests and propagates to the transport.
163
+ * @throws {ToolInputError} Unknown platforms, credential/host/auth failures or cancelled requests.
164
+ * @complexity Time: O(credentials + response size) plus bounded adapter requests. Space: O(response size).
165
+ * @example await runDeployOps(deps, { platform: platformId, target: targetId }, "status", signal);
166
+ */
167
+ export async function runDeployOps({ deps, input, operation }, { signal }) {
168
+ if (signal?.aborted)
169
+ throw aborted();
170
+ const registry = await deps.loadDeployOps({ workspaceId: deps.workspaceId });
171
+ const platform = requireDeployPlatform({ registry, id: input.platform }, {});
172
+ if (operation === "listTargets" && !platform.module.listTargets)
173
+ throw new ToolInputError({ message: `Deployment ops platform '${input.platform}' does not support listing targets. Supply a target for ${deps.toolIds.status}.` });
174
+ const ctx = await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal });
175
+ if (signal?.aborted)
176
+ throw aborted();
177
+ if (operation === "listTargets")
178
+ return platform.module.listTargets(ctx, { org: input.org });
179
+ if (operation === "logs")
180
+ return platform.module.logs(ctx, { ...input, limit: input.limit ?? 100 });
181
+ return platform.module.status(ctx, input);
182
+ }
183
+ const clip = (value) => String(value).slice(0, 2000);
184
+ function validateDeployResult({ input, result }, _optional = {}) {
185
+ if (typeof result?.started !== "boolean" || typeof result.summary !== "string")
186
+ throw new ToolInputError({ message: `Deployment ops platform '${input.platform}' returned an invalid deploy result.` });
187
+ if (result.runId !== undefined && !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(String(result.runId)))
188
+ throw new ToolInputError({ message: `Deployment ops platform '${input.platform}' returned an invalid run id.` });
189
+ }
190
+ /** Keep only the documented fields; platform/target come from the request, never from the module. O(machineIds). */
191
+ function normalizeDeployResult(input, result) {
192
+ validateDeployResult({ input, result }, {});
193
+ return {
194
+ platform: input.platform, target: input.target, started: result.started, summary: clip(result.summary),
195
+ ...(result.runId !== undefined ? { runId: String(result.runId) } : {}),
196
+ ...(typeof result.sha === "string" ? { sha: clip(result.sha) } : {}),
197
+ ...(Array.isArray(result.machineIds) ? { machineIds: result.machineIds.slice(0, 32).map(clip) } : {}),
198
+ ...(typeof result.image === "string" ? { image: clip(result.image) } : {}),
199
+ ...(typeof result.url === "string" && result.url.startsWith(HTTPS_AUTHORITY) ? { url: clip(result.url) } : {}),
200
+ };
201
+ }
202
+ /**
203
+ * Start a deploy through a freshly gated installed adapter. The chat tool and the admin route both call this.
204
+ * @param required - `deps`: saved-credential ports and the no-redirect HTTP client; `input`: platform, target, optional ref and credential label.
205
+ * @param optional - `signal` cancels before further requests and propagates to the transport.
206
+ * @returns The normalized accepted-deploy result; landing is observed afterwards with status/wait.
207
+ * @throws {ToolInputError} Unknown or observe-only platforms, credential/host/auth failures, invalid module results, or cancellation.
208
+ * @complexity Time: O(credentials + response size) plus bounded adapter requests. Space: O(response size).
209
+ * @example await runDeploy({ deps, input: { platform: "my-host", target: "owner/repo", ref: "main" } }, { signal });
210
+ */
211
+ export async function runDeploy(required, optional = {}) {
212
+ const { deps, input } = required;
213
+ const { signal } = optional;
214
+ if (signal?.aborted)
215
+ throw aborted();
216
+ const registry = await deps.loadDeployOps({ workspaceId: deps.workspaceId });
217
+ const platform = requireDeployPlatform({ registry, id: input.platform }, {});
218
+ if (!platform.module.deploy) {
219
+ const deployable = registry.list().filter(p => typeof p.module.deploy === "function").map(p => p.descriptor.id);
220
+ throw new ToolInputError({ message: `Deployment ops platform '${input.platform}' cannot deploy; it is observe-only. Platforms that can deploy: ${deployable.join(", ") || "(none)"}.` });
221
+ }
222
+ const ctx = await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal });
223
+ if (signal?.aborted)
224
+ throw aborted();
225
+ const adapterInput = await deployAdapterInput({ deps, input });
226
+ const result = await platform.module.deploy(ctx, adapterInput);
227
+ const normalized = normalizeDeployResult(input, result);
228
+ if (normalized.started)
229
+ await recordAcceptedDeploy({ deps, platform, normalized }, {});
230
+ return normalized;
231
+ }
232
+ async function recordAcceptedDeploy({ deps, platform, normalized }, _optional = {}) {
233
+ // Accepted requests are successful dispatches, not proof of a healthy landing. Preserve that
234
+ // distinction in status; never invent a URL when the adapter cannot supply one.
235
+ // Status may describe an older healthy run (runId is optional), so acceptance stays pending.
236
+ if (deps.publishHistoryStore) {
237
+ try {
238
+ await deps.publishHistoryStore.recordSuccess({ workspaceId: deps.workspaceId, entry: {
239
+ kind: "deploy", target: platform.descriptor.id, projectName: normalized.target, url: normalized.url ?? "",
240
+ reachable: false, status: "started", publishedAt: nowIso({ clock: deps.clock }), triggeredBy: "agent_tool",
241
+ } });
242
+ }
243
+ catch {
244
+ // Dispatch already succeeded; never turn a ledger failure into a duplicate deploy retry.
245
+ // No raw error: database parameters can contain credentials or provider response data.
246
+ console.warn("[deploy-ops] destination history write failed after accepted deploy");
247
+ }
248
+ }
249
+ }
250
+ /** Race an in-flight status against the deadline and cancellation. Listeners/timers always cleaned up.
251
+ * The signal is never already aborted here: the one caller chain (`waitForDeployOps` ->
252
+ * `pollBeforeDeadline`) checks `signal.aborted` and reaches this function synchronously, with no await
253
+ * in between, so a pre-aborted guard here could never fire and was removed. */
254
+ async function boundedPoll(status, remaining, signal) {
255
+ const controller = new AbortController();
256
+ let timer;
257
+ let onAbort;
258
+ const stopped = new Promise((_, reject) => {
259
+ onAbort = () => { controller.abort(); reject(aborted()); };
260
+ signal?.addEventListener("abort", onAbort, { once: true });
261
+ timer = setTimeout(() => { controller.abort(); reject(TIMEOUT); }, remaining);
262
+ });
263
+ try {
264
+ return await Promise.race([status(controller.signal), stopped]);
265
+ }
266
+ finally {
267
+ if (timer) {
268
+ clearTimeout(timer);
269
+ }
270
+ if (onAbort) {
271
+ signal?.removeEventListener("abort", onAbort);
272
+ }
273
+ }
274
+ }
275
+ async function pollBeforeDeadline({ status, clock, deadline }, { signal } = {}) {
276
+ try {
277
+ const observation = await boundedPoll(status, deadline - clock.now(), signal);
278
+ if (signal?.aborted)
279
+ throw aborted();
280
+ return observation;
281
+ }
282
+ catch (error) {
283
+ if (error === TIMEOUT) {
284
+ return TIMEOUT;
285
+ }
286
+ throw error;
287
+ }
288
+ }
289
+ function reachedCondition({ until, state }, _optional = {}) {
290
+ return until === "healthy" ? state === "healthy" : ["healthy", "failing", "stopped"].includes(state);
291
+ }
292
+ async function sleepBeforeDeadline({ clock, deadline }, { signal } = {}) {
293
+ const remaining = deadline - clock.now();
294
+ if (remaining > 0)
295
+ await clock.sleep(Math.min(10_000, remaining), signal);
296
+ }
297
+ function waitSettings({ deps, input }, _optional = {}) {
298
+ const clock = deps.clock ?? systemClock;
299
+ const started = clock.now();
300
+ const deadline = started + (input.timeoutSeconds ?? 180) * 1000;
301
+ const initial = deps.initial ?? { platform: "unknown", target: "unknown", state: "unknown", summary: "No status received before timeout.", items: [], checkedAt: "" };
302
+ return { clock, started, deadline, initial };
303
+ }
304
+ /**
305
+ * Poll immediately and every 10s, bounding sleeps and in-flight polls by the remaining deadline.
306
+ * @param deps - Status reader, optional monotonic clock/sleep seam, and initial unknown observation.
307
+ * @param input - Desired condition, timeout (default 180s; validated by the tool handler), and abort signal.
308
+ * @returns Reached flag, elapsed seconds, attempted poll count and last observation; timeout is a result.
309
+ * @throws {ToolInputError} Cancellation or a refusal from the status reader.
310
+ * @complexity Time: O(timeout / 10s) polls. Space: O(one status response).
311
+ * @example await waitForDeployOps({ status }, { until: "healthy", timeoutSeconds: 180, signal });
312
+ */
313
+ export async function waitForDeployOps(deps, input) {
314
+ const { clock, started, deadline, initial } = waitSettings({ deps, input }, {});
315
+ let polls = 0;
316
+ let last = initial;
317
+ const result = (reached) => ({ reached, waitedSeconds: Math.min((clock.now() - started) / 1000, (deadline - started) / 1000), polls, last });
318
+ while (clock.now() < deadline) {
319
+ if (input.signal?.aborted)
320
+ throw aborted();
321
+ polls++;
322
+ const observation = await pollBeforeDeadline({ status: deps.status, clock, deadline }, { signal: input.signal });
323
+ if (observation === TIMEOUT)
324
+ return result(false);
325
+ last = observation;
326
+ if (clock.now() > deadline)
327
+ return result(false);
328
+ if (reachedCondition({ until: input.until, state: last.state }, {}))
329
+ return result(true);
330
+ await sleepBeforeDeadline({ clock, deadline }, { signal: input.signal });
331
+ }
332
+ if (input.signal?.aborted)
333
+ throw aborted();
334
+ return result(false);
335
+ }
336
+ /** Pass active workflow choices per invocation without changing ordinary adapter input shapes. */
337
+ async function deployAdapterInput({ deps, input }, _options = {}) {
338
+ const workflowFiles = await deps.loadDeployWorkflowFiles?.({ workspaceId: deps.workspaceId });
339
+ return { target: input.target, ...(input.ref === undefined ? {} : { ref: input.ref }),
340
+ ...(input.workflowFile === undefined ? {} : { workflowFile: input.workflowFile }),
341
+ ...(workflowFiles === undefined ? {} : { workflowFiles }) };
342
+ }
343
+ //# sourceMappingURL=ops-runner.js.map
@@ -0,0 +1,13 @@
1
+ import { type ToolExecutionContext, type ToolExecutionOptions } from '@jini-ai/core';
2
+ import type { DeployOpsRuntime, DeployOpsSecretCards, SecretConfirm, SetSecretInput } from './ops-tool-contracts.js';
3
+ /** Only the human card receives the value. Neither source nor the model-facing result carries it. */
4
+ export declare function collectTypedDeploySecret({ ctx, deps, cards, input, permit }: {
5
+ ctx: ToolExecutionContext;
6
+ deps: DeployOpsRuntime;
7
+ cards: DeployOpsSecretCards;
8
+ input: SetSecretInput;
9
+ permit: () => Promise<void>;
10
+ }, { emitSurface, confirm }?: ToolExecutionOptions & {
11
+ confirm?: SecretConfirm | undefined;
12
+ }): Promise<unknown>;
13
+ //# sourceMappingURL=ops-secret-card.d.ts.map
@@ -0,0 +1,62 @@
1
+ // Mechanical extraction provenance is recorded in this package's source-map.md.
2
+ import { ToolInputError } from '@jini-ai/core';
3
+ import { requireDeployPlatform } from './ops-registry.js';
4
+ import { boundContext, DeployCredentialSetupRequired } from './ops-runner.js';
5
+ import { runSetSecret } from './ops-secrets.js';
6
+ /** Only the human card receives the value. Neither source nor the model-facing result carries it. */
7
+ export async function collectTypedDeploySecret({ ctx, deps, cards, input, permit }, { emitSurface, confirm } = {}) {
8
+ if (!cards.surfaceExchanges)
9
+ throw new ToolInputError({ message: cards.noEmitter });
10
+ let locale = cards.defaultLocale;
11
+ const title = `${input.name} · ${input.target}`;
12
+ const card = cards.defineSecretCardTool({
13
+ toolId: deps.toolIds.setSecret,
14
+ prepare: async () => {
15
+ if (ctx.signal.aborted)
16
+ return { locale };
17
+ // Resolve the host credential before collecting another secret, so recovery opens that card first.
18
+ const registry = await deps.loadDeployOps({ workspaceId: deps.workspaceId });
19
+ const platform = requireDeployPlatform({ registry, id: input.platform }, {});
20
+ if (!platform.module.setSecret)
21
+ throw new ToolInputError({ message: "This platform has no secrets adapter." });
22
+ await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal: ctx.signal });
23
+ locale = await cards.locale({ ctx });
24
+ return { locale };
25
+ },
26
+ form: ({ prep }) => cards.form({ locale: prep.locale, title }),
27
+ save: async ({ values, signal }) => {
28
+ try {
29
+ await permit();
30
+ // No trim: provider secrets may contain intentional whitespace and newlines.
31
+ const result = await runSetSecret({ deps, input }, { signal, confirm, typedValue: values.value });
32
+ return { result, saved: result.changed === true || result.comparison === "same" };
33
+ }
34
+ catch (error) {
35
+ if (error instanceof DeployCredentialSetupRequired)
36
+ return { result: { executed: false, credentialSetup: error.credentialSetup }, saved: false, recovery: true };
37
+ throw error;
38
+ }
39
+ },
40
+ result: ({ prep, run }) => {
41
+ if (run.status === "saved")
42
+ return run.saved.result;
43
+ if (run.status === "failed" || run.status === "blank")
44
+ return { changed: false, message: cards.text({ id: "storage", locale: prep.locale }) };
45
+ return { changed: false, cancelled: true };
46
+ },
47
+ outcome: ({ prep, run }) => {
48
+ if (run.status === "saved" && run.saved.recovery)
49
+ return undefined;
50
+ if (run.status !== "saved" && run.status !== "failed" && run.status !== "blank")
51
+ return undefined;
52
+ const saved = run.status === "saved" && run.saved.saved;
53
+ return { title, state: saved ? "success" : "failure", message: cards.text({ id: saved ? "savedTitle" : "storage", locale: prep.locale }) };
54
+ },
55
+ }, {
56
+ uriHost: cards.uriHost, text: { noEmitter: cards.noEmitter },
57
+ // Vendor and adapter errors can echo the just-submitted value. Return fixed text only.
58
+ safeError: () => cards.text({ id: "storage", locale }),
59
+ });
60
+ return card.handler({ surfaceExchanges: cards.surfaceExchanges, askThenReport: cards.askThenReport })(ctx, emitSurface ? { emitSurface } : {});
61
+ }
62
+ //# sourceMappingURL=ops-secret-card.js.map
@@ -0,0 +1,74 @@
1
+ import type { DeployOpsRuntime, SecretTargetInput, SetSecretInput, UnsetSecretInput, SecretConfirm, SetSecretResult, UnsetSecretResult } from './ops-tool-contracts.js';
2
+ import type { DeployOpsSecretInfo } from './ops-contracts.js';
3
+ /**
4
+ * @file Generic host-secrets verbs (owner 2026-10-05: "a tool that sets and unsets secrets ... not just
5
+ * for one host ... it should work for really any vendor"). Vendors are adapters exported by the trusted
6
+ * deploy plugin's deploy-ops modules (`listSecrets`/`setSecret`/`unsetSecret`, optional `readSecret`);
7
+ * this file owns everything vendor-neutral: the value source, the compare-before-write, the human
8
+ * confirmation before an overwrite or removal, and a result that never carries a secret value.
9
+ *
10
+ * A value never comes from the model. `source` names where the server reads it: this site's own key
11
+ * (`site-key`), or another secret on the same target (`secret`, copied vendor side through
12
+ * `readSecret`). Values stay inside this process: the audit records metadata only, and the result
13
+ * reports a one-way fingerprint.
14
+ */
15
+ export declare const SECRET_NAME_PATTERN: RegExp;
16
+ /**
17
+ * List a target's secret names with the vendor's digest and update time; never a value.
18
+ * @param required - `deps`: saved-credential ports and the no-redirect client; `input`: platform, target, optional credential label.
19
+ * @param optional - `signal` cancels before further requests.
20
+ * @returns Names, vendor digests, update times, truncation and when writes take effect.
21
+ * @throws {ToolInputError} Unknown or secrets-less platforms, credential/host/auth failures, malformed adapter output.
22
+ * @complexity Time and space: O(credentials + secrets).
23
+ * @example await runListSecrets({ deps, input: { platform: "my-host", target: "my-app" } });
24
+ */
25
+ export declare function runListSecrets(required: {
26
+ deps: DeployOpsRuntime;
27
+ input: SecretTargetInput;
28
+ }, optional?: {
29
+ signal?: AbortSignal | undefined;
30
+ }): Promise<{
31
+ appliesOn: import("./ops-contracts.js").DeployOpsSecretAppliesOn;
32
+ supportsStaging: boolean;
33
+ deployNeeded: boolean;
34
+ secrets: DeployOpsSecretInfo[];
35
+ truncated: boolean;
36
+ platform: string;
37
+ target: string;
38
+ }>;
39
+ /**
40
+ * Set one secret on a host target from a server-side source; skips the write when the value is already there.
41
+ * @param required - `deps`: credential ports, no-redirect client, site-key reader; `input`: platform, target, name, source, optional dryRun and credential label.
42
+ * @param optional - `signal` cancels; `confirm` asks a human before an existing secret is replaced.
43
+ * @returns changed, comparison, the value's fingerprint, when it applies, and an optional vendor version. Never the value.
44
+ * @throws {ToolInputError} Invalid names, unusable sources, secrets-less platforms, credential/host/auth failures, or an overwrite with no confirm channel.
45
+ * @complexity Time: O(credentials + secrets + value length) plus at most four adapter requests. Space: O(secrets).
46
+ * @example await runSetSecret({ deps, input: { platform: "my-host", target: "my-app", name: "APP_SITE_KEY", source: { kind: "site-key" } } }, { confirm });
47
+ */
48
+ /** @agent-note The confirm callback must approve the frozen overwrite request through an authenticated human answer. */
49
+ export declare function runSetSecret(required: {
50
+ deps: DeployOpsRuntime;
51
+ input: SetSecretInput;
52
+ }, optional?: {
53
+ signal?: AbortSignal | undefined;
54
+ confirm?: SecretConfirm | undefined;
55
+ typedValue?: unknown;
56
+ }): Promise<SetSecretResult>;
57
+ /**
58
+ * Remove one secret from a host target after a human confirms; an absent name is reported, not deleted.
59
+ * @param required - `deps`: credential ports and the no-redirect client; `input`: platform, target, name, optional credential label.
60
+ * @param optional - `signal` cancels; `confirm` is required for an actual removal.
61
+ * @returns removed, when the removal applies, and an optional vendor version.
62
+ * @throws {ToolInputError} Invalid names, secrets-less platforms, credential/host/auth failures, or no confirm channel.
63
+ * @complexity Time and space: O(credentials + secrets) plus at most three adapter requests.
64
+ * @example await runUnsetSecret({ deps, input: { platform: "my-host", target: "my-app", name: "OLD_KEY" } }, { confirm });
65
+ */
66
+ /** @agent-note The confirm callback must approve the frozen removal request through an authenticated human answer. */
67
+ export declare function runUnsetSecret(required: {
68
+ deps: DeployOpsRuntime;
69
+ input: UnsetSecretInput;
70
+ }, optional?: {
71
+ signal?: AbortSignal | undefined;
72
+ confirm?: SecretConfirm | undefined;
73
+ }): Promise<UnsetSecretResult>;
74
+ //# sourceMappingURL=ops-secrets.d.ts.map