@jini-ai/devops 0.6.22 → 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 (37) hide show
  1. package/CHANGELOG.md +17 -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/export-failure-summary.d.ts +9 -2
  7. package/dist/deploy/config-contracts.d.ts +82 -0
  8. package/dist/deploy/config-contracts.js +7 -0
  9. package/dist/deploy/config-descriptors.d.ts +47 -0
  10. package/dist/deploy/config-descriptors.js +92 -0
  11. package/dist/deploy/index.d.ts +12 -0
  12. package/dist/deploy/index.js +12 -0
  13. package/dist/deploy/ops-contracts.d.ts +168 -0
  14. package/dist/deploy/ops-contracts.js +2 -0
  15. package/dist/deploy/ops-descriptors.d.ts +23 -0
  16. package/dist/deploy/ops-descriptors.js +77 -0
  17. package/dist/deploy/ops-registry.d.ts +7 -0
  18. package/dist/deploy/ops-registry.js +15 -0
  19. package/dist/deploy/ops-runner.d.ts +103 -0
  20. package/dist/deploy/ops-runner.js +343 -0
  21. package/dist/deploy/ops-secret-card.d.ts +13 -0
  22. package/dist/deploy/ops-secret-card.js +62 -0
  23. package/dist/deploy/ops-secrets.d.ts +74 -0
  24. package/dist/deploy/ops-secrets.js +221 -0
  25. package/dist/deploy/ops-tool-contracts.d.ts +223 -0
  26. package/dist/deploy/ops-tool-contracts.js +2 -0
  27. package/dist/deploy/ops-tools.d.ts +8 -0
  28. package/dist/deploy/ops-tools.js +117 -0
  29. package/dist/deploy/target-contracts.d.ts +231 -0
  30. package/dist/deploy/target-contracts.js +2 -0
  31. package/dist/deploy/target-descriptors.d.ts +23 -0
  32. package/dist/deploy/target-descriptors.js +273 -0
  33. package/dist/local-dev/node-runtime.d.ts +3 -1
  34. package/dist/local-dev/node-runtime.js +4 -4
  35. package/dist/static-export/contracts.d.ts +3 -0
  36. package/dist/static-export/runner.js +2 -1
  37. package/package.json +6 -6
