@mostra/runtime 0.3.0 → 0.5.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.
@@ -1,7 +1,8 @@
1
- import { C as runtimeRoot$1, D as DEV_RELOAD_METHOD, E as DEV_METHOD, M as STAGING_FILES, O as DEV_SECRET_HEADER, S as runHelperAsync, T as DEV_CHANGED_METHOD, _ as ownedDirectory, a as nameKey, b as socketPathLimit, c as renamePath, d as samePath, f as sealPlaced, g as defaultHome, h as WINDOWS, i as linkTarget, j as LIVE_DECLARATION, l as renamePathSync, m as OS, o as pathKey, p as sealTree, r as linkDirectory, s as removeTree, t as fsyncPath, u as replaceDirectoryLink, v as pathsOf, w as BUILD_METHOD, x as helperPath, y as runtimeDirFor } from "./files-KxzOxckl.js";
1
+ import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-FygSJIzK.js";
2
+ import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-mJ1qlVht.js";
2
3
  import { builtinModules, createRequire } from "node:module";
3
4
  import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
4
- import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
5
+ import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
8
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
@@ -9348,6 +9349,36 @@ function writeRaw(socket, refused, extra = {}) {
9348
9349
  ...extra.headers ?? []
9349
9350
  ];
9350
9351
  socket.end(`${headers.join("\r\n")}\r\n\r\n${body}`);
9352
+ lingerAfterRefusal(socket);
9353
+ }
9354
+ /** Connections already answered with a refusal: a later parse error on them changes nothing. */
9355
+ const refusedSockets = /* @__PURE__ */ new WeakSet();
9356
+ /** How long a refused connection is read before it is closed regardless. */
9357
+ const LINGER_MS = 5e3;
9358
+ /** How much of a refused request is read and dropped before the connection is closed. */
9359
+ const LINGER_BYTES = 16777216;
9360
+ /**
9361
+ * Reads and drops what the client is still sending after its refusal, until it closes the
9362
+ * connection, for at most {@link LINGER_MS} and {@link LINGER_BYTES}. A socket closed with unread
9363
+ * bytes is reset, and a reset can reach the client before it read the answer, which it then never
9364
+ * sees: on Windows a browser sending a megabyte of cookies got a reset instead of the page that
9365
+ * clears them (WP-W2). The answer is already written; this only keeps the connection open long
9366
+ * enough for it to be read, as HTTP servers do for a "lingering close".
9367
+ */
9368
+ function lingerAfterRefusal(socket) {
9369
+ refusedSockets.add(socket);
9370
+ socket.removeAllListeners("data");
9371
+ socket.once("end", () => socket.destroy());
9372
+ let read = 0;
9373
+ const timer = setTimeout(() => socket.destroy(), LINGER_MS);
9374
+ timer.unref();
9375
+ socket.once("close", () => clearTimeout(timer));
9376
+ socket.on("error", () => socket.destroy());
9377
+ socket.on("data", (chunk) => {
9378
+ read += chunk.length;
9379
+ if (read > LINGER_BYTES) socket.destroy();
9380
+ });
9381
+ socket.resume();
9351
9382
  }
9352
9383
  /**
9353
9384
  * The answer to headers past {@link MAX_HEADER_SIZE}: a page that says what happened and clears
@@ -9414,6 +9445,7 @@ function createListener(options) {
9414
9445
  listener(incoming, outgoing);
9415
9446
  });
9416
9447
  server.on("clientError", (error, socket) => {
9448
+ if (refusedSockets.has(socket)) return;
9417
9449
  if (!socket.writable) {
9418
9450
  socket.destroy();
9419
9451
  return;
@@ -10630,6 +10662,12 @@ function createLive(options) {
10630
10662
  const retryAt = /* @__PURE__ */ new Map();
10631
10663
  /** Versions whose producers stopped because their worker is parked, by version, to their artifact. */
10632
10664
  const parkedVersions = /* @__PURE__ */ new Map();
10665
+ /** Why each parked version parked: its sources' error names the last cause. */
10666
+ const parkCauses = /* @__PURE__ */ new Map();
10667
+ const parkError = (cause) => ({
10668
+ code: "MOSTRA_RUNTIME_WORKER_PARKED",
10669
+ message: `The artifact's server code keeps crashing, so its live sources stopped (${cause}).`
10670
+ });
10633
10671
  let timer;
