@synopackageland/cli 0.48.12 → 0.48.14

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 CHANGED
@@ -1,10 +1,17 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.48.14
4
4
 
5
+ - status, install, uninstall and deploy no longer request the unsupported installing_target package-list field, so DSM versions that reject it work again
6
+ - --json prints one final object on stdout; progress goes to stderr once per change
7
+ - Closing the output pipe no longer abandons stop and uninstall; an interrupted uninstall resumes or reports the package as removed
5
8
  - Reject daemon.nofile in check, build and inspect until package-safe activation is supported
6
9
  - Stop daemons through the non-root SDK controller during migration and teardown; continue executor cleanup after a daemon stop failure
7
10
 
11
+ ## 0.48.13
12
+
13
+ - status and install report the upgrading state while DSM replaces an installed package instead of installed:false; waits use query limits and cancellation instead of short time budgets
14
+
8
15
  ## 0.48.5
9
16
 
10
17
  - Require templates ~0.40.0: new scaffolds pin SDK/App 0.50.0 and UI 0.20.0, whose AppShell pages show no visible title and scroll only their content; the CLI controller SDK default stays 0.49.5
package/README.md CHANGED
@@ -494,18 +494,22 @@ are sent only over a connection whose certificate was inspected. Public package
494
494
  feeds and SPK downloads retain normal HTTPS verification.
495
495
 
496
496
  DSM API requests tolerate slow NAS storage and startup. These environment
497
- variables also work in `.env`; each accepts integer seconds from 1 to 86400:
497
+ variables also work in `.env`; timeout/interval values accept integer seconds from 1 to 86400:
498
498
 
499
499
  | Variable | Default | Budget |
500
500
  | --- | ---: | --- |
501
501
  | `DSM_REQUEST_TIMEOUT_SECONDS` | 180 | One DSM read, login or other API request |
502
502
  | `DSM_OPERATION_TIMEOUT_SECONDS` | 600 | One SPK upload, install/upgrade compound, or package start/stop request |
503
- | `DSM_INSTALL_TIMEOUT_SECONDS` | 1800 | Per-package state check, pre-pull, upload, install/upgrade and startup together, in `install` and `deploy` |
503
+ | `DSM_INSTALL_MAX_POLLS` | 10000 | Per-package polling attempts across initial checks, pre-pull and install/start verification |
504
504
  | `DSM_UNINSTALL_TIMEOUT_SECONDS` | 1800 | State check, stop and uninstall together |
505
- | `DSM_POLL_INTERVAL_SECONDS` | 5 | Package-state polling and progress interval |
505
+ | `DSM_POLL_INTERVAL_SECONDS` | 5 | Package-state polling interval |
506
506
  | `DSM_IMAGE_PULL_STALL_TIMEOUT_SECONDS` | 1200 | No increase in NAS pull bytes; status heartbeats do not reset this budget |
507
507
 
508
- For example, set `DSM_INSTALL_TIMEOUT_SECONDS=3600` for an hour per package.
508
+ Install/upgrade waiting has no default elapsed-time deadline. Slow successful work
509
+ continues until the polling limit (an integer from 1 to 1000000), cancellation or a DSM failure.
510
+ `DSM_INSTALL_TIMEOUT_SECONDS` no longer limits install/deploy waiting. Individual
511
+ requests retain their timeouts; timed-out status requests count toward the polling limit.
512
+ Press Ctrl-C to stop waiting; this does not cancel the NAS operation.
509
513
  Container Apps pre-pull their inspected, locked image references on the NAS before
510
514
  SPK upload. An exact local repository digest skips the registry pull; an image
511
515
  configuration ID or a remote update digest is not sufficient proof. Progress includes bytes; failures name the image, requested registry
@@ -515,6 +519,11 @@ pinned image. Pinning alone does not download layers onto the NAS. Pull tasks
515
519
  are not cancelled or replayed when their response is lost or a budget expires.
516
520
  Broken packages skip stop during uninstall; their existing install error does not
517
521
  block removal, while new uninstall errors still fail clearly.
522
+ Uninstall resumes a stopped or stopping package, waits for an existing uninstall,
523
+ and succeeds when DSM already verifies the package is absent.
524
+ Polling progress goes to stderr only when it changes, in both text and JSON modes.
525
+ `--json` stdout contains one final JSON object. A closed stdout or stderr pipe does
526
+ not interrupt DSM writes; the command finishes and reports its result through its exit code.
518
527
 
519
528
  `logs --json` emits the usual single JSON envelope, including DSM `worker_msg`,
520
529
  status details and the last reported Compose error. A locally retained pre-pull
@@ -522,11 +531,28 @@ failure includes its source and timestamp; it is scoped to NAS origin and packag
522
531
  and cleared after a successful pre-pull. An unavailable lower-level cause stays
523
532
  unknown; a generic `install_corruption` does not prove a registry failure.
524
533
 
534
+ `status <package-id> --json` reports `state: "upgrading"`, `"installing"` or
535
+ `"starting"` during replacement/startup, with `fromVersion`/`toVersion` when known.
536
+ Stopping/removal reports `state: "stopping"` or `"uninstalling"` until DSM verifies completion.
537
+ It never reports `installed:false` for those transitions: an upgrade retains
538
+ `installed:true`; a fresh install without a verified payload uses `installed:null`.
539
+ `status` carries the effective DSM/CLI status. The result contract is
540
+ [schema/package-state.schema.json](schema/package-state.schema.json).
541
+
542
+ The CLI checks DSM package list/status views and retains its own task identity
543
+ in a private cache scoped to the NAS origin and package. Concurrent CLI processes
544
+ under the same local user can therefore identify an upgrade even while DSM lists
545
+ omit the package. After interrupted work, DSM evidence is needed to keep claiming
546
+ an active transition; unresolved absence is `state:"unknown", installed:null`.
547
+ Other clients/machines rely on DSM's exposed transitions. Stable completion requires
548
+ the target version and running state; `install --json` returns that verified state.
549
+
525
550
  An install/upgrade response timeout does not cancel DSM's work: the CLI keeps
526
551
  checking for the requested version **and running state**, without replaying the
527
552
  write. Progress continues on stderr, including with `--json`. A DSM failure
528
- reports `DSM_INSTALL_FAILED` and its reported details; an exhausted overall
529
- budget reports `DSM_INSTALL_TIMEOUT` and warns that DSM may still be working.
553
+ reports `DSM_INSTALL_FAILED` and its reported details. An exhausted polling limit
554
+ reports `DSM_INSTALL_LIMIT`; cancellation reports `DSM_INSTALL_CANCELED` (exit 130).
555
+ Both mean waiting stopped and DSM may still be working.
530
556
  Uninstall also keeps checking after stop/uninstall response or status timeouts,
