@f5-sales-demo/xcsh 23.3.3 → 23.4.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.
- package/CHANGELOG.md +2 -0
- package/package.json +8 -8
- package/src/extensibility/custom-tools/types.ts +5 -0
- package/src/extensibility/extensions/types.ts +3 -0
- package/src/index.ts +6 -0
- package/src/integrations/setup.ts +8 -2
- package/src/internal-urls/api-catalog-index.generated.ts +25301 -25301
- package/src/internal-urls/api-catalog-qmd-index.generated.ts +2 -2
- package/src/internal-urls/api-catalog-resolve.ts +4 -0
- package/src/internal-urls/api-spec-index.generated.ts +1 -1
- package/src/internal-urls/api-spec-resolve.ts +7 -1
- package/src/internal-urls/build-info.generated.ts +8 -8
- package/src/internal-urls/immutable-selection.ts +178 -0
- package/src/internal-urls/public-citation-destinations.generated.ts +1 -1
- package/src/internal-urls/terraform-documentation-assets.generated.ts +24 -24
- package/src/internal-urls/terraform-index.generated.ts +1 -1
- package/src/internal-urls/terraform-provider-pin.generated.ts +1 -1
- package/src/modes/components/plugin-lifecycle.ts +31 -0
- package/src/modes/components/plugin-view.ts +167 -0
- package/src/modes/components/tool-execution.ts +117 -164
- package/src/modes/interactive-mode.ts +3 -3
- package/src/modes/types.ts +2 -2
- package/src/modes/utils/ui-helpers.ts +16 -5
- package/src/prompts/tools/xcsh-api.md +2 -0
- package/src/slash-commands/builtin-registry.ts +67 -68
- package/src/tools/xcsh-api-renderer.ts +16 -0
- package/src/tools/xcsh-api-replacement.ts +524 -0
- package/src/tools/xcsh-api.ts +61 -0
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs/promises";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { isDeepStrictEqual } from "node:util";
|
|
6
|
+
import type { AgentToolResult } from "@f5-sales-demo/pi-agent-core";
|
|
7
|
+
import {
|
|
8
|
+
createBody,
|
|
9
|
+
type MutationContract,
|
|
10
|
+
objectValue,
|
|
11
|
+
selectedMember,
|
|
12
|
+
validateBody,
|
|
13
|
+
valueAt,
|
|
14
|
+
} from "../internal-urls/immutable-selection";
|
|
15
|
+
import type { XcshApiToolDetails } from "./xcsh-api";
|
|
16
|
+
|
|
17
|
+
type ObjectValue = Record<string, unknown>;
|
|
18
|
+
interface Stage {
|
|
19
|
+
version: 1;
|
|
20
|
+
id: string;
|
|
21
|
+
scope: string;
|
|
22
|
+
resourcePath: string;
|
|
23
|
+
name: string;
|
|
24
|
+
namespace: string;
|
|
25
|
+
originalUid: string;
|
|
26
|
+
originalVersion: string;
|
|
27
|
+
originalSelections: string[];
|
|
28
|
+
targetSelections: string[];
|
|
29
|
+
stage: "prepared" | "deleting" | "absent" | "creating" | "verifying" | "complete";
|
|
30
|
+
newUid?: string;
|
|
31
|
+
serviceState?: string;
|
|
32
|
+
certificateState?: string;
|
|
33
|
+
}
|
|
34
|
+
interface Options {
|
|
35
|
+
contract: MutationContract;
|
|
36
|
+
apiBase: string;
|
|
37
|
+
contextName?: string;
|
|
38
|
+
resourcePath: string;
|
|
39
|
+
payload: ObjectValue;
|
|
40
|
+
recreate: boolean;
|
|
41
|
+
replacementId?: string;
|
|
42
|
+
headers: Record<string, string>;
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
contextMatches: () => boolean;
|
|
45
|
+
stateDir?: string;
|
|
46
|
+
}
|
|
47
|
+
class ReplacementError extends Error {
|
|
48
|
+
constructor(
|
|
49
|
+
readonly code: string,
|
|
50
|
+
message: string,
|
|
51
|
+
readonly status = 409,
|
|
52
|
+
) {
|
|
53
|
+
super(message);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function identity(object: ObjectValue, name: string, namespace: string) {
|
|
57
|
+
const meta = objectValue(object.metadata);
|
|
58
|
+
const system = objectValue(object.system_metadata);
|
|
59
|
+
if (meta.name !== name || meta.namespace !== namespace)
|
|
60
|
+
throw new ReplacementError("identity_mismatch", "Readback name or namespace does not match the requested object");
|
|
61
|
+
const uid = system.uid;
|
|
62
|
+
const version = object.resource_version ?? system.resource_version;
|
|
63
|
+
if (typeof uid !== "string" || !uid || typeof version !== "string" || !version)
|
|
64
|
+
throw new ReplacementError("identity_unavailable", "The existing object must have a UID and resource version");
|
|
65
|
+
return { uid, version };
|
|
66
|
+
}
|
|
67
|
+
function mergeObject(current: ObjectValue, update: ObjectValue): ObjectValue {
|
|
68
|
+
const result = { ...current };
|
|
69
|
+
for (const [key, value] of Object.entries(update)) {
|
|
70
|
+
result[key] =
|
|
71
|
+
value &&
|
|
72
|
+
typeof value === "object" &&
|
|
73
|
+
!Array.isArray(value) &&
|
|
74
|
+
current[key] &&
|
|
75
|
+
typeof current[key] === "object" &&
|
|
76
|
+
!Array.isArray(current[key])
|
|
77
|
+
? mergeObject(objectValue(current[key]), objectValue(value))
|
|
78
|
+
: value;
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
function maskSensitiveDiagnostic(raw: string, payload: unknown): string {
|
|
83
|
+
const secrets: string[] = [];
|
|
84
|
+
const visit = (value: unknown, sensitive = false) => {
|
|
85
|
+
if (typeof value === "string") {
|
|
86
|
+
if (sensitive && value.length) secrets.push(value);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
value.forEach(v => {
|
|
91
|
+
visit(v, sensitive);
|
|
92
|
+
});
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (value && typeof value === "object")
|
|
96
|
+
for (const [key, child] of Object.entries(value))
|
|
97
|
+
visit(child, sensitive || /(?:token|password|private_key|secret|credential)/i.test(key));
|
|
98
|
+
};
|
|
99
|
+
visit(payload);
|
|
100
|
+
let text = raw;
|
|
101
|
+
for (const secret of secrets.sort((a, b) => b.length - a.length)) {
|
|
102
|
+
text = text.split(secret).join("[MASKED]");
|
|
103
|
+
const escaped = JSON.stringify(secret).slice(1, -1);
|
|
104
|
+
text = text.split(escaped).join("[MASKED]");
|
|
105
|
+
}
|
|
106
|
+
return text.replace(
|
|
107
|
+
/-----BEGIN (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |ENCRYPTED )?PRIVATE KEY-----/g,
|
|
108
|
+
"[MASKED PRIVATE KEY]",
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
function containsConfig(actual: unknown, expected: unknown): boolean {
|
|
112
|
+
if (expected === null || typeof expected !== "object") return isDeepStrictEqual(actual, expected);
|
|
113
|
+
if (Array.isArray(expected))
|
|
114
|
+
return (
|
|
115
|
+
Array.isArray(actual) &&
|
|
116
|
+
actual.length === expected.length &&
|
|
117
|
+
expected.every((value, index) => containsConfig(actual[index], value))
|
|
118
|
+
);
|
|
119
|
+
if (!actual || typeof actual !== "object" || Array.isArray(actual)) return false;
|
|
120
|
+
return Object.entries(expected).every(([key, value]) => containsConfig((actual as ObjectValue)[key], value));
|
|
121
|
+
}
|
|
122
|
+
async function writePrivate(file: string, value: unknown) {
|
|
123
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
124
|
+
const handle = await fs.open(temporary, "wx", 0o600);
|
|
125
|
+
try {
|
|
126
|
+
await handle.writeFile(JSON.stringify(value));
|
|
127
|
+
await handle.sync();
|
|
128
|
+
} finally {
|
|
129
|
+
await handle.close();
|
|
130
|
+
}
|
|
131
|
+
await fs.rename(temporary, file);
|
|
132
|
+
}
|
|
133
|
+
export async function checkImmutableMutation(
|
|
134
|
+
options: Options,
|
|
135
|
+
): Promise<(AgentToolResult<XcshApiToolDetails> & { isError?: boolean }) | undefined> {
|
|
136
|
+
const { contract, payload, resourcePath } = options;
|
|
137
|
+
const namespace = decodeURIComponent(resourcePath.split("/").at(-3)!);
|
|
138
|
+
const name = decodeURIComponent(resourcePath.split("/").at(-1)!);
|
|
139
|
+
const scope = createHash("sha256")
|
|
140
|
+
.update(JSON.stringify([options.apiBase, options.contextName ?? "", resourcePath]))
|
|
141
|
+
.digest("hex");
|
|
142
|
+
const root = options.stateDir ?? path.join(os.homedir(), ".xcsh", "state", "replacements");
|
|
143
|
+
let stage: Stage | undefined;
|
|
144
|
+
let locked = false;
|
|
145
|
+
const requestId = randomUUID();
|
|
146
|
+
const detail: XcshApiToolDetails = {
|
|
147
|
+
status: 409,
|
|
148
|
+
url: `${options.apiBase}${resourcePath}`,
|
|
149
|
+
method: "PUT",
|
|
150
|
+
requestId,
|
|
151
|
+
contextName: options.contextName,
|
|
152
|
+
};
|
|
153
|
+
const result = (code: string, message: string, status = 409, extra: ObjectValue = {}) => ({
|
|
154
|
+
content: [
|
|
155
|
+
{
|
|
156
|
+
type: "text" as const,
|
|
157
|
+
text: JSON.stringify({
|
|
158
|
+
code,
|
|
159
|
+
message,
|
|
160
|
+
replacementId: stage?.id,
|
|
161
|
+
stage: stage?.stage,
|
|
162
|
+
serviceState: stage?.serviceState,
|
|
163
|
+
certificateState: stage?.certificateState,
|
|
164
|
+
...extra,
|
|
165
|
+
}),
|
|
166
|
+
},
|
|
167
|
+
],
|
|
168
|
+
details: { ...detail, status, replacementId: stage?.id, replacementStage: stage?.stage },
|
|
169
|
+
isError: true,
|
|
170
|
+
});
|
|
171
|
+
const save = async () => {
|
|
172
|
+
if (stage) await writePrivate(path.join(root, `${stage.id}.json`), stage);
|
|
173
|
+
};
|
|
174
|
+
const read = async (method = "GET", body?: ObjectValue) => {
|
|
175
|
+
if (!options.contextMatches())
|
|
176
|
+
throw new ReplacementError(
|
|
177
|
+
"context_mismatch",
|
|
178
|
+
"The active API context changed; resume in the original context",
|
|
179
|
+
);
|
|
180
|
+
const timeout = AbortSignal.timeout(30_000);
|
|
181
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
182
|
+
const response = await fetch(`${options.apiBase}${method === "POST" ? contract.collection : resourcePath}`, {
|
|
183
|
+
method,
|
|
184
|
+
headers: {
|
|
185
|
+
...options.headers,
|
|
186
|
+
"X-Request-ID": randomUUID(),
|
|
187
|
+
...(body ? { "Content-Type": "application/json" } : {}),
|
|
188
|
+
},
|
|
189
|
+
signal,
|
|
190
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
191
|
+
});
|
|
192
|
+
const raw = await response.text();
|
|
193
|
+
const safeRaw = maskSensitiveDiagnostic(raw, payload);
|
|
194
|
+
let object: ObjectValue | undefined;
|
|
195
|
+
try {
|
|
196
|
+
object = objectValue(JSON.parse(raw));
|
|
197
|
+
} catch {}
|
|
198
|
+
return { status: response.status, ok: response.ok, object, raw: safeRaw };
|
|
199
|
+
};
|
|
200
|
+
const pause = async (attempt: number) => {
|
|
201
|
+
options.signal?.throwIfAborted();
|
|
202
|
+
await Bun.sleep(Math.min(250 * 2 ** attempt, 2000));
|
|
203
|
+
options.signal?.throwIfAborted();
|
|
204
|
+
};
|
|
205
|
+
try {
|
|
206
|
+
const meta = objectValue(payload.metadata);
|
|
207
|
+
if (meta.name !== name || meta.namespace !== namespace)
|
|
208
|
+
throw new ReplacementError("identity_mismatch", "Payload name and namespace must match the API path");
|
|
209
|
+
const target = contract.groups.map(g => selectedMember(payload, g));
|
|
210
|
+
if (options.replacementId && !/^[0-9a-f-]{36}$/.test(options.replacementId))
|
|
211
|
+
throw new ReplacementError("invalid_replacement_id", "Invalid replacement ID");
|
|
212
|
+
await fs.mkdir(root, { recursive: true, mode: 0o700 });
|
|
213
|
+
try {
|
|
214
|
+
await fs.mkdir(path.join(root, `${scope}.lock`), { mode: 0o700 });
|
|
215
|
+
locked = true;
|
|
216
|
+
} catch (err) {
|
|
217
|
+
if ((err as NodeJS.ErrnoException).code === "EEXIST")
|
|
218
|
+
return result("replacement_busy", "Another operation holds this object's replacement lock");
|
|
219
|
+
throw err;
|
|
220
|
+
}
|
|
221
|
+
if (!options.replacementId) {
|
|
222
|
+
for (const file of await fs.readdir(root)) {
|
|
223
|
+
if (!file.endsWith(".json")) continue;
|
|
224
|
+
const pending = JSON.parse(await fs.readFile(path.join(root, file), "utf8")) as Stage;
|
|
225
|
+
if (pending.scope === scope && pending.stage !== "complete") {
|
|
226
|
+
stage = pending;
|
|
227
|
+
return result(
|
|
228
|
+
"replacement_pending",
|
|
229
|
+
"This object already has a pending cutover. Resume the replacement ID instead of starting another deletion.",
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (options.replacementId) {
|
|
235
|
+
stage = JSON.parse(await fs.readFile(path.join(root, `${options.replacementId}.json`), "utf8")) as Stage;
|
|
236
|
+
if (
|
|
237
|
+
stage.version !== 1 ||
|
|
238
|
+
stage.id !== options.replacementId ||
|
|
239
|
+
stage.scope !== scope ||
|
|
240
|
+
stage.resourcePath !== resourcePath ||
|
|
241
|
+
stage.name !== name ||
|
|
242
|
+
stage.namespace !== namespace
|
|
243
|
+
)
|
|
244
|
+
throw new ReplacementError(
|
|
245
|
+
"replacement_scope_mismatch",
|
|
246
|
+
"Replacement ID does not match this context and object",
|
|
247
|
+
);
|
|
248
|
+
if (!isDeepStrictEqual(stage.targetSelections, target))
|
|
249
|
+
throw new ReplacementError(
|
|
250
|
+
"replacement_target_mismatch",
|
|
251
|
+
"A resumed replacement must keep its original target type",
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
const current = await read();
|
|
255
|
+
if (!stage) {
|
|
256
|
+
if (!current.ok || !current.object)
|
|
257
|
+
throw new ReplacementError(
|
|
258
|
+
"preflight_failed",
|
|
259
|
+
`Cannot read the current object (${current.status}): ${current.raw}`,
|
|
260
|
+
current.status,
|
|
261
|
+
);
|
|
262
|
+
const source = contract.groups.map(g => selectedMember(current.object!, g));
|
|
263
|
+
if (isDeepStrictEqual(source, target)) return undefined;
|
|
264
|
+
if (!options.recreate)
|
|
265
|
+
return result(
|
|
266
|
+
"replacement_required",
|
|
267
|
+
"The immutable type selection changed. Explicit conversion requests use onImmutableSelectionChange: recreate. DELETE then POST causes downtime and may change UID or VIP.",
|
|
268
|
+
409,
|
|
269
|
+
{ currentSelections: source, targetSelections: target },
|
|
270
|
+
);
|
|
271
|
+
const old = identity(current.object, name, namespace);
|
|
272
|
+
stage = {
|
|
273
|
+
version: 1,
|
|
274
|
+
id: randomUUID(),
|
|
275
|
+
scope,
|
|
276
|
+
resourcePath,
|
|
277
|
+
name,
|
|
278
|
+
namespace,
|
|
279
|
+
originalUid: old.uid,
|
|
280
|
+
originalVersion: old.version,
|
|
281
|
+
originalSelections: source,
|
|
282
|
+
targetSelections: target,
|
|
283
|
+
stage: "prepared",
|
|
284
|
+
};
|
|
285
|
+
} else if (!options.recreate)
|
|
286
|
+
return result("replacement_pending", "Resume requires onImmutableSelectionChange: recreate");
|
|
287
|
+
// The body snapshot is private configuration, separate from the payload-free stage journal.
|
|
288
|
+
// It never contains transport credentials and is never written to tool logs or details.
|
|
289
|
+
if (stage.stage === "complete")
|
|
290
|
+
return result("replacement_complete", "This replacement is already complete; use GET for its current state.");
|
|
291
|
+
let base: ObjectValue;
|
|
292
|
+
const bodyPath = path.join(root, `${stage.id}.body`);
|
|
293
|
+
if (stage.stage === "prepared" && !options.replacementId) {
|
|
294
|
+
const writable = current.object!.create_form ?? current.object!;
|
|
295
|
+
base = objectValue(createBody(writable, contract.createSchema, contract.spec));
|
|
296
|
+
} else {
|
|
297
|
+
base = objectValue(JSON.parse(await fs.readFile(bodyPath, "utf8")));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
await writePrivate(bodyPath, base);
|
|
301
|
+
await save();
|
|
302
|
+
const body = mergeObject(base, payload);
|
|
303
|
+
for (const [i, g] of contract.groups.entries()) {
|
|
304
|
+
const owner = valueAt(body, g.path);
|
|
305
|
+
for (const member of g.members) delete owner[member];
|
|
306
|
+
owner[target[i]!] = valueAt(payload, g.path)[target[i]!];
|
|
307
|
+
}
|
|
308
|
+
const projected = objectValue(createBody(body, contract.createSchema, contract.spec));
|
|
309
|
+
const errors = validateBody(projected, contract.createSchema, contract.spec);
|
|
310
|
+
const minimum = contract.createSchema["x-f5xc-minimum-configuration"] as
|
|
311
|
+
| { required_fields?: string[] }
|
|
312
|
+
| undefined;
|
|
313
|
+
for (const field of minimum?.required_fields ?? []) {
|
|
314
|
+
let value: unknown = projected;
|
|
315
|
+
for (const part of field.split(".")) value = (value as ObjectValue)?.[part];
|
|
316
|
+
if (value === undefined || value === null) errors.push(`${field}: required`);
|
|
317
|
+
}
|
|
318
|
+
if (errors.length)
|
|
319
|
+
return result(
|
|
320
|
+
"replacement_validation_failed",
|
|
321
|
+
"Correct the create payload and resume the replacement. No DELETE was issued by this attempt.",
|
|
322
|
+
422,
|
|
323
|
+
{ errors },
|
|
324
|
+
);
|
|
325
|
+
contract.groups.forEach(g => {
|
|
326
|
+
selectedMember(projected, g);
|
|
327
|
+
});
|
|
328
|
+
await writePrivate(bodyPath, projected);
|
|
329
|
+
await save();
|
|
330
|
+
if (stage.stage === "prepared" || stage.stage === "deleting") {
|
|
331
|
+
if (current.status === 404 && stage.stage === "deleting") {
|
|
332
|
+
stage.stage = "absent";
|
|
333
|
+
await save();
|
|
334
|
+
} else {
|
|
335
|
+
if (!current.ok || !current.object)
|
|
336
|
+
throw new ReplacementError("preflight_failed", "Existing object cannot be verified");
|
|
337
|
+
const original = identity(current.object, name, namespace);
|
|
338
|
+
if (
|
|
339
|
+
original.uid !== stage.originalUid ||
|
|
340
|
+
original.version !== stage.originalVersion ||
|
|
341
|
+
!isDeepStrictEqual(
|
|
342
|
+
contract.groups.map(g => selectedMember(current.object!, g)),
|
|
343
|
+
stage.originalSelections,
|
|
344
|
+
)
|
|
345
|
+
)
|
|
346
|
+
throw new ReplacementError("concurrent_change", "The original object changed; no DELETE was issued");
|
|
347
|
+
// Save deletion intent before the final read. No asynchronous operation intervenes
|
|
348
|
+
// between comparing this read and sending DELETE; the API still has no conditional DELETE.
|
|
349
|
+
stage.stage = "deleting";
|
|
350
|
+
await save();
|
|
351
|
+
const latest = await read();
|
|
352
|
+
if (
|
|
353
|
+
!latest.ok ||
|
|
354
|
+
!latest.object ||
|
|
355
|
+
!isDeepStrictEqual(identity(latest.object, name, namespace), original) ||
|
|
356
|
+
!isDeepStrictEqual(latest.object.spec, current.object.spec) ||
|
|
357
|
+
!isDeepStrictEqual(latest.object.metadata, current.object.metadata)
|
|
358
|
+
)
|
|
359
|
+
throw new ReplacementError(
|
|
360
|
+
"concurrent_change",
|
|
361
|
+
"Object changed immediately before deletion; no DELETE was issued",
|
|
362
|
+
);
|
|
363
|
+
const deleted = await read("DELETE");
|
|
364
|
+
if (!deleted.ok && deleted.status !== 404)
|
|
365
|
+
throw new ReplacementError(
|
|
366
|
+
"delete_failed",
|
|
367
|
+
`DELETE failed (${deleted.status}): ${deleted.raw}`,
|
|
368
|
+
deleted.status,
|
|
369
|
+
);
|
|
370
|
+
let absent = false;
|
|
371
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
372
|
+
const observed = await read();
|
|
373
|
+
if (observed.status === 404) {
|
|
374
|
+
absent = true;
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
if (!observed.ok)
|
|
378
|
+
throw new ReplacementError(
|
|
379
|
+
"absence_unverified",
|
|
380
|
+
`Cannot verify deletion (${observed.status})`,
|
|
381
|
+
observed.status,
|
|
382
|
+
);
|
|
383
|
+
if (observed.object && identity(observed.object, name, namespace).uid !== stage.originalUid)
|
|
384
|
+
throw new ReplacementError("identity_mismatch", "Another object appeared while waiting for deletion");
|
|
385
|
+
await pause(attempt);
|
|
386
|
+
}
|
|
387
|
+
if (!absent)
|
|
388
|
+
return result(
|
|
389
|
+
"replacement_pending",
|
|
390
|
+
"Deletion has not reached absence. Keep diagnosing and resume this replacement ID.",
|
|
391
|
+
);
|
|
392
|
+
stage.stage = "absent";
|
|
393
|
+
await save();
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
398
|
+
// Every uncertain create is followed by GET before any retry. Never delete a new object.
|
|
399
|
+
const observed =
|
|
400
|
+
stage.stage === "absent" && attempt === 0 && !options.replacementId
|
|
401
|
+
? { status: 404, ok: false, object: undefined }
|
|
402
|
+
: await read();
|
|
403
|
+
if (observed.ok && observed.object) {
|
|
404
|
+
const newIdentity = identity(observed.object, name, namespace);
|
|
405
|
+
if (
|
|
406
|
+
newIdentity.uid === stage.originalUid ||
|
|
407
|
+
(stage.newUid && stage.newUid !== newIdentity.uid) ||
|
|
408
|
+
!isDeepStrictEqual(
|
|
409
|
+
contract.groups.map(g => selectedMember(observed.object!, g)),
|
|
410
|
+
target,
|
|
411
|
+
)
|
|
412
|
+
)
|
|
413
|
+
throw new ReplacementError(
|
|
414
|
+
"replacement_identity_mismatch",
|
|
415
|
+
"Readback is not the expected new object; no deletion or POST will be attempted",
|
|
416
|
+
);
|
|
417
|
+
const writable = objectValue(
|
|
418
|
+
createBody(observed.object.create_form ?? observed.object, contract.createSchema, contract.spec),
|
|
419
|
+
);
|
|
420
|
+
if (!containsConfig(writable, projected))
|
|
421
|
+
throw new ReplacementError(
|
|
422
|
+
"replacement_configuration_mismatch",
|
|
423
|
+
"The new object's configuration does not match the requested create body; continue diagnosis without deleting it",
|
|
424
|
+
);
|
|
425
|
+
stage.newUid = newIdentity.uid;
|
|
426
|
+
stage.stage = "verifying";
|
|
427
|
+
await save();
|
|
428
|
+
const service = objectValue(observed.object.spec).state;
|
|
429
|
+
stage.serviceState = typeof service === "string" ? service : undefined;
|
|
430
|
+
const automatic = target.includes("https_auto_cert");
|
|
431
|
+
const certificateState = (objectValue(observed.object.spec).auto_cert_info as ObjectValue | undefined)
|
|
432
|
+
?.auto_cert_state;
|
|
433
|
+
stage.certificateState = typeof certificateState === "string" ? certificateState : undefined;
|
|
434
|
+
await save();
|
|
435
|
+
if (
|
|
436
|
+
typeof service !== "string" ||
|
|
437
|
+
!/^(?:VIRTUAL_HOST_READY|READY|ACTIVE|RUNNING)$/i.test(service) ||
|
|
438
|
+
(automatic &&
|
|
439
|
+
certificateState !== undefined &&
|
|
440
|
+
!/^(?:CertificateIssued|AutoCertIssued|CertificateValid)$/i.test(String(certificateState)))
|
|
441
|
+
) {
|
|
442
|
+
await pause(attempt);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
stage.stage = "complete";
|
|
446
|
+
await save();
|
|
447
|
+
await fs.rm(bodyPath, { force: true });
|
|
448
|
+
return {
|
|
449
|
+
content: [
|
|
450
|
+
{
|
|
451
|
+
type: "text",
|
|
452
|
+
text: JSON.stringify({
|
|
453
|
+
code: "replacement_complete",
|
|
454
|
+
message: `Recreated ${name} in ${namespace}. Verified target type, new UID, and service state. The cutover caused downtime and may have changed the VIP.`,
|
|
455
|
+
replacementId: stage.id,
|
|
456
|
+
originalUid: stage.originalUid,
|
|
457
|
+
newUid: stage.newUid,
|
|
458
|
+
targetSelections: target,
|
|
459
|
+
serviceState: service,
|
|
460
|
+
}),
|
|
461
|
+
},
|
|
462
|
+
],
|
|
463
|
+
details: {
|
|
464
|
+
...detail,
|
|
465
|
+
status: 200,
|
|
466
|
+
method: "POST",
|
|
467
|
+
replacementId: stage.id,
|
|
468
|
+
replacementStage: stage.stage,
|
|
469
|
+
mutationVerb: "Created",
|
|
470
|
+
resourceLabel: `load balancer ${name}`,
|
|
471
|
+
},
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
if (observed.status !== 404) {
|
|
475
|
+
await pause(attempt);
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (stage.stage === "verifying")
|
|
479
|
+
return result(
|
|
480
|
+
"replacement_pending",
|
|
481
|
+
"The new object disappeared during verification. Diagnose before retrying.",
|
|
482
|
+
);
|
|
483
|
+
stage.stage = "creating";
|
|
484
|
+
await save();
|
|
485
|
+
let created: Awaited<ReturnType<typeof read>>;
|
|
486
|
+
try {
|
|
487
|
+
created = await read("POST", projected);
|
|
488
|
+
} catch {
|
|
489
|
+
await pause(attempt);
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
if (created.ok && typeof (created.object?.system_metadata as ObjectValue)?.uid === "string") {
|
|
493
|
+
stage.newUid = (created.object!.system_metadata as ObjectValue).uid as string;
|
|
494
|
+
await save();
|
|
495
|
+
}
|
|
496
|
+
const validationFailure =
|
|
497
|
+
/(?:should be valid|should (?:be|have)|must be|required|invalid|does not exist|validation)/i.test(
|
|
498
|
+
created.raw,
|
|
499
|
+
);
|
|
500
|
+
if (!created.ok && (validationFailure || ![408, 409, 429, 500, 502, 503, 504].includes(created.status)))
|
|
501
|
+
return result(
|
|
502
|
+
"replacement_create_failed",
|
|
503
|
+
`POST failed (${created.status}): ${created.raw}. The original LB remains deleted. Correct the payload and resume this replacement ID; do not DELETE again.`,
|
|
504
|
+
created.status,
|
|
505
|
+
);
|
|
506
|
+
await pause(attempt);
|
|
507
|
+
}
|
|
508
|
+
return result(
|
|
509
|
+
"replacement_pending",
|
|
510
|
+
"The cutover is incomplete. Continue diagnosis and resume this replacement ID; the original LB is not restored.",
|
|
511
|
+
);
|
|
512
|
+
} catch (err) {
|
|
513
|
+
if (err instanceof ReplacementError) return result(err.code, err.message, err.status);
|
|
514
|
+
// Transport exceptions may contain private request data. Stage/HTTP diagnostics carry
|
|
515
|
+
// the actionable context without echoing arbitrary exception strings.
|
|
516
|
+
return result(
|
|
517
|
+
"replacement_pending",
|
|
518
|
+
"The immutable mutation could not finish. Inspect the object state and resume the private replacement stage. No success is claimed.",
|
|
519
|
+
503,
|
|
520
|
+
);
|
|
521
|
+
} finally {
|
|
522
|
+
if (locked) await fs.rmdir(path.join(root, `${scope}.lock`));
|
|
523
|
+
}
|
|
524
|
+
}
|
package/src/tools/xcsh-api.ts
CHANGED
|
@@ -6,12 +6,14 @@ import type { AgentTool, AgentToolResult } from "@f5-sales-demo/pi-agent-core";
|
|
|
6
6
|
import { prompt } from "@f5-sales-demo/pi-utils";
|
|
7
7
|
import { validateXcshApiCredentials } from "@f5-sales-demo/pi-utils/xcsh-auth";
|
|
8
8
|
import { type Static, Type } from "@sinclair/typebox";
|
|
9
|
+
import { mutationContract, objectValue } from "../internal-urls/immutable-selection";
|
|
9
10
|
import xcshApiDescription from "../prompts/tools/xcsh-api.md" with { type: "text" };
|
|
10
11
|
import { SecretObfuscator } from "../secrets";
|
|
11
12
|
import { type ContextEnv, createContextEnv } from "../services/context-env";
|
|
12
13
|
import { currentContextExecution } from "../services/context-execution";
|
|
13
14
|
import type { ToolSession } from ".";
|
|
14
15
|
import { humanizeResourceType } from "./render-utils";
|
|
16
|
+
import { checkImmutableMutation } from "./xcsh-api-replacement";
|
|
15
17
|
|
|
16
18
|
// Namespace filtering driven by x-f5xc-namespace-profile from enriched API specs.
|
|
17
19
|
|
|
@@ -61,6 +63,16 @@ function loadAllowedNamespaceTypes(domain?: string): ReadonlySet<NamespaceType>
|
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
const xcshApiSchema = Type.Object({
|
|
66
|
+
onImmutableSelectionChange: Type.Optional(
|
|
67
|
+
Type.Literal("recreate", {
|
|
68
|
+
description: "Recreate immutable conversion; downtime and UID/VIP changes.",
|
|
69
|
+
}),
|
|
70
|
+
),
|
|
71
|
+
replacementId: Type.Optional(
|
|
72
|
+
Type.String({
|
|
73
|
+
description: "Resume this cutover.",
|
|
74
|
+
}),
|
|
75
|
+
),
|
|
64
76
|
contextName: Type.Optional(
|
|
65
77
|
Type.String({
|
|
66
78
|
description:
|
|
@@ -101,6 +113,8 @@ const xcshApiSchema = Type.Object({
|
|
|
101
113
|
type XcshApiParams = Static<typeof xcshApiSchema>;
|
|
102
114
|
|
|
103
115
|
export interface XcshApiToolDetails {
|
|
116
|
+
replacementId?: string;
|
|
117
|
+
replacementStage?: string;
|
|
104
118
|
status: number;
|
|
105
119
|
url: string;
|
|
106
120
|
method: string;
|
|
@@ -1062,6 +1076,44 @@ export class XcshApiTool implements AgentTool<typeof xcshApiSchema, XcshApiToolD
|
|
|
1062
1076
|
}
|
|
1063
1077
|
|
|
1064
1078
|
const startMs = performance.now();
|
|
1079
|
+
if (params.method === "PUT") {
|
|
1080
|
+
try {
|
|
1081
|
+
const { API_SPEC_DATA } = require("../internal-urls/api-spec-index.generated") as {
|
|
1082
|
+
API_SPEC_DATA: Readonly<Record<string, unknown>>;
|
|
1083
|
+
};
|
|
1084
|
+
const contract = mutationContract(API_SPEC_DATA, params.method, resolvedPath);
|
|
1085
|
+
if (contract) {
|
|
1086
|
+
const expectedContext = this.#contextEnv.getContextName();
|
|
1087
|
+
const guarded = await checkImmutableMutation({
|
|
1088
|
+
contract,
|
|
1089
|
+
apiBase,
|
|
1090
|
+
contextName: expectedContext,
|
|
1091
|
+
resourcePath: resolvedPath,
|
|
1092
|
+
payload: objectValue(JSON.parse(resolvedPayload ?? "null")),
|
|
1093
|
+
recreate: params.onImmutableSelectionChange === "recreate",
|
|
1094
|
+
replacementId: params.replacementId,
|
|
1095
|
+
headers,
|
|
1096
|
+
signal,
|
|
1097
|
+
stateDir: process.env.XCSH_REPLACEMENT_STATE_DIR,
|
|
1098
|
+
contextMatches: () => {
|
|
1099
|
+
const [base, token] = this.#resolveCredentials();
|
|
1100
|
+
return (
|
|
1101
|
+
base === apiBase && token === apiToken && this.#contextEnv.getContextName() === expectedContext
|
|
1102
|
+
);
|
|
1103
|
+
},
|
|
1104
|
+
});
|
|
1105
|
+
if (guarded) return guarded;
|
|
1106
|
+
} else if (params.replacementId || params.onImmutableSelectionChange)
|
|
1107
|
+
return this.#errorResult("No immutable selection contract matches this request; no mutation was sent.");
|
|
1108
|
+
} catch {
|
|
1109
|
+
return this.#errorResult(
|
|
1110
|
+
"Immutable mutation preflight failed. Check payload selections and embedded schema; no PUT was sent.",
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
1113
|
+
} else if (params.replacementId || params.onImmutableSelectionChange)
|
|
1114
|
+
return this.#errorResult(
|
|
1115
|
+
"Immutable replacement options require the original PUT resource path; no mutation was sent.",
|
|
1116
|
+
);
|
|
1065
1117
|
try {
|
|
1066
1118
|
let response = await fetch(url, init);
|
|
1067
1119
|
|
|
@@ -1116,6 +1168,15 @@ export class XcshApiTool implements AgentTool<typeof xcshApiSchema, XcshApiToolD
|
|
|
1116
1168
|
|
|
1117
1169
|
const guidance = this.#statusGuidance(response.status);
|
|
1118
1170
|
if (guidance) {
|
|
1171
|
+
if (
|
|
1172
|
+
params.method === "PUT" &&
|
|
1173
|
+
/(?:Https|Http).*?(?:HttpsAutoCert|cannot.*(?:change|replace)|type)/i.test(bodyText)
|
|
1174
|
+
) {
|
|
1175
|
+
return this.#errorResult(
|
|
1176
|
+
`${statusLine}\n\n${bodyText}\n\nPossible immutable selection rejection. Read the schema contract and request recreation only for an explicit conversion; this error does not authorize DELETE.`,
|
|
1177
|
+
detail,
|
|
1178
|
+
);
|
|
1179
|
+
}
|
|
1119
1180
|
let errorCodePrefix = "";
|
|
1120
1181
|
const codeLabel = parsedBody ? XCSH_ERROR_CODES[parsedBody.code as number] : undefined;
|
|
1121
1182
|
if (codeLabel) {
|