@ductape/cli 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,6 +43,24 @@ ductape --help
43
43
 
44
44
  Do not use `sudo npm link`; it mixes root-owned globals with your normal user.
45
45
 
46
+ ## Troubleshooting workspace issues
47
+
48
+ Run the command in your logged-in CLI context. It uses the active workspace automatically.
49
+
50
+ ```bash
51
+ ductape troubleshoot
52
+ ductape troubleshoot --product ductape:statecraft --since 2h
53
+ ductape troubleshoot --since 2026-11-04T00:00:00Z --until 2026-11-05T00:00:00Z --json
54
+ ```
55
+
56
+ The default window is the last 24 hours. The report groups failures from retained workspace logs,
57
+ deployment journals and build history, with evidence references, possible causes and supported next steps.
58
+ It reports missing sources and scan limits. Use `--max-logs 10000` or narrow the product/time window
59
+ when the default 5000-record limit is reached. Reports show up to 200 issue groups and disclose omissions.
60
+ Provider console logs and browser-only failures require separate evidence. Payloads and headers are
61
+ omitted and selected messages are redacted. Review reports before sharing them.
62
+ The command performs reads only. If every source is unavailable it prints a report and exits with code 1.
63
+
46
64
  ## Quick start
47
65
 
48
66
  ```bash
@@ -110,3 +128,28 @@ npm test
110
128
  ## Changelog
111
129
 
112
130
  See [CHANGELOG.md](./CHANGELOG.md).
131
+
132
+ ### Functions inside deployed APIs
133
+
134
+ `ductape deploy deployments get <deploymentId>` and deployment list responses include
135
+ `servedFunctions` for service deployments. Ductape automatically queries the signed
136
+ SDK runtime inventory after the service's health checks pass. Each inventory names
137
+ its cloud revision, release hash, traffic allocation, function namespaces, independent
138
+ function versions, operation names and contract hashes. Workbench shows the same
139
+ inventory in the deployment detail and MCP returns it through `ductape_deploy_status`.
140
+
141
+ A discovered handler is **deployed**, with function verification **unverified**.
142
+ Discovery never runs a business operation, changes invocation routing, or creates a
143
+ standalone deployment. Health checks do not prove individual function correctness.
144
+ Replacing a revision removes its functions from the serving view; canaries show both
145
+ revisions and rollback restores the previous revision's recorded inventory.
146
+
147
+ Use an SDK with signed runtime inventory support and expose its portable HTTP handler.
148
+ NestJS does this through its module's portable function controller (with
149
+ `NestFactory.create(..., { rawBody: true })`). Service `DUCTAPE_ACCESS_KEY` must reference
150
+ an accessible workspace secret. Discovery reuses provider authorization and private
151
+ verification transports, across supported service providers. Missing support or failed
152
+ discovery is reported as `unavailable`, not as zero functions, and does not fail an
153
+ otherwise healthy generic HTTP service. Existing deployments need a redeploy to collect
154
+ an inventory. Function contracts retain their own versions independently of the API
155
+ version.
@@ -0,0 +1,2 @@
1
+ import { type TroubleshootOptions } from '../lib/troubleshoot/report.js';
2
+ export declare function runTroubleshoot(options: TroubleshootOptions): Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { ApiClient } from '../lib/api-client.js';
2
+ import { requireWorkspaceContext, workspaceAuthQuery } from '../lib/workspace-context.js';
3
+ import { resolveScope } from '../lib/troubleshoot/report.js';
4
+ import { collectTroubleshoot, formatTroubleshoot } from '../lib/troubleshoot/collect.js';
5
+ export async function runTroubleshoot(options) {
6
+ const context = requireWorkspaceContext();
7
+ const scope = resolveScope(context.workspaceId, options);
8
+ const api = ApiClient.forProfile(context.profile, context.credentials, 15_000);
9
+ const report = await collectTroubleshoot(scope, {
10
+ get: (path, query) => api.getPath(path, workspaceAuthQuery(context, query)),
11
+ });
12
+ console.log(options.json ? JSON.stringify(report, null, 2) : formatTroubleshoot(report));
13
+ if (report.coverage.every(source => source.status === 'unavailable'))
14
+ process.exitCode = 1;
15
+ }
@@ -0,0 +1,58 @@
1
+ export declare function runUiCreate(name: string, opts: {
2
+ framework?: string;
3
+ description?: string;
4
+ json?: boolean;
5
+ }): Promise<void>;
6
+ export declare function runUiValidate(name: string | undefined, opts: {
7
+ typecheck?: boolean;
8
+ json?: boolean;
9
+ }): Promise<void>;
10
+ export declare function runUiPack(name: string, opts: {
11
+ out?: string;
12
+ json?: boolean;
13
+ }): Promise<void>;
14
+ export declare function runUiPublish(name: string, opts: {
15
+ typecheck?: boolean;
16
+ dryRun?: boolean;
17
+ json?: boolean;
18
+ }): Promise<void>;
19
+ export declare function runUiList(opts: {
20
+ search?: string;
21
+ json?: boolean;
22
+ }): Promise<void>;
23
+ export declare function runUiInspect(ref: string, opts: {
24
+ json?: boolean;
25
+ }): Promise<void>;
26
+ export declare function runUiDeprecate(ref: string, opts: {
27
+ reason: string;
28
+ replacement?: string;
29
+ json?: boolean;
30
+ }): Promise<void>;
31
+ export declare function runUiUndeprecate(ref: string, opts: {
32
+ json?: boolean;
33
+ }): Promise<void>;
34
+ export declare function runUiAdd(ref: string, opts: {
35
+ ignorePeers?: boolean;
36
+ json?: boolean;
37
+ }): Promise<void>;
38
+ export declare function runUiInstall(opts: {
39
+ offline?: boolean;
40
+ json?: boolean;
41
+ }): Promise<void>;
42
+ export declare function runUiUpdate(name: string, opts: {
43
+ to?: string;
44
+ ignorePeers?: boolean;
45
+ json?: boolean;
46
+ }): Promise<void>;
47
+ export declare function runUiRemove(name: string, opts: {
48
+ json?: boolean;
49
+ }): Promise<void>;
50
+ export declare function runUiVerify(opts: {
51
+ skipPeers?: boolean;
52
+ json?: boolean;
53
+ }): Promise<void>;
54
+ export declare function runUiCheck(name: string | undefined, opts: {
55
+ product?: string;
56
+ env?: string;
57
+ json?: boolean;
58
+ }): Promise<void>;
@@ -0,0 +1,359 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { findProjectConfig } from '../lib/config.js';
4
+ import { UI_FRAMEWORKS } from '../lib/ui/manifest.js';
5
+ import { listAuthoredUi, scaffoldUi, uiProjectRoot, UI_DIR } from '../lib/ui/scaffold.js';
6
+ import { packUiDirectory, typecheckUiDirectory, validateUiDirectory } from '../lib/ui/validate.js';
7
+ import { parseRef, UiRegistry } from '../lib/ui/registry.js';
8
+ import { requireWorkspaceContext } from '../lib/workspace-context.js';
9
+ import { applyPlan, checkPeers, installedRoot, LOCKFILE, planAdd, planInstall, planRemove, planUpdate, readLockfile, syncImports, verifyInstalled, writeLockfile } from '../lib/ui/consume.js';
10
+ import { checkRequirements, platformLookup } from '../lib/ui/check.js';
11
+ const root = () => uiProjectRoot(findProjectConfig()?.dir);
12
+ function formatDiagnostics(name, diagnostics) {
13
+ if (diagnostics.length === 0)
14
+ return `${name}: ok`;
15
+ const lines = diagnostics.map((d) => ` ${d.severity === 'error' ? 'error' : 'warn '} ${d.code}${d.file ? ` ${d.file}${d.line ? `:${d.line}` : ''}` : ''} ${d.message}`);
16
+ const errors = diagnostics.filter((d) => d.severity === 'error').length;
17
+ return `${name}: ${errors > 0 ? `${errors} ${errors === 1 ? 'error' : 'errors'}` : 'ok'}\n${lines.join('\n')}`;
18
+ }
19
+ export async function runUiCreate(name, opts) {
20
+ const framework = (opts.framework ?? 'react');
21
+ if (!UI_FRAMEWORKS.includes(framework)) {
22
+ throw new Error(`Framework "${framework}" is not supported yet. Supported: ${UI_FRAMEWORKS.join(', ')}`);
23
+ }
24
+ const projectRoot = root();
25
+ const created = scaffoldUi(projectRoot, name, framework, opts.description);
26
+ const relative = path.relative(projectRoot, created.dir) || '.';
27
+ if (opts.json) {
28
+ console.log(JSON.stringify({ name, framework, dir: relative, files: created.files }, null, 2));
29
+ return;
30
+ }
31
+ console.log(`Created ${relative}\n${created.files.map((file) => ` ${file}`).join('\n')}\n\nNext: list the actions it needs in ui.json, then run \`ductape ui validate ${name}\`.`);
32
+ }
33
+ export async function runUiValidate(name, opts) {
34
+ const projectRoot = root();
35
+ const names = name ? [name] : listAuthoredUi(projectRoot);
36
+ if (names.length === 0)
37
+ throw new Error(`No UI pieces found under ${UI_DIR}. Create one with \`ductape ui create <name>\`.`);
38
+ const results = names.map((piece) => {
39
+ const dir = path.join(projectRoot, UI_DIR, piece);
40
+ if (!fs.existsSync(dir))
41
+ return { ok: false, dir, files: [], diagnostics: [{ severity: 'error', code: 'UI_NOT_FOUND', message: `${path.join(UI_DIR, piece)} does not exist` }] };
42
+ const result = validateUiDirectory(dir);
43
+ if (opts.typecheck && result.ok) {
44
+ const typeErrors = typecheckUiDirectory(dir, projectRoot);
45
+ result.diagnostics.push(...typeErrors);
46
+ result.ok = typeErrors.length === 0;
47
+ }
48
+ return result;
49
+ });
50
+ if (opts.json)
51
+ console.log(JSON.stringify({ ok: results.every((r) => r.ok), results: results.map((r) => ({ ...r, dir: path.relative(projectRoot, r.dir) })) }, null, 2));
52
+ else
53
+ console.log(results.map((r, i) => formatDiagnostics(names[i], r.diagnostics)).join('\n\n'));
54
+ if (!results.every((r) => r.ok))
55
+ process.exitCode = 1;
56
+ }
57
+ export async function runUiPack(name, opts) {
58
+ const projectRoot = root();
59
+ const dir = path.join(projectRoot, UI_DIR, name);
60
+ if (!fs.existsSync(dir))
61
+ throw new Error(`${path.join(UI_DIR, name)} does not exist`);
62
+ const { validation, pack } = packUiDirectory(dir);
63
+ if (!pack) {
64
+ if (opts.json)
65
+ console.log(JSON.stringify({ ok: false, diagnostics: validation.diagnostics }, null, 2));
66
+ else
67
+ console.log(formatDiagnostics(name, validation.diagnostics));
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ const out = path.resolve(opts.out ?? path.join(projectRoot, 'ductape', '.ui-packs', `${pack.manifest.name}@${pack.manifest.version}.json`));
72
+ fs.mkdirSync(path.dirname(out), { recursive: true });
73
+ fs.writeFileSync(out, `${JSON.stringify(pack, null, 2)}\n`);
74
+ const summary = { name: pack.manifest.name, version: pack.manifest.version, framework: pack.manifest.framework, files: pack.files.length, integrity: pack.integrity, out: path.relative(projectRoot, out) };
75
+ if (opts.json)
76
+ console.log(JSON.stringify(summary, null, 2));
77
+ else
78
+ console.log(`Packed ${summary.name}@${summary.version} (${summary.files} files)\n ${summary.integrity}\n ${summary.out}`);
79
+ }
80
+ // ---- Registry: the workspace's published UI pieces ---------------------------------------------------------------
81
+ const registry = () => new UiRegistry(requireWorkspaceContext());
82
+ const deprecationNote = (v) => v.deprecation ? `deprecated: ${v.deprecation.reason ?? 'no reason given'}${v.deprecation.replacement ? ` (use ${v.deprecation.replacement})` : ''}` : '';
83
+ export async function runUiPublish(name, opts) {
84
+ const projectRoot = root();
85
+ const dir = path.join(projectRoot, UI_DIR, name);
86
+ if (!fs.existsSync(dir))
87
+ throw new Error(`${path.join(UI_DIR, name)} does not exist`);
88
+ const { validation, pack } = packUiDirectory(dir);
89
+ const typeErrors = pack && opts.typecheck ? typecheckUiDirectory(dir, projectRoot) : [];
90
+ if (!pack || typeErrors.length > 0) {
91
+ const diagnostics = [...validation.diagnostics, ...typeErrors];
92
+ if (opts.json)
93
+ console.log(JSON.stringify({ ok: false, diagnostics }, null, 2));
94
+ else
95
+ console.log(`${formatDiagnostics(name, diagnostics)}\n\nNothing was published.`);
96
+ process.exitCode = 1;
97
+ return;
98
+ }
99
+ const label = `${pack.manifest.name}@${pack.manifest.version}`;
100
+ if (opts.dryRun) {
101
+ const summary = { dryRun: true, name: pack.manifest.name, version: pack.manifest.version, files: pack.files.length, integrity: pack.integrity };
102
+ if (opts.json)
103
+ console.log(JSON.stringify(summary, null, 2));
104
+ else
105
+ console.log(`Would publish ${label} (${pack.files.length} files)\n ${pack.integrity}`);
106
+ return;
107
+ }
108
+ const result = await registry().publish(pack);
109
+ if (opts.json) {
110
+ console.log(JSON.stringify(result, null, 2));
111
+ return;
112
+ }
113
+ const lines = [result.created ? `Published ${label} (${result.version.files} files)` : `${label} is already published with this exact content; nothing changed`, ` ${result.version.integrity}`];
114
+ for (const warning of result.warnings)
115
+ lines.push(` warning: ${warning}`);
116
+ console.log(lines.join('\n'));
117
+ }
118
+ export async function runUiList(opts) {
119
+ const pieces = await registry().list(opts.search);
120
+ if (opts.json) {
121
+ console.log(JSON.stringify(pieces, null, 2));
122
+ return;
123
+ }
124
+ if (pieces.length === 0) {
125
+ console.log(opts.search ? `No UI pieces match "${opts.search}".` : 'This workspace has not published any UI pieces yet. Publish one with `ductape ui publish <name>`.');
126
+ return;
127
+ }
128
+ const width = Math.max(...pieces.map((p) => p.name.length));
129
+ console.log(pieces.map((p) => `${p.name.padEnd(width)} ${(p.latest ?? 'no release').padEnd(12)} ${p.framework.padEnd(6)} ${p.versions} ${p.versions === 1 ? 'version' : 'versions'}${p.description ? ` ${p.description}` : ''}`).join('\n'));
130
+ }
131
+ export async function runUiInspect(ref, opts) {
132
+ const { name, version } = parseRef(ref);
133
+ const reg = registry();
134
+ if (version) {
135
+ const detail = await reg.getVersion(name, version);
136
+ if (opts.json) {
137
+ console.log(JSON.stringify(detail, null, 2));
138
+ return;
139
+ }
140
+ const manifest = detail.manifest;
141
+ const lines = [
142
+ `${detail.name}@${detail.version} ${detail.framework}${detail.deprecated ? ` ${deprecationNote(detail)}` : ''}`,
143
+ ...(detail.description ? [` ${detail.description}`] : []),
144
+ ` integrity ${detail.integrity}`,
145
+ ` published ${detail.publishedAt} by ${detail.publishedBy}`,
146
+ ` entry ${manifest.entry}`,
147
+ ` peers ${Object.entries(manifest.peerDependencies ?? {}).map(([k, v]) => `${k} ${v}`).join(', ') || 'none'}`,
148
+ ` uses ${Object.entries(manifest.uses ?? {}).map(([k, v]) => `${k}@${v}`).join(', ') || 'none'}`,
149
+ ` requires ${[
150
+ ...(manifest.requires?.actions ?? []).map((a) => `action ${a.app}/${a.action}`),
151
+ ...(manifest.requires?.features ?? []).map((f) => `feature ${f}`),
152
+ ...(manifest.requires?.sessions ?? []).map((s) => `session ${s}`),
153
+ ].join(', ') || 'nothing'}`,
154
+ ` files`,
155
+ ...detail.fileList.map((f) => ` ${f.path} ${f.bytes} B`),
156
+ ];
157
+ console.log(lines.join('\n'));
158
+ return;
159
+ }
160
+ const detail = await reg.get(name);
161
+ if (opts.json) {
162
+ console.log(JSON.stringify(detail, null, 2));
163
+ return;
164
+ }
165
+ console.log([
166
+ `${detail.name} ${detail.framework} latest ${detail.latest ?? 'none (every release is deprecated or a pre-release)'}`,
167
+ ...detail.versions.map((v) => ` ${v.version.padEnd(14)} ${v.publishedAt} ${v.integrity.slice(0, 19)}...${v.deprecated ? ` ${deprecationNote(v)}` : ''}`),
168
+ ].join('\n'));
169
+ }
170
+ export async function runUiDeprecate(ref, opts) {
171
+ const { name, version } = parseRef(ref, true);
172
+ if (opts.replacement)
173
+ parseRef(`${name}@${opts.replacement}`, true);
174
+ const result = await registry().deprecate(name, version, opts.reason, opts.replacement);
175
+ if (opts.json)
176
+ console.log(JSON.stringify(result, null, 2));
177
+ else
178
+ console.log(`${name}@${version} is deprecated. Applications that already pinned it keep building; \`latest\` no longer picks it.`);
179
+ }
180
+ export async function runUiUndeprecate(ref, opts) {
181
+ const { name, version } = parseRef(ref, true);
182
+ const result = await registry().undeprecate(name, version);
183
+ if (opts.json)
184
+ console.log(JSON.stringify(result, null, 2));
185
+ else
186
+ console.log(`${name}@${version} is no longer deprecated.`);
187
+ }
188
+ // ---- Using UI pieces in an application ----------------------------------------------------------------------------
189
+ function applicationRoot() {
190
+ const projectRoot = root();
191
+ if (!fs.existsSync(path.join(projectRoot, 'package.json')))
192
+ throw new Error('Run this inside an application: no package.json was found');
193
+ return projectRoot;
194
+ }
195
+ /** #ui/<name> needs a module resolution that reads package.json "imports". Says so when tsconfig.json clearly uses one that does not. */
196
+ function moduleResolutionWarning(projectRoot) {
197
+ const file = path.join(projectRoot, 'tsconfig.json');
198
+ if (!fs.existsSync(file))
199
+ return undefined;
200
+ const found = /"moduleResolution"\s*:\s*"([^"]+)"/i.exec(fs.readFileSync(file, 'utf8'))?.[1]?.toLowerCase();
201
+ return found && ['node', 'node10', 'classic'].includes(found)
202
+ ? `tsconfig.json uses "moduleResolution": "${found}", which does not read package.json "imports"; set it to "bundler" (or "node16"/"nodenext") so TypeScript resolves #ui/ imports`
203
+ : undefined;
204
+ }
205
+ function printPeerProblems(problems) {
206
+ for (const p of problems)
207
+ console.log(` ${p.severity === 'error' ? 'error' : 'warn '} ${p.code} ${p.message}`);
208
+ }
209
+ export async function runUiAdd(ref, opts) {
210
+ const { name, version } = parseRef(ref);
211
+ const projectRoot = applicationRoot();
212
+ const plan = await planAdd(registry(), readLockfile(projectRoot), name, version ?? 'latest');
213
+ const added = [...plan.write.values()];
214
+ const peerProblems = checkPeers(projectRoot, added.map((p) => p.manifest));
215
+ const blocking = peerProblems.filter((p) => p.severity === 'error');
216
+ if (blocking.length > 0 && !opts.ignorePeers) {
217
+ if (opts.json)
218
+ console.log(JSON.stringify({ ok: false, peers: peerProblems }, null, 2));
219
+ else {
220
+ console.log(`${name} needs packages this application does not have. Nothing was added.`);
221
+ printPeerProblems(peerProblems);
222
+ }
223
+ process.exitCode = 1;
224
+ return;
225
+ }
226
+ if (added.length > 0)
227
+ applyPlan(projectRoot, plan);
228
+ else
229
+ syncImports(projectRoot, plan.lock);
230
+ if (added.length === 0 && plan.lock.pieces[name])
231
+ writeLockfile(projectRoot, plan.lock);
232
+ const tsWarning = moduleResolutionWarning(projectRoot);
233
+ const summary = {
234
+ ok: true,
235
+ added: added.map((p) => ({ name: p.manifest.name, version: p.manifest.version, integrity: p.integrity, direct: plan.lock.pieces[p.manifest.name].direct })),
236
+ warnings: [...plan.warnings, ...peerProblems.map((p) => p.message), ...(tsWarning ? [tsWarning] : [])],
237
+ import: `#ui/${name}`,
238
+ };
239
+ if (opts.json) {
240
+ console.log(JSON.stringify(summary, null, 2));
241
+ return;
242
+ }
243
+ if (added.length === 0)
244
+ console.log(`${name}@${plan.lock.pieces[name].version} is already added.`);
245
+ for (const a of summary.added)
246
+ console.log(`Added ${a.name}@${a.version}${a.direct ? '' : ' (used by another piece)'}`);
247
+ for (const w of summary.warnings)
248
+ console.log(` warning: ${w}`);
249
+ console.log(`\nImport it from '#ui/${name}'. The source is in ${path.join(UI_DIR, 'installed', name)}, pinned in ductape/ui.lock.json: commit both.`);
250
+ }
251
+ export async function runUiInstall(opts) {
252
+ const projectRoot = applicationRoot();
253
+ const { plan, restored } = await planInstall(projectRoot, opts.offline ? undefined : registry);
254
+ const changed = plan.write.size > 0 || plan.removed.length > 0;
255
+ if (changed)
256
+ applyPlan(projectRoot, plan);
257
+ const importsChanged = changed ? false : syncImports(projectRoot, plan.lock);
258
+ const result = { restored, removed: plan.removed, importsUpdated: importsChanged };
259
+ if (opts.json)
260
+ console.log(JSON.stringify(result, null, 2));
261
+ else if (!changed && !importsChanged)
262
+ console.log(`Everything matches ${LOCKFILE} (${Object.keys(plan.lock.pieces).length} pieces).`);
263
+ else {
264
+ for (const name of restored)
265
+ console.log(`Restored ${name}@${plan.lock.pieces[name].version}`);
266
+ for (const name of plan.removed)
267
+ console.log(`Removed ${name}: it is not in ${LOCKFILE}`);
268
+ if (importsChanged)
269
+ console.log('Updated package.json "imports".');
270
+ }
271
+ }
272
+ export async function runUiUpdate(name, opts) {
273
+ if (opts.to)
274
+ parseRef(`${name}@${opts.to}`);
275
+ const projectRoot = applicationRoot();
276
+ const plan = await planUpdate(registry(), readLockfile(projectRoot), name, opts.to ?? 'latest');
277
+ if (plan.from === plan.to) {
278
+ if (opts.json)
279
+ console.log(JSON.stringify({ updated: false, version: plan.to }, null, 2));
280
+ else
281
+ console.log(`${name} is already at ${plan.to}.`);
282
+ return;
283
+ }
284
+ const peerProblems = checkPeers(projectRoot, [...plan.write.values()].map((p) => p.manifest));
285
+ if (peerProblems.some((p) => p.severity === 'error') && !opts.ignorePeers) {
286
+ if (opts.json)
287
+ console.log(JSON.stringify({ ok: false, peers: peerProblems }, null, 2));
288
+ else {
289
+ console.log(`${name}@${plan.to} needs packages this application does not have. Nothing was changed.`);
290
+ printPeerProblems(peerProblems);
291
+ }
292
+ process.exitCode = 1;
293
+ return;
294
+ }
295
+ applyPlan(projectRoot, plan);
296
+ const result = { updated: true, from: plan.from, to: plan.to, written: [...plan.write.keys()], removed: plan.removed, warnings: plan.warnings };
297
+ if (opts.json)
298
+ console.log(JSON.stringify(result, null, 2));
299
+ else {
300
+ console.log(`Updated ${name} ${plan.from} -> ${plan.to}`);
301
+ for (const other of result.written.filter((n) => n !== name))
302
+ console.log(` added ${other}@${plan.lock.pieces[other].version}`);
303
+ for (const other of plan.removed)
304
+ console.log(` removed ${other} (no longer used)`);
305
+ for (const w of plan.warnings)
306
+ console.log(` warning: ${w}`);
307
+ }
308
+ }
309
+ export async function runUiRemove(name, opts) {
310
+ const projectRoot = applicationRoot();
311
+ const plan = planRemove(readLockfile(projectRoot), name);
312
+ applyPlan(projectRoot, plan);
313
+ if (opts.json)
314
+ console.log(JSON.stringify({ removed: plan.removed }, null, 2));
315
+ else
316
+ console.log(`Removed ${plan.removed.join(', ')}. Imports of #ui/${name} will no longer resolve.`);
317
+ }
318
+ export async function runUiVerify(opts) {
319
+ const projectRoot = applicationRoot();
320
+ const result = verifyInstalled(projectRoot, { peers: !opts.skipPeers });
321
+ if (opts.json)
322
+ console.log(JSON.stringify(result, null, 2));
323
+ else if (result.diagnostics.length === 0)
324
+ console.log(`ok: ${result.checked.length} ${result.checked.length === 1 ? 'piece matches' : 'pieces match'} ${LOCKFILE}`);
325
+ else
326
+ console.log(formatDiagnostics('installed UI pieces', result.diagnostics));
327
+ if (!result.ok)
328
+ process.exitCode = 1;
329
+ }
330
+ export async function runUiCheck(name, opts) {
331
+ const projectRoot = applicationRoot();
332
+ const linked = findProjectConfig()?.config;
333
+ const product = opts.product ?? linked?.product_tag;
334
+ const env = opts.env ?? linked?.env_slug;
335
+ if (!product || !env)
336
+ throw new Error('Name the product and environment with --product and --env, or run `ductape link` in this application');
337
+ const lock = readLockfile(projectRoot);
338
+ const names = name ? [name] : Object.keys(lock.pieces).sort();
339
+ if (name && !lock.pieces[name])
340
+ throw new Error(`${name} is not added to this application`);
341
+ if (names.length === 0)
342
+ throw new Error('No UI pieces are added to this application');
343
+ const pieces = names.map((piece) => {
344
+ const manifest = JSON.parse(fs.readFileSync(path.join(installedRoot(projectRoot), piece, 'ui.json'), 'utf8'));
345
+ return { name: piece, requires: manifest.requires };
346
+ });
347
+ const result = await checkRequirements(platformLookup(requireWorkspaceContext(), product, env), env, pieces);
348
+ if (opts.json)
349
+ console.log(JSON.stringify({ product, env, ...result }, null, 2));
350
+ else {
351
+ console.log(`${product} (${env})${result.envKnown ? '' : `: the product has no environment "${env}"`}`);
352
+ if (result.results.length === 0)
353
+ console.log(' The pieces declare no requirements.');
354
+ for (const r of result.results)
355
+ console.log(` ${r.status === 'ok' ? 'ok ' : r.status === 'missing' ? 'missing' : 'unknown'} ${r.piece}: ${r.kind} ${r.ref}${r.detail ? ` (${r.detail})` : ''}`);
356
+ }
357
+ if (!result.ok)
358
+ process.exitCode = 1;
359
+ }
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import { runLogin } from './commands/login.js';
7
7
  import { runLogout } from './commands/logout.js';