531
557
  without replaying either write. Its exhausted budget reports `DSM_UNINSTALL_TIMEOUT`.
532
558
  Check Package Center before retrying. A timed-out same-version reinstall also
package/dist/bin.js CHANGED
@@ -7,5 +7,5 @@ loadDotEnv();
7
7
  // Successful completion leaves Node's default 0 or the command's exitCode intact.
8
8
  runCli(process.argv).catch((error) => {
9
9
  console.error(terminalSafe(error instanceof Error ? error.message : String(error)));
10
- process.exit(1);
10
+ process.exit(error?.code === 'DSM_INSTALL_CANCELED' ? 130 : 1);
11
11
  });
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { nasFlags, withNasOptions } from './nas/options.js';
2
+ import { installOutputGuards } from './terminal-output.js';
2
3
  import { upstreamRepository, upstreamMaintainer } from './upstream-attribution.js';
3
4
  import { Command, CommanderError } from "commander";
4
5
  import { CLI_VERSION } from "./cli-version.js";
@@ -298,6 +299,7 @@ async function containerBuild(project, arches, options) {
298
299
  }
299
300
  /** Resolves after dispatch; commands may set process.exitCode. Rejections are failures. */
300
301
  export async function runCli(argv) {
302
+ installOutputGuards();
301
303
  if (argv[2] === 'ctl' && argv[3] === 'external') {
302
304
  const { runCtl } = await import('./ctl/cli.js');
303
305
  return runCtl(argv.slice(3));
@@ -11,7 +11,11 @@ interface CatalogPackageEntry {
11
11
  replacepkgs?: unknown;
12
12
  }
13
13
  export interface InstalledPackageState {
14
- installed: boolean;
14
+ /** null means DSM cannot currently verify an installed payload. */
15
+ installed: boolean | null;
16
+ state?: 'installing' | 'upgrading' | 'starting' | 'stopping' | 'uninstalling' | 'unknown';
17
+ fromVersion?: string;
18
+ toVersion?: string;
15
19
  version?: string;
16
20
  status?: string;
17
21
  error?: {
@@ -32,7 +36,10 @@ export interface UploadedCatalogPackage {
32
36
  }
33
37
  export declare function packageStateFromRecord(value: unknown): InstalledPackageState;
34
38
  export declare function packageStateFromListPayload(payload: unknown, packageId: string): InstalledPackageState | undefined;
35
- export declare function fetchInstalledPackageState(dsmOrigin: string, cookieHeader: string, packageId: string, timeoutMs?: number): Promise<InstalledPackageState | undefined>;
39
+ export declare function fetchInstalledPackageState(dsmOrigin: string, cookieHeader: string, packageId: string, timeoutMs?: number, context?: {
40
+ signal?: AbortSignal;
41
+ ignoreOperation?: boolean;
42
+ }): Promise<InstalledPackageState | undefined>;
36
43
  export interface InstallWaitOptions {
37
44
  packageId: string;
38
45
  expectedVersion?: string;
@@ -41,8 +48,11 @@ export interface InstallWaitOptions {
41
48
  requireRunning?: boolean;
42
49
  requireTransition?: boolean;
43
50
  onProgress?: (message: string) => void;
51
+ maxPolls?: number;
52
+ consumePoll?: () => void;
53
+ signal?: AbortSignal;
44
54
  }
45
- export declare function waitForInstalledVersion(readState: (remainingMs: number) => InstalledPackageState | undefined | Promise<InstalledPackageState | undefined>, options: InstallWaitOptions): Promise<void>;
55
+ export declare function waitForInstalledVersion(readState: (remainingMs: number) => InstalledPackageState | undefined | Promise<InstalledPackageState | undefined>, options: InstallWaitOptions): Promise<InstalledPackageState>;
46
56
  export interface UninstallPackageOptions {
47
57
  dsmOrigin: string;
48
58
  cookieHeader: string;
@@ -73,6 +83,8 @@ export interface LocalSpkInstallOptions {
73
83
  pollMs?: number;
74
84
  onProgress?: (message: string) => void;
75
85
  containerImages?: string[];
86
+ maxPolls?: number;
87
+ signal?: AbortSignal;
76
88
  }
77
- export declare function installPackageFromLocalSpk(options: LocalSpkInstallOptions): Promise<void>;
89
+ export declare function installPackageFromLocalSpk(options: LocalSpkInstallOptions): Promise<InstalledPackageState>;
78
90
  export {};
@@ -1,11 +1,13 @@
1
1
  import { CtlError } from '../ctl/errors.js';
2
2
  import { readFileSync } from "node:fs";
3
- import { terminalSafe } from '../terminal-text.js';
3
+ import { progressReporter } from '../terminal-output.js';
4
4
  import { pullContainerImages } from './container-pull.js';
5
5
  import { savePullFailure } from './package-diagnostics.js';
6
+ import { readPackageOperation, operationOwnerAlive, savePackageOperation, clearPackageOperation, releasePackageOperation } from './package-operation.js';
7
+ import { cancelableInstall, installDelay, installWorkload, installCanceled } from './install-control.js';
6
8
  import { dsmFetch } from "./dsm-http.js";
7
9
  import { assertDsmCompoundResponse } from "./dsm-compound.js";
8
- import { dsmRequestTimeoutMs, dsmOperationTimeoutMs, dsmInstallTimeoutMs, dsmUninstallTimeoutMs, dsmPollIntervalMs, isHostTimeout } from '../nas/timeouts.js';
10
+ import { dsmRequestTimeoutMs, dsmOperationTimeoutMs, dsmUninstallTimeoutMs, dsmPollIntervalMs, isHostTimeout } from '../nas/timeouts.js';
9
11
  function normalizeDeppkgs(deppkgs) {
10
12
  if (typeof deppkgs === "string") {
11
13
  const match = /^([^><=]+)(>=|>|<=|<|==)(.+)$/.exec(deppkgs.trim());
@@ -29,6 +31,7 @@ async function dsmWebApi(dsmOrigin, cookieHeader, params, options = {}) {
29
31
  const query = new URLSearchParams(params);
30
32
  const response = await dsmFetch(`${dsmOrigin}/webapi/entry.cgi?${query.toString()}`, {
31
33
  headers: { cookie: cookieHeader },
34
+ signal: options.signal,
32
35
  }, options.timeoutMs);
33
36
  const body = (await response.json());
34
37
  const errorCode = body.error?.code;
@@ -79,6 +82,16 @@ export function packageStateFromRecord(value) {
79
82
  const state = {
80
83
  installed: Boolean(installedPath) || match.installed === true,
81
84
  };
85
+ const transition = status?.toLowerCase();
86
+ if (transition === 'installing' || transition === 'upgrading' || transition === 'starting' ||
87
+ transition === 'stopping' || transition === 'uninstalling') {
88
+ state.state = transition;
89
+ // DSM can remove installed_info while replacing the payload.
90
+ state.installed = state.installed || transition === 'upgrading' ? true : null;
91
+ const target = stringValue(record(additional.installing_target).version);
92
+ if (target)
93
+ state.toVersion = target;
94
+ }
82
95
  if (version !== undefined)
83
96
  state.version = version;
84
97
  if (status !== undefined)
@@ -115,16 +128,61 @@ export function packageStateFromListPayload(payload, packageId) {
115
128
  }
116
129
  return packageStateFromRecord(match);
117
130
  }
118
- export async function fetchInstalledPackageState(dsmOrigin, cookieHeader, packageId, timeoutMs) {
131
+ export async function fetchInstalledPackageState(dsmOrigin, cookieHeader, packageId, timeoutMs, context = {}) {
119
132
  try {
120
133
  const body = await dsmWebApi(dsmOrigin, cookieHeader, {
121
134
  api: "SYNO.Core.Package",
122
135
  version: "2",
123
136
  method: "list",
137
+ // installing_target is not a supported additional field on some DSM 7.x
138
+ // versions (error 120). Transitions come from status/list_status and the
139
+ // retained installation task; only report a target version with evidence.
124
140
  additional: JSON.stringify(["status", "installed_info"]),
125
141
  ignore_hidden: "false",
126
- }, { timeoutMs });
127
- return packageStateFromListPayload(body, packageId);
142
+ }, { timeoutMs, signal: context.signal });
143
+ if (!Array.isArray(record(body.data).packages))
144
+ return undefined;
145
+ let state = packageStateFromListPayload(body, packageId);
146
+ const operation = context.ignoreOperation ? undefined : readPackageOperation(dsmOrigin, packageId);
147
+ if (operation && state.installed && state.version === operation.toVersion && /^(run|running)$/i.test(state.status ?? '') &&
148
+ operation.fromVersion !== operation.toVersion)
149
+ return state;
150
+ if (!state.installed && !state.state) {
151
+ // An independent DSM view can retain a transition while list temporarily omits the package.
152
+ const statuses = await dsmWebApi(dsmOrigin, cookieHeader, {
153
+ api: 'SYNO.Core.Package', method: 'list_status', version: '1',
154
+ }, { timeoutMs, signal: context.signal });
155
+ if (!Array.isArray(record(statuses.data).packages))
156
+ return undefined;
157
+ const entry = record(statuses.data).packages.map(record).find(item => item.id === packageId);
158
+ if (entry) {
159
+ state = packageStateFromRecord(entry);
160
+ if (!state.state)
161
+ state.installed = true;
162
+ }
163
+ }
164
+ if (operation && !state.state && !(state.installed && packageFailure(state))) {
165
+ const task = await dsmWebApi(dsmOrigin, cookieHeader, {
166
+ api: 'SYNO.Core.Package.Installation', method: 'status', version: '1', task_id: jsonApiParam(operation.taskId),
167
+ }, { timeoutMs, signal: context.signal, allowFailure: true });
168
+ const data = record(task.data);
169
+ const active = task.success === true && data.id === packageId &&
170
+ (/^(installing|upgrading|starting)$/i.test(String(data.status ?? '')) || data.installing === true);
171
+ if (active || operationOwnerAlive(operation))
172
+ return {
173
+ ...state, installed: operation.operation === 'upgrading' ? true : null,
174
+ state: operation.operation, status: operation.operation,
175
+ fromVersion: operation.fromVersion, toVersion: operation.toVersion,
176
+ };
177
+ if (state.installed === false)
178
+ return { ...state, installed: null, state: 'unknown',
179
+ fromVersion: operation.fromVersion, toVersion: operation.toVersion };
180
+ }
181
+ if (operation && state.state)
182
+ return { ...state,
183
+ installed: operation.operation === 'upgrading' ? true : state.installed,
184
+ fromVersion: operation.fromVersion, toVersion: operation.toVersion };
185
+ return state;
128
186
  }
129
187
  catch (error) {
130
188
  if (error instanceof CtlError)
@@ -155,18 +213,23 @@ function installBudgetExpired(options) {
155
213
  return new CtlError('DSM_INSTALL_TIMEOUT', `Timed out waiting for ${options.packageId}${target}: overall install budget exhausted; DSM may still be installing/starting.`, 'Check Package Center state before retrying; the install was not replayed');
156
214
  }
157
215
  export async function waitForInstalledVersion(readState, options) {
158
- const deadline = Date.now() + (options.deadlineMs ?? dsmInstallTimeoutMs());
216
+ // Only an explicitly supplied caller deadline constrains elapsed time.
217
+ const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + options.deadlineMs;
218
+ const consumePoll = options.consumePoll ?? installWorkload(options.packageId, options.maxPolls);
159
219
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
220
+ const progress = progressReporter(options.onProgress);
160
221
  let transitioned = !options.requireTransition;
161
222
  while (Date.now() < deadline) {
223
+ consumePoll();
162
224
  let state;
225
+ let timedOut = false;
163
226
  try {
164
- state = await readState(Math.max(1, deadline - Date.now()));
227
+ state = await cancelableInstall(() => Promise.resolve(readState(Math.min(dsmRequestTimeoutMs(), Math.max(1, deadline - Date.now())))), options.signal);
165
228
  }
166
229
  catch (error) {
167
230
  if (!isHostTimeout(error))
168
231
  throw error;
169
- options.onProgress?.(`${options.packageId}: status request timed out; still installing/starting…`);
232
+ timedOut = true;
170
233
  }
171
234
  if (state && !installInProgress(state) && packageFailure(state)) {
172
235
  throw new CtlError('DSM_INSTALL_FAILED', `DSM reports package ${options.packageId} install did not complete (Package Center status ${state.status ?? 'unknown'}): ${failureDetail(state)}`.trim(), 'Check the DSM Package Center install/start log');
@@ -180,9 +243,10 @@ export async function waitForInstalledVersion(readState, options) {
180
243
  if (state?.installed && !/installing|upgrading|starting/i.test(state.status ?? '') &&
181
244
  (!options.expectedVersion || state.version === options.expectedVersion) &&
182
245
  (!options.requireRunning || running) && transitioned)
183
- return;
184
- options.onProgress?.(`${options.packageId}: installing/starting… (DSM status ${state?.status ?? 'unavailable'})`);
185
- await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
246
+ return state;
247
+ progress(timedOut ? `${options.packageId}: status request timed out; still installing/starting…` :
248
+ `${options.packageId}: installing/starting… (DSM status ${state?.status ?? 'unavailable'})`);
249
+ await installDelay(Math.min(pollMs, Math.max(0, deadline - Date.now())), options.signal);
186
250
  }
187
251
  throw installBudgetExpired(options);
188
252
  }
@@ -202,7 +266,7 @@ export async function uninstallPackageFromDsm(options) {
202
266
  const deadline = Date.now() + (options.deadlineMs ?? dsmUninstallTimeoutMs());
203
267
  const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
204
268
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
205
- const progress = options.onProgress ?? (message => process.stderr.write(`${terminalSafe(message)}\n`));
269
+ const progress = progressReporter(options.onProgress);
206
270
  let phase = 'checking package state';
207
271
  let previousFailure;
208
272
  const expired = () => new CtlError('DSM_UNINSTALL_TIMEOUT', `Package ${options.packageId}: overall uninstall budget exhausted while ${phase}; DSM may still be stopping/uninstalling.`, 'Check Package Center before retrying; stop/uninstall requests were not replayed');
@@ -211,19 +275,19 @@ export async function uninstallPackageFromDsm(options) {
211
275
  throw expired();
212
276
  return Math.min(limit, deadline - Date.now());
213
277
  };
214
- const heartbeat = setInterval(() => progress(`${options.packageId}: ${phase}…`), pollMs);
215
278
  try {
216
279
  const sid = extractSid(options.cookieHeader);
217
280
  const wait = async (done) => {
218
281
  while (Date.now() < deadline) {
219
282
  let state;
283
+ let timedOut = false;
220
284
  try {
221
285
  state = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs));
222
286
  }
223
287
  catch (error) {
224
288
  if (!isHostTimeout(error))
225
289
  throw error;
226
- progress(`${options.packageId}: status request timed out; ${phase}…`);
290
+ timedOut = true;
227
291
  }
228
292
  if (state && Date.now() < deadline) {
229
293
  if (done(state))
@@ -231,7 +295,8 @@ export async function uninstallPackageFromDsm(options) {
231
295
  if (packageFailure(state) && !(phase === 'uninstalling' && previousFailure === failureDetail(state)))
232
296
  throw new CtlError('DSM_UNINSTALL_FAILED', `DSM reports ${options.packageId} failed while ${phase}: ${failureDetail(state) || state.status}`, 'Check the DSM Package Center stop/uninstall log');
233
297
  }
234
- progress(`${options.packageId}: ${phase}… (DSM status ${state?.status ?? 'unavailable'})`);
298
+ progress(timedOut ? `${options.packageId}: status request timed out; ${phase}…` :
299
+ `${options.packageId}: ${phase}…${state?.status === phase ? '' : ` (DSM status ${state?.status ?? 'unavailable'})`}`);
235
300
  await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
236
301
  }
237
302
  throw expired();
@@ -250,8 +315,21 @@ export async function uninstallPackageFromDsm(options) {
250
315
  progress(`${options.packageId}: ${method} request timed out; checking DSM state without replay…`);
251
316
  }
252
317
  };
253
- const before = await wait(() => true);
254
- if (!before.installed)
318
+ let before = await wait(() => true);
319
+ if (before.state === 'uninstalling') {
320
+ phase = 'uninstalling';
321
+ progress(`${options.packageId}: ${phase}…`);
322
+ await wait(state => state.installed === false);
323
+ return;
324
+ }
325
+ if (before.state === 'stopping') {
326
+ phase = 'stopping';
327
+ progress(`${options.packageId}: ${phase}…`);
328
+ before = await wait(state => state.installed === false || packageStatusIsStopped(state));
329
+ }
330
+ if (before.state || before.installed === null)
331
+ throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} has an unresolved operation`, 'Wait for DSM to finish before uninstalling');
332
+ if (before.installed === false)
255
333
  return;
256
334
  const broken = packageFailure(before) && !installInProgress(before);
257
335
  if (broken) {
@@ -261,20 +339,17 @@ export async function uninstallPackageFromDsm(options) {
261
339
  if (!broken && !packageStatusIsStopped(before)) {
262
340
  phase = 'stopping';
263
341
  await dispatch('SYNO.Core.Package.Control', 'stop');
264
- const stopped = await wait(state => !state.installed || packageStatusIsStopped(state));
265
- if (!stopped.installed)
342
+ const stopped = await wait(state => state.installed === false || packageStatusIsStopped(state));
343
+ if (stopped.installed === false)
266
344
  return;
267
345
  }
268
346
  phase = 'uninstalling';
269
347
  await dispatch('SYNO.Core.Package.Uninstallation', 'uninstall');
270
- await wait(state => !state.installed);
348
+ await wait(state => state.installed === false);
271
349
  }
272
350
  catch (error) {
273
351
  throw uninstallFailure(options.packageId, error);
274
352
  }
275
- finally {
276
- clearInterval(heartbeat);
277
- }
278
353
  }
279
354
  export function catalogInstallationRequests(entry, installed, sid, volumePath) {
280
355
  const install = {
@@ -368,6 +443,7 @@ async function uploadLocalSpk(options, sid, timeoutMs) {
368
443
  method: "POST",
369
444
  headers: { cookie: options.cookieHeader },
370
445
  body: form,
446
+ signal: options.signal,
371
447
  }, timeoutMs);
372
448
  const body = (await uploadResponse.json());
373
449
  if (!body.success || !body.data?.id || !body.data.task_id) {
@@ -376,24 +452,34 @@ async function uploadLocalSpk(options, sid, timeoutMs) {
376
452
  return { id: body.data.id, taskId: body.data.task_id };
377
453
  }
378
454
  export async function installPackageFromLocalSpk(options) {
379
- // The same wall budget covers upload, install/upgrade and startup verification.
380
- const deadline = Date.now() + (options.deadlineMs ?? dsmInstallTimeoutMs());
455
+ const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + options.deadlineMs;
456
+ const consumePoll = installWorkload(options.packageId, options.maxPolls);
457
+ const controller = new AbortController();
458
+ const cancel = () => controller.abort();
459
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
460
+ options = { ...options, signal };
461
+ let operation;
462
+ let verified = false;
381
463
  const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
382
464
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
383
- const progress = options.onProgress ?? (message => process.stderr.write(`${terminalSafe(message)}\n`));
465
+ const progress = progressReporter(options.onProgress);
384
466
  let phase = 'checking package state';
385
467
  const remaining = (limit) => {
468
+ if (signal.aborted)
469
+ throw installCanceled();
386
470
  if (Date.now() >= deadline)
387
471
  throw installBudgetExpired(options);
388
472
  return Math.min(limit, deadline - Date.now());
389
473
  };
390
- const heartbeat = setInterval(() => progress(`${options.packageId}: ${phase}…`), pollMs);
474
+ process.once('SIGINT', cancel);
475
+ process.once('SIGTERM', cancel);
391
476
  try {
392
477
  const sid = extractSid(options.cookieHeader);
393
478
  let before;
394
479
  while (!before) {
480
+ consumePoll();
395
481
  try {
396
- before = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs));
482
+ before = await cancelableInstall(() => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal }), signal);
397
483
  }
398
484
  catch (error) {
399
485
  if (!isHostTimeout(error))
@@ -401,14 +487,16 @@ export async function installPackageFromLocalSpk(options) {
401
487
  }
402
488
  if (!before) {
403
489
  progress(`${options.packageId}: waiting for DSM package state…`);
404
- await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, remaining(requestMs))));
490
+ await installDelay(Math.min(pollMs, remaining(requestMs)), signal);
405
491
  }
406
492
  }
493
+ if (before.state || before.installed === null)
494
+ throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} already has an unresolved operation`, 'Check package status before installing again');
407
495
  if (options.containerImages?.length) {
408
496
  phase = 'pulling container images';
409
497
  try {
410
498
  await pullContainerImages({ ...options, images: options.containerImages,
411
- deadlineMs: remaining(Number.MAX_SAFE_INTEGER), pollMs, onProgress: progress });
499
+ deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, consumePoll, signal, pollMs, onProgress: progress });
412
500
  savePullFailure(options.dsmOrigin, options.packageId);
413
501
  }
414
502
  catch (error) {
@@ -418,16 +506,18 @@ export async function installPackageFromLocalSpk(options) {
418
506
  }
419
507
  phase = 'uploading';
420
508
  progress(`${options.packageId}: uploading…`);
421
- const uploaded = await uploadLocalSpk(options, sid, remaining(operationMs));
509
+ const uploaded = await cancelableInstall(() => uploadLocalSpk(options, sid, remaining(operationMs)), signal);
422
510
  const compound = JSON.stringify(catalogCompoundSteps(uploaded, { version: options.version, size: readFileSync(options.spkPath).byteLength }, { blupgrade: before.installed, extraValues: options.extraValues }));
423
- phase = 'installing/starting';
511
+ phase = before.installed ? 'upgrading' : 'installing';
512
+ operation = savePackageOperation(options.dsmOrigin, options.packageId, { taskId: uploaded.taskId,
513
+ operation: before.installed ? 'upgrading' : 'installing', fromVersion: before.installed ? before.version : undefined, toVersion: options.version });
424
514
  progress(`${options.packageId}: ${phase}…`);
425
515
  let timedOut = false;
426
516
  try {
427
- const response = await dsmWebApi(options.dsmOrigin, options.cookieHeader, {
517
+ const response = await cancelableInstall(() => dsmWebApi(options.dsmOrigin, options.cookieHeader, {
428
518
  api: 'SYNO.Entry.Request', version: '1', method: 'request', stop_when_error: 'true',
429
519
  mode: jsonApiParam('sequential'), compound, _sid: sid,
430
- }, { allowFailure: true, timeoutMs: remaining(operationMs) });
520
+ }, { allowFailure: true, timeoutMs: remaining(operationMs), signal }), signal);
431
521
  assertDsmCompoundResponse(response);
432
522
  }
433
523
  catch (error) {
@@ -436,13 +526,18 @@ export async function installPackageFromLocalSpk(options) {
436
526
  timedOut = true;
437
527
  progress(`${options.packageId}: install/upgrade request timed out; DSM may still be installing/starting; checking state…`);
438
528
  }
439
- await waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget)), { packageId: options.packageId, expectedVersion: options.version,
440
- deadlineMs: remaining(Number.MAX_SAFE_INTEGER), pollMs, requireRunning: true,
529
+ const completed = await waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version,
530
+ deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, pollMs, requireRunning: true, consumePoll, signal,
441
531
  // A lost same-version reinstall reply must not accept the old running instance.
442
- requireTransition: timedOut && before.installed && before.version === options.version,
532
+ requireTransition: timedOut && before.installed === true && before.version === options.version,
443
533
  onProgress: progress });
534
+ verified = true;
535
+ progress(`${options.packageId}: ${phase} complete (${completed.version}, DSM status ${completed.status})`);
536
+ return completed;
444
537
  }
445
538
  catch (error) {
539
+ if (signal.aborted)
540
+ throw installCanceled();
446
541
  if (isHostTimeout(error)) {
447
542
  if (Date.now() >= deadline)
448
543
  throw installBudgetExpired(options);
@@ -451,6 +546,13 @@ export async function installPackageFromLocalSpk(options) {
451
546
  throw error;
452
547
  }
453
548
  finally {
454
- clearInterval(heartbeat);
549
+ process.removeListener('SIGINT', cancel);
550
+ process.removeListener('SIGTERM', cancel);
551
+ if (operation) {
552
+ if (verified)
553
+ clearPackageOperation(options.dsmOrigin, options.packageId, operation);
554
+ else
555
+ releasePackageOperation(options.dsmOrigin, options.packageId, operation);
556
+ }
455
557
  }
456
558
  }
@@ -12,6 +12,8 @@ interface PullOptions {
12
12
  stallMs?: number;
13
13
  pollMs?: number;
14
14
  onProgress?: (message: string) => void;
15
+ consumePoll?: () => void;
16
+ signal?: AbortSignal;
15
17
  }
16
18
  /** Pull on the NAS, before Package Center can turn a registry failure into broken/150. */
17
19
  export declare function pullContainerImages(options: PullOptions): Promise<void>;
@@ -1,10 +1,11 @@
1
1
  import { CtlError } from '../ctl/errors.js';
2
2
  import { parseImageReference } from '../images/pin.js';
3
3
  import { registryBaseUrl } from '../compose/registry-mirrors.js';
4
- import { terminalSafe } from '../terminal-text.js';
4
+ import { progressReporter } from '../terminal-output.js';
5
5
  import { maskDiagnostic } from './package-diagnostics.js';
6
+ import { installWorkload, installCanceled, installDelay } from './install-control.js';
6
7
  import { dsmFetch } from './dsm-http.js';
7
- import { dsmRequestTimeoutMs, dsmInstallTimeoutMs, dsmPollIntervalMs, dsmPullStallTimeoutMs, isHostTimeout } from '../nas/timeouts.js';
8
+ import { dsmRequestTimeoutMs, dsmPollIntervalMs, dsmPullStallTimeoutMs, isHostTimeout } from '../nas/timeouts.js';
8
9
  /** Use inspected effective references: these include the lock's digest and mirror. */
9
10
  export function containerImageReferences(report) {
10
11
  return [...new Set((report.compose?.images ?? []).map(value => {
@@ -18,10 +19,11 @@ const hint = 'Configure a reachable registry mirror, trust the inspecting CA in
18
19
  const causePattern = /error|fail|denied|forbidden|unauthorized|x509|certificate|tls|timeout|timed out|refused|no such host|not found|too many requests|429|403|unexpected.*status/i;
19
20
  /** Pull on the NAS, before Package Center can turn a registry failure into broken/150. */
20
21
  export async function pullContainerImages(options) {
21
- const deadline = Date.now() + (options.deadlineMs ?? dsmInstallTimeoutMs());
22
+ const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + options.deadlineMs;
23
+ const consumePoll = options.consumePoll ?? installWorkload('container image pull');
22
24
  const stallMs = options.stallMs ?? dsmPullStallTimeoutMs();
23
25
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
24
- const progress = options.onProgress ?? (line => process.stderr.write(`${terminalSafe(line)}\n`));
26
+ const progress = progressReporter(options.onProgress);
25
27
  for (const image of new Set(options.images)) {
26
28
  const parsed = parseImageReference(image);
27
29
  if (!parsed)
@@ -32,6 +34,8 @@ export async function pullContainerImages(options) {
32
34
  const fail = (code, detail) => new CtlError(code, maskDiagnostic(`${context}: ${detail}`), hint);
33
35
  let lastAdvance = Date.now(), downloaded = -1;
34
36
  const remaining = () => {
37
+ if (options.signal?.aborted)
38
+ throw installCanceled();
35
39
  if (Date.now() >= deadline)
36
40
  throw fail('CONTAINER_PULL_TIMEOUT', 'overall install/pull budget exhausted; NAS pull outcome may still be pending');
37
41
  if (Date.now() - lastAdvance >= stallMs)
@@ -41,6 +45,7 @@ export async function pullContainerImages(options) {
41
45
  const call = async (method, params) => {
42
46
  const response = await dsmFetch(`${options.dsmOrigin}/webapi/entry.cgi`, {
43
47
  method: 'POST', headers: { cookie: options.cookieHeader, 'content-type': 'application/x-www-form-urlencoded' },
48
+ signal: options.signal,
44
49
  body: new URLSearchParams({ api: 'SYNO.Docker.Image', version: '1', method, ...params }),
45
50
  }, remaining());
46
51
  const body = await response.json();
@@ -51,8 +56,6 @@ export async function pullContainerImages(options) {
51
56
  return body.data;
52
57
  };
53
58
  progress(`${context}: starting NAS image pull…`);
54
- // Even while a NAS request is pending, keep stderr alive.
55
- const heartbeat = setInterval(() => progress(`${context}: pulling… (${Math.max(0, downloaded)} bytes)`), pollMs);
56
59
  try {
57
60
  if (parsed.digest) {
58
61
  const inventory = await call('list', { offset: '0', limit: '-1' });
@@ -81,6 +84,7 @@ export async function pullContainerImages(options) {
81
84
  lastAdvance = Date.now();
82
85
  while (true) {
83
86
  remaining();
87
+ consumePoll();
84
88
  let state;
85
89
  try {
86
90
  state = await call('pull_status', { task_id: task.task_id });
@@ -105,16 +109,13 @@ export async function pullContainerImages(options) {
105
109
  if (state.finished)
106
110
  break;
107
111
  }
108
- await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, remaining())));
112
+ await installDelay(Math.min(pollMs, remaining()), options.signal);
109
113
  }
110
114
  }
111
115
  catch (error) {
112
- if (error instanceof CtlError && error.code.startsWith('CONTAINER_PULL_'))
116
+ if (error instanceof CtlError && (error.code.startsWith('CONTAINER_PULL_') || error.code.startsWith('DSM_INSTALL_')))
113
117
  throw error;
114
118
  throw fail('CONTAINER_PULL_FAILED', `NAS image pull failed: ${error instanceof Error ? error.message : 'unknown transport error'}`);
115
119
  }
116
- finally {
117
- clearInterval(heartbeat);
118
- }
119
120
  }
120
121
  }
@@ -0,0 +1,6 @@
1
+ import { CtlError } from '../ctl/errors.js';
2
+ export declare function installCanceled(): CtlError;
3
+ export declare function cancelableInstall<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T>;
4
+ export declare function installDelay(ms: number, signal?: AbortSignal): Promise<void>;
5
+ export declare function installPollLimit(): number;
6
+ export declare function installWorkload(packageId: string, maximum?: number): () => void;
@@ -0,0 +1,39 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { CtlError } from '../ctl/errors.js';
3
+ export function installCanceled() {
4
+ return new CtlError('DSM_INSTALL_CANCELED', 'Stopped waiting for DSM; the package operation may still be running.', 'Check package status before retrying; the write was not replayed', 130);
5
+ }
6
+ export async function cancelableInstall(work, signal) {
7
+ if (signal?.aborted)
8
+ throw installCanceled();
9
+ return new Promise((resolve, reject) => {
10
+ const abort = () => { signal?.removeEventListener('abort', abort); reject(installCanceled()); };
11
+ signal?.addEventListener('abort', abort, { once: true });
12
+ Promise.resolve().then(() => { if (signal?.aborted)
13
+ throw installCanceled(); return work(); }).then(value => { signal?.removeEventListener('abort', abort); resolve(value); }, error => { signal?.removeEventListener('abort', abort); reject(error); });
14
+ });
15
+ }
16
+ export async function installDelay(ms, signal) {
17
+ try {
18
+ await delay(ms, undefined, { signal });
19
+ }
20
+ catch {
21
+ throw installCanceled();
22
+ }
23
+ }
24
+ export function installPollLimit() {
25
+ const raw = process.env.DSM_INSTALL_MAX_POLLS ?? '10000';
26
+ const value = Number(raw);
27
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < 1 || value > 1000000)
28
+ throw new CtlError('DSM_INSTALL_LIMIT_INVALID', 'DSM_INSTALL_MAX_POLLS must be an integer from 1 to 1000000', 'Set a positive poll limit');
29
+ return value;
30
+ }
31
+ export function installWorkload(packageId, maximum = installPollLimit()) {
32
+ if (!Number.isSafeInteger(maximum) || maximum < 1)
33
+ throw new Error('Invalid install poll limit');
34
+ let polls = 0;
35
+ return () => {
36
+ if (++polls > maximum)
37
+ throw new CtlError('DSM_INSTALL_LIMIT', `Package ${packageId}: install status query limit reached; DSM may still be working.`, 'Check package status before retrying; no mutation was replayed');
38
+ };
39
+ }
@@ -58,20 +58,22 @@ export declare function uninstallPackage(id: string, options?: {
58
58
  yes?: boolean;
59
59
  dryRun?: boolean;
60
60
  }): Promise<{
61
- dryRun: boolean;
61
+ dryRun?: boolean | undefined;
62
62
  host: string;
63
63
  package: string;
64
- action: string;
65
- installed?: undefined;
64
+ installed: boolean;
65
+ action?: undefined;
66
66
  } | {
67
+ dryRun: boolean;
67
68
  host: string;
68
69
  package: string;
69
- installed: boolean;
70
- dryRun?: undefined;
71
- action?: undefined;
70
+ action: string;
72
71
  }>;
73
72
  export declare function packageStatus(id: string, host?: string): Promise<{
74
- installed: boolean;
73
+ installed: boolean | null;
74
+ state?: "installing" | "upgrading" | "starting" | "stopping" | "uninstalling" | "unknown";
75
+ fromVersion?: string;
76
+ toVersion?: string;
75
77
  version?: string;
76
78
  status?: string;
77
79
  error?: {
@@ -174,8 +174,9 @@ export async function installPackage(spec, options = {}, connection) {
174
174
  files.set(entry.package, file);
175
175
  images.set(entry.package, containerImageReferences(checked));
176
176
  }
177
- for (const entry of changes)
178
- await installPackageFromLocalSpk({
177
+ let completed;
178
+ for (const entry of changes) {
179
+ const state = await installPackageFromLocalSpk({
179
180
  dsmOrigin: nas.session.origin,
180
181
  cookieHeader: nas.session.cookie,
181
182
  packageId: entry.package,
@@ -184,9 +185,12 @@ export async function installPackage(spec, options = {}, connection) {
184
185
  containerImages: images.get(entry.package),
185
186
  extraValues: entry.package === root.package ? options.param : undefined,
186
187
  });
188
+ if (entry.package === root.package)
189
+ completed = state;
190
+ }
187
191
  return {
188
192
  ...publicPlan,
189
- status: await fetchInstalledPackageState(nas.session.origin, nas.session.cookie, root.package),
193
+ status: completed ?? await fetchInstalledPackageState(nas.session.origin, nas.session.cookie, root.package),
190
194
  };
191
195
  }
192
196
  finally {
@@ -197,8 +201,13 @@ export async function uninstallPackage(id, options = {}) {
197
201
  packageId(id);
198
202
  const nas = await connectNas(options.host);
199
203
  const state = await fetchInstalledPackageState(nas.session.origin, nas.session.cookie, id);
200
- if (!state?.installed)
201
- throw fail("PACKAGE_NOT_INSTALLED", `Package ${id} is not installed`);
204
+ if (!state)
205
+ throw fail('PACKAGE_STATUS_UNKNOWN', 'DSM did not return a verifiable package state');
206
+ if (state.installed === false && !state.state)
207
+ return { host: nas.name, package: id, installed: false, ...(options.dryRun ? { dryRun: true } : {}) };
208
+ const resuming = state.state === 'stopping' || state.state === 'uninstalling';
209
+ if (!resuming && (state.state || state.installed === null))
210
+ throw fail('PACKAGE_BUSY', `Package ${id} has an unresolved operation`);
202
211
  if (options.dryRun)
203
212
  return { dryRun: true, host: nas.name, package: id, action: "uninstall" };
204
213
  await requireAdministrator(nas);
@@ -0,0 +1,15 @@
1
+ /** Shared by concurrent CLI processes; never contains DSM credentials or wizard input. */
2
+ export interface PackageOperation {
3
+ token: string;
4
+ pid: number;
5
+ taskId: string;
6
+ operation: 'installing' | 'upgrading';
7
+ fromVersion?: string;
8
+ toVersion: string;
9
+ }
10
+ export declare function readPackageOperation(origin: string, id: string): PackageOperation | undefined;
11
+ export declare function operationOwnerAlive(operation: PackageOperation): boolean;
12
+ /** Preserve uncertain work after cancellation/transport loss, without claiming a live waiter. */
13
+ export declare function releasePackageOperation(origin: string, id: string, operation: PackageOperation): void;
14
+ export declare function savePackageOperation(origin: string, id: string, input: Omit<PackageOperation, 'token' | 'pid'>): PackageOperation;
15
+ export declare function clearPackageOperation(origin: string, id: string, operation: PackageOperation): void;
@@ -0,0 +1,52 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, dirname } from 'node:path';
5
+ function pathFor(origin, id) {
6
+ const key = createHash('sha256').update(new URL(origin).origin + '\0' + id).digest('hex');
7
+ return join(process.env.SYNOPKGLAND_OPERATIONS_DIR ?? join(homedir(), '.cache/synopkgland/operations'), key + '.json');
8
+ }
9
+ export function readPackageOperation(origin, id) {
10
+ try {
11
+ const value = JSON.parse(readFileSync(pathFor(origin, id), 'utf8'));
12
+ if (typeof value.token === 'string' && Number.isInteger(value.pid) && value.pid >= 0 &&
13
+ typeof value.taskId === 'string' && typeof value.toVersion === 'string' &&
14
+ ['installing', 'upgrading'].includes(value.operation) &&
15
+ (value.fromVersion === undefined || typeof value.fromVersion === 'string'))
16
+ return value;
17
+ }
18
+ catch { /* No retained operation. */ }
19
+ return undefined;
20
+ }
21
+ export function operationOwnerAlive(operation) {
22
+ if (!operation.pid)
23
+ return false;
24
+ try {
25
+ process.kill(operation.pid, 0);
26
+ return true;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** Preserve uncertain work after cancellation/transport loss, without claiming a live waiter. */
33
+ export function releasePackageOperation(origin, id, operation) {
34
+ if (readPackageOperation(origin, id)?.token !== operation.token)
35
+ return;
36
+ const file = pathFor(origin, id), temporary = `${file}.${operation.token}.tmp`;
37
+ writeFileSync(temporary, JSON.stringify({ ...operation, pid: 0 }), { mode: 0o600 });
38
+ renameSync(temporary, file);
39
+ }
40
+ export function savePackageOperation(origin, id, input) {
41
+ const operation = { ...input, token: randomUUID(), pid: process.pid };
42
+ const file = pathFor(origin, id);
43
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
44
+ const temporary = `${file}.${operation.token}.tmp`;
45
+ writeFileSync(temporary, JSON.stringify(operation), { mode: 0o600 });
46
+ renameSync(temporary, file);
47
+ return operation;
48
+ }
49
+ export function clearPackageOperation(origin, id, operation) {
50
+ if (readPackageOperation(origin, id)?.token === operation.token)
51
+ rmSync(pathFor(origin, id), { force: true });
52
+ }
@@ -1,6 +1,7 @@
1
1
  export declare const dsmRequestTimeoutMs: () => number;
2
2
  export declare const dsmOperationTimeoutMs: () => number;
3
3
  export declare const dsmUninstallTimeoutMs: () => number;
4
+ /** @deprecated Install waiting now uses a workload limit and cancellation. */
4
5
  export declare const dsmInstallTimeoutMs: () => number;
5
6
  export declare const dsmPollIntervalMs: () => number;
6
7
  export declare const dsmPullStallTimeoutMs: () => number;
@@ -11,6 +11,7 @@ function seconds(name, fallback) {
11
11
  export const dsmRequestTimeoutMs = () => seconds('DSM_REQUEST_TIMEOUT_SECONDS', 180);
12
12
  export const dsmOperationTimeoutMs = () => seconds('DSM_OPERATION_TIMEOUT_SECONDS', 600);
13
13
  export const dsmUninstallTimeoutMs = () => seconds('DSM_UNINSTALL_TIMEOUT_SECONDS', 1800);
14
+ /** @deprecated Install waiting now uses a workload limit and cancellation. */
14
15
  export const dsmInstallTimeoutMs = () => seconds('DSM_INSTALL_TIMEOUT_SECONDS', 1800);
15
16
  export const dsmPollIntervalMs = () => seconds('DSM_POLL_INTERVAL_SECONDS', 5);
16
17
  export const dsmPullStallTimeoutMs = () => seconds('DSM_IMAGE_PULL_STALL_TIMEOUT_SECONDS', 1200);
@@ -0,0 +1,4 @@
1
+ /** A disconnected output consumer must not abandon a dispatched DSM mutation. */
2
+ export declare function installOutputGuards(): void;
3
+ /** Report changes, keeping machine-readable command results on stdout. */
4
+ export declare function progressReporter(output?: (message: string) => void): (message: string) => void;
@@ -0,0 +1,36 @@
1
+ import { terminalSafe } from './terminal-text.js';
2
+ const guarded = new WeakSet();
3
+ let signalGuarded = false;
4
+ const brokenPipe = (error) => error?.code === 'EPIPE';
5
+ /** A disconnected output consumer must not abandon a dispatched DSM mutation. */
6
+ export function installOutputGuards() {
7
+ for (const stream of [process.stdout, process.stderr]) {
8
+ if (guarded.has(stream))
9
+ continue;
10
+ guarded.add(stream);
11
+ stream.on('error', error => { if (!brokenPipe(error))
12
+ throw error; });
13
+ }
14
+ if (!signalGuarded) {
15
+ signalGuarded = true;
16
+ process.on('SIGPIPE', () => { });
17
+ }
18
+ }
19
+ /** Report changes, keeping machine-readable command results on stdout. */
20
+ export function progressReporter(output = message => {
21
+ process.stderr.write(`${terminalSafe(message)}\n`);
22
+ }) {
23
+ let previous;
24
+ return message => {
25
+ if (message === previous)
26
+ return;
27
+ previous = message;
28
+ try {
29
+ output(message);
30
+ }
31
+ catch (error) {
32
+ if (!brokenPipe(error))
33
+ throw error;
34
+ }
35
+ };
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.48.12",
3
+ "version": "0.48.14",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,90 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://synopkgland.com/schema/package-state.schema.json",
4
+ "title": "DSM package state",
5
+ "description": "The data of status <package-id> --json, or the status field of install --json. installed:null means the installed payload cannot currently be verified.",
6
+ "type": "object",
7
+ "required": [
8
+ "installed"
9
+ ],
10
+ "properties": {
11
+ "installed": {
12
+ "type": [
13
+ "boolean",
14
+ "null"
15
+ ]
16
+ },
17
+ "state": {
18
+ "enum": [
19
+ "installing",
20
+ "upgrading",
21
+ "starting",
22
+ "stopping",
23
+ "uninstalling",
24
+ "unknown"
25
+ ]
26
+ },
27
+ "status": {
28
+ "type": "string",
29
+ "description": "Raw DSM status, or the retained CLI operation when DSM temporarily omits the package."
30
+ },
31
+ "version": {
32
+ "type": "string",
33
+ "description": "Version reported by DSM; may change during replacement."
34
+ },
35
+ "fromVersion": {
36
+ "type": "string",
37
+ "description": "Previously installed version, only when known."
38
+ },
39
+ "toVersion": {
40
+ "type": "string",
41
+ "description": "Requested target version, only when known."
42
+ },
43
+ "host": {
44
+ "type": "string"
45
+ },
46
+ "package": {
47
+ "type": "string"
48
+ },
49
+ "error": {
50
+ "type": "object"
51
+ },
52
+ "statusCode": {
53
+ "type": "number"
54
+ },
55
+ "statusDescription": {
56
+ "type": "string"
57
+ }
58
+ },
59
+ "allOf": [
60
+ {
61
+ "if": {
62
+ "required": [
63
+ "state"
64
+ ],
65
+ "properties": {
66
+ "state": {
67
+ "enum": [
68
+ "installing",
69
+ "upgrading",
70
+ "starting",
71
+ "stopping",
72
+ "uninstalling"
73
+ ]
74
+ }
75
+ }
76
+ },
77
+ "then": {
78
+ "properties": {
79
+ "installed": {
80
+ "enum": [
81
+ true,
82
+ null
83
+ ]
84
+ }
85
+ }
86
+ }
87
+ }
88
+ ],
89
+ "additionalProperties": true
90
+ }
@@ -64,3 +64,21 @@ fingerprint after confirmation. `host add --fingerprint <sha256>` checks an
64
64
  explicit expected leaf during registration; it does not turn on strict mode.
65
65
  No global TLS override is used. Public package feeds and downloads keep normal
66
66
  HTTPS verification. Network errors distinguish DNS, refusal and timeout.
67
+
68
+
69
+ During replacement, `status <package-id> --json` returns `state: "upgrading"`,
70
+ `"installing"` or `"starting"` and known `fromVersion`/`toVersion` values. These
71
+ states never use `installed:false`; `installed:null` means payload presence cannot
72
+ currently be verified. Treat `state:"unknown"` after interrupted work as unresolved,
73
+ not as removal. Concurrent CLI processes using the same local user share the
74
+ private origin/package task record; other clients rely on DSM status evidence.
75
+ See `schema/package-state.schema.json` for the result contract.
76
+
77
+ Install/upgrade verification waits for the target version and running state. It
78
+ has no default wall-clock deadline. `DSM_INSTALL_MAX_POLLS` limits polling attempts
79
+ (default 10000, integer 1–1000000), including timed-out reads and pre-pull checks.
80
+ `DSM_INSTALL_TIMEOUT_SECONDS` no longer limits install/deploy waiting. Ctrl-C stops
81
+ waiting with `DSM_INSTALL_CANCELED` (exit 130); `DSM_INSTALL_LIMIT` means the query
82
+ limit was reached. Neither proves DSM failed, cancels its work, or permits replaying
83
+ a write. Check status first. Progress stays on stderr with `--json`; the final
84
+ install result contains the verified completion state.