@scopebond/agent 0.5.6 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/agent.d.ts +6 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +10 -3
  4. package/dist/agent.js.map +1 -1
  5. package/dist/allowance-sender.js +10 -4
  6. package/dist/allowance-sender.js.map +1 -1
  7. package/dist/apps-entry.d.ts +46 -0
  8. package/dist/apps-entry.d.ts.map +1 -0
  9. package/dist/apps-entry.js +118 -0
  10. package/dist/apps-entry.js.map +1 -0
  11. package/dist/autostart.d.ts +11 -5
  12. package/dist/autostart.d.ts.map +1 -1
  13. package/dist/autostart.js +60 -6
  14. package/dist/autostart.js.map +1 -1
  15. package/dist/awake.d.ts +31 -0
  16. package/dist/awake.d.ts.map +1 -0
  17. package/dist/awake.js +57 -0
  18. package/dist/awake.js.map +1 -0
  19. package/dist/cli-main.d.ts.map +1 -1
  20. package/dist/cli-main.js +28 -1
  21. package/dist/cli-main.js.map +1 -1
  22. package/dist/index.d.ts +12 -7
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +8 -5
  25. package/dist/index.js.map +1 -1
  26. package/dist/ipc.d.ts +9 -4
  27. package/dist/ipc.d.ts.map +1 -1
  28. package/dist/ipc.js +15 -9
  29. package/dist/ipc.js.map +1 -1
  30. package/dist/log-file.js.map +1 -1
  31. package/dist/native-update.d.ts +83 -7
  32. package/dist/native-update.d.ts.map +1 -1
  33. package/dist/native-update.js +230 -33
  34. package/dist/native-update.js.map +1 -1
  35. package/dist/prompt.d.ts.map +1 -1
  36. package/dist/prompt.js +1 -0
  37. package/dist/prompt.js.map +1 -1
  38. package/dist/selfcheck.d.ts.map +1 -1
  39. package/dist/selfcheck.js +4 -1
  40. package/dist/selfcheck.js.map +1 -1
  41. package/dist/service.d.ts +20 -3
  42. package/dist/service.d.ts.map +1 -1
  43. package/dist/service.js +141 -44
  44. package/dist/service.js.map +1 -1
  45. package/dist/setup.d.ts +12 -0
  46. package/dist/setup.d.ts.map +1 -1
  47. package/dist/setup.js +42 -13
  48. package/dist/setup.js.map +1 -1
  49. package/dist/tray-model.d.ts +2 -0
  50. package/dist/tray-model.d.ts.map +1 -1
  51. package/dist/tray-model.js +2 -0
  52. package/dist/tray-model.js.map +1 -1
  53. package/dist/update.d.ts +56 -12
  54. package/dist/update.d.ts.map +1 -1
  55. package/dist/update.js +209 -38
  56. package/dist/update.js.map +1 -1
  57. package/dist/upkeep.d.ts +16 -0
  58. package/dist/upkeep.d.ts.map +1 -0
  59. package/dist/upkeep.js +55 -0
  60. package/dist/upkeep.js.map +1 -0
  61. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,+FAA+F;AAC/F,8FAA8F;AAC9F,qEAAqE;AAErE,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/F,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,cAAc,EAAE,aAAa,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,cAAc,EAAE,kBAAkB,EAAE,eAAe,EAAE,kBAAkB,EAAgB,MAAM,iBAAiB,CAAC;AACrQ,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,QAAQ,EAAoB,MAAM,YAAY,CAAC;AAC/G,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAA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AG,IAAI,CAAC,OAAO;YAAE,KAAK,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC;QAC1F,gBAAgB,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7B,CAAC;IACD,MAAM,KAAK,EAAE,CAAC;IACd,QAAQ,EAAE,CAAC;IACX,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;AACnG,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,WAAW,CAAC,OAA+D;IACzF,QAAQ,OAAO,EAAE,CAAC;QAChB,KAAK,SAAS,CAAC,CAAC,OAAO,uDAAuD,CAAC;QAC/E,KAAK,UAAU,CAAC,CAAC,OAAO,mGAAmG,CAAC;QAC5H,KAAK,OAAO,CAAC,CAAC,OAAO,0FAA0F,CAAC;QAChH,KAAK,UAAU,CAAC,CAAC,OAAO,sBAAsB,CAAC;QAC/C,KAAK,MAAM,CAAC,CAAC,OAAO,oEAAoE,CAAC;IAC3F,CAAC;AACH,CAAC","sourcesContent":["// The resident loop: one cycle now, then one every interval, sooner after a change is asked for,\n// backing off while the workspace is unreachable. Exactly one agent serves a Scopebond home: a\n// second one finds the first answering and exits. Every six hours it asks the workspace which\n// versions to run, and once a day it runs the end-to-end self-check.\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { join } from \"node:path\";\nimport { actOnBlocked, blockedQuestion, hookVersion, isSingleExecutable, isManaged, loadConnection, localActivity, readBlocked, readMeta, ruleReport, runStoreUpkeep, writeDeliveryState, userHarnessFile, writeHarnessConfig, type Harness } from \"@scopebond/hook\";\nimport { computerStatus, expectedHarnesses, missingHookEntries, runCycle, type CycleResult } from \"./agent.js\";\nimport { agentCliPath } from \"./self.js\";\nimport { fetchVerifiedInstaller, installAfterExit, installKind } from \"./native-update.js\";\nimport { AGENT_LOG_ENV, launcherIsCurrent, launcherPath, refreshLauncher, startCommands } from \"./autostart.js\";\nimport { callAgent, startControl } from \"./ipc.js\";\nimport { runSelfCheck } from \"./selfcheck.js\";\nimport { flushReasons, queueReason } from \"./override-reasons.js\";\nimport { parseQuestion, serialized, systemPrompter, type Prompter } from \"./prompt.js\";\nimport { healthOf, type HealthLevel } from \"./health.js\";\nimport { notifyChange, startTray } from \"./tray.js\";\nimport { sendAllowancesAndRequests } from \"./allowance-sender.js\";\nimport { checkResult, trayModel, type RecentBlock, type TrayModel } from \"./tray-model.js\";\nimport { fetchComputerSummary, openInBrowser, sameOrigin, type ComputerSummary } from \"./summary.js\";\nimport { startReconnect, type ReconnectStart } from \"./reconnect.js\";\nimport { agentVersion, compareVersions, fetchClientVersion, installAgent, maintainHookEntries, maintainedHookCommand } from \"./update.js\";\n\nexport const AGENT_VERSION = `agent/${agentVersion()}`;\nconst INTERVAL_MS = 60_000;\nconst MAX_BACKOFF_MS = 15 * 60_000;\nconst UPDATE_EVERY_MS = 6 * 60 * 60 * 1000;\nconst SELF_CHECK_EVERY_MS = 24 * 60 * 60 * 1000;\nconst SUMMARY_EVERY_MS = 5 * 60 * 1000;\nexport const AFTER_PID_ENV = \"SCOPEBOND_AGENT_AFTER_PID\";\n/** The person's tray settings (D143: notifications about problems by default, none about blocks). */\nexport const TRAY_SETTINGS_FILE = \"agent-settings.json\";\nexport type NotificationSetting = \"all\" | \"problems\" | \"off\";\nexport interface TraySettings { notifications: NotificationSetting }\n\nexport function readTraySettings(dir: string): TraySettings {\n try {\n const parsed = JSON.parse(readFileSync(join(dir, TRAY_SETTINGS_FILE), \"utf8\")) as Partial<TraySettings>;\n return { notifications: parsed.notifications === \"all\" || parsed.notifications === \"off\" ? parsed.notifications : \"problems\" };\n } catch { return { notifications: \"problems\" }; }\n}\n\nexport function writeTraySettings(dir: string, patch: unknown): TraySettings {\n const next = readTraySettings(dir);\n const value = (patch as { notifications?: unknown } | null)?.notifications;\n if (value === \"all\" || value === \"problems\" || value === \"off\") next.notifications = value;\n writeFileSync(join(dir, TRAY_SETTINGS_FILE), JSON.stringify(next, null, 2) + \"\\n\", { mode: 0o600 });\n return next;\n}\n\n/** Set for a replacement started directly because the launcher is an older one: it rewrites the launcher once the old agent is gone. */\nexport const REFRESH_LAUNCHER_ENV = \"SCOPEBOND_AGENT_REFRESH_LAUNCHER\";\n/** The exit code that asks a service manager to start the agent again (systemd's Restart=on-failure), used where a detached replacement would not survive. */\nexport const RESTART_EXIT_CODE = 75;\n\nexport interface ServiceOptions {\n dir: string; intervalMs?: number; fetchImpl?: typeof fetch; log?: (line: string) => void;\n /** Off in tests: the update check and self-check run only when asked. */\n maintenance?: boolean;\n /** Called after a successful update instead of restarting (tests). */\n onUpdated?: (version: string) => void;\n /** Shows the Scopebond window for an override (tests replace it). */\n prompter?: Prompter;\n /** The Windows tray icon (default on Windows; SCOPEBOND_AGENT_TRAY=off turns it off). */\n tray?: boolean;\n /** Called once the agent has stopped because `stop` (or `autostart off`) asked it to; the CLI exits. */\n onStopped?: () => void;\n /** Each delivery request's time limit (default 30 s) and one cycle's (default 10 minutes). A cycle that runs past its\n * limit is counted as a failure and the next one is scheduled; nothing waits on it. */\n deliveryTimeoutMs?: number;\n cycleLimitMs?: number;\n}\n\n/** The agent's own delivery problem, kept apart from a hook call's cut-off. */\nfunction recordAgentError(dir: string, message: string): void {\n writeDeliveryState(dir, { last_error: message, last_status: null, last_error_source: \"agent\", last_error_at: Date.now() });\n}\n\n/** How long one delivery cycle may run before the agent stops waiting for it. */\nexport const CYCLE_LIMIT_MS = 10 * 60_000;\n\nexport interface Service {\n stop(): Promise<void>;\n cycleNow(): Promise<CycleResult>;\n maintainNow(): Promise<MaintenanceResult>;\n port: number;\n}\n\nexport interface MaintenanceResult {\n at: number;\n policy: \"recommended\" | \"hold\" | \"unknown\";\n updatedTo: string | null;\n hookEntries: Array<{ harness: Harness; file: string; reason: string }>;\n selfCheck: Awaited<ReturnType<typeof runSelfCheck>>;\n /** The local store's upkeep this pass (D144): rows rewritten, receipts past retention removed, space returned. */\n store?: ReturnType<typeof runStoreUpkeep>;\n error: string | null;\n}\n\n/** Put the Scopebond hook back into agent settings that lost it. A visible change: each one is\n * logged and returned, and only settings of agents this computer has are touched. */\nexport function repairHookEntries(harnesses: Harness[] = expectedHarnesses()): Array<{ harness: Harness; file: string }> {\n const repaired: Array<{ harness: Harness; file: string }> = [];\n for (const harness of missingHookEntries(harnesses)) {\n const file = writeHarnessConfig(userHarnessFile(harness), harness, maintainedHookCommand(harness));\n repaired.push({ harness, file });\n }\n return repaired;\n}\n\n/** How the updated agent takes over from this one. */\nexport type Handover =\n | { kind: \"spawn\"; command: string; args: string[]; env: Record<string, string | undefined>; verbatim: boolean }\n | { kind: \"service-restart\" };\n\n/** Decide how to start the updated agent. Through the autostart launcher when there is one, so it finds Node the same way\n * sign-in does and is restarted after a crash. On Windows an older launcher cannot do it: it redirects the agent's output\n * into agent.log, this agent's children inherit that handle, and the new launcher's own redirect then fails, which cmd\n * takes for a clean exit. So under an older launcher the updated agent starts directly and rewrites the launcher once\n * this one is gone. Under systemd a detached child is stopped with the service, so the service manager restarts it. */\nexport function handoverPlan(o: {\n dir: string; cli: string; pid: number; execPath: string; platform: NodeJS.Platform;\n /** The single executable: the program is the agent itself, with no cli.js and no Node options. */\n singleExecutable?: boolean;\n env: Record<string, string | undefined>; launcherText: string | null;\n}): Handover {\n if (o.platform === \"linux\" && o.env.INVOCATION_ID) return { kind: \"service-restart\" };\n const launcher = launcherPath(o.dir, o.platform);\n const env = { ...o.env, [AFTER_PID_ENV]: String(o.pid), [AGENT_LOG_ENV]: join(o.dir, \"agent.log\") };\n if (o.launcherText !== null && launcherIsCurrent(o.launcherText, o.platform)) {\n if (o.platform === \"win32\") {\n const [command, args] = startCommands(launcher, o.platform)[1];\n return { kind: \"spawn\", command, args, env, verbatim: true };\n }\n return { kind: \"spawn\", command: \"/bin/sh\", args: [launcher], env, verbatim: false };\n }\n return {\n kind: \"spawn\", command: o.execPath, args: o.singleExecutable ? [\"run\"] : [\"--disable-warning=ExperimentalWarning\", o.cli, \"run\"], verbatim: false,\n env: o.launcherText !== null ? { ...env, [REFRESH_LAUNCHER_ENV]: \"1\" } : env,\n };\n}\n\n/** Start the updated agent, which waits for this process to exit. Returns false when a service manager restarts it instead\n * (this process then exits with RESTART_EXIT_CODE). */\nexport function spawnReplacement(dir: string, cli = agentCliPath()): boolean {\n let launcherText: string | null = null;\n try { launcherText = readFileSync(launcherPath(dir), \"utf8\"); } catch { /* no autostart launcher */ }\n const plan = handoverPlan({ dir, cli, pid: process.pid, execPath: process.execPath, platform: process.platform, env: process.env, launcherText, singleExecutable: isSingleExecutable() });\n if (plan.kind === \"service-restart\") return false;\n const child = spawn(plan.command, plan.args, { env: plan.env, detached: true, stdio: \"ignore\", windowsHide: true, windowsVerbatimArguments: plan.verbatim });\n child.on(\"error\", () => { /* the next sign-in starts it */ });\n child.unref();\n return true;\n}\n\n/** The first thing a starting agent does: wait for the agent it replaces to exit, then, when asked, rewrite the older launcher\n * that agent ran under (by now nothing runs it). The handover variables are dropped, so a later restart waits for nothing. */\nexport async function takeOver(dir: string, cli: string, waitMs = 30_000): Promise<void> {\n const previous = Number(process.env[AFTER_PID_ENV]);\n const refresh = process.env[REFRESH_LAUNCHER_ENV] === \"1\";\n delete process.env[AFTER_PID_ENV];\n delete process.env[REFRESH_LAUNCHER_ENV];\n if (Number.isInteger(previous) && previous > 0) await waitForExit(previous, waitMs);\n if (!refresh) return;\n // The old launcher reads its last lines after its agent exits; give it a moment to finish before its file changes.\n await new Promise((r) => setTimeout(r, 2_000));\n try { if (refreshLauncher(dir, cli)) console.log(`${new Date().toISOString()} rewrote the autostart launcher for this version`); }\n catch (error) { console.log(`${new Date().toISOString()} could not rewrite the autostart launcher: ${(error as Error).message}`); }\n}\n\nexport async function waitForExit(pid: number, timeoutMs: number): Promise<void> {\n const until = Date.now() + timeoutMs;\n while (Date.now() < until) {\n try { process.kill(pid, 0); } catch { return; }\n await new Promise((r) => setTimeout(r, 250));\n }\n}\n\nexport const AGENT_LOCK = \"agent.lock\";\n\n/** How long a lock whose agent never answered on its local channel still counts as an agent starting up. */\nexport const AGENT_LOCK_STARTING_MS = 60_000;\n\n/** Take the one-agent-per-home lock: created exclusively, or taken over when the agent named in it is\n * gone. The caller has already found no agent answering on the local channel, so a lock older than\n * AGENT_LOCK_STARTING_MS is left over even when its process id is alive: Windows reuses process ids\n * soon after a restart, and a sign-in after a reboot must not find \"already running\". A newer lock\n * is an agent still starting (or one whose id is not written yet): this start gives way.\n * Returns the lock file, or null while another agent holds it. */\nexport function acquireAgentLock(dir: string, now = Date.now()): string | null {\n const file = join(dir, AGENT_LOCK);\n mkdirSync(dir, { recursive: true });\n const mine = `${process.pid} ${now}`;\n try { writeFileSync(file, mine, { flag: \"wx\" }); return file; } catch { /* held, or left behind */ }\n let text = \"\";\n let written = now;\n try { text = readFileSync(file, \"utf8\").trim(); written = statSync(file).mtimeMs; } catch { /* removed meanwhile */ }\n const [pidText, atText] = text.split(/\\s+/);\n const holder = Number(pidText);\n const at = Number(atText);\n const since = Number.isFinite(at) && at > 0 ? at : written;\n const fresh = now - since < AGENT_LOCK_STARTING_MS;\n if (holder !== process.pid && fresh) {\n if (!(Number.isInteger(holder) && holder > 0)) return null; // being written by an agent starting this moment\n try { process.kill(holder, 0); return null; } catch { /* that agent is gone: take the lock over */ }\n }\n writeFileSync(file, mine);\n return file;\n}\n\nexport function releaseAgentLock(file: string): void {\n try { if (readFileSync(file, \"utf8\").trim().split(/\\s+/)[0] === String(process.pid)) rmSync(file, { force: true }); } catch { /* already gone */ }\n}\n\nexport async function startService(options: ServiceOptions): Promise<Service> {\n const log = options.log ?? ((line: string) => console.log(`${new Date().toISOString()} ${line}`));\n if (await callAgent(options.dir, \"GET\", \"/status\", undefined, 2_000)) throw new Error(\"a Scopebond Agent is already running for this computer\");\n // Two agents started within moments of each other (a slow first start, then a second start) both see\n // nobody answering yet: the lock file decides, so the second exits instead of orphaning the first.\n const lock = acquireAgentLock(options.dir);\n if (!lock) throw new Error(\"a Scopebond Agent is already running for this computer\");\n const interval = options.intervalMs ?? INTERVAL_MS;\n let last: CycleResult | null = null;\n let lastMaintenance: MaintenanceResult | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let maintenanceTimer: ReturnType<typeof setInterval> | null = null;\n let running: Promise<CycleResult> | null = null;\n let cycleStartedAt: number | null = null;\n const cycleLimit = options.cycleLimitMs ?? CYCLE_LIMIT_MS;\n let stopped = false;\n let lastSelfCheckAt = 0;\n // SB388: time asleep never counts as records waiting. A gap between cycles longer than the schedule allows means the\n // computer slept (or the agent was stopped); waiting is counted again from the next cycle.\n let awakeSince = Date.now();\n let lastCycleAt = 0;\n // A long step the person should see as \"working\" (an update), or null.\n let working: string | null = null;\n // SB391: the workspace's own summary for the tray (names, links, open reviews), refreshed every five minutes; null when the\n // workspace does not answer it (a self-hosted gateway), and the tray simply leaves those rows out.\n // SB392: a sign-in started from the tray, while it waits for approval.\n let reconnecting: ReconnectStart | null = null;\n let summary: ComputerSummary | null = null;\n let summaryAt = 0;\n const refreshSummary = async () => {\n summaryAt = Date.now();\n const connection = loadConnection(options.dir);\n summary = connection ? await fetchComputerSummary(connection, options.fetchImpl) : null;\n };\n\n const prompt = serialized(options.prompter ?? systemPrompter);\n let shownLevel: HealthLevel | null = null;\n const health = () => healthOf(computerStatus(options.dir), lastMaintenance?.selfCheck ?? null);\n const noticeHealth = () => { const h = health(); notifyChange(shownLevel, h); shownLevel = h.level; };\n const sendReasons = async () => {\n const connection = loadConnection(options.dir);\n if (!connection) return;\n try { const sent = await flushReasons(options.dir, connection, options.fetchImpl); if (sent) log(`sent ${sent} override reason(s) to the workspace`); }\n catch { /* they wait for the next cycle */ }\n // D144: allowances a person made here, and their requests to an admin.\n try {\n const sent = await sendAllowancesAndRequests(options.dir, connection, options.fetchImpl);\n if (sent.allowances || sent.requests) log(`sent ${sent.allowances} allowance(s) and ${sent.requests} request(s) to the workspace`);\n } catch { /* they wait for the next cycle */ }\n };\n const cycle = async (): Promise<CycleResult> => {\n if (running) return running;\n const started = Date.now();\n const allowedGap = failures ? MAX_BACKOFF_MS + 5 * 60_000 : Math.max(3 * interval, 5 * 60_000);\n if (lastCycleAt && started - lastCycleAt > allowedGap) awakeSince = started;\n lastCycleAt = started;\n cycleStartedAt = started;\n // A cycle that does not finish within its limit is left behind (its requests time out on their own), counted as\n // a failure, and the loop goes on. Nothing — the next cycle, Send now, stop — waits on it.\n let limitTimer: ReturnType<typeof setTimeout> | undefined;\n const overrun = new Promise<CycleResult>((resolve) => {\n limitTimer = setTimeout(() => resolve({ at: started, connected: true, delivered: 0, pending: computerStatus(options.dir).delivery.pending,\n deliveryError: `a delivery cycle did not finish within ${Math.round(cycleLimit / 1000)} s`, rules: \"skipped\", missingHookEntries: [], requested: null }), cycleLimit);\n limitTimer.unref?.();\n });\n const work = runCycle({ dir: options.dir, fetchImpl: options.fetchImpl, deliveryTimeoutMs: options.deliveryTimeoutMs });\n running = Promise.race([work, overrun]).then(async (result) => {\n if (limitTimer) clearTimeout(limitTimer);\n if (result.deliveryError?.startsWith(\"a delivery cycle did not finish\")) recordAgentError(options.dir, result.deliveryError);\n await sendReasons();\n try { noticeHealth(); } catch { /* status is best effort */ }\n last = result;\n failures = result.deliveryError ? failures + 1 : 0;\n if (result.delivered) log(`delivered ${result.delivered} record(s); ${result.pending} waiting`);\n if (result.deliveryError) log(`delivery problem: ${result.deliveryError}`);\n // SB390: asked from the workspace's computer page. Send again now (the cycle sent before its rules check), or run the\n // self-check; each once.\n if (result.requested === \"flush\") { log(\"the workspace asked this computer to send now\"); setTimeout(() => { void cycle(); }, 0); }\n if (result.requested === \"self_check\") { log(\"the workspace asked this computer to check now\"); setTimeout(() => { void maintain(true); }, 0); }\n if (result.connected && Date.now() - summaryAt > SUMMARY_EVERY_MS) void refreshSummary();\n return result;\n }).finally(() => { running = null; cycleStartedAt = null; });\n return running;\n };\n\n const maintain = async (forceSelfCheck = false): Promise<MaintenanceResult> => {\n const result: MaintenanceResult = { at: Date.now(), policy: \"unknown\", updatedTo: null, hookEntries: [], selfCheck: null, error: null };\n try {\n const connection = loadConnection(options.dir);\n const harnesses = expectedHarnesses();\n const target = connection ? await fetchClientVersion(connection, options.fetchImpl) : null;\n if (target) result.policy = target.policy;\n const current = agentVersion();\n // Hook entries first: under \"recommended\" they move to the newest hook named or carried; under \"hold\" only broken ones\n // are repaired, at the version they already name or the one the agent carries. Done before a self-update, so an update\n // whose handover fails never leaves the hook behind.\n const hookTarget = target?.policy === \"recommended\" && target.hook && compareVersions(target.hook, hookVersion()) > 0 ? target.hook : hookVersion();\n result.hookEntries = maintainHookEntries(harnesses, hookTarget, target?.policy !== \"hold\");\n for (const change of result.hookEntries) log(`${change.reason}: ${change.file}`);\n const kind = installKind();\n if (target?.policy === \"recommended\" && target.agent && compareVersions(target.agent, current) > 0 && kind === \"per-machine\") {\n // Installed for every user: the organisation that deployed it updates it.\n log(`the workspace recommends the Scopebond Agent ${target.agent}; this install is updated by your organization`);\n } else if (target?.policy === \"recommended\" && target.agent && compareVersions(target.agent, current) > 0 && kind === \"per-user\") {\n log(`updating the Scopebond Agent ${current} -> ${target.agent} (signed installer)`);\n const verified = await fetchVerifiedInstaller(target.agent, { dir: options.dir, fetchImpl: options.fetchImpl });\n if (verified.ok) {\n result.updatedTo = target.agent;\n lastMaintenance = result;\n if (options.onUpdated) options.onUpdated(target.agent);\n else {\n // The installer replaces this file, so it runs after this agent has exited, and starts the agent again.\n installAfterExit(verified.path, process.pid, existsSync(launcherPath(options.dir)) ? launcherPath(options.dir) : null);\n setTimeout(() => { setTimeout(() => process.exit(0), 5_000).unref(); void stop().finally(() => process.exit(0)); }, 500);\n }\n return result;\n }\n result.error = `update to ${target.agent} could not be verified: ${verified.reason}; nothing was installed`;\n log(result.error);\n } else if (target?.policy === \"recommended\" && target.agent && compareVersions(target.agent, current) > 0) {\n log(`updating the Scopebond Agent ${current} -> ${target.agent}`);\n const installed = await installAgent(target.agent);\n if (installed.ok) {\n result.updatedTo = target.agent;\n lastMaintenance = result;\n if (options.onUpdated) options.onUpdated(target.agent);\n else {\n const code = spawnReplacement(options.dir) ? 0 : RESTART_EXIT_CODE;\n // Hand over: stop, then exit. A stop that never finishes (a tray or window child that will not close) must not\n // keep the old agent alive with the replacement waiting on it, so the exit has a hard deadline.\n setTimeout(() => { setTimeout(() => process.exit(code), 5_000).unref(); void stop().finally(() => process.exit(code)); }, 500);\n }\n return result;\n }\n result.error = `update to ${target.agent} failed: ${installed.output.slice(-300)}`;\n log(result.error);\n }\n // The local store: older rows rewritten, acknowledged receipts past the retention window removed, space returned.\n // The agent may rewrite the whole file once (the hook never does that during a tool call).\n try {\n result.store = runStoreUpkeep(options.dir, { budgetMs: 30_000, allowFullVacuum: true });\n const kept = result.store;\n if (kept && (kept.migrated || kept.receiptsRemoved || kept.stateRemoved || kept.pagesFreed)) {\n log(`local store: ${kept.migrated} row(s) rewritten, ${kept.receiptsRemoved} receipt(s) past retention removed, ${kept.stateRemoved} finished check record(s) removed, ${kept.pagesFreed} page(s) returned`);\n }\n } catch (error) { log(`local store upkeep failed: ${(error as Error).message}`); }\n if (connection && (forceSelfCheck || Date.now() - lastSelfCheckAt >= SELF_CHECK_EVERY_MS)) {\n result.selfCheck = await runSelfCheck(options.dir, connection, harnesses, current, { fetchImpl: options.fetchImpl });\n lastSelfCheckAt = Date.now();\n log(`self-check ${result.selfCheck?.ok ? \"passed\" : `failed: ${result.selfCheck?.failed.join(\", \") ?? \"no result\"}`}`);\n }\n } catch (error) { result.error = (error as Error).message; }\n lastMaintenance = result;\n return result;\n };\n\n const schedule = () => {\n if (stopped) return;\n const delay = failures ? Math.min(MAX_BACKOFF_MS, interval * 2 ** Math.min(failures, 6)) : interval;\n timer = setTimeout(() => { void cycle().finally(schedule); }, delay);\n };\n\n // D144: a block under a rule a person may allow or ask about can be acted on afterwards, from the tray.\n const actionable = (blocks: Array<{ action_id: string | null; summary: string; at: string; rule: string | null }>, now: number): RecentBlock[] => {\n const known = new Map(readBlocked(options.dir).map((b) => [b.id, b]));\n return blocks.map((b) => {\n const item = b.action_id ? known.get(b.action_id) : undefined;\n return { ...b, rule: b.rule ?? item?.rule ?? null, can_act: Boolean(item && b.action_id && blockedQuestion(options.dir, b.action_id, now)), acted: item?.acted ?? null };\n });\n };\n\n const trayState = (): TrayModel => {\n const now = Date.now();\n const status = computerStatus(options.dir);\n const meta = readMeta(options.dir);\n const report = ruleReport(options.dir);\n const modes = report ? Object.values(report).map(([mode]) => mode) : [];\n const activity = localActivity(options.dir);\n return trayModel({\n status, health: health(), now, awakeSince, working,\n rules: report ? { checked_at: meta.checked_at ? Date.parse(meta.checked_at) : null, managed: isManaged(options.dir), block: modes.filter((m) => m === \"enforce\").length, monitor: modes.filter((m) => m === \"monitor\").length } : null,\n today: activity?.today ?? null,\n recentBlocks: actionable(activity?.recent_blocks ?? [], now),\n version: { agent: agentVersion(), hook: hookVersion(), policy: lastMaintenance?.policy ?? \"unknown\", recommendedAgent: meta.recommended?.agent ?? null, recommendedHook: meta.recommended?.hook ?? null },\n workspace: summary ? { name: summary.workspace_name, environment: summary.environment_name, computer_url: summary.computer_url } : null,\n openReviews: summary?.open_reviews ?? 0,\n computerName: hostname(),\n canReconnect: true,\n });\n };\n\n const control = await startControl(options.dir, `${AGENT_VERSION} hook/${hookVersion()}`, {\n // SB387: what the tray draws, and the person's tray settings.\n \"GET /tray\": () => ({ tray: trayState(), settings: readTraySettings(options.dir) }),\n \"POST /settings\": (body) => ({ settings: writeTraySettings(options.dir, body) }),\n // SB387: \"Check now\" always says what it found.\n \"POST /check\": async () => {\n const result = await maintain(true);\n return { text: checkResult(result.selfCheck, result.error), tray: trayState() };\n },\n // SB389: install the version the workspace recommends now, instead of at the next six-hourly check.\n \"POST /update\": async () => {\n working = \"Updating Scopebond…\";\n try { const result = await maintain(true); return { updated_to: result.updatedTo, error: result.error }; }\n finally { working = null; }\n },\n // SB389: the newest blocks on this computer, summarised the way `log` prints them (never raw arguments).\n // SB391: open this computer's page in the workspace, only on the workspace this computer is connected to.\n \"POST /open-workspace\": () => {\n const connection = loadConnection(options.dir);\n const url = summary?.computer_url;\n if (!connection || !url || !sameOrigin(url, connection.url)) return { opened: false };\n openInBrowser(url);\n return { opened: true };\n },\n // SB392: sign in again for the connected workspace; the tray shows the code, the approval page opens in the browser.\n \"POST /reconnect\": async () => {\n if (reconnecting) return reconnecting;\n working = \"Signing in again…\";\n const result = await startReconnect(options.dir, (ok) => {\n reconnecting = null; working = null;\n log(ok ? \"signed in again\" : \"the sign-in did not finish\");\n if (ok) void cycle();\n });\n if (\"error\" in result) { working = null; return { error: result.error }; }\n reconnecting = result.started;\n log(`signing in again: waiting for approval of code ${result.started.user_code}`);\n return result.started;\n },\n \"GET /recent-blocks\": () => ({ recent_blocks: actionable(localActivity(options.dir, { limit: 10 })?.recent_blocks ?? [], Date.now()) }),\n // D144: allow an earlier block, or ask an admin, from the tray. The caller names the block; only the Scopebond window\n // answers (the same window the hook uses), so whoever calls this channel cannot allow anything by itself. Scopebond never\n // runs the action: the person or the coding agent runs it again.\n \"POST /blocked\": async (body) => {\n const id = typeof (body as { action_id?: unknown } | null)?.action_id === \"string\" ? String((body as { action_id: string }).action_id) : \"\";\n const q = id ? blockedQuestion(options.dir, id) : null;\n if (!q) return { outcome: \"gone\", text: \"This block can no longer be allowed or sent to an admin from here.\" };\n log(`asking about an earlier block under \"${q.title}\"`);\n const answer = await prompt({ action_id: id, rule: q.item.rule, title: q.title, summary: q.item.summary, reason_min: q.reason_min,\n lasts: \"the next time it runs\", timeout_ms: 55_000, mode: q.mode, offers: q.offers });\n if (answer.decision === \"unavailable\") return { outcome: \"unavailable\", text: \"The Scopebond window could not be shown.\" };\n const done = actOnBlocked(options.dir, id, answer);\n if (done.outcome === \"allowed\" || done.outcome === \"proposed\" || done.outcome === \"asked\") setTimeout(() => { void sendReasons(); }, 1_000);\n log(`earlier block under \"${q.title}\": ${done.outcome}`);\n return { outcome: done.outcome, text: blockedText(done.outcome) };\n },\n \"GET /status\": () => ({ ...computerStatus(options.dir), health: health(), agent: { pid: process.pid, version: AGENT_VERSION, last_cycle: last, cycle_started_at: cycleStartedAt, last_maintenance: lastMaintenance } }),\n \"POST /flush\": async () => ({ cycle: await cycle() }),\n \"POST /repair\": () => {\n const repaired = repairHookEntries();\n for (const r of repaired) log(`repaired the Scopebond hook entry in ${r.file}`);\n return { repaired };\n },\n \"POST /maintain\": async () => ({ maintenance: await maintain(true) }),\n // `scopebond-agent stop` and `autostart off`: answer first, then stop, so the caller hears back.\n \"POST /stop\": () => {\n log(\"stopping: asked to by this computer's user\");\n setTimeout(() => { void stop().finally(() => options.onStopped?.()); }, 50);\n return { stopping: true };\n },\n // Warn mode: the hook asks; only the window answers. The caller learns the answer, never decides it.\n \"POST /override\": async (body) => {\n const question = parseQuestion(body);\n if (!question) return { decision: \"unavailable\" };\n log(`asking whether to allow \"${question.title}\"`);\n const answer = await prompt(question);\n log(`override ${answer.decision === \"allow\" ? \"given\" : answer.decision === \"deny\" ? \"not given\" : \"not available\"} for \"${question.title}\"`);\n if (answer.decision === \"allow\" && answer.reason) { queueReason(options.dir, question.action_id, answer.reason); setTimeout(() => { void sendReasons(); }, 1_000); }\n // The hook writes the request or allowance after this answer; send it shortly after.\n if (answer.decision === \"ask\" || answer.lasts === \"always\" || answer.lasts === \"15m\") setTimeout(() => { void sendReasons(); }, 2_000);\n return answer;\n },\n });\n const tray = (options.tray ?? true) && process.env.SCOPEBOND_AGENT_TRAY !== \"off\" ? startTray(options.dir) : null;\n const stop = async () => {\n stopped = true;\n try { tray?.kill(); } catch { /* already gone */ }\n if (timer) clearTimeout(timer);\n if (maintenanceTimer) clearInterval(maintenanceTimer);\n // A cycle under way gets a moment to finish; stop never waits on one that does not.\n if (running) await Promise.race([running.catch(() => undefined), new Promise((resolve) => setTimeout(resolve, 2_000).unref?.())]);\n await control.close();\n releaseAgentLock(lock);\n };\n log(`Scopebond Agent ${agentVersion()} running for ${options.dir} (control on 127.0.0.1:${control.endpoint.port})`);\n // Maintenance is armed before the first cycle, so a first cycle that hangs cannot keep it from ever starting.\n if (options.maintenance !== false) {\n // Shortly after start (so a fresh sign-in is not slowed), then every six hours.\n setTimeout(() => { if (!stopped) void maintain(); }, 2 * 60_000).unref?.();\n maintenanceTimer = setInterval(() => { if (!stopped) void maintain(); }, UPDATE_EVERY_MS);\n maintenanceTimer.unref?.();\n }\n await cycle();\n schedule();\n return { port: control.endpoint.port, cycleNow: cycle, maintainNow: () => maintain(true), stop };\n}\n\n/** What the tray says after a person acted on an earlier block. */\nexport function blockedText(outcome: \"allowed\" | \"proposed\" | \"asked\" | \"declined\" | \"gone\"): string {\n switch (outcome) {\n case \"allowed\": return \"Allowed. Run it again, or let the coding agent retry.\";\n case \"proposed\": return \"Allowed for 15 minutes. Your workspace's admins decide whether it stands; run it again meanwhile.\";\n case \"asked\": return \"Asked your workspace's admins. The Scopebond icon shows their answer; then run it again.\";\n case \"declined\": return \"Nothing was allowed.\";\n case \"gone\": return \"This block can no longer be allowed or sent to an admin from here.\";\n }\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,+FAA+F;AAC/F,8FAA8F;AAC9F,qEAAqE;AAErE,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/F,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE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AAC,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC;QAC1F,gBAAgB,CAAC,KAAK,EAAE,EAAE,CAAC;IAC7B,CAAC;IACD,MAAM,KAAK,EAAE,CAAC;IACd,QAAQ,EAAE,CAAC;IACX,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;AACnG,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,WAAW,CAAC,OAA+D;IACzF,QAAQ,OAAO,EAAE,CAAC;QAChB,KAAK,SAAS,CAAC,CAAC,OAAO,uDAAuD,CAAC;QAC/E,KAAK,UAAU,CAAC,CAAC,OAAO,mGAAmG,CAAC;QAC5H,KAAK,OAAO,CAAC,CAAC,OAAO,0FAA0F,CAAC;QAChH,KAAK,UAAU,CAAC,CAAC,OAAO,sBAAsB,CAAC;QAC/C,KAAK,MAAM,CAAC,CAAC,OAAO,oEAAoE,CAAC;IAC3F,CAAC;AACH,CAAC","sourcesContent":["// The resident loop: one cycle now, then one every interval, sooner after a change is asked for,\n// backing off while the workspace is unreachable. Exactly one agent serves a Scopebond home: a\n// second one finds the first answering and exits. Every six hours it asks the workspace which\n// versions to run, and once a day it runs the end-to-end self-check.\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { hostname, uptime } from \"node:os\";\nimport { join } from \"node:path\";\nimport { actOnBlocked, blockedQuestion, hookVersion, isSingleExecutable, isManaged, loadConnection, localActivity, noteUnresolvableHooks, readBlocked, readMeta, ruleReport, writeDeliveryState, userHarnessFile, writeHarnessConfig, type Harness } from \"@scopebond/hook\";\nimport { computerStatus, expectedHarnesses, missingHookEntries, runCycle, type CycleResult } from \"./agent.js\";\nimport { agentCliPath } from \"./self.js\";\nimport { fetchVerifiedInstaller, installAfterExit, installerUnchanged, installKind, nativeTrayPath, takeInstallResult } from \"./native-update.js\";\nimport { AGENT_LOG_ENV, launcherIsCurrent, launcherPath, refreshLauncher, retireLauncherRunValue, startCommands } from \"./autostart.js\";\nimport { callAgent, startControl } from \"./ipc.js\";\nimport { runSelfCheck } from \"./selfcheck.js\";\nimport { flushReasons, queueReason } from \"./override-reasons.js\";\nimport { parseQuestion, serialized, systemPrompter, type Prompter } from \"./prompt.js\";\nimport { healthOf, type HealthLevel } from \"./health.js\";\nimport { notifyChange, startTray } from \"./tray.js\";\nimport { sendAllowancesAndRequests } from \"./allowance-sender.js\";\nimport { checkResult, trayModel, type RecentBlock, type TrayModel } from \"./tray-model.js\";\nimport { fetchComputerSummary, openInBrowser, sameOrigin, type ComputerSummary } from \"./summary.js\";\nimport { startReconnect, type ReconnectStart } from \"./reconnect.js\";\nimport {\n agentVersion, compareVersions, fetchClientVersion, installAgent, maintainHookEntries, maintainedHookCommand, recentlyFailedUpdate, recordFailedUpdate, startCheck,\n} from \"./update.js\";\nimport { runUpkeepApart, type UpkeepReport } from \"./upkeep.js\";\nimport { awakeSinceAtStart, readAwake, writeAwake } from \"./awake.js\";\n\nexport const AGENT_VERSION = `agent/${agentVersion()}`;\nconst INTERVAL_MS = 60_000;\nconst MAX_BACKOFF_MS = 15 * 60_000;\nconst UPDATE_EVERY_MS = 6 * 60 * 60 * 1000;\nconst SELF_CHECK_EVERY_MS = 24 * 60 * 60 * 1000;\nconst SUMMARY_EVERY_MS = 5 * 60 * 1000;\nexport const AFTER_PID_ENV = \"SCOPEBOND_AGENT_AFTER_PID\";\n/** Left in the Scopebond folder when this computer's user stops the agent (`scopebond-agent stop`), and removed when it\n * starts: the native tray then leaves it stopped instead of starting it again. */\nexport const STOPPED_FILE = \"agent-stopped.json\";\n/** The person's tray settings (D143: notifications about problems by default, none about blocks). */\nexport const TRAY_SETTINGS_FILE = \"agent-settings.json\";\nexport type NotificationSetting = \"all\" | \"problems\" | \"off\";\nexport interface TraySettings { notifications: NotificationSetting }\n\nexport function readTraySettings(dir: string): TraySettings {\n try {\n const parsed = JSON.parse(readFileSync(join(dir, TRAY_SETTINGS_FILE), \"utf8\")) as Partial<TraySettings>;\n return { notifications: parsed.notifications === \"all\" || parsed.notifications === \"off\" ? parsed.notifications : \"problems\" };\n } catch { return { notifications: \"problems\" }; }\n}\n\nexport function writeTraySettings(dir: string, patch: unknown): TraySettings {\n const next = readTraySettings(dir);\n const value = (patch as { notifications?: unknown } | null)?.notifications;\n if (value === \"all\" || value === \"problems\" || value === \"off\") next.notifications = value;\n writeFileSync(join(dir, TRAY_SETTINGS_FILE), JSON.stringify(next, null, 2) + \"\\n\", { mode: 0o600 });\n return next;\n}\n\n/** Set for a replacement started directly because the launcher is an older one: it rewrites the launcher once the old agent is gone. */\nexport const REFRESH_LAUNCHER_ENV = \"SCOPEBOND_AGENT_REFRESH_LAUNCHER\";\n/** The exit code that asks a service manager to start the agent again (systemd's Restart=on-failure), used where a detached replacement would not survive. */\nexport const RESTART_EXIT_CODE = 75;\n\nexport interface ServiceOptions {\n dir: string; intervalMs?: number; fetchImpl?: typeof fetch; log?: (line: string) => void;\n /** Off in tests: the update check and self-check run only when asked. */\n maintenance?: boolean;\n /** Called after a successful update instead of restarting (tests). */\n onUpdated?: (version: string) => void;\n /** Confirms the newly installed agent starts and reports its version before this one hands over (tests replace it). */\n startCheck?: (version: string) => Promise<{ ok: boolean; output: string }>;\n /** Shows the Scopebond window for an override (tests replace it). */\n prompter?: Prompter;\n /** The Windows tray icon (default on Windows; SCOPEBOND_AGENT_TRAY=off turns it off). */\n tray?: boolean;\n /** Runs one local store upkeep pass (default: `scopebond-agent upkeep` in a child process; tests replace it). */\n upkeep?: (dir: string) => Promise<UpkeepReport>;\n /** Called once the agent has stopped because `stop` (or `autostart off`) asked it to; the CLI exits. */\n onStopped?: () => void;\n /** Each delivery request's time limit (default 30 s) and one cycle's (default 10 minutes). A cycle that runs past its\n * limit is counted as a failure and the next one is scheduled; nothing waits on it. */\n deliveryTimeoutMs?: number;\n cycleLimitMs?: number;\n}\n\n/** The agent's own delivery problem, kept apart from a hook call's cut-off. */\nfunction recordAgentError(dir: string, message: string): void {\n writeDeliveryState(dir, { last_error: message, last_status: null, last_error_source: \"agent\", last_error_at: Date.now() });\n}\n\n/** How long one delivery cycle may run before the agent stops waiting for it. */\nexport const CYCLE_LIMIT_MS = 10 * 60_000;\n\nexport interface Service {\n stop(): Promise<void>;\n cycleNow(): Promise<CycleResult>;\n maintainNow(): Promise<MaintenanceResult>;\n port: number;\n}\n\nexport interface MaintenanceResult {\n at: number;\n policy: \"recommended\" | \"hold\" | \"unknown\";\n updatedTo: string | null;\n hookEntries: Array<{ harness: Harness; file: string; reason: string }>;\n selfCheck: Awaited<ReturnType<typeof runSelfCheck>>;\n /** The local store's upkeep this pass (D144): rows rewritten, receipts past retention removed, space returned. */\n store?: UpkeepReport;\n error: string | null;\n}\n\n/** Put the Scopebond hook back into agent settings that lost it. A visible change: each one is\n * logged and returned, and only settings of agents this computer has are touched. */\nexport function repairHookEntries(harnesses: Harness[] = expectedHarnesses()): Array<{ harness: Harness; file: string }> {\n const repaired: Array<{ harness: Harness; file: string }> = [];\n for (const harness of missingHookEntries(harnesses)) {\n const file = writeHarnessConfig(userHarnessFile(harness), harness, maintainedHookCommand(harness));\n repaired.push({ harness, file });\n }\n return repaired;\n}\n\n/** How the updated agent takes over from this one. */\nexport type Handover =\n | { kind: \"spawn\"; command: string; args: string[]; env: Record<string, string | undefined>; verbatim: boolean }\n | { kind: \"service-restart\" };\n\n/** Decide how to start the updated agent. Through the autostart launcher when there is one, so it finds Node the same way\n * sign-in does and is restarted after a crash. On Windows an older launcher cannot do it: it redirects the agent's output\n * into agent.log, this agent's children inherit that handle, and the new launcher's own redirect then fails, which cmd\n * takes for a clean exit. So under an older launcher the updated agent starts directly and rewrites the launcher once\n * this one is gone. Under systemd a detached child is stopped with the service, so the service manager restarts it. */\nexport function handoverPlan(o: {\n dir: string; cli: string; pid: number; execPath: string; platform: NodeJS.Platform;\n /** The single executable: the program is the agent itself, with no cli.js and no Node options. */\n singleExecutable?: boolean;\n env: Record<string, string | undefined>; launcherText: string | null;\n}): Handover {\n if (o.platform === \"linux\" && o.env.INVOCATION_ID) return { kind: \"service-restart\" };\n const launcher = launcherPath(o.dir, o.platform);\n const env = { ...o.env, [AFTER_PID_ENV]: String(o.pid), [AGENT_LOG_ENV]: join(o.dir, \"agent.log\") };\n if (o.launcherText !== null && launcherIsCurrent(o.launcherText, o.platform)) {\n if (o.platform === \"win32\") {\n const [command, args] = startCommands(launcher, o.platform)[1];\n return { kind: \"spawn\", command, args, env, verbatim: true };\n }\n return { kind: \"spawn\", command: \"/bin/sh\", args: [launcher], env, verbatim: false };\n }\n return {\n kind: \"spawn\", command: o.execPath, args: o.singleExecutable ? [\"run\"] : [\"--disable-warning=ExperimentalWarning\", o.cli, \"run\"], verbatim: false,\n env: o.launcherText !== null ? { ...env, [REFRESH_LAUNCHER_ENV]: \"1\" } : env,\n };\n}\n\n/** Start the updated agent, which waits for this process to exit. Returns false when a service manager restarts it instead\n * (this process then exits with RESTART_EXIT_CODE). */\nexport function spawnReplacement(dir: string, cli = agentCliPath()): boolean {\n let launcherText: string | null = null;\n try { launcherText = readFileSync(launcherPath(dir), \"utf8\"); } catch { /* no autostart launcher */ }\n const plan = handoverPlan({ dir, cli, pid: process.pid, execPath: process.execPath, platform: process.platform, env: process.env, launcherText, singleExecutable: isSingleExecutable() });\n if (plan.kind === \"service-restart\") return false;\n const child = spawn(plan.command, plan.args, { env: plan.env, detached: true, stdio: \"ignore\", windowsHide: true, windowsVerbatimArguments: plan.verbatim });\n child.on(\"error\", () => { /* the next sign-in starts it */ });\n child.unref();\n return true;\n}\n\n/** The first thing a starting agent does: wait for the agent it replaces to exit, then, when asked, rewrite the older launcher\n * that agent ran under (by now nothing runs it). The handover variables are dropped, so a later restart waits for nothing. */\nexport async function takeOver(dir: string, cli: string, waitMs = 30_000): Promise<void> {\n const previous = Number(process.env[AFTER_PID_ENV]);\n const refresh = process.env[REFRESH_LAUNCHER_ENV] === \"1\";\n delete process.env[AFTER_PID_ENV];\n delete process.env[REFRESH_LAUNCHER_ENV];\n // The agent being replaced stops serving (control channel closed, lock released) and then waits for this one to answer\n // before it exits, so it can go back to its own version if this one never starts. Unless the launcher must be rewritten\n // (nothing may still run it), its stopping is enough.\n if (Number.isInteger(previous) && previous > 0) await waitForExit(previous, waitMs, refresh ? undefined : () => !lockHeldBy(dir, previous));\n if (!refresh) return;\n // The old launcher reads its last lines after its agent exits; give it a moment to finish before its file changes.\n await new Promise((r) => setTimeout(r, 2_000));\n try { if (refreshLauncher(dir, cli)) console.log(`${new Date().toISOString()} rewrote the autostart launcher for this version`); }\n catch (error) { console.log(`${new Date().toISOString()} could not rewrite the autostart launcher: ${(error as Error).message}`); }\n}\n\nexport async function waitForExit(pid: number, timeoutMs: number, released?: () => boolean): Promise<void> {\n const until = Date.now() + timeoutMs;\n while (Date.now() < until) {\n try { process.kill(pid, 0); } catch { return; }\n if (released?.()) return;\n await new Promise((r) => setTimeout(r, 250));\n }\n}\n\n/** Whether the one-agent lock names `pid`. */\nexport function lockHeldBy(dir: string, pid: number): boolean {\n try { return readFileSync(join(dir, AGENT_LOCK), \"utf8\").trim().split(/\\s+/)[0] === String(pid); } catch { return false; }\n}\n\n/** How long the agent that handed over waits for its replacement to answer before going back to its own version. */\nexport const HANDOVER_CONFIRM_MS = 3 * 60_000;\n\n/** Wait until an agent other than this process answers on the local channel reporting `version`. */\nexport async function waitForAgentVersion(dir: string, version: string, timeoutMs: number): Promise<boolean> {\n const until = Date.now() + timeoutMs;\n while (Date.now() < until) {\n const status = await callAgent(dir, \"GET\", \"/status\", undefined, 2_000) as { agent?: { pid?: number; version?: string } | null } | null;\n if (status?.agent && status.agent.pid !== process.pid && status.agent.version === `agent/${version}`) return true;\n await new Promise((r) => setTimeout(r, 1_000));\n }\n return false;\n}\n\nexport const AGENT_LOCK = \"agent.lock\";\n\n/** How long a lock whose agent never answered on its local channel still counts as an agent starting up. */\nexport const AGENT_LOCK_STARTING_MS = 60_000;\n\n/** Take the one-agent-per-home lock: created exclusively, or taken over when the agent named in it is\n * gone. The caller has already found no agent answering on the local channel, so a lock older than\n * AGENT_LOCK_STARTING_MS is left over even when its process id is alive: Windows reuses process ids\n * soon after a restart, and a sign-in after a reboot must not find \"already running\". A newer lock\n * is an agent still starting (or one whose id is not written yet): this start gives way.\n * Returns the lock file, or null while another agent holds it. */\nexport function acquireAgentLock(dir: string, now = Date.now()): string | null {\n const file = join(dir, AGENT_LOCK);\n mkdirSync(dir, { recursive: true });\n const mine = `${process.pid} ${now}`;\n try { writeFileSync(file, mine, { flag: \"wx\" }); return file; } catch { /* held, or left behind */ }\n let text = \"\";\n let written = now;\n try { text = readFileSync(file, \"utf8\").trim(); written = statSync(file).mtimeMs; } catch { /* removed meanwhile */ }\n const [pidText, atText] = text.split(/\\s+/);\n const holder = Number(pidText);\n const at = Number(atText);\n const since = Number.isFinite(at) && at > 0 ? at : written;\n const fresh = now - since < AGENT_LOCK_STARTING_MS;\n if (holder !== process.pid && fresh) {\n if (!(Number.isInteger(holder) && holder > 0)) return null; // being written by an agent starting this moment\n try { process.kill(holder, 0); return null; } catch { /* that agent is gone: take the lock over */ }\n }\n writeFileSync(file, mine);\n return file;\n}\n\nexport function releaseAgentLock(file: string): void {\n try { if (readFileSync(file, \"utf8\").trim().split(/\\s+/)[0] === String(process.pid)) rmSync(file, { force: true }); } catch { /* already gone */ }\n}\n\nexport async function startService(options: ServiceOptions): Promise<Service> {\n const log = options.log ?? ((line: string) => console.log(`${new Date().toISOString()} ${line}`));\n if (await callAgent(options.dir, \"GET\", \"/status\", undefined, 2_000)) throw new Error(\"a Scopebond Agent is already running for this computer\");\n // Two agents started within moments of each other (a slow first start, then a second start) both see\n // nobody answering yet: the lock file decides, so the second exits instead of orphaning the first.\n const lock = acquireAgentLock(options.dir);\n if (!lock) throw new Error(\"a Scopebond Agent is already running for this computer\");\n rmSync(join(options.dir, STOPPED_FILE), { force: true });\n // What the install helper of a signed update recorded before this start (installAfterExit).\n const installed = takeInstallResult(options.dir);\n if (installed) log(installed.installed ? `the Scopebond Agent ${installed.version} was installed` : `the update to ${installed.version} was not installed: ${installed.reason ?? \"unknown\"}`);\n const interval = options.intervalMs ?? INTERVAL_MS;\n const nativeTray = process.platform === \"win32\" ? nativeTrayPath() : null;\n let last: CycleResult | null = null;\n let lastMaintenance: MaintenanceResult | null = null;\n let failures = 0;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let maintenanceTimer: ReturnType<typeof setInterval> | null = null;\n let running: Promise<CycleResult> | null = null;\n let cycleStartedAt: number | null = null;\n const cycleLimit = options.cycleLimitMs ?? CYCLE_LIMIT_MS;\n let stopped = false;\n let lastSelfCheckAt = 0;\n // SB388: time asleep never counts as records waiting. A gap between cycles longer than the schedule allows means the\n // computer slept (or the agent was stopped); waiting is counted again from the next cycle. The wake time is kept across\n // restarts of the agent alone (awake.ts), so a restart never hides a backlog; after a long gap the waiting records decide.\n const allowedGapMs = Math.max(3 * interval, 5 * 60_000);\n const startedAt = Date.now();\n let oldestPendingAt: number | null = null;\n try {\n const age = computerStatus(options.dir, startedAt).delivery.oldest_pending_age_s;\n oldestPendingAt = age === null ? null : startedAt - age * 1000;\n } catch { /* no store yet: nothing waiting */ }\n let awakeSince = awakeSinceAtStart({ saved: readAwake(options.dir), now: startedAt, uptimeMs: uptime() * 1000, allowedGapMs, oldestPendingAt });\n let lastCycleAt = 0;\n // A long step the person should see as \"working\" (an update), or null.\n let working: string | null = null;\n // SB391: the workspace's own summary for the tray (names, links, open reviews), refreshed every five minutes; null when the\n // workspace does not answer it (a self-hosted gateway), and the tray simply leaves those rows out.\n // SB392: a sign-in started from the tray, while it waits for approval.\n let reconnecting: ReconnectStart | null = null;\n let summary: ComputerSummary | null = null;\n let summaryAt = 0;\n const refreshSummary = async () => {\n summaryAt = Date.now();\n const connection = loadConnection(options.dir);\n summary = connection ? await fetchComputerSummary(connection, options.fetchImpl) : null;\n };\n\n const prompt = serialized(options.prompter ?? systemPrompter);\n let shownLevel: HealthLevel | null = null;\n const health = () => healthOf(computerStatus(options.dir), lastMaintenance?.selfCheck ?? null);\n const noticeHealth = () => { const h = health(); notifyChange(shownLevel, h); shownLevel = h.level; };\n const sendReasons = async () => {\n const connection = loadConnection(options.dir);\n if (!connection) return;\n try { const sent = await flushReasons(options.dir, connection, options.fetchImpl); if (sent) log(`sent ${sent} override reason(s) to the workspace`); }\n catch { /* they wait for the next cycle */ }\n // D144: allowances a person made here, and their requests to an admin.\n try {\n const sent = await sendAllowancesAndRequests(options.dir, connection, options.fetchImpl);\n if (sent.allowances || sent.requests) log(`sent ${sent.allowances} allowance(s) and ${sent.requests} request(s) to the workspace`);\n } catch { /* they wait for the next cycle */ }\n };\n const cycle = async (): Promise<CycleResult> => {\n if (running) return running;\n const started = Date.now();\n const allowedGap = failures ? MAX_BACKOFF_MS + 5 * 60_000 : allowedGapMs;\n if (lastCycleAt && started - lastCycleAt > allowedGap) awakeSince = started;\n lastCycleAt = started;\n writeAwake(options.dir, { awake_since: awakeSince, last_cycle_at: started });\n cycleStartedAt = started;\n // A cycle that does not finish within its limit is left behind (its requests time out on their own), counted as\n // a failure, and the loop goes on. Nothing — the next cycle, Send now, stop — waits on it.\n let limitTimer: ReturnType<typeof setTimeout> | undefined;\n const overrun = new Promise<CycleResult>((resolve) => {\n limitTimer = setTimeout(() => resolve({ at: started, connected: true, delivered: 0, pending: computerStatus(options.dir).delivery.pending,\n deliveryError: `a delivery cycle did not finish within ${Math.round(cycleLimit / 1000)} s`, rules: \"skipped\", missingHookEntries: [], requested: null, more: false }), cycleLimit);\n limitTimer.unref?.();\n });\n const work = runCycle({ dir: options.dir, fetchImpl: options.fetchImpl, deliveryTimeoutMs: options.deliveryTimeoutMs });\n running = Promise.race([work, overrun]).then(async (result) => {\n if (limitTimer) clearTimeout(limitTimer);\n if (result.deliveryError?.startsWith(\"a delivery cycle did not finish\")) recordAgentError(options.dir, result.deliveryError);\n await sendReasons();\n try { noticeHealth(); } catch { /* status is best effort */ }\n last = result;\n failures = result.deliveryError ? failures + 1 : 0;\n if (result.delivered) log(`delivered ${result.delivered} record(s); ${result.pending} waiting`);\n if (result.deliveryError) log(`delivery problem: ${result.deliveryError}`);\n // SB390: asked from the workspace's computer page. Send again now (the cycle sent before its rules check), or run the\n // self-check; each once.\n if (result.requested === \"flush\") { log(\"the workspace asked this computer to send now\"); setTimeout(() => { void cycle(); }, 0); }\n // A long queue: this cycle's sending time ran out, so the next one starts right away instead of at the next interval.\n else if (result.more && !stopped) setTimeout(() => { void cycle(); }, 1_000);\n if (result.requested === \"self_check\") { log(\"the workspace asked this computer to check now\"); setTimeout(() => { void maintain(true); }, 0); }\n if (result.connected && Date.now() - summaryAt > SUMMARY_EVERY_MS) void refreshSummary();\n return result;\n }).finally(() => { running = null; cycleStartedAt = null; });\n return running;\n };\n\n const maintain = async (forceSelfCheck = false): Promise<MaintenanceResult> => {\n const result: MaintenanceResult = { at: Date.now(), policy: \"unknown\", updatedTo: null, hookEntries: [], selfCheck: null, error: null };\n try {\n const connection = loadConnection(options.dir);\n const harnesses = expectedHarnesses();\n const target = connection ? await fetchClientVersion(connection, options.fetchImpl) : null;\n if (target) result.policy = target.policy;\n const current = agentVersion();\n // Hook entries first: always the hook this agent carries, by its path (never a version the workspace names, and never\n // an npx form resolved at run time). Under \"hold\" only broken ones are repaired. After an update the new agent pins\n // them to the hook it carries at its own first upkeep.\n // Codex and Cursor send nothing between actions, so a hook entry of theirs that cannot start is kept as a gap the\n // workspace hears of, before the repair below (the actions in between ran unchecked either way).\n const outage = noteUnresolvableHooks(options.dir, harnesses.filter((h) => h === \"codex\" || h === \"cursor\"));\n if (outage.recorded.length) log(`hook entry cannot start for ${outage.recorded.join(\", \")}: kept as a gap for the workspace`);\n result.hookEntries = maintainHookEntries(harnesses, target?.policy !== \"hold\");\n for (const change of result.hookEntries) log(`${change.reason}: ${change.file}`);\n const kind = installKind();\n const newer = target?.policy === \"recommended\" && target.agent && compareVersions(target.agent, current) > 0 ? target.agent : null;\n if (newer && kind === \"per-machine\") {\n // Installed for every user: the organisation that deployed it updates it.\n log(`the workspace recommends the Scopebond Agent ${newer}; this install is updated by your organization`);\n } else if (newer && kind === \"per-user\") {\n log(`updating the Scopebond Agent ${current} -> ${newer} (signed installer)`);\n const verified = await fetchVerifiedInstaller(newer, { dir: options.dir, fetchImpl: options.fetchImpl });\n if (verified.ok && installerUnchanged(verified)) {\n result.updatedTo = newer;\n lastMaintenance = result;\n if (options.onUpdated) options.onUpdated(newer);\n else {\n // The installer replaces this file, so it runs after this agent has exited, checks it again, and starts the tray\n // (which starts the agent) or the agent again.\n installAfterExit(verified, process.pid, existsSync(launcherPath(options.dir)) ? launcherPath(options.dir) : null, nativeTray);\n setTimeout(() => { setTimeout(() => process.exit(0), 5_000).unref(); void stop().finally(() => process.exit(0)); }, 500);\n }\n return result;\n }\n result.error = `update to ${newer} could not be verified: ${verified.ok ? \"the installer changed after it was checked\" : verified.reason}; nothing was installed`;\n log(result.error);\n } else if (newer && recentlyFailedUpdate(options.dir, newer)) {\n log(`the Scopebond Agent ${newer} did not start here earlier; staying on ${current} for now`);\n } else if (newer) {\n log(`updating the Scopebond Agent ${current} -> ${newer}`);\n const installed = await installAgent(newer, { fetchImpl: options.fetchImpl });\n const started = installed.ok ? await (options.startCheck ?? startCheck)(newer) : null;\n if (installed.ok && started?.ok) {\n result.updatedTo = newer;\n lastMaintenance = result;\n if (options.onUpdated) options.onUpdated(newer);\n else handOver(newer, current);\n return result;\n }\n if (installed.ok) {\n // Installed, but the new program does not start: put the running version back.\n recordFailedUpdate(options.dir, newer);\n const back = await installAgent(current, { provenance: false });\n result.error = `the Scopebond Agent ${newer} did not start (${(started?.output ?? \"\").slice(-200)}); ${back.ok ? `went back to ${current}` : `going back to ${current} failed: ${back.output.slice(-200)}`}`;\n } else result.error = `update to ${newer} failed: ${installed.output.slice(-300)}`;\n log(result.error);\n }\n // The local store: older rows rewritten, acknowledged receipts past the retention window removed, space returned.\n // The agent may rewrite the whole file once (the hook never does that during a tool call).\n try {\n // In a process of its own: a pass is synchronous SQLite work for up to 30 s, and the agent keeps answering meanwhile.\n result.store = await (options.upkeep ?? runUpkeepApart)(options.dir);\n const kept = result.store;\n if (kept && (kept.migrated || kept.receiptsRemoved || kept.stateRemoved || kept.pagesFreed)) {\n log(`local store: ${kept.migrated} row(s) rewritten, ${kept.receiptsRemoved} receipt(s) past retention removed, ${kept.stateRemoved} finished check record(s) removed, ${kept.pagesFreed} page(s) returned`);\n }\n } catch (error) { log(`local store upkeep failed: ${(error as Error).message}`); }\n if (connection && (forceSelfCheck || Date.now() - lastSelfCheckAt >= SELF_CHECK_EVERY_MS)) {\n result.selfCheck = await runSelfCheck(options.dir, connection, harnesses, current, { fetchImpl: options.fetchImpl });\n lastSelfCheckAt = Date.now();\n log(`self-check ${result.selfCheck?.ok ? \"passed\" : `failed: ${result.selfCheck?.failed.join(\", \") ?? \"no result\"}`}`);\n }\n } catch (error) { result.error = (error as Error).message; }\n lastMaintenance = result;\n return result;\n };\n\n const schedule = () => {\n if (stopped) return;\n const delay = failures ? Math.min(MAX_BACKOFF_MS, interval * 2 ** Math.min(failures, 6)) : interval;\n timer = setTimeout(() => { void cycle().finally(schedule); }, delay);\n };\n\n // D144: a block under a rule a person may allow or ask about can be acted on afterwards, from the tray.\n const actionable = (blocks: Array<{ action_id: string | null; summary: string; at: string; rule: string | null }>, now: number): RecentBlock[] => {\n const known = new Map(readBlocked(options.dir).map((b) => [b.id, b]));\n return blocks.map((b) => {\n const item = b.action_id ? known.get(b.action_id) : undefined;\n return { ...b, rule: b.rule ?? item?.rule ?? null, can_act: Boolean(item && b.action_id && blockedQuestion(options.dir, b.action_id, now)), acted: item?.acted ?? null };\n });\n };\n\n const trayState = (): TrayModel => {\n const now = Date.now();\n const status = computerStatus(options.dir);\n const meta = readMeta(options.dir);\n const report = ruleReport(options.dir);\n const modes = report ? Object.values(report).map(([mode]) => mode) : [];\n const activity = localActivity(options.dir);\n return trayModel({\n status, health: health(), now, awakeSince, working,\n rules: report ? { checked_at: meta.checked_at ? Date.parse(meta.checked_at) : null, managed: isManaged(options.dir), block: modes.filter((m) => m === \"enforce\").length, monitor: modes.filter((m) => m === \"monitor\").length } : null,\n today: activity?.today ?? null,\n recentBlocks: actionable(activity?.recent_blocks ?? [], now),\n version: { agent: agentVersion(), hook: hookVersion(), policy: lastMaintenance?.policy ?? \"unknown\", recommendedAgent: meta.recommended?.agent ?? null, recommendedHook: meta.recommended?.hook ?? null },\n workspace: summary ? { name: summary.workspace_name, environment: summary.environment_name, computer_url: summary.computer_url } : null,\n openReviews: summary?.open_reviews ?? 0,\n computerName: hostname(),\n canReconnect: true,\n });\n };\n\n const control = await startControl(options.dir, `${AGENT_VERSION} hook/${hookVersion()}`, {\n // SB387: what the tray draws, and the person's tray settings.\n \"GET /tray\": () => ({ tray: trayState(), settings: readTraySettings(options.dir) }),\n \"POST /settings\": (body) => ({ settings: writeTraySettings(options.dir, body) }),\n // SB387: \"Check now\" always says what it found.\n \"POST /check\": async () => {\n const result = await maintain(true);\n return { text: checkResult(result.selfCheck, result.error), tray: trayState() };\n },\n // SB389: install the version the workspace recommends now, instead of at the next six-hourly check.\n \"POST /update\": async () => {\n working = \"Updating Scopebond…\";\n try { const result = await maintain(true); return { updated_to: result.updatedTo, error: result.error }; }\n finally { working = null; }\n },\n // SB389: the newest blocks on this computer, summarised the way `log` prints them (never raw arguments).\n // SB391: open this computer's page in the workspace, only on the workspace this computer is connected to.\n \"POST /open-workspace\": () => {\n const connection = loadConnection(options.dir);\n const url = summary?.computer_url;\n if (!connection || !url || !sameOrigin(url, connection.url)) return { opened: false };\n openInBrowser(url);\n return { opened: true };\n },\n // SB392: sign in again for the connected workspace; the tray shows the code, the approval page opens in the browser.\n \"POST /reconnect\": async () => {\n if (reconnecting) return reconnecting;\n working = \"Signing in again…\";\n const result = await startReconnect(options.dir, (ok) => {\n reconnecting = null; working = null;\n log(ok ? \"signed in again\" : \"the sign-in did not finish\");\n if (ok) void cycle();\n });\n if (\"error\" in result) { working = null; return { error: result.error }; }\n reconnecting = result.started;\n log(`signing in again: waiting for approval of code ${result.started.user_code}`);\n return result.started;\n },\n \"GET /recent-blocks\": () => ({ recent_blocks: actionable(localActivity(options.dir, { limit: 10 })?.recent_blocks ?? [], Date.now()) }),\n // D144: allow an earlier block, or ask an admin, from the tray. The caller names the block; only the Scopebond window\n // answers (the same window the hook uses), so whoever calls this channel cannot allow anything by itself. Scopebond never\n // runs the action: the person or the coding agent runs it again.\n \"POST /blocked\": async (body) => {\n const id = typeof (body as { action_id?: unknown } | null)?.action_id === \"string\" ? String((body as { action_id: string }).action_id) : \"\";\n const q = id ? blockedQuestion(options.dir, id) : null;\n if (!q) return { outcome: \"gone\", text: \"This block can no longer be allowed or sent to an admin from here.\" };\n log(`asking about an earlier block under \"${q.title}\"`);\n const answer = await prompt({ action_id: id, rule: q.item.rule, title: q.title, summary: q.item.summary, reason_min: q.reason_min,\n lasts: \"the next time it runs\", timeout_ms: 55_000, mode: q.mode, offers: q.offers });\n if (answer.decision === \"unavailable\") return { outcome: \"unavailable\", text: \"The Scopebond window could not be shown.\" };\n const done = actOnBlocked(options.dir, id, answer);\n if (done.outcome === \"allowed\" || done.outcome === \"proposed\" || done.outcome === \"asked\") setTimeout(() => { void sendReasons(); }, 1_000);\n log(`earlier block under \"${q.title}\": ${done.outcome}`);\n return { outcome: done.outcome, text: blockedText(done.outcome) };\n },\n \"GET /status\": () => ({ ...computerStatus(options.dir), health: health(), agent: { pid: process.pid, version: AGENT_VERSION, last_cycle: last, cycle_started_at: cycleStartedAt, last_maintenance: lastMaintenance } }),\n \"POST /flush\": async () => ({ cycle: await cycle() }),\n \"POST /repair\": () => {\n const repaired = repairHookEntries();\n for (const r of repaired) log(`repaired the Scopebond hook entry in ${r.file}`);\n return { repaired };\n },\n \"POST /maintain\": async () => ({ maintenance: await maintain(true) }),\n // `scopebond-agent stop` and `autostart off`: answer first, then stop, so the caller hears back.\n \"POST /stop\": () => {\n log(\"stopping: asked to by this computer's user\");\n try { writeFileSync(join(options.dir, STOPPED_FILE), `${JSON.stringify({ stopped_at: new Date().toISOString(), pid: process.pid })}\\n`); } catch { /* the tray may start it again */ }\n setTimeout(() => { void stop().finally(() => options.onStopped?.()); }, 50);\n return { stopping: true };\n },\n // Warn mode: the hook asks; only the window answers. The caller learns the answer, never decides it.\n \"POST /override\": async (body) => {\n const question = parseQuestion(body);\n if (!question) return { decision: \"unavailable\" };\n log(`asking whether to allow \"${question.title}\"`);\n const answer = await prompt(question);\n log(`override ${answer.decision === \"allow\" ? \"given\" : answer.decision === \"deny\" ? \"not given\" : \"not available\"} for \"${question.title}\"`);\n if (answer.decision === \"allow\" && answer.reason) { queueReason(options.dir, question.action_id, answer.reason); setTimeout(() => { void sendReasons(); }, 1_000); }\n // The hook writes the request or allowance after this answer; send it shortly after.\n if (answer.decision === \"ask\" || answer.lasts === \"always\" || answer.lasts === \"15m\") setTimeout(() => { void sendReasons(); }, 2_000);\n return answer;\n },\n }, nativeTray ? { loopback: false } : {}); // beside the native tray nothing uses loopback: its tray and its hook use the pipe\n // Beside the native tray (the signed install), the tray is that program: it started this agent, or starts at sign-in.\n const tray = (options.tray ?? true) && process.env.SCOPEBOND_AGENT_TRAY !== \"off\" && !nativeTray ? startTray(options.dir) : null;\n if (nativeTray && retireLauncherRunValue()) log(\"removed the ScopebondAgent sign-in entry: the Scopebond tray starts the agent\");\n const stop = async () => {\n stopped = true;\n try { tray?.kill(); } catch { /* already gone */ }\n if (timer) clearTimeout(timer);\n if (maintenanceTimer) clearInterval(maintenanceTimer);\n // A cycle under way gets a moment to finish; stop never waits on one that does not.\n if (running) await Promise.race([running.catch(() => undefined), new Promise((resolve) => setTimeout(resolve, 2_000).unref?.())]);\n await control.close();\n releaseAgentLock(lock);\n };\n /** Hand over to the agent just installed: start it, stop serving, and wait for it to answer with the new version. If it\n * never does, put `previous` back, start that, and exit. A service manager (systemd) restarts the agent itself instead. */\n const handOver = (version: string, previous: string) => {\n setTimeout(() => {\n void (async () => {\n // Whatever happens below, this process ends.\n setTimeout(() => process.exit(0), HANDOVER_CONFIRM_MS + 10 * 60_000).unref();\n const spawned = spawnReplacement(options.dir);\n // A stop that never finishes (a tray or window child that will not close) must not keep this agent serving.\n await Promise.race([stop().catch(() => undefined), new Promise((r) => setTimeout(r, 5_000))]);\n if (!spawned) process.exit(RESTART_EXIT_CODE);\n if (await waitForAgentVersion(options.dir, version, HANDOVER_CONFIRM_MS)) process.exit(0);\n log(`the Scopebond Agent ${version} did not answer within ${Math.round(HANDOVER_CONFIRM_MS / 1000)} s; going back to ${previous}`);\n recordFailedUpdate(options.dir, version);\n const back = await installAgent(previous, { provenance: false });\n log(back.ok ? `went back to the Scopebond Agent ${previous}` : `going back to ${previous} failed: ${back.output.slice(-300)}`);\n // The replacement's launcher may restart it on the files just put back; otherwise start the previous version now.\n if (!await waitForAgentVersion(options.dir, previous, 45_000)) spawnReplacement(options.dir);\n process.exit(0);\n })();\n }, 500);\n };\n log(`Scopebond Agent ${agentVersion()} running for ${options.dir} (control on ${[control.endpoint.socket, control.endpoint.port ? `127.0.0.1:${control.endpoint.port}` : null].filter(Boolean).join(\" and \")})`);\n // Maintenance is armed before the first cycle, so a first cycle that hangs cannot keep it from ever starting.\n if (options.maintenance !== false) {\n // Shortly after start (so a fresh sign-in is not slowed), then every six hours.\n setTimeout(() => { if (!stopped) void maintain(); }, 2 * 60_000).unref?.();\n maintenanceTimer = setInterval(() => { if (!stopped) void maintain(); }, UPDATE_EVERY_MS);\n maintenanceTimer.unref?.();\n }\n await cycle();\n schedule();\n return { port: control.endpoint.port, cycleNow: cycle, maintainNow: () => maintain(true), stop };\n}\n\n/** What the tray says after a person acted on an earlier block. */\nexport function blockedText(outcome: \"allowed\" | \"proposed\" | \"asked\" | \"declined\" | \"gone\"): string {\n switch (outcome) {\n case \"allowed\": return \"Allowed. Run it again, or let the coding agent retry.\";\n case \"proposed\": return \"Allowed for 15 minutes. Your workspace's admins decide whether it stands; run it again meanwhile.\";\n case \"asked\": return \"Asked your workspace's admins. The Scopebond icon shows their answer; then run it again.\";\n case \"declined\": return \"Nothing was allowed.\";\n case \"gone\": return \"This block can no longer be allowed or sent to an admin from here.\";\n }\n}\n"]}