8
8
  import { runWhoami } from './commands/whoami.js';
9
+ import { runTroubleshoot } from './commands/troubleshoot.js';
9
10
  import { runDoctor } from './commands/doctor.js';
10
11
  import { runProfilesList, runProfilesUse } from './commands/profiles.js';
11
12
  import { runLink } from './commands/link.js';
@@ -19,6 +20,7 @@ import { runDb, runDbActions, runDbContext } from './commands/db.js';
19
20
  import { runComponentActions } from './commands/component-actions.js';
20
21
  import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback, runDbMigrateBaseline } from './commands/db-migrate.js';
21
22
  import { runFeaturesSync, runFeaturesValidate } from './commands/features-sync.js';
23
+ import { runUiAdd, runUiCheck, runUiCreate, runUiDeprecate, runUiInspect, runUiInstall, runUiList, runUiPack, runUiPublish, runUiRemove, runUiUndeprecate, runUiUpdate, runUiValidate, runUiVerify } from './commands/ui.js';
22
24
  import { runSessionsValidate } from './commands/sessions-validate.js';
23
25
  import { runRateLimits } from './commands/rate-limits.js';
24
26
  import { runDeploy } from './commands/deploy.js';
@@ -127,13 +129,13 @@ const codeTarget = (c) => c
127
129
  .option('--product <tag>').option('--function <name>').option('--fn-version <version>').option('--env <slug>');