10634
10672
  let scheduled = false;
10635
10673
  let stopped = false;
@@ -10728,6 +10766,10 @@ function createLive(options) {
10728
10766
  throw error;
10729
10767
  }
10730
10768
  } catch (error) {
10769
+ if (parkedVersions.has(versionId)) {
10770
+ if (failures.get(id)?.code !== "MOSTRA_RUNTIME_WORKER_PARKED") fail(artifactId, key, parkError(parkCauses.get(versionId) ?? "its last start failed"));
10771
+ return;
10772
+ }
10731
10773
  const diagnostic = error instanceof RpcError ? error.diagnostic : void 0;
10732
10774
  fail(artifactId, key, {
10733
10775
  message: diagnostic?.message ?? String(error),
@@ -10883,14 +10925,18 @@ function createLive(options) {
10883
10925
  }
10884
10926
  },
10885
10927
  crashed(crash) {
10886
- for (const [id, producer] of running) if (producer.versionId === crash.versionId) running.delete(id);
10928
+ const ended = new Set(crash.liveKeys);
10929
+ for (const [id, producer] of running) {
10930
+ if (producer.versionId !== crash.versionId) continue;
10931
+ running.delete(id);
10932
+ ended.add(producer.key);
10933
+ }
10887
10934
  if (crash.parked) {
10888
- for (const key of crash.liveKeys) fail(crash.artifactId, key, {
10889
- code: "MOSTRA_RUNTIME_WORKER_PARKED",
10890
- message: `The artifact's server code keeps crashing, so its live sources stopped (${crash.cause}).`
10891
- });
10935
+ for (const source of described.get(crash.versionId) ?? []) ended.add(source.key);
10936
+ for (const key of ended) fail(crash.artifactId, key, parkError(crash.cause));
10892
10937
  retryAt.set(crash.versionId, Number.POSITIVE_INFINITY);
10893
10938
  parkedVersions.set(crash.versionId, crash.artifactId);
10939
+ parkCauses.set(crash.versionId, crash.cause);
10894
10940
  return;
10895
10941
  }
10896
10942
  retryAt.set(crash.versionId, Date.now() + crash.backoffMs);
@@ -10911,6 +10957,7 @@ function createLive(options) {
10911
10957
  for (const [versionId, owner] of parkedVersions) {
10912
10958
  if (owner !== artifactId) continue;
10913
10959
  parkedVersions.delete(versionId);
10960
+ parkCauses.delete(versionId);
10914
10961
  retryAt.delete(versionId);
10915
10962
  cleared = true;
10916
10963
  }
@@ -11127,6 +11174,16 @@ const PINGS_MISSED_BEFORE_STOP = 3;
11127
11174
  * to count as running out of memory rather than hanging.
11128
11175
  */
11129
11176
  const OOM_STALL_FRACTION = .8;
11177
+ /**
11178
+ * An exit code as people look it up: a Windows status (`0xC0000005`, an access violation) in
11179
+ * hexadecimal, any other code as a number. Node.js reports a Windows status as an unsigned
11180
+ * 32-bit number; on POSIX codes are below 256.
11181
+ */
11182
+ function exitCodeText(code) {
11183
+ if (code === null) return "?";
11184
+ if (code >= 2147483648 || code < 0) return `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, "0")}`;
11185
+ return String(code);
11186
+ }
11130
11187
  function crashed(message) {
11131
11188
  return new RpcError(createDiagnostic("MOSTRA_RUNTIME_WORKER_CRASHED", { message }));
11132
11189
  }
@@ -11185,7 +11242,7 @@ function createWorkerPool(options) {
11185
11242
  }
11186
11243
  const lines = exit.stderrTail.filter((line) => line.trim() !== "" && !/^Node\.js v\d/.test(line.trim()));
11187
11244
  const last = lines.findLast((line) => /^[A-Za-z_$][\w$.]*(?:Error|Exception)\b.*:/.test(line.trim())) ?? lines.findLast((line) => !/^\s+at\s/.test(line)) ?? lines.at(-1);
11188
- const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exit.code ?? "?"}`;
11245
+ const how = exit.signal !== null ? `it was ended by ${exit.signal}` : `it exited with code ${exitCodeText(exit.code)}`;
11189
11246
  return {
11190
11247
  kind: "crash",
11191
11248
  cause: last ? `${how}: ${last.slice(0, 300)}` : how
@@ -14158,10 +14215,7 @@ async function recoverDev(home, log) {
14158
14215
  } catch {
14159
14216
  return;
14160
14217
  }
14161
- for (const name of left) await rm(join(devRoot(home), name), {
14162
- recursive: true,
14163
- force: true
14164
- });
14218
+ for (const name of left) await removeTree(join(devRoot(home), name));
14165
14219
  if (left.length > 0) log.info("dev.sessions_removed", { count: left.length });
14166
14220
  }
14167
14221
  const LOOPBACK = /* @__PURE__ */ new Set([
@@ -14214,13 +14268,23 @@ function createDev(options) {
14214
14268
  let manifestKey = "";
14215
14269
  let artifactId = "";
14216
14270
  const mirrored = /* @__PURE__ */ new Map();
14217
- /** Copies changed files into the mirror and removes deleted ones; what changed. */
14271
+ /** When each mirrored file was first missed: a save that moves the old file aside first. */
14272
+ const missing = /* @__PURE__ */ new Map();
14273
+ /**
14274
+ * Copies changed files into the mirror and removes deleted ones; what changed. Editors save
14275
+ * in several ways (in place, a temporary file renamed over the old one, the old one renamed
14276
+ * to a backup first), and on Windows an editor may hold a file it is writing so that nothing
14277
+ * else can read it: a file that can't be read now is left for the next sync, never recorded,
14278
+ * and a file is removed from the mirror only once it has been missing for
14279
+ * {@link MISSING_GRACE_MS}, so a save never looks like a deletion (WP-W2).
14280
+ */
14218
14281
  const sync = async () => {
14219
14282
  const files = await listSource(source);
14220
14283
  const changed = [];
14221
14284
  const seen = /* @__PURE__ */ new Set();
14222
14285
  for (const file of files) {
14223
14286
  seen.add(file.path);
14287
+ missing.delete(file.path);
14224
14288
  let info;
14225
14289
  try {
14226
14290
  info = await stat(file.absolute);
@@ -14231,16 +14295,30 @@ function createDev(options) {
14231
14295
  const before = mirrored.get(file.path);
14232
14296
  if (before === key) continue;
14233
14297
  const target = join(root, "source", ...file.path.split("/"));
14234
- await mkdir(dirname(target), { recursive: true });
14235
- await copyFile(file.absolute, target);
14298
+ try {
14299
+ await mkdir(dirname(target), { recursive: true });
14300
+ await copyFile(file.absolute, target);
14301
+ } catch (error) {
14302
+ log.info("dev.sync_deferred", {
14303
+ sessionId,
14304
+ file: file.path,
14305
+ error
14306
+ });
14307
+ continue;
14308
+ }
14236
14309
  mirrored.set(file.path, key);
14237
14310
  changed.push({
14238
14311
  file: file.path,
14239
14312
  kind: before === void 0 ? "add" : "change"
14240
14313
  });
14241
14314
  }
14315
+ const now = Date.now();
14242
14316
  for (const path of [...mirrored.keys()]) {
14243
14317
  if (seen.has(path)) continue;
14318
+ const since = missing.get(path) ?? now;
14319
+ missing.set(path, since);
14320
+ if (now - since < MISSING_GRACE_MS) continue;
14321
+ missing.delete(path);
14244
14322
  mirrored.delete(path);
14245
14323
  await unlink(join(root, "source", ...path.split("/"))).catch(() => {});
14246
14324
  changed.push({
@@ -14253,7 +14331,7 @@ function createDev(options) {
14253
14331
  /** The manifest and identity of the mirrored source. */
14254
14332
  const describe = async () => {
14255
14333
  const extracted = extractManifest(source.entry, await readFile(join(root, "source", source.entry), "utf8"));
14256
- const manifest = extracted.manifest ?? { title: titleOf(source) };
14334
+ const manifest = extracted.manifest ?? { title: defaultTitle(source) };
14257
14335
  return {
14258
14336
  manifest,
14259
14337
  artifactId: manifest.id ?? options.registry.artifactAt(source.bindingPath) ?? stableId(source.bindingPath),
@@ -14373,10 +14451,7 @@ function createDev(options) {
14373
14451
  await child?.stop().catch(() => {});
14374
14452
  await sandbox?.close().catch(() => {});
14375
14453
  locksInUse.delete(sessionId);
14376
- await rm(dir, {
14377
- recursive: true,
14378
- force: true
14379
- });
14454
+ await removeTree(dir);
14380
14455
  };
14381
14456
  const stop = async () => {
14382
14457
  if (closed) return;
@@ -14481,10 +14556,12 @@ function createDev(options) {
14481
14556
  }
14482
14557
  };
14483
14558
  }
14484
- /** The title of a source without a manifest: its directory's or file's name (INTERFACES §2.2). */
14485
- function titleOf(source) {
14486
- return (source.kind === "dir" ? source.root.split("/").at(-1) : source.entry.replace(/\.[^.]+$/, "")) || "Untitled";
14487
- }
14559
+ /**
14560
+ * How long a mirrored file must stay missing before `mostra dev` removes it: an editor that moves
14561
+ * the old file aside before writing the new one leaves a gap of milliseconds, a deletion lasts.
14562
+ * The 1 s comparison notices the removal within this and a second more.
14563
+ */
14564
+ const MISSING_GRACE_MS = 1500;
14488
14565
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
14489
14566
  /** A stand-in artifact ID for a source no manifest `id` or binding names: stable per path. */
14490
14567
  function stableId(bindingPath) {
@@ -15361,11 +15438,14 @@ function watchIdle(options) {
15361
15438
  //#endregion
15362
15439
  //#region src/service/unit.ts
15363
15440
  /**
15364
- * The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's daemon
15365
- * with the user's service manager, so an artifact answers at any hour, even after a reboot. A
15366
- * launchd agent on macOS, a systemd user unit on Linux; either runs `mostra-runtime daemon
15367
- * --always-on --home <home>`, which never exits for lack of work, and restarts it when it ends
15368
- * unexpectedly. The unit carries no secret: the daemon reads them from the home (D44).
15441
+ * The home's login service (D62, D63, RT-08, RT-11): `mostra daemon install` registers the home's
15442
+ * daemon with the user's service manager, so an artifact answers at any hour, even after a reboot.
15443
+ * A launchd agent on macOS, a systemd user unit on Linux, a Task Scheduler task at the user's logon
15444
+ * on Windows (D151); each runs `mostra-runtime daemon --always-on --home <home>`, which never
15445
+ * exits for lack of work, and restarts it when it ends unexpectedly. On Windows the task runs the
15446
+ * daemon through `mostra-win-service`, a launcher without a console, so no window opens at logon,
15447
+ * which also does the restarting (Task Scheduler's own setting didn't, VERIFIED_FACTS WP-W2). The
15448
+ * definition carries no secret: the daemon reads them from the home (D44).
15369
15449
  */
15370
15450
  function failed(message) {
15371
15451
  return new RpcError(createDiagnostic("MOSTRA_ENV_SERVICE_FAILED", { message }));
@@ -15408,24 +15488,182 @@ function serviceFor(spec) {
15408
15488
  command
15409
15489
  };
15410
15490
  }
15491
+ if (platform === "win32") {
15492
+ const file = win32.join(spec.home, "service", "task.xml");
15493
+ return {
15494
+ manager: "task-scheduler",
15495
+ name: `mostra-${hash.toLowerCase()}`,
15496
+ file,
15497
+ installed: existsSync(file),
15498
+ command: [
15499
+ spec.launcher ?? launcherOrName(),
15500
+ "--stop-event",
15501
+ stopEventOf(file) ?? newStopEvent(hash),
15502
+ "--log",
15503
+ win32.join(spec.home, "logs", "service.log"),
15504
+ ...windowsServiceVariables(env).flatMap(([name, value]) => ["--env", `${name}=${value}`]),
15505
+ "--",
15506
+ ...command
15507
+ ]
15508
+ };
15509
+ }
15411
15510
  throw new RpcError(createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", { message: `Mostra can't install a login service on ${platform}.` }));
15412
15511
  }
15413
15512
  /**
15513
+ * What a Windows task passes on besides the user's logon environment, which Task Scheduler gives
15514
+ * it: the development switch while Windows needs it (D150 item 7, until WP-W3), the helper a
15515
+ * checkout names, and the locale and time zone, as the POSIX units carry theirs. Nothing secret.
15516
+ */
15517
+ function windowsServiceVariables(env) {
15518
+ return [
15519
+ "MOSTRA_DEV_WINDOWS",
15520
+ "MOSTRA_WIN_HELPER",
15521
+ "LANG",
15522
+ "TZ"
15523
+ ].flatMap((name) => {
15524
+ const value = env[name];
15525
+ return value ? [[name, value]] : [];
15526
+ });
15527
+ }
15528
+ /**
15529
+ * A new name for the event that asks a home's launcher to stop: in `Local\` (the logon session's
15530
+ * namespace, the only one an ordinary user may create names in), with a random part, so nobody who
15531
+ * can't read the task or the home can create it first (Opus review of WP-W2, finding 6).
15532
+ */
15533
+ const newStopEvent = (hash) => `Local\\mostra-service-${hash.toLowerCase()}-${randomBytes(8).toString("hex")}`;
15534
+ /** The stop event a definition Mostra wrote names, if the file is there. */
15535
+ function stopEventOf(file) {
15536
+ try {
15537
+ const text = readFileSync(file).toString("utf16le");
15538
+ return /--stop-event (Local\\mostra-service-[0-9a-z]+-[0-9a-f]{16})\b/.exec(text)?.[1];
15539
+ } catch {
15540
+ return;
15541
+ }
15542
+ }
15543
+ /** The launcher's path, or its bare name where it isn't installed (a status only reads it). */
15544
+ function launcherOrName() {
15545
+ try {
15546
+ return serviceLauncherPath();
15547
+ } catch {
15548
+ return "mostra-win-service.exe";
15549
+ }
15550
+ }
15551
+ /** One word of a Windows command line, quoted as the Microsoft C runtime parses it. */
15552
+ function windowsArgument(word) {
15553
+ if (word !== "" && !/[\s"]/.test(word)) return word;
15554
+ let out = "\"";
15555
+ let backslashes = 0;
15556
+ for (const char of word) {
15557
+ if (char === "\\") {
15558
+ backslashes += 1;
15559
+ continue;
15560
+ }
15561
+ out += "\\".repeat(char === "\"" ? backslashes * 2 + 1 : backslashes) + char;
15562
+ backslashes = 0;
15563
+ }
15564
+ return `${out}${"\\".repeat(backslashes * 2)}"`;
15565
+ }
15566
+ /** The Task Scheduler definition (schema 1.2) of a home's task. */
15567
+ function taskFile(spec, status) {
15568
+ const user = xml(spec.user ?? currentUserSid());
15569
+ const [program = "", ...args] = status.command;
15570
+ return `<?xml version="1.0" encoding="UTF-16"?>
15571
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
15572
+ <RegistrationInfo>
15573
+ <Description>${xml(`Mostra daemon for ${spec.home}`)}</Description>
15574
+ </RegistrationInfo>
15575
+ <Triggers>
15576
+ <LogonTrigger>
15577
+ <Enabled>true</Enabled>
15578
+ <UserId>${user}</UserId>
15579
+ </LogonTrigger>
15580
+ </Triggers>
15581
+ <Principals>
15582
+ <Principal id="Author">
15583
+ <UserId>${user}</UserId>
15584
+ <LogonType>InteractiveToken</LogonType>
15585
+ <RunLevel>LeastPrivilege</RunLevel>
15586
+ </Principal>
15587
+ </Principals>
15588
+ <Settings>
15589
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
15590
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
15591
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
15592
+ <AllowHardTerminate>true</AllowHardTerminate>
15593
+ <StartWhenAvailable>false</StartWhenAvailable>
15594
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
15595
+ <IdleSettings>
15596
+ <StopOnIdleEnd>false</StopOnIdleEnd>
15597
+ <RestartOnIdle>false</RestartOnIdle>
15598
+ </IdleSettings>
15599
+ <AllowStartOnDemand>true</AllowStartOnDemand>
15600
+ <Enabled>true</Enabled>
15601
+ <Hidden>false</Hidden>
15602
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
15603
+ <WakeToRun>false</WakeToRun>
15604
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
15605
+ <Priority>5</Priority>
15606
+ </Settings>
15607
+ <Actions Context="Author">
15608
+ <Exec>
15609
+ <Command>${xml(program)}</Command>
15610
+ <Arguments>${xml(args.map(windowsArgument).join(" "))}</Arguments>
15611
+ </Exec>
15612
+ </Actions>
15613
+ </Task>
15614
+ `;
15615
+ }
15616
+ /**
15414
15617
  * Whether `home` has a login service installed: its daemon then never exits for lack of work,
15415
15618
  * whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
15416
15619
  */
15417
15620
  function hasLoginService(home, env = process.env) {
15418
15621
  try {
15419
- return serviceFor({
15622
+ const status = serviceFor({
15420
15623
  home,
15421
15624
  node: "",
15422
15625
  entry: "",
15423
15626
  env
15424
- }).installed;
15627
+ });
15628
+ if (!status.installed) return false;
15629
+ return status.manager !== "task-scheduler" || registeredLately(status);
15425
15630
  } catch {
15426
15631
  return false;
15427
15632
  }
15428
15633
  }
15634
+ /** What the idle check last learnt of each task: whether Task Scheduler holds it, and when. */
15635
+ const registrations = /* @__PURE__ */ new Map();
15636
+ /**
15637
+ * Whether Task Scheduler held the task when last asked, asking again in the background at most
15638
+ * once a minute: the idle check runs every few seconds and must never wait for `schtasks`. A task
15639
+ * removed in Task Scheduler's own window then stops counting, so a daemon started by hand exits
15640
+ * when idle again (Opus review of WP-W2, finding 5). Until the first answer, the definition in the
15641
+ * home counts.
15642
+ */
15643
+ function registeredLately(status) {
15644
+ const interval = Number(process.env["MOSTRA_TEST_SERVICE_QUERY_MS"]) || 6e4;
15645
+ const entry = registrations.get(status.name) ?? {
15646
+ at: Number.NEGATIVE_INFINITY,
15647
+ asking: false
15648
+ };
15649
+ registrations.set(status.name, entry);
15650
+ if (!entry.asking && Date.now() - entry.at >= interval) {
15651
+ entry.asking = true;
15652
+ execFile("schtasks", [
15653
+ "/Query",
15654
+ "/TN",
15655
+ status.name
15656
+ ], {
15657
+ timeout: 3e4,
15658
+ windowsHide: true
15659
+ }, (error) => {
15660
+ entry.registered = error === null;
15661
+ entry.at = Date.now();
15662
+ entry.asking = false;
15663
+ });
15664
+ }
15665
+ return entry.registered ?? true;
15666
+ }
15429
15667
  const xml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
15430
15668
  /** systemd's quoting for one `ExecStart` word. */
15431
15669
  const systemdWord = (word) => /^[A-Za-z0-9_./:@=+-]+$/.test(word) ? word : `"${word.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
@@ -15447,6 +15685,7 @@ function serviceEnvironment(env) {
15447
15685
  }
15448
15686
  /** The text of the service's file. */
15449
15687
  function serviceFile(spec, status) {
15688
+ if (status.manager === "task-scheduler") return taskFile(spec, status);
15450
15689
  const env = serviceEnvironment(spec.env ?? process.env);
15451
15690
  const log = join(spec.home, "logs", "service.log");
15452
15691
  if (status.manager === "launchd") {
@@ -15516,29 +15755,60 @@ function run(command, args) {
15516
15755
  }
15517
15756
  }
15518
15757
  const uid = () => process.getuid?.() ?? 0;
15758
+ /** The definition's bytes: Task Scheduler reads UTF-16 with its byte order mark. */
15759
+ function encoded(status, text) {
15760
+ return status.manager === "task-scheduler" ? Buffer.from(`\ufeff${text}`, "utf16le") : text;
15761
+ }
15762
+ /** The definition as written, decoded as {@link encoded} wrote it. */
15763
+ function readDefinition(status) {
15764
+ const bytes = readFileSync(status.file);
15765
+ if (status.manager !== "task-scheduler") return bytes.toString("utf8");
15766
+ return bytes.toString("utf16le").replace(/^\ufeff/, "");
15767
+ }
15519
15768
  /** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
15520
- function installService(spec, options = {}) {
15521
- const status = serviceFor(spec);
15769
+ async function installService(spec, options = {}) {
15770
+ const status = serviceFor((spec.platform ?? OS) === "win32" && spec.launcher === void 0 ? {
15771
+ ...spec,
15772
+ launcher: serviceLauncherPath()
15773
+ } : spec);
15522
15774
  const text = serviceFile(spec, status);
15775
+ const registering = status.manager === "task-scheduler" && !options.noStart;
15776
+ const written = registering ? `${status.file}.new` : status.file;
15523
15777
  try {
15524
15778
  mkdirSync(dirname(status.file), { recursive: true });
15525
15779
  mkdirSync(join(spec.home, "logs"), {
15526
15780
  recursive: true,
15527
15781
  mode: 448
15528
15782
  });
15529
- if (status.installed && !options.noStart) stopService(status);
15530
- writeFileSync(status.file, text, { mode: 420 });
15783
+ if (status.installed && !options.noStart) await stopService(status, spec.home, options);
15784
+ writeFileSync(written, encoded(status, text), { mode: 420 });
15531
15785
  } catch (error) {
15532
15786
  if (error instanceof RpcError) throw error;
15533
15787
  throw failed(`Writing ${status.file} failed: ${error.message}`);
15534
15788
  }
15789
+ if (registering) {
15790
+ try {
15791
+ run("schtasks", [
15792
+ "/Create",
15793
+ "/TN",
15794
+ status.name,
15795
+ "/XML",
15796
+ written,
15797
+ "/F"
15798
+ ]);
15799
+ renameSync(written, status.file);
15800
+ } finally {
15801
+ rmSync(written, { force: true });
15802
+ }
15803
+ registrations.delete(status.name);
15804
+ }
15535
15805
  if (!options.noStart) {
15536
15806
  if (status.manager === "launchd") run("launchctl", [
15537
15807
  "bootstrap",
15538
15808
  `gui/${uid()}`,
15539
15809
  status.file
15540
15810
  ]);
15541
- else {
15811
+ else if (status.manager === "systemd") {
15542
15812
  run("systemctl", ["--user", "daemon-reload"]);
15543
15813
  run("systemctl", [
15544
15814
  "--user",
@@ -15546,29 +15816,104 @@ function installService(spec, options = {}) {
15546
15816
  "--now",
15547
15817
  status.name
15548
15818
  ]);
15549
- }
15819
+ } else run("schtasks", [
15820
+ "/Run",
15821
+ "/TN",
15822
+ status.name
15823
+ ]);
15550
15824
  }
15551
15825
  return {
15552
15826
  ...status,
15553
15827
  installed: true
15554
15828
  };
15555
15829
  }
15556
- function stopService(status) {
15830
+ async function stopService(status, home, options) {
15557
15831
  try {
15558
15832
  if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
15559
- else run("systemctl", [
15833
+ else if (status.manager === "systemd") run("systemctl", [
15560
15834
  "--user",
15561
15835
  "disable",
15562
15836
  "--now",
15563
15837
  status.name
15564
15838
  ]);
15839
+ else await stopTask(status, home, options);
15840
+ } catch {}
15841
+ }
15842
+ /**
15843
+ * Stops and deletes a home's task, the daemon first and in order (D87), as launchd's `bootout`
15844
+ * and systemd's `disable --now` send it SIGTERM:
15845
+ * - through the launcher's stop event, when this logon session has it: the launcher gives the
15846
+ * daemon Ctrl+Break, which the runtime handles as `mostra/shutdown`;
15847
+ * - otherwise (the launcher runs in another session, as when the user is logged on at the console
15848
+ * and uninstalls over SSH, or the home lost the definition naming the event) with
15849
+ * `mostra/shutdown` over the home's pipe, which reaches the daemon from any session; its exit
15850
+ * with code 0 ends the launcher (Opus review of WP-W2, finding 4);
15851
+ *
15852
+ * then the task is ended, which ends whatever its job still holds, and deleted.
15853
+ */
15854
+ async function stopTask(status, home, options) {
15855
+ const event = status.installed ? status.command[status.command.indexOf("--stop-event") + 1] : void 0;
15856
+ let signalled = false;
15857
+ if (event !== void 0 && process.env["MOSTRA_TEST_SERVICE_STOP"] !== "pipe") try {
15858
+ signalled = stopServiceLauncher(event).signalled;
15859
+ } catch {}
15860
+ if (!signalled) await shutDownInstance(home, options.client);
15861
+ try {
15862
+ run("schtasks", [
15863
+ "/End",
15864
+ "/TN",
15865
+ status.name
15866
+ ]);
15565
15867
  } catch {}
15868
+ run("schtasks", [
15869
+ "/Delete",
15870
+ "/TN",
15871
+ status.name,
15872
+ "/F"
15873
+ ]);
15874
+ registrations.delete(status.name);
15875
+ }
15876
+ /** Asks the home's running daemon, if any, to stop (`mostra/shutdown`), and waits until it has. */
15877
+ async function shutDownInstance(home, client) {
15878
+ const record = await readLiveInstanceRecord(home);
15879
+ if (record === void 0 || record.mode !== "daemon") return;
15880
+ try {
15881
+ const session = await attach(record.socket, client ?? {
15882
+ name: "mostra-service",
15883
+ version: "0"
15884
+ });
15885
+ await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
15886
+ session.client.close();
15887
+ } catch {
15888
+ return;
15889
+ }
15890
+ const deadline = Date.now() + 2e4;
15891
+ while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
15566
15892
  }
15567
- /** Stops and removes the home's login service; a home without one is left as it is. */
15568
- function uninstallService(spec, options = {}) {
15893
+ /** Whether Task Scheduler holds the home's task. */
15894
+ function taskRegistered(status) {
15895
+ try {
15896
+ run("schtasks", [
15897
+ "/Query",
15898
+ "/TN",
15899
+ status.name
15900
+ ]);
15901
+ return true;
15902
+ } catch {
15903
+ return false;
15904
+ }
15905
+ }
15906
+ /**
15907
+ * Stops and removes the home's login service; a home without one is left as it is. On Windows a
15908
+ * task Task Scheduler still holds is removed though the home lost its definition (restored from a
15909
+ * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
15910
+ * of WP-W2, finding 5).
15911
+ */
15912
+ async function uninstallService(spec, options = {}) {
15569
15913
  const status = serviceFor(spec);
15570
- if (!status.installed) return status;
15571
- if (!options.noStart) stopService(status);
15914
+ const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
15915
+ if (!status.installed && !orphaned) return status;
15916
+ if (!options.noStart) await stopService(status, spec.home, options);
15572
15917
  rmSync(status.file, { force: true });
15573
15918
  if (!options.noStart && status.manager === "systemd") try {
15574
15919
  run("systemctl", ["--user", "daemon-reload"]);
@@ -15578,17 +15923,22 @@ function uninstallService(spec, options = {}) {
15578
15923
  installed: false
15579
15924
  };
15580
15925
  }
15581
- /** Whether the home has a login service whose file runs this home's daemon (`mostra doctor`). */
15926
+ /**
15927
+ * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
15928
+ * Windows also whether Task Scheduler holds its task (`registered`).
15929
+ */
15582
15930
  function serviceStatus(spec) {
15583
15931
  const status = serviceFor(spec);
15932
+ const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
15584
15933
  if (!status.installed) return {
15585
15934
  ...status,
15586
- current: false
15935
+ current: false,
15936
+ ...registered
15587
15937
  };
15588
- const text = readFileSync(status.file, "utf8");
15589
15938
  return {
15590
15939
  ...status,
15591
- current: text === serviceFile(spec, status)
15940
+ current: readDefinition(status) === serviceFile(spec, status),
15941
+ ...registered
15592
15942
  };
15593
15943
  }
15594
15944
  //#endregion
@@ -15683,7 +16033,7 @@ async function startInstance(options) {
15683
16033
  }
15684
16034
  function sameHome(home, path) {
15685
16035
  try {
15686
- return realpathSync(path) === home;
16036
+ return realPath(path) === home;
15687
16037
  } catch {
15688
16038
  return resolve(path) === home;
15689
16039
  }
@@ -16328,4 +16678,4 @@ function sourceDirectory(path) {
16328
16678
  //#endregion
16329
16679
  export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
16330
16680
 
16331
- //# sourceMappingURL=instance-DiKSe7s6.js.map
16681
+ //# sourceMappingURL=instance-CYvNd7mP.js.map