@@ -0,0 +1,221 @@
1
+ // Mechanical extraction provenance is recorded in this package's source-map.md.
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { createHash, timingSafeEqual } from 'node:crypto';
4
+ import { ToolInputError } from '@jini-ai/core';
5
+ import { requireDeployPlatform } from './ops-registry.js';
6
+ import { aborted, boundContext } from './ops-runner.js';
7
+ /**
8
+ * @file Generic host-secrets verbs (owner 2026-10-05: "a tool that sets and unsets secrets ... not just
9
+ * for one host ... it should work for really any vendor"). Vendors are adapters exported by the trusted
10
+ * deploy plugin's deploy-ops modules (`listSecrets`/`setSecret`/`unsetSecret`, optional `readSecret`);
11
+ * this file owns everything vendor-neutral: the value source, the compare-before-write, the human
12
+ * confirmation before an overwrite or removal, and a result that never carries a secret value.
13
+ *
14
+ * A value never comes from the model. `source` names where the server reads it: this site's own key
15
+ * (`site-key`), or another secret on the same target (`secret`, copied vendor side through
16
+ * `readSecret`). Values stay inside this process: the audit records metadata only, and the result
17
+ * reports a one-way fingerprint.
18
+ */
19
+ export const SECRET_NAME_PATTERN = /^[A-Za-z_]\w{0,127}$/;
20
+ const clip = (value, max) => String(value).slice(0, max);
21
+ const sha256 = (value) => createHash("sha256").update(value, "utf8").digest();
22
+ /** Constant-time over fixed-length digests, so neither length nor prefix leaks through timing. O(n). */
23
+ function sameValue(left, right) {
24
+ return timingSafeEqual(sha256(left), sha256(right));
25
+ }
26
+ function requireSiteKey(deps) {
27
+ const hex = deps.siteKey.read({}, {});
28
+ if (!hex)
29
+ throw new ToolInputError({ message: deps.messages.noUsableSiteKey });
30
+ return hex;
31
+ }
32
+ /** Refuse unknown platforms and platforms without a secrets adapter before any credential or network work. */
33
+ async function secretsPlatform(deps, id, signal) {
34
+ if (signal?.aborted)
35
+ throw aborted();
36
+ const registry = await deps.loadDeployOps({ workspaceId: deps.workspaceId });
37
+ const platform = requireDeployPlatform({ registry, id }, {});
38
+ if (!platform.module.setSecret || !platform.module.secretCapabilities) {
39
+ const capable = registry.list().filter(p => typeof p.module.setSecret === "function").map(p => p.descriptor.id);
40
+ throw new ToolInputError({ message: `Deployment ops platform '${id}' has no secrets adapter. Platforms with one: ${capable.join(", ") || "(none)"}.` });
41
+ }
42
+ return platform;
43
+ }
44
+ function requireName(value, key = "name") {
45
+ if (!SECRET_NAME_PATTERN.test(value))
46
+ throw new ToolInputError({ message: `${key} must be an environment variable name (letters, digits and underscores, not starting with a digit, at most 128 characters).` });
47
+ return value;
48
+ }
49
+ /** Keep only documented fields; a malformed adapter result is refused rather than echoed. O(secrets). */
50
+ async function listNormalized(platform, ctx, target) {
51
+ const result = await platform.module.listSecrets(ctx, { target });
52
+ if (!Array.isArray(result?.secrets) || result.secrets.some(s => !s || typeof s.name !== "string" || !s.name))
53
+ throw new ToolInputError({ message: `Deployment ops platform '${platform.descriptor.id}' returned an invalid secret list.` });
54
+ const secrets = result.secrets.slice(0, 500).map(s => ({ name: clip(s.name, 128), ...(typeof s.digest === "string" ? { digest: clip(s.digest, 200) } : {}), ...(typeof s.updatedAt === "string" ? { updatedAt: clip(s.updatedAt, 64) } : {}) }));
55
+ return { secrets, truncated: result.truncated === true || result.secrets.length > 500 };
56
+ }
57
+ const applies = (platform) => {
58
+ const { appliesOn, supportsStaging } = platform.module.secretCapabilities;
59
+ return { appliesOn, supportsStaging, deployNeeded: appliesOn === "next-deploy" };
60
+ };
61
+ const version = (write) => (typeof write?.version === "string" || typeof write?.version === "number" ? { version: clip(write.version, 64) } : {});
62
+ const nextStep = (deps, platform, target) => (platform.module.secretCapabilities.appliesOn === "next-deploy" ? ` The running app keeps the old environment until the next deploy of '${target}' (${deps.toolIds.deploy}).` : "");
63
+ /**
64
+ * List a target's secret names with the vendor's digest and update time; never a value.
65
+ * @param required - `deps`: saved-credential ports and the no-redirect client; `input`: platform, target, optional credential label.
66
+ * @param optional - `signal` cancels before further requests.
67
+ * @returns Names, vendor digests, update times, truncation and when writes take effect.
68
+ * @throws {ToolInputError} Unknown or secrets-less platforms, credential/host/auth failures, malformed adapter output.
69
+ * @complexity Time and space: O(credentials + secrets).
70
+ * @example await runListSecrets({ deps, input: { platform: "my-host", target: "my-app" } });
71
+ */
72
+ export async function runListSecrets(required, optional = {}) {
73
+ const { deps, input } = required;
74
+ const { signal } = optional;
75
+ const platform = await secretsPlatform(deps, input.platform, signal);
76
+ const ctx = await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal });
77
+ const listed = await listNormalized(platform, ctx, input.target);
78
+ return { platform: input.platform, target: input.target, ...listed, ...applies(platform) };
79
+ }
80
+ /** Read the source value server side. A copy needs the adapter's read verb and a source that exists. */
81
+ async function resolveValue({ deps, platform, ctx, input, siteKey }, { typedValue } = {}) {
82
+ if (input.source.kind === "typed")
83
+ return requireTypedValue({ value: typedValue }, {});
84
+ if (siteKey !== undefined)
85
+ return siteKey;
86
+ const source = input.source;
87
+ const read = await platform.module.readSecret(ctx, { target: input.target, name: source.name });
88
+ if (!read || !("value" in read) || typeof read.value !== "string")
89
+ throw new ToolInputError({ message: `Secret '${source.name}' is not set on '${input.target}', so there is nothing to copy. List the secrets with ${deps.toolIds.listSecrets}.` });
90
+ return read.value;
91
+ }
92
+ function comparisonOfRead({ current, value }, _optional = {}) {
93
+ if (current && "value" in current && typeof current.value === "string")
94
+ return sameValue(current.value, value) ? "same" : "different";
95
+ if (current && "absent" in current && current.absent === true)
96
+ return "absent";
97
+ return undefined;
98
+ }
99
+ async function readComparison({ platform, ctx, input, value }, { signal } = {}) {
100
+ if (platform.module.readSecret) {
101
+ try {
102
+ const current = await platform.module.readSecret(ctx, { target: input.target, name: input.name });
103
+ return comparisonOfRead({ current, value }, {});
104
+ }
105
+ catch (error) {
106
+ if (signal?.aborted)
107
+ throw error; /* An unreadable value (e.g. a token without secret-read scope) degrades to a presence check. */
108
+ }
109
+ }
110
+ return undefined;
111
+ }
112
+ /** Compare the stored value when the adapter can read it; otherwise only a complete list can establish absence. */
113
+ async function compareCurrent(platform, ctx, input, value, signal) {
114
+ const comparison = await readComparison({ platform, ctx, input, value }, { signal });
115
+ if (comparison !== undefined)
116
+ return comparison;
117
+ const listed = await listNormalized(platform, ctx, input.target);
118
+ return listed.truncated || listed.secrets.some(s => s.name === input.name) ? "unknown" : "absent";
119
+ }
120
+ /** Fail closed: an overwrite or removal without a confirmation channel never runs. */
121
+ async function confirmOrRefuse(confirm, request) {
122
+ if (!confirm)
123
+ throw new ToolInputError({ message: `Changing existing secret '${request.name}' needs a human confirmation, and this call has no way to ask. Nothing was changed.` });
124
+ return confirm(request);
125
+ }
126
+ function validateSetInput(platform, input) {
127
+ requireName(input.name);
128
+ if (input.source.kind !== "secret")
129
+ return;
130
+ requireName(input.source.name, "source.name");
131
+ if (input.source.name === input.name)
132
+ throw new ToolInputError({ message: "source.name must differ from name; a secret cannot be copied onto itself." });
133
+ if (!platform.module.readSecret)
134
+ throw new ToolInputError({ message: `Deployment ops platform '${input.platform}' cannot read secret values, so it cannot copy one secret to another. Use source kind 'site-key'.` });
135
+ }
136
+ /** Private card-only value: preserve bytes and refuse missing values without displaying them. */
137
+ function requireTypedValue({ value }, _optional = {}) {
138
+ if (typeof value !== "string" || value.trim() === "" || value.length > 8192)
139
+ throw new ToolInputError({ message: "The secure form requires a non-blank secret of at most 8192 characters." });
140
+ return value;
141
+ }
142
+ function describeSource({ source }, _optional = {}) {
143
+ if (source.kind === "site-key")
144
+ return "this site's key";
145
+ return source.kind === "typed" ? "the secure card" : `secret ${source.name}`;
146
+ }
147
+ /**
148
+ * Set one secret on a host target from a server-side source; skips the write when the value is already there.
149
+ * @param required - `deps`: credential ports, no-redirect client, site-key reader; `input`: platform, target, name, source, optional dryRun and credential label.
150
+ * @param optional - `signal` cancels; `confirm` asks a human before an existing secret is replaced.
151
+ * @returns changed, comparison, the value's fingerprint, when it applies, and an optional vendor version. Never the value.
152
+ * @throws {ToolInputError} Invalid names, unusable sources, secrets-less platforms, credential/host/auth failures, or an overwrite with no confirm channel.
153
+ * @complexity Time: O(credentials + secrets + value length) plus at most four adapter requests. Space: O(secrets).
154
+ * @example await runSetSecret({ deps, input: { platform: "my-host", target: "my-app", name: "APP_SITE_KEY", source: { kind: "site-key" } } }, { confirm });
155
+ */
156
+ /** @agent-note The confirm callback must approve the frozen overwrite request through an authenticated human answer. */
157
+ export async function runSetSecret(required, optional = {}) {
158
+ const { deps, input } = required;
159
+ const { signal, confirm } = optional;
160
+ const platform = await secretsPlatform(deps, input.platform, signal);
161
+ validateSetInput(platform, input);
162
+ const siteKey = input.source.kind === "site-key" ? requireSiteKey(deps) : undefined;
163
+ const ctx = await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal });
164
+ const value = await resolveValue({ deps, platform, ctx, input, siteKey }, { typedValue: optional.typedValue });
165
+ const comparison = await compareCurrent(platform, ctx, input, value, signal);
166
+ const source = describeSource({ source: input.source }, {});
167
+ const base = { platform: input.platform, target: input.target, name: input.name, source: input.source, comparison, ...deps.siteKey.fingerprint({ value }, {}), ...applies(platform) };
168
+ if (comparison === "same")
169
+ return { ...base, changed: false, deployNeeded: false, summary: `'${input.name}' on '${input.target}' already holds ${source}; nothing was written.` };
170
+ if (input.dryRun)
171
+ return { ...base, changed: false, dryRun: true, deployNeeded: false, summary: `Dry run: '${input.name}' would be ${comparison === "absent" ? "created" : "replaced"} from ${source}. Nothing was written.` };
172
+ if (comparison !== "absent") {
173
+ const decision = await confirmOrRefuse(confirm, { action: "overwrite", platform: input.platform, target: input.target, name: input.name, source, comparison, appliesOn: base.appliesOn });
174
+ if (!decision.confirmed)
175
+ return { ...base, changed: false, deployNeeded: false, ...decision.result };
176
+ }
177
+ if (signal?.aborted)
178
+ throw aborted();
179
+ const write = await platform.module.setSecret(ctx, { target: input.target, name: input.name, value });
180
+ return { ...base, changed: true, ...version(write), summary: `Set '${input.name}' on '${input.target}' from ${source}.${nextStep(deps, platform, input.target)}` };
181
+ }
182
+ /** Confirmation must be tied to an identifiable provider version. */
183
+ function requireSecretSnapshot({ deps, secrets, name }, _optional = {}) {
184
+ const targetSnapshot = secrets.find(secret => secret.name === name);
185
+ if (!targetSnapshot || (!targetSnapshot.digest && !targetSnapshot.updatedAt))
186
+ throw new ToolInputError({ message: `${deps.toolIds.unsetSecret}: the provider cannot identify the current secret version safely. Remove it in the provider console; nothing was deleted.` });
187
+ return targetSnapshot;
188
+ }
189
+ /**
190
+ * Remove one secret from a host target after a human confirms; an absent name is reported, not deleted.
191
+ * @param required - `deps`: credential ports and the no-redirect client; `input`: platform, target, name, optional credential label.
192
+ * @param optional - `signal` cancels; `confirm` is required for an actual removal.
193
+ * @returns removed, when the removal applies, and an optional vendor version.
194
+ * @throws {ToolInputError} Invalid names, secrets-less platforms, credential/host/auth failures, or no confirm channel.
195
+ * @complexity Time and space: O(credentials + secrets) plus at most three adapter requests.
196
+ * @example await runUnsetSecret({ deps, input: { platform: "my-host", target: "my-app", name: "OLD_KEY" } }, { confirm });
197
+ */
198
+ /** @agent-note The confirm callback must approve the frozen removal request through an authenticated human answer. */
199
+ export async function runUnsetSecret(required, optional = {}) {
200
+ const { deps, input } = required;
201
+ const { signal, confirm } = optional;
202
+ const platform = await secretsPlatform(deps, input.platform, signal);
203
+ requireName(input.name);
204
+ const ctx = await boundContext({ deps, platform, explicit: input.credentialLabel }, { signal, allowDelete: true });
205
+ const listed = await listNormalized(platform, ctx, input.target);
206
+ const base = { platform: input.platform, target: input.target, name: input.name, ...applies(platform) };
207
+ if (!listed.truncated && !listed.secrets.some(s => s.name === input.name))
208
+ return { ...base, removed: false, deployNeeded: false, summary: `'${input.name}' is not set on '${input.target}'; nothing was removed.` };
209
+ const targetSnapshot = requireSecretSnapshot({ deps, secrets: listed.secrets, name: input.name }, {});
210
+ const decision = await confirmOrRefuse(confirm, { action: "remove", platform: input.platform, target: input.target, name: input.name, appliesOn: base.appliesOn });
211
+ if (!decision.confirmed)
212
+ return { ...base, removed: false, deployNeeded: false, ...decision.result };
213
+ if (signal?.aborted)
214
+ throw aborted();
215
+ const current = (await listNormalized(platform, ctx, input.target)).secrets.find(secret => secret.name === input.name);
216
+ if (!isDeepStrictEqual(current, targetSnapshot))
217
+ throw new ToolInputError({ message: `${deps.toolIds.unsetSecret}: target changed while confirmation was open. Request a new confirmation; nothing was deleted.` });
218
+ const write = await platform.module.unsetSecret(ctx, { target: input.target, name: input.name });
219
+ return { ...base, removed: true, ...version(write), summary: `Removed '${input.name}' from '${input.target}'.${nextStep(deps, platform, input.target)}` };
220
+ }
221
+ //# sourceMappingURL=ops-secrets.js.map
@@ -0,0 +1,223 @@
1
+ import type { AgentToolDefinition, DerivedRiskByToolId, ToolMetadataById, ToolExecutionContext, ToolExecutionOptions, SurfaceAskThenReport, SurfaceExchangeStore } from '@jini-ai/core';
2
+ import type { Clock } from '@jini-ai/core/primitives';
3
+ import type { SurfaceCardsPort, SurfaceCardSecretForm } from '@jini-ai/core/contracts/cards';
4
+ import type { CredentialedRequestRequired, CredentialedRequestOptional, CredentialedRequestResult, CredentialedRequestPort } from '@jini-ai/core/contracts/credentials';
5
+ import type { DeployOpsRegistry, DeployOpsSecretAppliesOn } from './ops-contracts.js';
6
+ export type SecretValueSource = {
7
+ kind: "site-key";
8
+ } | {
9
+ kind: "secret";
10
+ name: string;
11
+ } | {
12
+ kind: "typed";
13
+ };
14
+ export interface SecretTargetInput {
15
+ platform: string;
16
+ target: string;
17
+ credentialLabel?: string | undefined;
18
+ }
19
+ /** @agent-note A source names metadata only, while a typed value must arrive separately from the authenticated human card and never model input. */
20
+ export interface SetSecretInput extends SecretTargetInput {
21
+ name: string;
22
+ source: SecretValueSource;
23
+ dryRun?: boolean;
24
+ }
25
+ export interface UnsetSecretInput extends SecretTargetInput {
26
+ name: string;
27
+ }
28
+ /** `unknown`: the secret may exist but cannot be compared or ruled out by a complete listing. */
29
+ export type SecretComparison = "same" | "different" | "absent" | "unknown";
30
+ /** What a human is asked to approve; fixed before the card is drawn. */
31
+ export interface SecretConfirmRequest {
32
+ action: "overwrite" | "remove";
33
+ platform: string;
34
+ target: string;
35
+ name: string;
36
+ source?: string;
37
+ comparison?: SecretComparison;
38
+ appliesOn: DeployOpsSecretAppliesOn;
39
+ }
40
+ /** The model-facing shape of a card the human did not confirm (`notConfirmedResult`). */
41
+ export interface SecretNotConfirmed {
42
+ cancelled: boolean;
43
+ reason?: "expired" | "abandoned";
44
+ note: string;
45
+ }
46
+ /** The tool layer's card. A refusal carries the model-facing not-confirmed result to spread into the reply. */
47
+ /** @agent-note A declined, expired or abandoned human answer must produce no provider mutation. */
48
+ export type SecretConfirm = (request: SecretConfirmRequest) => Promise<{
49
+ confirmed: true;
50
+ } | {
51
+ confirmed: false;
52
+ result: SecretNotConfirmed;
53
+ }>;
54
+ interface SecretWriteResultBase extends Partial<SecretNotConfirmed> {
55
+ platform: string;
56
+ target: string;
57
+ name: string;
58
+ appliesOn: DeployOpsSecretAppliesOn;
59
+ supportsStaging: boolean;
60
+ deployNeeded: boolean;
61
+ summary?: string;
62
+ version?: string;
63
+ }
64
+ /** Never carries a value: only the comparison verdict and a one-way fingerprint. */
65
+ export interface SetSecretResult extends SecretWriteResultBase {
66
+ source: SecretValueSource;
67
+ comparison: SecretComparison;
68
+ fingerprint: string;
69
+ fingerprintKind: "site-key" | "sha256";
70
+ changed: boolean;
71
+ dryRun?: true;
72
+ }
73
+ export interface UnsetSecretResult extends SecretWriteResultBase {
74
+ removed: boolean;
75
+ }
76
+ /** @agent-note After awaiting auth schemes, recheck abort at actual I/O, forward the signal, enforce maxResponseBytes and preserve transport truncation without retries. */
77
+ export interface DeployOpsBoundedRequest {
78
+ request(required: CredentialedRequestRequired & {
79
+ maxResponseBytes: number;
80
+ }, optional: CredentialedRequestOptional & {
81
+ signal?: AbortSignal | undefined;
82
+ }): Promise<CredentialedRequestResult & {
83
+ bodyTruncated: boolean;
84
+ }>;
85
+ }
86
+ /** @agent-note Use a monotonic clock and abortable sleep that removes timers and listeners on every completion. */
87
+ export interface WaitClock {
88
+ now(): number;
89
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
90
+ }
91
+ /** @agent-note Preserve the issued diagnostic object identity, including its non-enumerable authority and provenance. */
92
+ export interface DeployCredentialDiagnostic {
93
+ readonly setupToolId?: string;
94
+ readonly prefill?: Readonly<Record<string, string | number | boolean | null>>;
95
+ readonly hint?: string;
96
+ readonly remedyToolId?: string;
97
+ }
98
+ export interface DeployOpsToolIds {
99
+ status: string;
100
+ logs: string;
101
+ wait: string;
102
+ listTargets: string;
103
+ deploy: string;
104
+ listSecrets: string;
105
+ setSecret: string;
106
+ unsetSecret: string;
107
+ credentialVerify: string;
108
+ }
109
+ /** @agent-note Use the SAME workspace and saved store as host request routes so inventory and target authorization describe the same credentials. */
110
+ export interface DeployOpsRuntime {
111
+ workspaceId: string;
112
+ clock: Clock;
113
+ loadDeployOps(input: {
114
+ workspaceId: string;
115
+ }): Promise<DeployOpsRegistry>;
116
+ loadDeployWorkflowFiles?: ((input: {
117
+ workspaceId: string;
118
+ }) => Promise<readonly string[]>) | undefined;
119
+ waitClock?: WaitClock | undefined;
120
+ credentials: DeployOpsBoundedRequest & Pick<CredentialedRequestPort, 'resolveTarget' | 'classifyError'> & {
121
+ /** @agent-note Return non-decrypting metadata with exact HTTPS origins such as https://host without a trailing slash, read only when no explicit credential label is supplied. */
122
+ list(required: Record<string, never>, optional?: Record<string, never>): Promise<readonly {
123
+ label: string;
124
+ allowedOrigins: readonly string[];
125
+ }[]>;
126
+ available: boolean;
127
+ };
128
+ siteKey: {
129
+ /** @agent-note Reread the ordered active host key sources on each call without exposing key material to the model. */
130
+ read(required: Record<string, never>, optional?: Record<string, never>): string | undefined;
131
+ /** @agent-note Use the host key projection for a recognized key, otherwise the first 12 SHA256 hex characters of exact UTF-8 bytes without trimming. */
132
+ fingerprint(required: {
133
+ value: string;
134
+ }, optional?: Record<string, never>): {
135
+ fingerprint: string;
136
+ fingerprintKind: 'site-key' | 'sha256';
137
+ };
138
+ };
139
+ publishHistoryStore?: {
140
+ /** @agent-note A history failure must never retry an accepted dispatch or disclose secret material. */
141
+ recordSuccess(input: {
142
+ workspaceId: string;
143
+ entry: {
144
+ kind: 'deploy';
145
+ target: string;
146
+ projectName: string;
147
+ url: string;
148
+ reachable: false;
149
+ status: 'started';
150
+ publishedAt: string;
151
+ triggeredBy: 'agent_tool';
152
+ };
153
+ }): Promise<unknown>;
154
+ } | undefined;
155
+ recovery: {
156
+ /** @agent-note Return the original issued diagnostic with its identity and provenance intact, without provider or vault data. */
157
+ setupRequired(required: {
158
+ label: string;
159
+ baseUrl: string;
160
+ }): {
161
+ message: string;
162
+ credentialSetup: DeployCredentialDiagnostic;
163
+ };
164
+ };
165
+ toolIds: DeployOpsToolIds;
166
+ messages: {
167
+ noUsableSiteKey: string;
168
+ severalCredentials(required: {
169
+ host: string;
170
+ labels: readonly string[];
171
+ }): string;
172
+ noSavedCredential(required: {
173
+ label: string;
174
+ }): string;
175
+ };
176
+ }
177
+ /** @agent-note Use the same actor-bound exchange store as the answer route, and emit the outcome on the same URI only after the save completes. */
178
+ export interface DeployOpsSecretCards {
179
+ defineSecretCardTool: SurfaceCardsPort['defineSecretCardTool'];
180
+ askThenReport: SurfaceAskThenReport;
181
+ surfaceExchanges?: Pick<SurfaceExchangeStore, 'open'> | undefined;
182
+ uriHost: string;
183
+ defaultLocale: string;
184
+ noEmitter: string;
185
+ locale(required: {
186
+ ctx: ToolExecutionContext;
187
+ }): Promise<string>;
188
+ form(required: {
189
+ locale: string;
190
+ title: string;
191
+ }): SurfaceCardSecretForm;
192
+ text(required: {
193
+ locale: string;
194
+ id: 'storage' | 'savedTitle';
195
+ }): string;
196
+ }
197
+ export interface DeployOpsRegistrationHost {
198
+ /** @agent-note Catalog names must equal toolIds values, with handler keys platform/target/credentialLabel for secret inventory, additionally name for unset and name/source/dryRun for set; deployment uses platform/target/ref/workflowFile/credentialLabel, target inventory uses platform/credentialLabel/org, status uses platform/target/credentialLabel/runId/branch, logs adds limit, and wait adds until/timeoutSeconds. */
199
+ catalog: readonly AgentToolDefinition[];
200
+ metadata: ToolMetadataById;
201
+ derivedRisk: DerivedRiskByToolId;
202
+ domain: string;
203
+ catalogModule: string;
204
+ permissions: {
205
+ write: string;
206
+ siteKey: string;
207
+ };
208
+ /** @agent-note Preserve the host evaluator's canonical refusal class and entity scope. */
209
+ permit(required: {
210
+ ctx: ToolExecutionContext;
211
+ permission: string;
212
+ }, optional?: Record<string, never>): Promise<void>;
213
+ approvals: {
214
+ /** @agent-note Freeze the public request on the same actor-bound exchange; the callback rechecks write permission after the human answer and denies every declined or aborted mutation. */
215
+ confirmFor(required: {
216
+ ctx: ToolExecutionContext;
217
+ permit: (permission: string) => Promise<void>;
218
+ }, optional: ToolExecutionOptions): SecretConfirm | undefined;
219
+ };
220
+ cards: DeployOpsSecretCards;
221
+ }
222
+ export {};
223
+ //# sourceMappingURL=ops-tool-contracts.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ops-tool-contracts.js.map
@@ -0,0 +1,8 @@
1
+ import { type ToolRegistration } from '@jini-ai/core';
2
+ import type { DeployOpsRuntime, DeployOpsRegistrationHost } from './ops-tool-contracts.js';
3
+ /** Permission precedes any plugin/credential read. Handler input validation is independent of the schema. */
4
+ export declare function buildDeployOpsRegistrations({ deps, host }: {
5
+ deps: DeployOpsRuntime;
6
+ host: DeployOpsRegistrationHost;
7
+ }, _optional?: {}): ToolRegistration[];
8
+ //# sourceMappingURL=ops-tools.d.ts.map
@@ -0,0 +1,117 @@
1
+ // Mechanical extraction provenance is recorded in this package's source-map.md.
2
+ import { nowIso } from '@jini-ai/core/primitives';
3
+ import { ToolInputError, buildDomainRegistrations, indexCatalogById, requireInputRecord } from '@jini-ai/core';
4
+ import { collectTypedDeploySecret } from './ops-secret-card.js';
5
+ import { runListSecrets, runSetSecret, runUnsetSecret } from './ops-secrets.js';
6
+ import { DeployCredentialSetupRequired, MAX_WAIT_SECONDS, runDeploy, runDeployOps, waitForDeployOps } from './ops-runner.js';
7
+ /** Read a bounded string; JSON schema alone cannot protect direct calls to the handler. */
8
+ function string(input, key, required = false) {
9
+ const value = input[key];
10
+ if (value === undefined && !required)
11
+ return undefined;
12
+ if (typeof value !== "string" || !value.trim() || value.length > 200)
13
+ throw new ToolInputError({ message: `${key} must be a non-empty string of at most 200 characters.` });
14
+ return value;
15
+ }
16
+ /** Enforce integer bounds even when a caller bypasses schema validation. */
17
+ function integer(input, key, fallback, min, max) {
18
+ const value = input[key] === undefined ? fallback : input[key];
19
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
20
+ throw new ToolInputError({ message: `${key} must be an integer from ${min} to ${max}.` });
21
+ return value;
22
+ }
23
+ /** Validate deploy input independently of the schema, then call the same feature function as the admin route. */
24
+ function deployHandler(deps, input, signal) {
25
+ onlyKeys(input, ["platform", "target", "ref", "credentialLabel", "workflowFile"]);
26
+ const ref = string(input, "ref");
27
+ const credentialLabel = string(input, "credentialLabel");
28
+ return runDeploy({ deps, input: { platform: string(input, "platform", true), target: string(input, "target", true), workflowFile: string(input, "workflowFile"), ...(ref !== undefined ? { ref } : {}), ...(credentialLabel !== undefined ? { credentialLabel } : {}) } }, { signal });
29
+ }
30
+ function onlyKeys(input, allowed) {
31
+ for (const key of Object.keys(input))
32
+ if (!allowed.includes(key))
33
+ throw new ToolInputError({ message: `Unexpected deployment ops input '${key}'.` });
34
+ }
35
+ /** `source` is a closed shape: a value can never ride in on it. O(1). */
36
+ function valueSource(raw) {
37
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
38
+ throw new ToolInputError({ message: "source must be {kind:'typed'}, {kind:'site-key'} or {kind:'secret', name}." });
39
+ const record = raw;
40
+ if ((record.kind === "typed" || record.kind === "site-key") && Object.keys(record).length === 1)
41
+ return { kind: record.kind };
42
+ if (record.kind === "secret" && typeof record.name === "string" && Object.keys(record).length === 2)
43
+ return { kind: "secret", name: record.name };
44
+ throw new ToolInputError({ message: "source must be {kind:'typed'}, {kind:'site-key'} or {kind:'secret', name}." });
45
+ }
46
+ const SECRET_KEYS = {
47
+ list: ["platform", "target", "credentialLabel"],
48
+ unset: ["platform", "target", "credentialLabel", "name"],
49
+ set: ["platform", "target", "credentialLabel", "name", "source", "dryRun"],
50
+ };
51
+ /** Secrets handlers: validation independent of the schema; copying the site key also needs the site-key permission. */
52
+ function secretsHandler(deps, host, name, permit) {
53
+ return async (ctx, options) => {
54
+ const input = requireInputRecord({ input: ctx.input });
55
+ const role = name === deps.toolIds.unsetSecret ? "unset" : "set";
56
+ onlyKeys(input, SECRET_KEYS[name === deps.toolIds.listSecrets ? "list" : role]);
57
+ const target = { platform: string(input, "platform", true), target: string(input, "target", true), credentialLabel: string(input, "credentialLabel") };
58
+ if (name === deps.toolIds.listSecrets)
59
+ return runListSecrets({ deps, input: target }, { signal: ctx.signal });
60
+ const optional = { signal: ctx.signal, confirm: host.approvals.confirmFor({ ctx, permit }, options ?? {}) };
61
+ if (name === deps.toolIds.unsetSecret)
62
+ return runUnsetSecret({ deps, input: { ...target, name: string(input, "name", true) } }, optional);
63
+ const source = valueSource(input.source);
64
+ if (input.dryRun !== undefined && typeof input.dryRun !== "boolean")
65
+ throw new ToolInputError({ message: "dryRun must be a boolean." });
66
+ if (source.kind === "site-key")
67
+ await permit(host.permissions.siteKey);
68
+ const setInput = { ...target, name: string(input, "name", true), source, dryRun: input.dryRun === true };
69
+ if (source.kind === "typed")
70
+ return collectTypedDeploySecret({ ctx, deps, cards: host.cards, input: setInput, permit: () => permit(host.permissions.write) }, { ...options, confirm: optional.confirm });
71
+ return runSetSecret({ deps, input: setInput }, optional);
72
+ };
73
+ }
74
+ function observationInput({ deps, name, input }, _optional = {}) {
75
+ const isList = name === deps.toolIds.listTargets;
76
+ const allowed = isList ? ["platform", "credentialLabel", "org"] : ["platform", "target", "credentialLabel", "runId", "branch", ...(name === deps.toolIds.logs ? ["limit"] : []), ...(name === deps.toolIds.wait ? ["until", "timeoutSeconds"] : [])];
77
+ onlyKeys(input, allowed);
78
+ const args = { platform: string(input, "platform", true), target: isList ? "" : string(input, "target", true), credentialLabel: string(input, "credentialLabel"), ...(isList ? { org: string(input, "org") } : { runId: string(input, "runId"), branch: string(input, "branch") }) };
79
+ return args;
80
+ }
81
+ async function observationHandler({ deps, input, name }, { signal } = {}) {
82
+ const args = observationInput({ deps, name, input }, {});
83
+ if (name === deps.toolIds.listTargets)
84
+ return await runDeployOps({ deps, input: args, operation: "listTargets" }, { signal });
85
+ if (name === deps.toolIds.logs)
86
+ return await runDeployOps({ deps, input: { ...args, limit: integer(input, "limit", 100, 1, 500) }, operation: "logs" }, { signal });
87
+ if (name === deps.toolIds.status)
88
+ return await runDeployOps({ deps, input: args, operation: "status" }, { signal });
89
+ if (input.until !== "healthy" && input.until !== "finished")
90
+ throw new ToolInputError({ message: "until must be 'healthy' or 'finished'." });
91
+ return await waitForDeployOps({ status: signal => runDeployOps({ deps, input: args, operation: "status" }, { signal }), clock: deps.waitClock, initial: { platform: args.platform, target: args.target, state: "unknown", summary: "No status received before timeout.", items: [], checkedAt: nowIso({ clock: deps.clock }) } }, { until: input.until, timeoutSeconds: integer(input, "timeoutSeconds", 180, 10, MAX_WAIT_SECONDS), signal });
92
+ }
93
+ /** Permission precedes any plugin/credential read. Handler input validation is independent of the schema. */
94
+ export function buildDeployOpsRegistrations({ deps, host }, _optional = {}) {
95
+ const catalog = host.catalog;
96
+ const handlers = {};
97
+ for (const tool of catalog)
98
+ handlers[tool.name] = async (ctx, options) => {
99
+ try {
100
+ const permit = permission => host.permit({ ctx, permission }, {});
101
+ await permit(tool.authorization.permission);
102
+ if ([deps.toolIds.listSecrets, deps.toolIds.setSecret, deps.toolIds.unsetSecret].includes(tool.name))
103
+ return await secretsHandler(deps, host, tool.name, permit)(ctx, options);
104
+ const input = requireInputRecord({ input: ctx.input });
105
+ if (tool.name === deps.toolIds.deploy)
106
+ return await deployHandler(deps, input, ctx.signal);
107
+ return await observationHandler({ deps, input, name: tool.name }, { signal: ctx.signal });
108
+ }
109
+ catch (error) {
110
+ if (error instanceof DeployCredentialSetupRequired)
111
+ return { executed: false, credentialSetup: error.credentialSetup };
112
+ throw error;
113
+ }
114
+ };
115
+ return buildDomainRegistrations({ metadata: host.metadata, domain: host.domain, catalogModule: host.catalogModule, catalog: indexCatalogById({ catalog: catalog }), handlers, derivedRisk: host.derivedRisk });
116
+ }
117
+ //# sourceMappingURL=ops-tools.js.map