128
130
  remote('step-up', 'start', 'Email yourself a six-digit code for one change (a person only)', codeTarget).action(op('stepup.start'));
129
131
  remote('step-up', 'verify', 'Check the code and print a grant, good for ten minutes and for that one change; put it in an environment variable and pass its name with --grant-env', (c) => codeTarget(c).requiredOption('--code <code>', 'the six-digit code from your email')).action(op('stepup.verify'));
130
- remote('plans', 'create', 'Create a plan from a JSON file; nothing is changed', (c) => c.requiredOption('--file <file>', 'Plan request JSON (static egress uses runtime.vpcEgress on Cloud Run with optional provision: true or runtime.awsVpcEgress on Lambda or ECS Fargate)')).action(op('plans.create'));
132
+ remote('plans', 'create', 'Create a plan from a JSON file; nothing is changed', (c) => c.requiredOption('--file <file>', 'Plan request JSON (Cloud Run, Azure Container Apps, and AWS Lambda services accept runtime.publicAccess: true or false with human approval; static egress uses runtime.vpcEgress on Cloud Run with optional provision: true or runtime.awsVpcEgress on Lambda or ECS Fargate)')).action(op('plans.create'));
131
133
  remote('plans', 'approve <planId>', 'Approve a plan (a person only; refused for agents)', grantOption).action(op('plans.approve'));