package/dist/setup.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type Harness } from "@scopebond/hook";
2
+ import { agentCliPath } from "./self.js";
2
3
  export type SetupStep = "login" | "install_agent" | "autostart";
3
4
  export interface SetupState {
4
5
  /** The workspace origin this computer's user-level connection points at, if any. */
@@ -20,6 +21,17 @@ export declare function globalBinDir(prefix: string, platform?: NodeJS.Platform)
20
21
  export declare function onPath(dir: string, pathEnv?: string, platform?: NodeJS.Platform): boolean;
21
22
  /** The PowerShell line that adds a folder to this user's PATH for new windows. */
22
23
  export declare function addToPathCommand(dir: string): string;
24
+ /** Where the agent setup works with: the signed single executable is already installed (its own version, no npm asked),
25
+ * otherwise the copy in npm's global folder, if any. */
26
+ export declare function agentOnThisComputer(single: boolean, version: string, fromNpm?: () => {
27
+ prefix: string | null;
28
+ cli: string | null;
29
+ version: string | null;
30
+ }, self?: typeof agentCliPath): {
31
+ prefix: string | null;
32
+ cli: string | null;
33
+ version: string | null;
34
+ };
23
35
  export interface SetupOptions {
24
36
  dir: string;
25
37
  origin: string;
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAWA,OAAO,EAAuE,KAAK,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAMpH,MAAM,MAAM,SAAS,GAAG,OAAO,GAAG,eAAe,GAAG,WAAW,CAAC;AAEhE,MAAM,WAAW,UAAU;IACzB,oFAAoF;IACpF,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,kFAAkF;IAClF,iBAAiB,EAAE,OAAO,CAAC;IAC3B,kEAAkE;I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O,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAE9H,wBAAsB,QAAQ,CAAC,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAwF/D"}
package/dist/setup.js CHANGED
@@ -8,10 +8,13 @@ import { spawn, spawnSync } from "node:child_process";
8
8
  import { existsSync, readFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
10
  import { join } from "node:path";
11
- import { hookSelfCommand, loadConnection, nodeTooOldLines, readDeliveryState } from "@scopebond/hook";
11
+ import { hookSelfCommand, isSingleExecutable, loadConnection, nodeTooOldLines, readDeliveryState } from "@scopebond/hook";
12
+ import { agentCliPath, agentSelfCommand } from "./self.js";
12
13
  import { autostartHealth, enableAutostart, startNow } from "./autostart.js";
14
+ import { writeAppsEntry } from "./apps-entry.js";
15
+ import { installKind } from "./native-update.js";
13
16
  import { callAgent } from "./ipc.js";
14
- import { compareVersions, ownNpm } from "./update.js";
17
+ import { compareVersions, npmEnvironment, npmInstallArgs, ownNpm } from "./update.js";
15
18
  import { repairHookEntries } from "./service.js";
16
19
  /** What a setup run has to do, given what is already true. Pure, so a second run is provably a no-op
17
20
  * (or a repair) rather than a second sign-in or install. */
@@ -49,13 +52,13 @@ export function onPath(dir, pathEnv = process.env.PATH ?? process.env.Path ?? ""
49
52
  export function addToPathCommand(dir) {
50
53
  return `[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";${dir}", "User")`;
51
54
  }
52
- function npm(args) {
55
+ function npm(args, env) {
53
56
  const win = process.platform === "win32";
54
57
  // This Node's own npm, without a shell; otherwise npm on PATH (a .cmd on Windows, started through a shell, each argument quoted).
55
58
  const own = ownNpm();
56
59
  const r = own
57
- ? spawnSync(own[0], [...own[1], ...args], { encoding: "utf8", windowsHide: true, timeout: 5 * 60_000 })
58
- : spawnSync(win ? "npm.cmd" : "npm", win ? args.map((a) => `"${a}"`) : args, { encoding: "utf8", shell: win, windowsHide: true, timeout: 5 * 60_000 });
60
+ ? spawnSync(own[0], [...own[1], ...args], { encoding: "utf8", windowsHide: true, timeout: 5 * 60_000, env })
61
+ : spawnSync(win ? "npm.cmd" : "npm", win ? args.map((a) => `"${a}"`) : args, { encoding: "utf8", shell: win, windowsHide: true, timeout: 5 * 60_000, env });
59
62
  return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}` };
60
63
  }
61
64
  function globalAgent() {
@@ -72,6 +75,11 @@ function globalAgent() {
72
75
  catch { /* not installed */ }
73
76
  return { prefix: prefix.ok ? prefix.out.trim().split(/\r?\n/).pop() ?? null : null, cli: existsSync(cli) ? cli : null, version };
74
77
  }
78
+ /** Where the agent setup works with: the signed single executable is already installed (its own version, no npm asked),
79
+ * otherwise the copy in npm's global folder, if any. */
80
+ export function agentOnThisComputer(single, version, fromNpm = globalAgent, self = agentCliPath) {
81
+ return single ? { prefix: null, cli: self(), version } : fromNpm();
82
+ }
75
83
  export async function runSetup(o) {
76
84
  const say = (line) => console.log(line);
77
85
  if (!nodeSupported()) {
@@ -80,14 +88,17 @@ export async function runSetup(o) {
80
88
  return 1;
81
89
  }
82
90
  const connection = loadConnection(o.dir);
83
- let connectedTo = null;
91
+ let connectedTo;
84
92
  try {
85
93
  connectedTo = connection ? new URL(connection.url).origin : null;
86
94
  }
87
95
  catch {
88
96
  connectedTo = null;
89
97
  }
90
- const global = globalAgent();
98
+ // The signed installer put the agent (one executable with the hook) in place: nothing to install with npm, and no Node
99
+ // or npm need be on this computer. Autostart then starts this executable itself.
100
+ const single = isSingleExecutable();
101
+ const global = agentOnThisComputer(single, o.version);
91
102
  const state = {
92
103
  connectedTo,
93
104
  credentialRefused: readDeliveryState(o.dir).invalid_since != null,
@@ -101,7 +112,10 @@ export async function runSetup(o) {
101
112
  const flag = o.harness === "claude" ? "--claude" : `--${o.harness}`;
102
113
  // From the home folder, so a project's own setup in the current folder can never take the sign-in;
103
114
  // and a failed sign-in names this setup command, which also installs and starts the agent.
104
- const again = `${process.platform === "win32" ? "npx.cmd" : "npx"} -y @scopebond/agent@${o.version} setup ${o.origin}${o.harness === "claude" ? "" : ` --${o.harness}`}`;
115
+ const harnessFlag = o.harness === "claude" ? "" : ` --${o.harness}`;
116
+ const again = single
117
+ ? `"${process.execPath}" setup ${o.origin}${harnessFlag}`
118
+ : `${process.platform === "win32" ? "npx.cmd" : "npx"} -y @scopebond/agent@${o.version} setup ${o.origin}${harnessFlag}`;
105
119
  const [program, args] = hookSelfCommand(["login", o.origin, flag]);
106
120
  const r = spawnSync(program, args, { stdio: "inherit", cwd: homedir(), env: { ...process.env, SCOPEBOND_HOME: o.dir, SCOPEBOND_RETRY_COMMAND: again } });
107
121
  if (r.status !== 0) {
@@ -119,7 +133,8 @@ export async function runSetup(o) {
119
133
  if (steps.includes("install_agent")) {
120
134
  const spec = process.env.SCOPEBOND_AGENT_INSTALL_SPEC || `@scopebond/agent@${o.version}`;
121
135
  say(`Installing the Scopebond Agent for this user: ${process.platform === "win32" ? "npm.cmd" : "npm"} install -g ${spec}`);
122
- const installed = npm(["install", "-g", spec, "--no-fund", "--no-audit"]);
136
+ // Package scripts off and the public registry pinned, as the agent's own updates do.
137
+ const installed = npm(npmInstallArgs(spec), npmEnvironment());
123
138
  if (!installed.ok) {
124
139
  console.error(`Setup stopped: npm could not install the agent.\n${installed.out.slice(-1500)}`);
125
140
  return 1;
@@ -131,7 +146,7 @@ export async function runSetup(o) {
131
146
  }
132
147
  }
133
148
  else
134
- say(`✓ The Scopebond Agent ${global.version} is installed for this user.`);
149
+ say(single ? `✓ The Scopebond Agent ${global.version} is installed (signed installer).` : `✓ The Scopebond Agent ${global.version} is installed for this user.`);
135
150
  const bin = global.prefix ? globalBinDir(global.prefix) : null;
136
151
  if (bin && !onPath(bin)) {
137
152
  say(`Note: npm's global folder ${bin} is not on PATH, so new terminals will not find ${o.me}.`);
@@ -146,6 +161,17 @@ export async function runSetup(o) {
146
161
  }
147
162
  else
148
163
  say("✓ The agent already starts with your sign-in.");
164
+ // Listed in Settings -> Apps, so it can be removed there like any other app (refreshed each run: the version moves).
165
+ if (cli && process.platform === "win32" && installKind() === "npm") {
166
+ try {
167
+ const listed = writeAppsEntry(o.dir, { version: globalAgent().version ?? o.version, cli });
168
+ if (listed)
169
+ say(`✓ ${listed}`);
170
+ }
171
+ catch (error) {
172
+ say(`Note: could not list Scopebond in Settings -> Apps (${error.message}).`);
173
+ }
174
+ }
149
175
  if (cli && !await callAgent(o.dir, "GET", "/status", undefined, 2_000)) {
150
176
  const up = async (tries) => {
151
177
  for (let i = 0; i < tries; i++) {
@@ -164,14 +190,17 @@ export async function runSetup(o) {
164
190
  }
165
191
  else {
166
192
  // No systemd user session (a container, WSL without systemd): run it detached until the next sign-in.
167
- if (!await up(10) && process.platform === "linux")
168
- spawn(process.execPath, [cli, "run"], { detached: true, stdio: "ignore", env: { ...process.env, SCOPEBOND_HOME: o.dir } }).unref();
193
+ if (!await up(10) && process.platform === "linux") {
194
+ const [program, args] = single ? agentSelfCommand(["run"]) : [process.execPath, [cli, "run"]];
195
+ spawn(program, args, { detached: true, stdio: "ignore", env: { ...process.env, SCOPEBOND_HOME: o.dir } }).unref();
196
+ }
169
197
  await up(20);
170
198
  }
171
199
  }
172
200
  // 4. Status, from the installed agent.
173
201
  say("");
174
- const status = spawnSync(process.execPath, [cli ?? process.argv[1], "status"], { stdio: "inherit", env: { ...process.env, SCOPEBOND_HOME: o.dir } });
202
+ const [statusProgram, statusArgs] = single ? agentSelfCommand(["status"]) : [process.execPath, [cli ?? process.argv[1], "status"]];
203
+ const status = spawnSync(statusProgram, statusArgs, { stdio: "inherit", env: { ...process.env, SCOPEBOND_HOME: o.dir } });
175
204
  return status.status === 0 ? 0 : 1;
176
205
  }
177
206
  //# sourceMappingURL=setup.js.map
package/dist/setup.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","sourceRo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AC,CAAC;QACpG,CAAC;aAAM,CAAC;YACN,sGAAsG;YACtG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO;gBAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;YACtL,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;IACH,CAAC;IAED,uCAAuC;IACvC,GAAG,CAAC,EAAE,CAAC,CAAC;IACR,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACrJ,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACrC,CAAC","sourcesContent":["// `scopebond-agent setup <workspace-url>`: one command from nothing to a connected computer.\n// It checks Node, signs this person in with a code (which puts the hook in the user-level agent\n// settings), installs the agent for this user so autostart has a stable path, turns autostart on\n// and ends with `status`. Run again, it repairs what is missing and duplicates nothing: an\n// existing connection to the same workspace is kept, the same agent version is not reinstalled,\n// and the hook entry and autostart are put back only where they are gone.\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { hookSelfCommand, loadConnection, nodeTooOldLines, readDeliveryState, type Harness } from \"@scopebond/hook\";\nimport { autostartHealth, enableAutostart, startNow } from \"./autostart.js\";\nimport { callAgent } from \"./ipc.js\";\nimport { compareVersions, ownNpm } from \"./update.js\";\nimport { repairHookEntries } from \"./service.js\";\n\nexport type SetupStep = \"login\" | \"install_agent\" | \"autostart\";\n\nexport interface SetupState {\n /** The workspace origin this computer's user-level connection points at, if any. */\n connectedTo: string | null;\n /** The workspace refused that connection's credential (it must sign in again). */\n credentialRefused: boolean;\n /** The agent version installed for this user with npm, if any. */\n installedVersion: string | null;\n /** Autostart is on and its launcher exists. */\n autostartOk: boolean;\n}\n\n/** What a setup run has to do, given what is already true. Pure, so a second run is provably a no-op\n * (or a repair) rather than a second sign-in or install. */\nexport function setupPlan(state: SetupState, origin: string, version: string, relogin = false): SetupStep[] {\n const steps: SetupStep[] = [];\n if (relogin || state.connectedTo !== origin || state.credentialRefused) steps.push(\"login\");\n const install = state.installedVersion === null || compareVersions(state.installedVersion, version) < 0;\n if (install) steps.push(\"install_agent\");\n if (install || !state.autostartOk) steps.push(\"autostart\");\n return steps;\n}\n\nexport function nodeSupported(version = process.versions.node): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return major > 22 || (major === 22 && minor >= 13);\n}\n\n/** The folder npm puts global commands in: the prefix itself on Windows, <prefix>/bin elsewhere. */\nexport function globalBinDir(prefix: string, platform: NodeJS.Platform = process.platform): string {\n return platform === \"win32\" ? prefix : join(prefix, \"bin\");\n}\n\n/** Whether `dir` is on PATH (case-insensitive on Windows, ignoring a trailing separator). */\nexport function onPath(dir: string, pathEnv = process.env.PATH ?? process.env.Path ?? \"\", platform: NodeJS.Platform = process.platform): boolean {\n const norm = (p: string) => {\n let t = p.trim();\n while (t.endsWith(\"/\") || t.endsWith(\"\\\\\")) t = t.slice(0, -1); // a loop, not a regex: PATH entries are untrusted input\n return platform === \"win32\" ? t.toLowerCase().replace(/\\//g, \"\\\\\") : t;\n };\n const target = norm(dir);\n return pathEnv.split(platform === \"win32\" ? \";\" : \":\").some((p) => p && norm(p) === target);\n}\n\n/** The PowerShell line that adds a folder to this user's PATH for new windows. */\nexport function addToPathCommand(dir: string): string {\n return `[Environment]::SetEnvironmentVariable(\"Path\", [Environment]::GetEnvironmentVariable(\"Path\", \"User\") + \";${dir}\", \"User\")`;\n}\n\nfunction npm(args: string[]): { ok: boolean; out: string } {\n const win = process.platform === \"win32\";\n // This Node's own npm, without a shell; otherwise npm on PATH (a .cmd on Windows, started through a shell, each argument quoted).\n const own = ownNpm();\n const r = own\n ? spawnSync(own[0], [...own[1], ...args], { encoding: \"utf8\", windowsHide: true, timeout: 5 * 60_000 })\n : spawnSync(win ? \"npm.cmd\" : \"npm\", win ? args.map((a) => `\"${a}\"`) : args, { encoding: \"utf8\", shell: win, windowsHide: true, timeout: 5 * 60_000 });\n return { ok: r.status === 0, out: `${r.stdout ?? \"\"}${r.stderr ?? \"\"}` };\n}\n\nfunction globalAgent(): { prefix: string | null; cli: string | null; version: string | null } {\n const prefix = npm([\"prefix\", \"-g\"]);\n const root = npm([\"root\", \"-g\"]);\n if (!root.ok) return { prefix: null, cli: null, version: null };\n const dir = join(root.out.trim().split(/\\r?\\n/).pop() ?? \"\", \"@scopebond\", \"agent\");\n const cli = join(dir, \"dist\", \"cli.js\");\n let version: string | null = null;\n try { version = (JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as { version?: string }).version ?? null; } catch { /* not installed */ }\n return { prefix: prefix.ok ? prefix.out.trim().split(/\\r?\\n/).pop() ?? null : null, cli: existsSync(cli) ? cli : null, version };\n}\n\n\nexport interface SetupOptions { dir: string; origin: string; harness: Harness; relogin: boolean; version: string; me: string }\n\nexport async function runSetup(o: SetupOptions): Promise<number> {\n const say = (line: string) => console.log(line);\n if (!nodeSupported()) { for (const line of nodeTooOldLines(process.versions.node)) console.error(line); return 1; }\n const connection = loadConnection(o.dir);\n let connectedTo: string | null = null;\n try { connectedTo = connection ? new URL(connection.url).origin : null; } catch { connectedTo = null; }\n const global = globalAgent();\n const state: SetupState = {\n connectedTo,\n credentialRefused: readDeliveryState(o.dir).invalid_since != null,\n installedVersion: global.version,\n autostartOk: autostartHealth(o.dir).ok,\n };\n const steps = setupPlan(state, o.origin, o.version, o.relogin);\n say(`Setting up Scopebond for this user (${steps.length ? steps.join(\", \").replace(/_/g, \" \") : \"nothing missing\"}).`);\n\n // 1. Sign in with a code. The hook's own login prints the link and code and waits for approval.\n if (steps.includes(\"login\")) {\n const flag = o.harness === \"claude\" ? \"--claude\" : `--${o.harness}`;\n // From the home folder, so a project's own setup in the current folder can never take the sign-in;\n // and a failed sign-in names this setup command, which also installs and starts the agent.\n const again = `${process.platform === \"win32\" ? \"npx.cmd\" : \"npx\"} -y @scopebond/agent@${o.version} setup ${o.origin}${o.harness === \"claude\" ? \"\" : ` --${o.harness}`}`;\n const [program, args] = hookSelfCommand([\"login\", o.origin, flag]);\n const r = spawnSync(program, args, { stdio: \"inherit\", cwd: homedir(), env: { ...process.env, SCOPEBOND_HOME: o.dir, SCOPEBOND_RETRY_COMMAND: again } });\n if (r.status !== 0) { console.error(\"Setup stopped: the sign-in did not finish. Run the same command again for a new code.\"); return 1; }\n } else {\n say(`✓ Already connected to ${o.origin} (to sign in again anyway, add --relogin).`);\n for (const fixed of repairHookEntries()) say(`✓ Put the Scopebond hook back in ${fixed.file}`);\n }\n\n // 2. The agent, installed for this user so autostart points at a path npm will not clear.\n let cli = global.cli;\n if (steps.includes(\"install_agent\")) {\n const spec = process.env.SCOPEBOND_AGENT_INSTALL_SPEC || `@scopebond/agent@${o.version}`;\n say(`Installing the Scopebond Agent for this user: ${process.platform === \"win32\" ? \"npm.cmd\" : \"npm\"} install -g ${spec}`);\n const installed = npm([\"install\", \"-g\", spec, \"--no-fund\", \"--no-audit\"]);\n if (!installed.ok) { console.error(`Setup stopped: npm could not install the agent.\\n${installed.out.slice(-1500)}`); return 1; }\n cli = globalAgent().cli;\n if (!cli) { console.error(\"Setup stopped: npm reported success but the agent is not in npm's global folder.\"); return 1; }\n } else say(`✓ The Scopebond Agent ${global.version} is installed for this user.`);\n const bin = global.prefix ? globalBinDir(global.prefix) : null;\n if (bin && !onPath(bin)) {\n say(`Note: npm's global folder ${bin} is not on PATH, so new terminals will not find ${o.me}.`);\n say(process.platform === \"win32\"\n ? ` Add it for your user in PowerShell, then open a new window: ${addToPathCommand(bin)}\n (or: Start, \"Edit environment variables for your account\", Path, New)`\n : ` Add it to PATH in your shell profile: export PATH=\"${bin}:$PATH\"`);\n }\n\n // 3. Autostart, and the agent running now.\n if (steps.includes(\"autostart\") && cli) {\n say(enableAutostart(o.dir, cli));\n } else say(\"✓ The agent already starts with your sign-in.\");\n if (cli && !await callAgent(o.dir, \"GET\", \"/status\", undefined, 2_000)) {\n const up = async (tries: number) => {\n for (let i = 0; i < tries; i++) { if (await callAgent(o.dir, \"GET\", \"/status\", undefined, 1_000)) return true; await new Promise((r) => setTimeout(r, 500)); }\n return false;\n };\n if (process.platform === \"win32\") {\n // The headless console first; where it does not start, the launcher through a hidden cmd.exe.\n if (!(startNow(o.dir, \"win32\", 0) && await up(12))) { startNow(o.dir, \"win32\", 1); await up(18); }\n } else {\n // No systemd user session (a container, WSL without systemd): run it detached until the next sign-in.\n if (!await up(10) && process.platform === \"linux\") spawn(process.execPath, [cli, \"run\"], { detached: true, stdio: \"ignore\", env: { ...process.env, SCOPEBOND_HOME: o.dir } }).unref();\n await up(20);\n }\n }\n\n // 4. Status, from the installed agent.\n say(\"\");\n const status = spawnSync(process.execPath, [cli ?? process.argv[1], \"status\"], { stdio: \"inherit\", env: { ...process.env, SCOPEBOND_HOME: o.dir } });\n return status.status === 0 ? 0 : 1;\n}\n"]}
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,gGAAgG;AAChG,iGAAiG;AACjG,2FAA2F;AAC3F,gGAAgG;AAChG,0EAA0E;AAE1E,OAAO,EAAE,KAAK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AAC,EAAE,CAAC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAClD,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;gBAC9F,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC;YACpH,CAAC;YACD,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;IACH,CAAC;IAED,uCAAuC;IACvC,GAAG,CAAC,EAAE,CAAC,CAAC;IACR,MAAM,CAAC,aAAa,EAAE,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IACnI,MAAM,MAAM,GAAG,SAAS,CAAC,aAAa,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAC1H,OAAO,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACrC,CAAC","sourcesContent":["// `scopebond-agent setup <workspace-url>`: one command from nothing to a connected computer.\n// It checks Node, signs this person in with a code (which puts the hook in the user-level agent\n// settings), installs the agent for this user so autostart has a stable path, turns autostart on\n// and ends with `status`. Run again, it repairs what is missing and duplicates nothing: an\n// existing connection to the same workspace is kept, the same agent version is not reinstalled,\n// and the hook entry and autostart are put back only where they are gone.\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { hookSelfCommand, isSingleExecutable, loadConnection, nodeTooOldLines, readDeliveryState, type Harness } from \"@scopebond/hook\";\nimport { agentCliPath, agentSelfCommand } from \"./self.js\";\nimport { autostartHealth, enableAutostart, startNow } from \"./autostart.js\";\nimport { writeAppsEntry } from \"./apps-entry.js\";\nimport { installKind } from \"./native-update.js\";\nimport { callAgent } from \"./ipc.js\";\nimport { compareVersions, npmEnvironment, npmInstallArgs, ownNpm } from \"./update.js\";\nimport { repairHookEntries } from \"./service.js\";\n\nexport type SetupStep = \"login\" | \"install_agent\" | \"autostart\";\n\nexport interface SetupState {\n /** The workspace origin this computer's user-level connection points at, if any. */\n connectedTo: string | null;\n /** The workspace refused that connection's credential (it must sign in again). */\n credentialRefused: boolean;\n /** The agent version installed for this user with npm, if any. */\n installedVersion: string | null;\n /** Autostart is on and its launcher exists. */\n autostartOk: boolean;\n}\n\n/** What a setup run has to do, given what is already true. Pure, so a second run is provably a no-op\n * (or a repair) rather than a second sign-in or install. */\nexport function setupPlan(state: SetupState, origin: string, version: string, relogin = false): SetupStep[] {\n const steps: SetupStep[] = [];\n if (relogin || state.connectedTo !== origin || state.credentialRefused) steps.push(\"login\");\n const install = state.installedVersion === null || compareVersions(state.installedVersion, version) < 0;\n if (install) steps.push(\"install_agent\");\n if (install || !state.autostartOk) steps.push(\"autostart\");\n return steps;\n}\n\nexport function nodeSupported(version = process.versions.node): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return major > 22 || (major === 22 && minor >= 13);\n}\n\n/** The folder npm puts global commands in: the prefix itself on Windows, <prefix>/bin elsewhere. */\nexport function globalBinDir(prefix: string, platform: NodeJS.Platform = process.platform): string {\n return platform === \"win32\" ? prefix : join(prefix, \"bin\");\n}\n\n/** Whether `dir` is on PATH (case-insensitive on Windows, ignoring a trailing separator). */\nexport function onPath(dir: string, pathEnv = process.env.PATH ?? process.env.Path ?? \"\", platform: NodeJS.Platform = process.platform): boolean {\n const norm = (p: string) => {\n let t = p.trim();\n while (t.endsWith(\"/\") || t.endsWith(\"\\\\\")) t = t.slice(0, -1); // a loop, not a regex: PATH entries are untrusted input\n return platform === \"win32\" ? t.toLowerCase().replace(/\\//g, \"\\\\\") : t;\n };\n const target = norm(dir);\n return pathEnv.split(platform === \"win32\" ? \";\" : \":\").some((p) => p && norm(p) === target);\n}\n\n/** The PowerShell line that adds a folder to this user's PATH for new windows. */\nexport function addToPathCommand(dir: string): string {\n return `[Environment]::SetEnvironmentVariable(\"Path\", [Environment]::GetEnvironmentVariable(\"Path\", \"User\") + \";${dir}\", \"User\")`;\n}\n\nfunction npm(args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string } {\n const win = process.platform === \"win32\";\n // This Node's own npm, without a shell; otherwise npm on PATH (a .cmd on Windows, started through a shell, each argument quoted).\n const own = ownNpm();\n const r = own\n ? spawnSync(own[0], [...own[1], ...args], { encoding: \"utf8\", windowsHide: true, timeout: 5 * 60_000, env })\n : spawnSync(win ? \"npm.cmd\" : \"npm\", win ? args.map((a) => `\"${a}\"`) : args, { encoding: \"utf8\", shell: win, windowsHide: true, timeout: 5 * 60_000, env });\n return { ok: r.status === 0, out: `${r.stdout ?? \"\"}${r.stderr ?? \"\"}` };\n}\n\nfunction globalAgent(): { prefix: string | null; cli: string | null; version: string | null } {\n const prefix = npm([\"prefix\", \"-g\"]);\n const root = npm([\"root\", \"-g\"]);\n if (!root.ok) return { prefix: null, cli: null, version: null };\n const dir = join(root.out.trim().split(/\\r?\\n/).pop() ?? \"\", \"@scopebond\", \"agent\");\n const cli = join(dir, \"dist\", \"cli.js\");\n let version: string | null = null;\n try { version = (JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as { version?: string }).version ?? null; } catch { /* not installed */ }\n return { prefix: prefix.ok ? prefix.out.trim().split(/\\r?\\n/).pop() ?? null : null, cli: existsSync(cli) ? cli : null, version };\n}\n\n\n/** Where the agent setup works with: the signed single executable is already installed (its own version, no npm asked),\n * otherwise the copy in npm's global folder, if any. */\nexport function agentOnThisComputer(single: boolean, version: string, fromNpm: () => { prefix: string | null; cli: string | null; version: string | null } = globalAgent, self = agentCliPath): { prefix: string | null; cli: string | null; version: string | null } {\n return single ? { prefix: null, cli: self(), version } : fromNpm();\n}\n\nexport interface SetupOptions { dir: string; origin: string; harness: Harness; relogin: boolean; version: string; me: string }\n\nexport async function runSetup(o: SetupOptions): Promise<number> {\n const say = (line: string) => console.log(line);\n if (!nodeSupported()) { for (const line of nodeTooOldLines(process.versions.node)) console.error(line); return 1; }\n const connection = loadConnection(o.dir);\n let connectedTo: string | null;\n try { connectedTo = connection ? new URL(connection.url).origin : null; } catch { connectedTo = null; }\n // The signed installer put the agent (one executable with the hook) in place: nothing to install with npm, and no Node\n // or npm need be on this computer. Autostart then starts this executable itself.\n const single = isSingleExecutable();\n const global = agentOnThisComputer(single, o.version);\n const state: SetupState = {\n connectedTo,\n credentialRefused: readDeliveryState(o.dir).invalid_since != null,\n installedVersion: global.version,\n autostartOk: autostartHealth(o.dir).ok,\n };\n const steps = setupPlan(state, o.origin, o.version, o.relogin);\n say(`Setting up Scopebond for this user (${steps.length ? steps.join(\", \").replace(/_/g, \" \") : \"nothing missing\"}).`);\n\n // 1. Sign in with a code. The hook's own login prints the link and code and waits for approval.\n if (steps.includes(\"login\")) {\n const flag = o.harness === \"claude\" ? \"--claude\" : `--${o.harness}`;\n // From the home folder, so a project's own setup in the current folder can never take the sign-in;\n // and a failed sign-in names this setup command, which also installs and starts the agent.\n const harnessFlag = o.harness === \"claude\" ? \"\" : ` --${o.harness}`;\n const again = single\n ? `\"${process.execPath}\" setup ${o.origin}${harnessFlag}`\n : `${process.platform === \"win32\" ? \"npx.cmd\" : \"npx\"} -y @scopebond/agent@${o.version} setup ${o.origin}${harnessFlag}`;\n const [program, args] = hookSelfCommand([\"login\", o.origin, flag]);\n const r = spawnSync(program, args, { stdio: \"inherit\", cwd: homedir(), env: { ...process.env, SCOPEBOND_HOME: o.dir, SCOPEBOND_RETRY_COMMAND: again } });\n if (r.status !== 0) { console.error(\"Setup stopped: the sign-in did not finish. Run the same command again for a new code.\"); return 1; }\n } else {\n say(`✓ Already connected to ${o.origin} (to sign in again anyway, add --relogin).`);\n for (const fixed of repairHookEntries()) say(`✓ Put the Scopebond hook back in ${fixed.file}`);\n }\n\n // 2. The agent, installed for this user so autostart points at a path npm will not clear.\n let cli = global.cli;\n if (steps.includes(\"install_agent\")) {\n const spec = process.env.SCOPEBOND_AGENT_INSTALL_SPEC || `@scopebond/agent@${o.version}`;\n say(`Installing the Scopebond Agent for this user: ${process.platform === \"win32\" ? \"npm.cmd\" : \"npm\"} install -g ${spec}`);\n // Package scripts off and the public registry pinned, as the agent's own updates do.\n const installed = npm(npmInstallArgs(spec), npmEnvironment());\n if (!installed.ok) { console.error(`Setup stopped: npm could not install the agent.\\n${installed.out.slice(-1500)}`); return 1; }\n cli = globalAgent().cli;\n if (!cli) { console.error(\"Setup stopped: npm reported success but the agent is not in npm's global folder.\"); return 1; }\n } else say(single ? `✓ The Scopebond Agent ${global.version} is installed (signed installer).` : `✓ The Scopebond Agent ${global.version} is installed for this user.`);\n const bin = global.prefix ? globalBinDir(global.prefix) : null;\n if (bin && !onPath(bin)) {\n say(`Note: npm's global folder ${bin} is not on PATH, so new terminals will not find ${o.me}.`);\n say(process.platform === \"win32\"\n ? ` Add it for your user in PowerShell, then open a new window: ${addToPathCommand(bin)}\n (or: Start, \"Edit environment variables for your account\", Path, New)`\n : ` Add it to PATH in your shell profile: export PATH=\"${bin}:$PATH\"`);\n }\n\n // 3. Autostart, and the agent running now.\n if (steps.includes(\"autostart\") && cli) {\n say(enableAutostart(o.dir, cli));\n } else say(\"✓ The agent already starts with your sign-in.\");\n // Listed in Settings -> Apps, so it can be removed there like any other app (refreshed each run: the version moves).\n if (cli && process.platform === \"win32\" && installKind() === \"npm\") {\n try { const listed = writeAppsEntry(o.dir, { version: globalAgent().version ?? o.version, cli }); if (listed) say(`✓ ${listed}`); }\n catch (error) { say(`Note: could not list Scopebond in Settings -> Apps (${(error as Error).message}).`); }\n }\n if (cli && !await callAgent(o.dir, \"GET\", \"/status\", undefined, 2_000)) {\n const up = async (tries: number) => {\n for (let i = 0; i < tries; i++) { if (await callAgent(o.dir, \"GET\", \"/status\", undefined, 1_000)) return true; await new Promise((r) => setTimeout(r, 500)); }\n return false;\n };\n if (process.platform === \"win32\") {\n // The headless console first; where it does not start, the launcher through a hidden cmd.exe.\n if (!(startNow(o.dir, \"win32\", 0) && await up(12))) { startNow(o.dir, \"win32\", 1); await up(18); }\n } else {\n // No systemd user session (a container, WSL without systemd): run it detached until the next sign-in.\n if (!await up(10) && process.platform === \"linux\") {\n const [program, args] = single ? agentSelfCommand([\"run\"]) : [process.execPath, [cli, \"run\"]];\n spawn(program, args, { detached: true, stdio: \"ignore\", env: { ...process.env, SCOPEBOND_HOME: o.dir } }).unref();\n }\n await up(20);\n }\n }\n\n // 4. Status, from the installed agent.\n say(\"\");\n const [statusProgram, statusArgs] = single ? agentSelfCommand([\"status\"]) : [process.execPath, [cli ?? process.argv[1], \"status\"]];\n const status = spawnSync(statusProgram, statusArgs, { stdio: \"inherit\", env: { ...process.env, SCOPEBOND_HOME: o.dir } });\n return status.status === 0 ? 0 : 1;\n}\n"]}