132
134
  remote('plans', 'list', 'List plans with where each stands: blocked, pending_approval, approved, ready, applied or expired', (c) => c.option('--product <tag>').option('--env <env>').option('--stage <stage>')).action(op('plans.list'));
133
135
  remote('plans', 'get <planId>', 'Show one plan: what it would change, its warnings and the state of the cloud it was made from').action(op('plans.get'));
134
136
  remote('plans', 'apply <planId>', 'Apply an approved or permitted plan').action(op('plans.apply'));
135
137
  remote('deployments', 'list', 'List deployments (functions and services)', (c) => c.option('--product <tag>').option('--env <env>').option('--fn-version <version>').option('--kind <kind>', 'function or service').option('--connection <tag>', 'only what was applied through this cloud connection')).action(op('deployments.list'));
136
- remote('deployments', 'get <deploymentId>', 'Show one deployment').action(op('deployments.get'));
138
+ remote('deployments', 'get <deploymentId>', 'Show one deployment, including functions served by each active service revision').action(op('deployments.get'));
137
139
  remote('deployments', 'journal <deploymentId>', 'Show a deployment\'s journal').action(op('deployments.journal'));
138
140
  const planFromDeployment = (c) => c
139
141
  .option('--runtime-file <file>', 'Runtime settings JSON that replace the deployment\'s own (cpu, memory, minInstances, maxInstances, or Cloud Run vpcEgress with network and subnet names)')
@@ -193,6 +195,15 @@ program
193
195
  skipWorkspaceSelect: Boolean(opts.skipWorkspaceSelect),
194
196
  })));
195
197
  program.command('logout').description('Clear local credentials').action(wrap(runLogout));
198
+ program
199
+ .command('troubleshoot')
200
+ .description('Summarize issues from logs, deployment journals and builds in the active workspace')
201
+ .option('--product <tag>', 'Only this product')
202
+ .option('--since <time>', 'Duration such as 24h or ISO timestamp with timezone', '24h')
203
+ .option('--until <time>', 'ISO timestamp with timezone; defaults to now')
204
+ .option('--max-logs <count>', 'Maximum workspace log records to inspect, 1 to 10000', '5000')
205
+ .option('--json', 'Structured report with evidence and coverage')
206
+ .action(wrap(runTroubleshoot));
196
207
  program
197
208
  .command('doctor')
198
209
  .description('Report CLI, SDK, MCP, API/schema, authentication, and project compatibility facts')
@@ -1090,6 +1101,95 @@ db
1090
1101
  throw new Error('Specify a verb: connect | query');
1091
1102
  return runDb(verb, { file: opts.file, json: opts.json });
1092
1103
  }));
1104
+ const ui = program
1105
+ .command('ui')
1106
+ .description('Frontend UI pieces written once in ductape/ui/ and added to any application of the workspace, which compiles them with its own bundler');
1107
+ ui
1108
+ .command('create <name>')
1109
+ .description('Write a new UI piece under ductape/ui/<name>: manifest, component, styles and README')
1110
+ .option('--framework <framework>', 'react, vue or javascript (plain DOM code any application can use)', 'react')
1111
+ .option('--description <text>', 'One line saying what it is for')
1112
+ .option('--json', 'JSON output')
1113
+ .action(wrap((name, opts) => runUiCreate(name, opts)));
1114
+ ui
1115
+ .command('validate [name]')
1116
+ .description('Check a UI piece (or all of them): manifest, published files, imports, secrets. Offline; changes nothing')
1117
+ .option('--typecheck', 'Also type-check it with this project\'s TypeScript, React and Ductape SDK types')
1118
+ .option('--json', 'JSON output')
1119
+ .action(wrap((name, opts) => runUiValidate(name, { typecheck: Boolean(opts.typecheck), json: Boolean(opts.json) })));
1120
+ ui
1121
+ .command('pack <name>')
1122
+ .description('Validate, then write the publishable artifact with its integrity hash. Offline')
1123
+ .option('--out <file>', 'Where to write it (default ductape/.ui-packs/<name>@<version>.json)')
1124
+ .option('--json', 'JSON output')
1125
+ .action(wrap((name, opts) => runUiPack(name, { out: opts.out, json: Boolean(opts.json) })));
1126
+ ui
1127
+ .command('publish <name>')
1128
+ .description('Validate and pack ductape/ui/<name>, then publish it to this workspace. Published versions never change')
1129
+ .option('--typecheck', 'Type-check before publishing')
1130
+ .option('--dry-run', 'Validate and pack, and say what would be published, without publishing')
1131
+ .option('--json', 'JSON output')
1132
+ .action(wrap((name, opts) => runUiPublish(name, { typecheck: Boolean(opts.typecheck), dryRun: Boolean(opts.dryRun), json: Boolean(opts.json) })));
1133
+ ui
1134
+ .command('list')
1135
+ .description('The UI pieces published in this workspace, with their latest release')
1136
+ .option('--search <text>', 'Only pieces whose name or description contains this')
1137
+ .option('--json', 'JSON output')
1138
+ .action(wrap((opts) => runUiList({ search: opts.search, json: Boolean(opts.json) })));
1139
+ ui
1140
+ .command('inspect <ref>')
1141
+ .description('A piece\'s versions (name), or one version\'s manifest, requirements and files (name@version or name@latest)')
1142
+ .option('--json', 'JSON output')
1143
+ .action(wrap((ref, opts) => runUiInspect(ref, { json: Boolean(opts.json) })));
1144
+ ui
1145
+ .command('deprecate <ref>')
1146
+ .description('Mark name@version deprecated. It stays installable by exact version; latest stops choosing it')
1147
+ .requiredOption('--reason <text>', 'Why, shown to anyone who installs it')
1148
+ .option('--replacement <version>', 'The version to use instead')
1149
+ .option('--json', 'JSON output')
1150
+ .action(wrap((ref, opts) => runUiDeprecate(ref, { reason: opts.reason, replacement: opts.replacement, json: Boolean(opts.json) })));
1151
+ ui
1152
+ .command('undeprecate <ref>')
1153
+ .description('Clear the deprecation of name@version')
1154
+ .option('--json', 'JSON output')
1155
+ .action(wrap((ref, opts) => runUiUndeprecate(ref, { json: Boolean(opts.json) })));
1156
+ ui
1157
+ .command('add <ref>')
1158
+ .description('Add a published piece (name, name@version or name@latest) to this application: its verified source goes in ductape/ui/installed/, pinned in ductape/ui.lock.json, importable as #ui/<name>')
1159
+ .option('--ignore-peers', 'Add it even when the packages it needs are missing or the wrong version')
1160
+ .option('--json', 'JSON output')
1161
+ .action(wrap((ref, opts) => runUiAdd(ref, { ignorePeers: Boolean(opts.ignorePeers), json: Boolean(opts.json) })));
1162
+ ui
1163
+ .command('install')
1164
+ .description('Make ductape/ui/installed/ and package.json match ductape/ui.lock.json, fetching exactly the pinned artifacts where files are missing or changed')
1165
+ .option('--offline', 'Fetch nothing; fail if anything would need fetching')
1166
+ .option('--json', 'JSON output')
1167
+ .action(wrap((opts) => runUiInstall({ offline: Boolean(opts.offline), json: Boolean(opts.json) })));
1168
+ ui
1169
+ .command('update <name>')
1170
+ .description('Move an added piece to its latest release, or to --to <version>')
1171
+ .option('--to <version>', 'Exact version to move to')
1172
+ .option('--ignore-peers', 'Update even when the packages it needs are missing or the wrong version')
1173
+ .option('--json', 'JSON output')
1174
+ .action(wrap((name, opts) => runUiUpdate(name, { to: opts.to, ignorePeers: Boolean(opts.ignorePeers), json: Boolean(opts.json) })));
1175
+ ui
1176
+ .command('remove <name>')
1177
+ .description('Remove an added piece, and any piece it used that nothing else uses')
1178
+ .option('--json', 'JSON output')
1179
+ .action(wrap((name, opts) => runUiRemove(name, { json: Boolean(opts.json) })));
1180
+ ui
1181
+ .command('verify')
1182
+ .description('Offline check for CI: installed pieces are exactly the pinned artifacts, package.json imports them, and the packages they need are installed')
1183
+ .option('--skip-peers', 'Do not check the packages the pieces need')
1184
+ .option('--json', 'JSON output')
1185
+ .action(wrap((opts) => runUiVerify({ skipPeers: Boolean(opts.skipPeers), json: Boolean(opts.json) })));
1186
+ ui
1187
+ .command('check [name]')
1188
+ .description('Online: does the product have the actions, features and sessions the added pieces need? Uses the linked product and environment unless given')
1189
+ .option('--product <tag>', 'Product tag')
1190
+ .option('--env <slug>', 'Environment slug')
1191
+ .option('--json', 'JSON output')
1192
+ .action(wrap((name, opts) => runUiCheck(name, { product: opts.product, env: opts.env, json: Boolean(opts.json) })));
1093
1193
  const features = program.command('features').description('Code-first Ductape Features (ductape/features/)');
1094
1194
  const sessions = program.command('sessions').description('Session lifecycle and propagation checks');
1095
1195
  sessions
@@ -7,8 +7,9 @@ export interface ApiEnvelope<T> {
7
7
  export declare class ApiClient {
8
8
  private readonly apiUrl;
9
9
  private readonly token?;
10
- constructor(apiUrl: string, token?: string | undefined);
11
- static forProfile(profileName?: string, creds?: Credentials | null): ApiClient;
10
+ private readonly timeoutMs?;
11
+ constructor(apiUrl: string, token?: string | undefined, timeoutMs?: number | undefined);
12
+ static forProfile(profileName?: string, creds?: Credentials | null, timeoutMs?: number): ApiClient;
12
13
  request<T>(method: string, path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<T>;
13
14
  post<T>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;
14
15
  put<T>(path: string, body?: unknown, headers?: Record<string, string>): Promise<T>;