@space-lens/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/assets/{serve-entry-Dk9zwise.js → serve-entry-DESAwchC.js} +3158 -723
  2. package/dist/cli.mjs +2 -2
  3. package/dist/web/200.html +53 -0
  4. package/dist/web/_app/immutable/assets/0.DaFvPEiH.css +2 -0
  5. package/dist/web/_app/immutable/assets/2.Rwbdhuvh.css +1 -0
  6. package/dist/web/_app/immutable/assets/inter-cyrillic-ext-wght-normal.BOeWTOD4.woff2 +0 -0
  7. package/dist/web/_app/immutable/assets/inter-cyrillic-wght-normal.DqGufNeO.woff2 +0 -0
  8. package/dist/web/_app/immutable/assets/inter-greek-ext-wght-normal.DlzME5K_.woff2 +0 -0
  9. package/dist/web/_app/immutable/assets/inter-greek-wght-normal.CkhJZR-_.woff2 +0 -0
  10. package/dist/web/_app/immutable/assets/inter-latin-ext-wght-normal.DO1Apj_S.woff2 +0 -0
  11. package/dist/web/_app/immutable/assets/inter-latin-wght-normal.Dx4kXJAl.woff2 +0 -0
  12. package/dist/web/_app/immutable/assets/inter-vietnamese-wght-normal.CBcvBZtf.woff2 +0 -0
  13. package/dist/web/_app/immutable/chunks/BjAaj2_R.js +1 -0
  14. package/dist/web/_app/immutable/chunks/Bjy-W4x2.js +81 -0
  15. package/dist/web/_app/immutable/chunks/CEhA94eo.js +1 -0
  16. package/dist/web/_app/immutable/chunks/Czmuk0Xq.js +9 -0
  17. package/dist/web/_app/immutable/chunks/D_inIiOK.js +3 -0
  18. package/dist/web/_app/immutable/chunks/uBIymjUX.js +1 -0
  19. package/dist/web/_app/immutable/chunks/xihTtKlq.js +1 -0
  20. package/dist/web/_app/immutable/entry/app.6tYYuHtv.js +2 -0
  21. package/dist/web/_app/immutable/entry/start.B7_bvdWx.js +1 -0
  22. package/dist/web/_app/immutable/nodes/0.BfNK78ja.js +1 -0
  23. package/dist/web/_app/immutable/nodes/1.DocSAEhb.js +1 -0
  24. package/dist/web/_app/immutable/nodes/2.c02Tt4_b.js +163 -0
  25. package/dist/web/_app/version.json +1 -0
  26. package/dist/web/favicon.png +0 -0
  27. package/dist/web/index.html +55 -0
  28. package/dist/web/logo-mark.png +0 -0
  29. package/dist/web/manifest.webmanifest +18 -0
  30. package/dist/web/service-worker.js +1 -0
  31. package/package.json +8 -7
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { spawn } from "node:child_process";
3
+ import { execFile, spawn } from "node:child_process";
4
4
  import { createHash, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
5
- import { accessSync, constants, existsSync, lstatSync, realpathSync, statSync } from "node:fs";
5
+ import { accessSync, constants, cpSync, existsSync, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { homedir, networkInterfaces, platform } from "node:os";
7
7
  import { basename, dirname, extname, isAbsolute, join, normalize, resolve, sep } from "node:path";
8
- import { fileURLToPath } from "node:url";
9
- import { readFile, realpath, stat } from "node:fs/promises";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { readFile, readdir, realpath, stat } from "node:fs/promises";
10
10
  import { BlockList, isIP } from "node:net";
11
11
  import { Worker } from "node:worker_threads";
12
12
  import { createServer } from "http";
@@ -118,6 +118,20 @@ var AuthService = class {
118
118
  };
119
119
  }
120
120
  this.tickets.delete(key);
121
+ return {
122
+ ok: true,
123
+ session: this.mintSession()
124
+ };
125
+ }
126
+ /**
127
+ * Creates a session with this host's scopes, without a ticket.
128
+ *
129
+ * Only the development-only `--dev-open-session` route uses it: the operator
130
+ * asked for a host that a loopback client can use without the pairing
131
+ * handshake. It is not a way around the ticket in normal operation — the
132
+ * route that reaches it refuses to exist unless the flag is on.
133
+ */
134
+ mintSession() {
121
135
  const session = {
122
136
  token: randomId("sls_"),
123
137
  sessionId: randomId("sess_", 12),
@@ -130,10 +144,7 @@ var AuthService = class {
130
144
  if (oldest !== void 0) this.sessions.delete(oldest);
131
145
  }
132
146
  this.sessions.set(sha256(session.token), session);
133
- return {
134
- ok: true,
135
- session
136
- };
147
+ return session;
137
148
  }
138
149
  authorize(bearer) {
139
150
  if (!bearer?.startsWith("Bearer ")) return null;
@@ -2054,7 +2065,7 @@ var Hono = class extends Hono$1 {
2054
2065
  };
2055
2066
  //#endregion
2056
2067
  //#region ../../packages/contract/src/version.ts
2057
- var CONTRACT_VERSION = "1.0.0";
2068
+ var CONTRACT_VERSION = "1.1.0";
2058
2069
  //#endregion
2059
2070
  //#region ../../node_modules/zod/v4/core/util.js
2060
2071
  function getEnumValues(entries) {
@@ -4901,16 +4912,16 @@ function cloneIssues(issues) {
4901
4912
  }
4902
4913
  var recursive = /*@__PURE__*/ new WeakMap();
4903
4914
  /** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */
4904
- var NONE = 0;
4915
+ var NONE$1 = 0;
4905
4916
  var ASSUMED = 1;
4906
4917
  var PROVEN = 2;
4907
4918
  /** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
4908
4919
  function isRecursive(inst, stack, resolve) {
4909
4920
  const cached = recursive.get(inst);
4910
- if (cached !== void 0) return cached ? PROVEN : NONE;
4921
+ if (cached !== void 0) return cached ? PROVEN : NONE$1;
4911
4922
  if (stack.has(inst)) return PROVEN;
4912
4923
  stack.add(inst);
4913
- let result = NONE;
4924
+ let result = NONE$1;
4914
4925
  const check = (child) => {
4915
4926
  if (result !== PROVEN && child?._zod) {
4916
4927
  const answer = isRecursive(child, stack, resolve);
@@ -4918,11 +4929,11 @@ function isRecursive(inst, stack, resolve) {
4918
4929
  }
4919
4930
  };
4920
4931
  const shape = (sh, spread) => {
4921
- let answer = NONE;
4932
+ let answer = NONE$1;
4922
4933
  for (const key of Reflect.ownKeys(sh)) {
4923
4934
  const desc = Object.getOwnPropertyDescriptor(sh, key);
4924
4935
  if (spread && !desc.enumerable) continue;
4925
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
4936
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE$1;
4926
4937
  if (child > answer) answer = child;
4927
4938
  }
4928
4939
  return answer;
@@ -5069,7 +5080,7 @@ var memo = {
5069
5080
  const wrapped = (payload, ctx) => {
5070
5081
  if (isRecursiveInst === void 0) {
5071
5082
  const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false);
5072
- if (walked === NONE) {
5083
+ if (walked === NONE$1) {
5073
5084
  inst._zod.parse = base;
5074
5085
  if (inst._zod.run === wrapped) inst._zod.run = base;
5075
5086
  return base(payload, ctx);
@@ -7695,7 +7706,7 @@ function problem(code, message, options) {
7695
7706
  //#endregion
7696
7707
  //#region ../../packages/contract/src/local-scan.ts
7697
7708
  var UintSchema$5 = number().int().nonnegative();
7698
- var PathSchema$2 = string().min(1).max(4096);
7709
+ var PathSchema$3 = string().min(1).max(4096);
7699
7710
  var LocalNodeStateSchema = _enum([
7700
7711
  "complete",
7701
7712
  "partial",
@@ -7709,7 +7720,7 @@ var LocalNodeMetadataShape = {
7709
7720
  };
7710
7721
  var localScanNodeShape = {
7711
7722
  name: string(),
7712
- path: PathSchema$2,
7723
+ path: PathSchema$3,
7713
7724
  size: UintSchema$5,
7714
7725
  depth: UintSchema$5,
7715
7726
  ignored: boolean(),
@@ -7736,25 +7747,57 @@ var ScanCoverageSchema = strictObject({
7736
7747
  files: UintSchema$5,
7737
7748
  directories: UintSchema$5,
7738
7749
  skippedCount: UintSchema$5,
7750
+ /** `skippedCount` split by skip reason; the values sum to it. Absent from older reports. */
7751
+ skippedByReason: record(string().min(1).max(64), UintSchema$5).optional(),
7739
7752
  deniedCount: UintSchema$5,
7740
7753
  issueCount: UintSchema$5,
7741
7754
  issuesTruncated: boolean(),
7742
7755
  issues: array(strictObject({
7743
- path: PathSchema$2,
7756
+ path: PathSchema$3,
7744
7757
  reason: string(),
7745
7758
  message: string()
7746
7759
  })).max(1e3),
7747
7760
  elapsedMs: UintSchema$5
7748
7761
  });
7749
7762
  var ScanVolumeSchema = strictObject({
7750
- path: PathSchema$2,
7763
+ path: PathSchema$3,
7751
7764
  totalBytes: UintSchema$5,
7752
7765
  availableBytes: UintSchema$5,
7753
7766
  freeBytes: UintSchema$5,
7754
7767
  isLocal: boolean()
7755
7768
  });
7769
+ var ApfsVolumeUsageSchema = strictObject({
7770
+ name: string().max(256),
7771
+ /** APFS role (`Data`, `System`, `VM`, `Preboot`, `Recovery`, `Update`, ...) or `None`. */
7772
+ role: string().min(1).max(64),
7773
+ device: string().min(1).max(64),
7774
+ inUseBytes: UintSchema$5
7775
+ });
7776
+ /**
7777
+ * APFS container accounting captured when a scan finishes, so the UI can
7778
+ * reconcile the measured bytes with the disk's own "used" figure. macOS does
7779
+ * not size individual snapshots, so they are counted, not sized.
7780
+ */
7781
+ var StorageBreakdownSchema = strictObject({
7782
+ container: string().min(1).max(64),
7783
+ capacityBytes: UintSchema$5,
7784
+ /** Everything allocated in the container: all volumes, snapshots and purgeable files. */
7785
+ inUseBytes: UintSchema$5,
7786
+ /** Space macOS can free on demand (local snapshots, cached iCloud files). */
7787
+ purgeableBytes: UintSchema$5.nullable(),
7788
+ /** Bytes this scan measured under roots inside the container. */
7789
+ scannedBytes: UintSchema$5,
7790
+ volumes: array(ApfsVolumeUsageSchema).max(64),
7791
+ snapshots: strictObject({
7792
+ volume: string().min(1).max(64),
7793
+ count: UintSchema$5,
7794
+ timeMachineCount: UintSchema$5,
7795
+ /** Local time of the oldest Time Machine snapshot, `YYYY-MM-DDTHH:MM:SS`. */
7796
+ oldestTimeMachine: string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/).nullable()
7797
+ }).nullable()
7798
+ });
7756
7799
  var LocalScanProgressSchema = strictObject({
7757
- currentPath: PathSchema$2.nullable(),
7800
+ currentPath: PathSchema$3.nullable(),
7758
7801
  bytesScanned: UintSchema$5,
7759
7802
  entriesScanned: UintSchema$5,
7760
7803
  files: UintSchema$5,
@@ -7783,6 +7826,71 @@ var LocalScanMessageSchema = discriminatedUnion("type", [
7783
7826
  })
7784
7827
  ]);
7785
7828
  //#endregion
7829
+ //#region ../../packages/contract/src/apps.ts
7830
+ var AppAuditClassificationSchema = _enum([
7831
+ "application",
7832
+ "cache",
7833
+ "versions",
7834
+ "logs",
7835
+ "re-downloadable",
7836
+ "user-data",
7837
+ "support"
7838
+ ]);
7839
+ var AppAuditSourceSchema = _enum(["catalog", "heuristic"]);
7840
+ var AppAuditLocationSchema = strictObject({
7841
+ path: string().min(1).max(4096),
7842
+ label: string().nullable(),
7843
+ classification: AppAuditClassificationSchema,
7844
+ purgeable: boolean(),
7845
+ comment: string().nullable(),
7846
+ size: number().int().nonnegative(),
7847
+ source: AppAuditSourceSchema
7848
+ });
7849
+ var AppAuditEntrySchema = strictObject({
7850
+ id: string().min(1).max(128),
7851
+ name: string().min(1).max(256),
7852
+ kind: _enum(["app", "cli"]),
7853
+ source: AppAuditSourceSchema,
7854
+ bundleId: string().nullable(),
7855
+ appPath: string().nullable(),
7856
+ installedSize: number().int().nonnegative(),
7857
+ totalSize: number().int().nonnegative(),
7858
+ locations: array(AppAuditLocationSchema).max(200)
7859
+ });
7860
+ var AppAuditRequestSchema = strictObject({
7861
+ minSize: number().int().nonnegative().default(0),
7862
+ includeHeuristic: boolean().default(true),
7863
+ limit: number().int().min(1).max(1e3).default(500)
7864
+ });
7865
+ var AppAuditReportSchema = strictObject({
7866
+ platform: string().min(1),
7867
+ generatedAt: datetime(),
7868
+ apps: array(AppAuditEntrySchema).max(1e3),
7869
+ totalApps: number().int().nonnegative(),
7870
+ truncated: boolean(),
7871
+ /** Opaque per-generation authorization token minted by the desktop host.
7872
+ * Optional so older hosts that predate V2 still parse. */
7873
+ auditId: string().regex(/^audit_[0-9a-zA-Z]{8,64}$/).optional()
7874
+ });
7875
+ var AuditIdSchema = string().regex(/^audit_[0-9a-zA-Z]{8,64}$/);
7876
+ var AppScanOriginSchema = strictObject({
7877
+ appId: string().min(1).max(128),
7878
+ appName: string().min(1).max(256),
7879
+ auditId: AuditIdSchema
7880
+ });
7881
+ strictObject({
7882
+ auditId: AuditIdSchema,
7883
+ appId: string().min(1).max(128)
7884
+ });
7885
+ strictObject({
7886
+ appId: string().min(1).max(128),
7887
+ appName: string().min(1).max(256),
7888
+ auditId: AuditIdSchema,
7889
+ lastScannedAt: datetime()
7890
+ });
7891
+ var AppIconRequestSchema = strictObject({ appPath: string().min(1).max(4096) });
7892
+ strictObject({ dataUrl: string().min(1) });
7893
+ //#endregion
7786
7894
  //#region ../../packages/contract/src/scan.ts
7787
7895
  var IgnoredModeSchema = _enum(["summarize", "exclude"]);
7788
7896
  var SortModeSchema = _enum([
@@ -7792,12 +7900,12 @@ var SortModeSchema = _enum([
7792
7900
  ]);
7793
7901
  var IsoDateTimeSchema$2 = datetime();
7794
7902
  var UintSchema$4 = number().int().nonnegative();
7795
- var PathSchema$1 = string().min(1).max(4096);
7903
+ var PathSchema$2 = string().min(1).max(4096);
7796
7904
  var ScanIdSchema = string().regex(/^scan_[0-9a-zA-Z]{8,64}$/);
7797
7905
  var NodeIdSchema = string().min(1).max(128);
7798
7906
  var ScanStartRequestSchema = strictObject({
7799
7907
  /** Absolute directories to scan. At least one, at most 16. */
7800
- paths: array(PathSchema$1).min(1).max(16),
7908
+ paths: array(PathSchema$2).min(1).max(16),
7801
7909
  ignoreHidden: boolean().default(false),
7802
7910
  respectGitignore: boolean().default(true),
7803
7911
  ignoredMode: IgnoredModeSchema.default("summarize"),
@@ -7808,7 +7916,8 @@ strictObject({
7808
7916
  scanId: ScanIdSchema,
7809
7917
  rootIds: array(NodeIdSchema),
7810
7918
  createdAt: IsoDateTimeSchema$2,
7811
- label: string().nullable()
7919
+ label: string().nullable(),
7920
+ app: AppScanOriginSchema.optional()
7812
7921
  });
7813
7922
  var ScanStatusSchema = strictObject({
7814
7923
  scanId: ScanIdSchema,
@@ -7833,13 +7942,16 @@ var ScanStatusSchema = strictObject({
7833
7942
  label: string().nullable(),
7834
7943
  updatedAt: IsoDateTimeSchema$2,
7835
7944
  coverage: ScanCoverageSchema.optional(),
7836
- volumes: array(ScanVolumeSchema).optional()
7945
+ volumes: array(ScanVolumeSchema).optional(),
7946
+ /** APFS accounting for the container holding the scan; absent off APFS or when unreadable. */
7947
+ storage: StorageBreakdownSchema.optional(),
7948
+ app: AppScanOriginSchema.optional()
7837
7949
  });
7838
7950
  strictObject({ scans: array(ScanStatusSchema) });
7839
7951
  var TreeNodeSummarySchema = strictObject({
7840
7952
  id: NodeIdSchema,
7841
7953
  name: string(),
7842
- path: PathSchema$1,
7954
+ path: PathSchema$2,
7843
7955
  size: UintSchema$4,
7844
7956
  depth: UintSchema$4,
7845
7957
  ignored: boolean(),
@@ -7851,7 +7963,7 @@ var TreeNodeSummarySchema = strictObject({
7851
7963
  var TreeSliceNodeSchema = strictObject({
7852
7964
  id: NodeIdSchema,
7853
7965
  name: string(),
7854
- path: PathSchema$1,
7966
+ path: PathSchema$2,
7855
7967
  size: UintSchema$4,
7856
7968
  depth: UintSchema$4,
7857
7969
  ignored: boolean(),
@@ -7900,7 +8012,7 @@ strictObject({});
7900
8012
  strictObject({ roots: array(strictObject({
7901
8013
  id: string().min(1).max(128),
7902
8014
  label: string().min(1).max(200),
7903
- path: PathSchema$1,
8015
+ path: PathSchema$2,
7904
8016
  kind: _enum([
7905
8017
  "volume",
7906
8018
  "folder",
@@ -7913,6 +8025,7 @@ strictObject({ roots: array(strictObject({
7913
8025
  removable: boolean().default(false),
7914
8026
  lastScannedAt: IsoDateTimeSchema$2.optional()
7915
8027
  })) });
8028
+ strictObject({ volumes: array(ScanVolumeSchema) });
7916
8029
  //#endregion
7917
8030
  //#region ../../packages/contract/src/discovery.ts
7918
8031
  var UintSchema$3 = number().int().nonnegative();
@@ -7943,11 +8056,29 @@ strictObject({
7943
8056
  offset: UintSchema$3,
7944
8057
  limit: LimitSchema
7945
8058
  });
8059
+ strictObject({
8060
+ baseUrl: string(),
8061
+ model: string(),
8062
+ /** True when the host holds an API key. The key itself is never returned. */
8063
+ hasKey: boolean(),
8064
+ disableThinking: boolean(),
8065
+ managed: literal(true)
8066
+ });
8067
+ var AiChatRequestSchema = strictObject({
8068
+ messages: array(record(string(), unknown())).min(1).max(2e3),
8069
+ tools: array(record(string(), unknown())).max(64).optional(),
8070
+ /**
8071
+ * When `true` the host forwards the upstream body as `text/event-stream` raw
8072
+ * chunks instead of one parsed JSON body. Optional so every existing caller
8073
+ * (and host) keeps working unchanged.
8074
+ */
8075
+ stream: boolean().optional()
8076
+ });
7946
8077
  //#endregion
7947
8078
  //#region ../../packages/contract/src/cleanup.ts
7948
8079
  var UintSchema$2 = number().int().nonnegative();
7949
8080
  var IsoDateTimeSchema$1 = datetime();
7950
- var PathSchema = string().min(1).max(4096);
8081
+ var PathSchema$1 = string().min(1).max(4096);
7951
8082
  var PlanIdSchema = string().regex(/^plan_[0-9a-zA-Z]{8,64}$/);
7952
8083
  var CleanupPlanRequestSchema = strictObject({
7953
8084
  scanId: ScanIdSchema,
@@ -7963,7 +8094,7 @@ var EntryFingerprintSchema = strictObject({
7963
8094
  mtimeMs: number()
7964
8095
  });
7965
8096
  var PlanEntrySchema = strictObject({
7966
- path: PathSchema,
8097
+ path: PathSchema$1,
7967
8098
  size: UintSchema$2,
7968
8099
  reason: string(),
7969
8100
  preset: string().nullable(),
@@ -7992,26 +8123,355 @@ var CleanupExecuteRequestSchema = strictObject({
7992
8123
  });
7993
8124
  strictObject({
7994
8125
  trashed: array(strictObject({
7995
- path: PathSchema,
8126
+ path: PathSchema$1,
7996
8127
  size: UintSchema$2
7997
8128
  })),
7998
8129
  bytesFreed: UintSchema$2,
7999
8130
  failed: array(strictObject({
8000
- path: PathSchema,
8131
+ path: PathSchema$1,
8001
8132
  code: _enum(PROBLEM_CODES),
8002
8133
  message: string()
8003
8134
  }))
8004
8135
  });
8136
+ strictObject({
8137
+ auditId: AuditIdSchema,
8138
+ appId: string().min(1).max(128),
8139
+ paths: array(PathSchema$1).min(1).max(200)
8140
+ });
8141
+ strictObject({
8142
+ planId: PlanIdSchema,
8143
+ /** Must be the literal `true`. A default, a missing field, or `false` refuses. */
8144
+ confirm: literal(true)
8145
+ });
8146
+ strictObject({
8147
+ planId: PlanIdSchema,
8148
+ auditId: AuditIdSchema,
8149
+ appId: string().min(1).max(128),
8150
+ mode: literal("trash"),
8151
+ entries: array(PlanEntrySchema).max(200),
8152
+ totalSize: UintSchema$2,
8153
+ errors: array(string()),
8154
+ createdAt: IsoDateTimeSchema$1,
8155
+ expiresAt: IsoDateTimeSchema$1
8156
+ });
8005
8157
  strictObject({
8006
8158
  id: string().min(1).max(128),
8007
8159
  scanId: ScanIdSchema,
8008
8160
  nodeId: string().min(1).max(128),
8009
- path: PathSchema,
8161
+ path: PathSchema$1,
8010
8162
  name: string().min(1).max(1024),
8011
8163
  size: UintSchema$2,
8012
8164
  addedAt: IsoDateTimeSchema$1
8013
8165
  });
8014
8166
  //#endregion
8167
+ //#region ../../packages/contract/src/memory.ts
8168
+ /**
8169
+ * Memory view and process-control contract (§4.1/§4.3 of
8170
+ * docs/memory-cleaner-plan.md): the Zod mirror of the Rust wire types in
8171
+ * `crates/memory`. Field names are camelCase; byte counts and microsecond
8172
+ * timestamps are unsigned integers below 2^53. The literal arrays below are
8173
+ * written exactly once and reused by the capability view in ./capabilities.ts.
8174
+ *
8175
+ * `packages/contract/src/apps.ts` already exports `AuditIdSchema` (audit
8176
+ * generations), so this module's audit id is `MemoryAuditIdSchema`.
8177
+ */
8178
+ var Uint = number().int().nonnegative();
8179
+ var Iso = datetime();
8180
+ var Name = string().max(256);
8181
+ var MEMORY_PLATFORMS = [
8182
+ "macos",
8183
+ "linux",
8184
+ "windows",
8185
+ "unsupported"
8186
+ ];
8187
+ var PRESSURE_LEVELS = [
8188
+ "normal",
8189
+ "warning",
8190
+ "critical",
8191
+ "unknown"
8192
+ ];
8193
+ var PRESSURE_SOURCES = [
8194
+ "kernel",
8195
+ "derived",
8196
+ "unavailable"
8197
+ ];
8198
+ var PROCESS_KINDS = [
8199
+ "app",
8200
+ "helper",
8201
+ "agent",
8202
+ "cli",
8203
+ "system",
8204
+ "other"
8205
+ ];
8206
+ /** Scheduler states; the platforms disagree on details, anything else is `unknown`. */
8207
+ var PROCESS_STATES = [
8208
+ "running",
8209
+ "sleeping",
8210
+ "idle",
8211
+ "stopped",
8212
+ "zombie",
8213
+ "unknown"
8214
+ ];
8215
+ var PROTECTIONS = [
8216
+ "kernel",
8217
+ "init",
8218
+ "sessionCritical",
8219
+ "systemComponent",
8220
+ "selfOrAncestor",
8221
+ "selfChild",
8222
+ "otherUser",
8223
+ "unidentified",
8224
+ "zombie"
8225
+ ];
8226
+ var SNAPSHOT_NOTES = [
8227
+ "cpuWarmingUp",
8228
+ "restrictedProcesses",
8229
+ "breakdownUnavailable",
8230
+ "pressureDerived",
8231
+ "truncated"
8232
+ ];
8233
+ var TERMINATE_MODES = ["graceful", "force"];
8234
+ var TERMINATE_ORIGINS = [
8235
+ "manual",
8236
+ "freeUp",
8237
+ "advisor"
8238
+ ];
8239
+ var TERMINATE_METHODS = [
8240
+ "appQuit",
8241
+ "sigterm",
8242
+ "sigkill"
8243
+ ];
8244
+ var RISK_FLAGS = [
8245
+ "appMayPromptToSave",
8246
+ "unsavedWorkMayBeLost",
8247
+ "endsChildProcesses",
8248
+ "backgroundAgent",
8249
+ "recentlyUsed",
8250
+ "restarts"
8251
+ ];
8252
+ var REFUSAL_CODES = [
8253
+ "protected",
8254
+ "notFound",
8255
+ "identityChanged",
8256
+ "duplicate",
8257
+ "tooMany",
8258
+ "frontmost"
8259
+ ];
8260
+ var TERMINATE_STATUSES = [
8261
+ "exited",
8262
+ "stillRunning",
8263
+ "alreadyGone",
8264
+ "identityChanged",
8265
+ "refused",
8266
+ "failed"
8267
+ ];
8268
+ var REASON_CODES = [
8269
+ "large",
8270
+ "idle",
8271
+ "background",
8272
+ "growing",
8273
+ "manyProcesses"
8274
+ ];
8275
+ /** FNV-1a 64 of the group key, lowercase hex. */
8276
+ var GroupIdSchema = string().regex(/^grp_[0-9a-f]{16}$/);
8277
+ var TerminatePlanIdSchema = string().regex(/^tplan_[0-9a-zA-Z]{16}$/);
8278
+ var MemoryAuditIdSchema = string().regex(/^aud_[0-9a-zA-Z]{16}$/);
8279
+ var PlatformSchema = _enum(MEMORY_PLATFORMS);
8280
+ var PressureLevelSchema = _enum(PRESSURE_LEVELS);
8281
+ var PressureSourceSchema = _enum(PRESSURE_SOURCES);
8282
+ var ProcessKindSchema = _enum(PROCESS_KINDS);
8283
+ var ProcessStateSchema = _enum(PROCESS_STATES);
8284
+ var ProtectionSchema = _enum(PROTECTIONS);
8285
+ var SnapshotNoteSchema = _enum(SNAPSHOT_NOTES);
8286
+ var TerminateModeSchema = _enum(TERMINATE_MODES);
8287
+ var TerminateOriginSchema = _enum(TERMINATE_ORIGINS);
8288
+ var TerminateMethodSchema = _enum(TERMINATE_METHODS);
8289
+ var RiskFlagSchema = _enum(RISK_FLAGS);
8290
+ var RefusalCodeSchema = _enum(REFUSAL_CODES);
8291
+ var TerminateStatusSchema = _enum(TERMINATE_STATUSES);
8292
+ var ReasonCodeSchema = _enum(REASON_CODES);
8293
+ /** f32 percentages: nonnegative where the range is open, 0..100 where it is a share. */
8294
+ var RatioSchema = number().nonnegative();
8295
+ var PercentSchema = number().min(0).max(100);
8296
+ var MemoryBreakdownSchema = strictObject({
8297
+ totalBytes: Uint,
8298
+ usedBytes: Uint,
8299
+ freeBytes: Uint,
8300
+ availableBytes: Uint.nullable(),
8301
+ appBytes: Uint.nullable(),
8302
+ wiredBytes: Uint.nullable(),
8303
+ compressedBytes: Uint.nullable(),
8304
+ cachedFilesBytes: Uint.nullable(),
8305
+ swapTotalBytes: Uint,
8306
+ swapUsedBytes: Uint
8307
+ });
8308
+ var MemoryPressureSchema = strictObject({
8309
+ level: PressureLevelSchema,
8310
+ source: PressureSourceSchema,
8311
+ availablePercent: PercentSchema.nullable()
8312
+ });
8313
+ var ProcessRowSchema = strictObject({
8314
+ pid: Uint,
8315
+ ppid: Uint.nullable(),
8316
+ startTimeUs: Uint,
8317
+ name: Name,
8318
+ ownedByCurrentUser: boolean(),
8319
+ groupId: GroupIdSchema,
8320
+ kind: ProcessKindSchema,
8321
+ cpuPercent: RatioSchema.nullable(),
8322
+ footprintBytes: Uint.nullable(),
8323
+ residentBytes: Uint.nullable(),
8324
+ virtualBytes: Uint.nullable(),
8325
+ restricted: boolean(),
8326
+ protection: ProtectionSchema.nullable(),
8327
+ /** Full argv joined with spaces; null when the kernel does not expose it. */
8328
+ command: string().max(4096).nullable(),
8329
+ /** Owning account name, when resolvable. */
8330
+ user: string().max(128).nullable(),
8331
+ state: ProcessStateSchema,
8332
+ /** Thread count, when the platform reports it. */
8333
+ threads: Uint.nullable(),
8334
+ /** Listening TCP ports, sorted ascending (at most 32). */
8335
+ listeningPorts: array(Uint).max(32)
8336
+ });
8337
+ var MemorySnapshotSchema = strictObject({
8338
+ sequence: Uint,
8339
+ sampledAt: Iso,
8340
+ intervalMs: Uint,
8341
+ platform: PlatformSchema,
8342
+ breakdown: MemoryBreakdownSchema,
8343
+ pressure: MemoryPressureSchema,
8344
+ groups: array(strictObject({
8345
+ groupId: GroupIdSchema,
8346
+ name: Name,
8347
+ bundleId: string().nullable(),
8348
+ bundlePath: string().nullable(),
8349
+ kind: ProcessKindSchema,
8350
+ mainPid: Uint,
8351
+ pids: array(Uint),
8352
+ cpuPercent: RatioSchema.nullable(),
8353
+ footprintBytes: Uint,
8354
+ residentBytes: Uint,
8355
+ frontmost: boolean(),
8356
+ lastFrontmostAt: Iso.nullable(),
8357
+ startedAt: Iso,
8358
+ protection: ProtectionSchema.nullable()
8359
+ })).max(5e3),
8360
+ processes: array(ProcessRowSchema).max(2e4),
8361
+ notes: array(SnapshotNoteSchema)
8362
+ });
8363
+ var TerminatePlanRequestSchema = strictObject({
8364
+ targets: array(discriminatedUnion("kind", [strictObject({
8365
+ kind: literal("group"),
8366
+ groupId: GroupIdSchema
8367
+ }), strictObject({
8368
+ kind: literal("process"),
8369
+ pid: Uint,
8370
+ startTimeUs: Uint
8371
+ })])).min(1).max(20),
8372
+ mode: TerminateModeSchema,
8373
+ origin: TerminateOriginSchema
8374
+ });
8375
+ var TerminatePlanEntrySchema = strictObject({
8376
+ pid: Uint,
8377
+ startTimeUs: Uint,
8378
+ name: Name,
8379
+ groupId: GroupIdSchema,
8380
+ footprintBytes: Uint.nullable(),
8381
+ method: TerminateMethodSchema,
8382
+ risks: array(RiskFlagSchema),
8383
+ descendantCount: Uint
8384
+ });
8385
+ var TerminateRefusalSchema = strictObject({
8386
+ pid: Uint.nullable(),
8387
+ groupId: GroupIdSchema.nullable(),
8388
+ name: Name,
8389
+ code: RefusalCodeSchema,
8390
+ protection: ProtectionSchema.nullable()
8391
+ });
8392
+ var TerminatePlanSchema = strictObject({
8393
+ planId: TerminatePlanIdSchema,
8394
+ mode: TerminateModeSchema,
8395
+ origin: TerminateOriginSchema,
8396
+ entries: array(TerminatePlanEntrySchema).max(64),
8397
+ refused: array(TerminateRefusalSchema),
8398
+ expectedReleaseBytes: Uint,
8399
+ createdAt: Iso,
8400
+ expiresAt: Iso
8401
+ });
8402
+ var TerminateExecuteRequestSchema = strictObject({
8403
+ planId: TerminatePlanIdSchema,
8404
+ /** Must be the literal `true`. A default, a missing field, or `false` refuses. */
8405
+ confirm: literal(true)
8406
+ });
8407
+ var TerminateOutcomeSchema = strictObject({
8408
+ planId: TerminatePlanIdSchema,
8409
+ results: array(strictObject({
8410
+ pid: Uint,
8411
+ startTimeUs: Uint,
8412
+ name: Name,
8413
+ status: TerminateStatusSchema,
8414
+ method: TerminateMethodSchema,
8415
+ errno: number().int().nullable()
8416
+ })),
8417
+ releasedBytesEstimate: Uint,
8418
+ auditIds: array(MemoryAuditIdSchema)
8419
+ });
8420
+ var FreeUpCandidatesSchema = strictObject({
8421
+ sequence: Uint,
8422
+ pressure: MemoryPressureSchema,
8423
+ observedMinutes: Uint,
8424
+ candidates: array(strictObject({
8425
+ groupId: GroupIdSchema,
8426
+ name: Name,
8427
+ footprintBytes: Uint,
8428
+ reasons: array(strictObject({
8429
+ code: ReasonCodeSchema,
8430
+ bytes: Uint.nullable(),
8431
+ minutes: Uint.nullable(),
8432
+ cpuPercent: RatioSchema.nullable(),
8433
+ count: Uint.nullable(),
8434
+ fromBytes: Uint.nullable()
8435
+ })),
8436
+ risks: array(RiskFlagSchema),
8437
+ preselected: boolean()
8438
+ })).max(8),
8439
+ potentialReleaseBytes: Uint
8440
+ });
8441
+ var CandidatesRequestSchema = strictObject({ exclude: array(GroupIdSchema).max(200) });
8442
+ var SystemPointSchema = strictObject({
8443
+ at: Iso,
8444
+ usedBytes: Uint,
8445
+ compressedBytes: Uint.nullable(),
8446
+ swapUsedBytes: Uint,
8447
+ pressure: PressureLevelSchema
8448
+ });
8449
+ var GroupSeriesSchema = strictObject({
8450
+ groupId: GroupIdSchema,
8451
+ name: Name,
8452
+ footprintBytes: array(Uint.nullable())
8453
+ });
8454
+ var MemoryHistorySchema = strictObject({
8455
+ stepMs: Uint,
8456
+ points: array(SystemPointSchema).max(600),
8457
+ groups: array(GroupSeriesSchema).max(8)
8458
+ });
8459
+ var HistoryRequestSchema = strictObject({ groupIds: array(GroupIdSchema).max(8) });
8460
+ var AuditLogSchema = strictObject({ records: array(strictObject({
8461
+ auditId: MemoryAuditIdSchema,
8462
+ at: Iso,
8463
+ origin: TerminateOriginSchema,
8464
+ mode: TerminateModeSchema,
8465
+ method: TerminateMethodSchema,
8466
+ pid: Uint,
8467
+ startTimeUs: Uint,
8468
+ name: Name,
8469
+ groupName: Name,
8470
+ bundleId: string().nullable(),
8471
+ status: TerminateStatusSchema,
8472
+ footprintBytes: Uint.nullable()
8473
+ })).max(200) });
8474
+ //#endregion
8015
8475
  //#region ../../packages/contract/src/capabilities.ts
8016
8476
  var UintSchema$1 = number().int().nonnegative();
8017
8477
  strictObject({
@@ -8021,17 +8481,65 @@ strictObject({
8021
8481
  start: boolean(),
8022
8482
  cancel: boolean(),
8023
8483
  discovery: boolean().optional(),
8484
+ appAudit: boolean().optional(),
8485
+ appScan: boolean().optional(),
8024
8486
  maxConcurrent: UintSchema$1
8025
8487
  }),
8026
8488
  cleanup: strictObject({
8027
8489
  plan: boolean(),
8028
8490
  execute: boolean(),
8029
- mode: _enum(CLEANUP_MODES)
8491
+ mode: _enum(CLEANUP_MODES),
8492
+ /** V2 app-scoped cleanup plan/execute submit arms (audit-generation
8493
+ * authorized, outside the engine). Absent on older hosts. */
8494
+ appPlan: boolean().optional(),
8495
+ appExecute: boolean().optional()
8496
+ }),
8497
+ host: strictObject({
8498
+ /** Native folder pickers exist only in desktop/webview hosts, never over HTTP. */
8499
+ folderPicker: boolean(),
8500
+ /** Finder reveal of an allow-listed audited app location. Absent on older hosts. */
8501
+ appLocationReveal: boolean().optional(),
8502
+ /**
8503
+ * Reveal of a *scanned* path in the host's own file manager. Absent on
8504
+ * older hosts, which never had the route.
8505
+ */
8506
+ pathReveal: boolean().optional(),
8507
+ /**
8508
+ * One-level folder listing for the scan picker's browse mode. Absent on
8509
+ * older hosts, whose picker falls back to typing a path.
8510
+ */
8511
+ pathList: boolean().optional(),
8512
+ /** The host's operating system, so the UI can name the file manager. */
8513
+ platform: _enum([
8514
+ "macos",
8515
+ "windows",
8516
+ "linux",
8517
+ "unknown"
8518
+ ]).optional()
8030
8519
  }),
8031
- host: strictObject({
8032
- /** Native folder pickers exist only in desktop/webview hosts, never over HTTP. */
8033
- folderPicker: boolean() }),
8034
- icloud: _enum(["unavailable"])
8520
+ icloud: _enum(["unavailable"]),
8521
+ /**
8522
+ * True when the host is configured with an operator-owned AI advisor
8523
+ * (`packages/contract/src/ai.ts`). Absent on older hosts, which never
8524
+ * advertise it.
8525
+ */
8526
+ ai: boolean().optional(),
8527
+ /**
8528
+ * Memory view and process control (crates/memory). Absent on older hosts and
8529
+ * on machine-mode hosts that never pass the allow flags, in which case the
8530
+ * Memory view stays hidden.
8531
+ */
8532
+ memory: strictObject({
8533
+ /** snapshot/history/candidates/audit readable. */
8534
+ sample: boolean(),
8535
+ /** plan/execute available to this session's host config. */
8536
+ terminate: boolean(),
8537
+ /** AppKit quit works (macOS + appkit feature). */
8538
+ gracefulAppQuit: boolean(),
8539
+ /** desktop-only "Reopen" from audit. */
8540
+ reopen: boolean(),
8541
+ platform: _enum(MEMORY_PLATFORMS)
8542
+ }).optional()
8035
8543
  });
8036
8544
  strictObject({
8037
8545
  status: literal("ok"),
@@ -8051,17 +8559,92 @@ function healthPayload(serviceInstanceId) {
8051
8559
  contractVersion: CONTRACT_VERSION
8052
8560
  };
8053
8561
  }
8562
+ /**
8563
+ * Reveal a path the scan already reported in the *host's* own file manager
8564
+ * (Finder / Explorer / the desktop's file manager).
8565
+ *
8566
+ * The path is data, never a command: the host resolves it against the roots
8567
+ * it serves and hands it to the platform's file-manager launcher as one
8568
+ * argument. A path outside those roots is refused, never opened.
8569
+ */
8570
+ var RevealPathRequestSchema = strictObject({
8571
+ /** Absolute path of a scanned file or folder. */
8572
+ path: string().min(1),
8573
+ /** Defaults to `reveal`. */
8574
+ action: _enum(["reveal", "open"]).optional()
8575
+ });
8576
+ strictObject({ revealed: boolean() });
8577
+ //#endregion
8578
+ //#region ../../packages/contract/src/fs.ts
8579
+ var PathSchema = string().min(1).max(4096);
8580
+ /**
8581
+ * Folder browsing for the scan picker.
8582
+ *
8583
+ * The host lists one directory at a time inside the roots it already serves,
8584
+ * so a browser (or a remote workbench reached over SSH) can drill to a folder
8585
+ * instead of typing an absolute path it cannot see. Listing is never
8586
+ * recursive: sizes are the entry's own length, not a measured subtree.
8587
+ */
8588
+ var FsEntryKindSchema = _enum([
8589
+ "dir",
8590
+ "file",
8591
+ "other"
8592
+ ]);
8593
+ var FsEntrySchema = strictObject({
8594
+ name: string().min(1).max(1024),
8595
+ /** Absolute path, already resolved through symlinks. */
8596
+ path: PathSchema,
8597
+ kind: FsEntryKindSchema,
8598
+ /** Entry length in bytes; null when the entry could not be stat'ed. */
8599
+ size: number().int().nonnegative().nullable()
8600
+ });
8601
+ var FsListRequestSchema = strictObject({
8602
+ /** Absolute folder or `~/…`; omitted means the first served root. */
8603
+ path: PathSchema.optional(),
8604
+ /** Entry cap; the host clamps it to its own maximum. */
8605
+ limit: number().int().positive().max(5e3).optional()
8606
+ });
8607
+ strictObject({
8608
+ /** The folder that was listed, resolved through symlinks. */
8609
+ path: PathSchema,
8610
+ /**
8611
+ * The folder above, or null at a served root. The breadcrumb uses it to
8612
+ * stop walking up where the host stops serving.
8613
+ */
8614
+ parent: PathSchema.nullable(),
8615
+ /** Roots this host serves, so the picker can jump between them. */
8616
+ roots: array(PathSchema),
8617
+ entries: array(FsEntrySchema),
8618
+ /** True when the folder held more entries than the limit. */
8619
+ truncated: boolean()
8620
+ });
8054
8621
  var ScopeSchema = _enum([
8055
8622
  "scan:read",
8056
8623
  "scan:start",
8057
8624
  "cleanup:plan",
8058
- "cleanup:execute"
8625
+ "cleanup:execute",
8626
+ "ai:chat",
8627
+ "memory:read",
8628
+ "memory:terminate",
8629
+ "host:reveal"
8059
8630
  ]);
8060
8631
  var SessionExchangeRequestSchema = strictObject({
8061
8632
  ticket: string().min(16).max(512),
8062
8633
  /** Required only when the host was started with a hosted password. */
8063
8634
  password: string().min(1).max(256).optional()
8064
8635
  });
8636
+ /**
8637
+ * A paired supervisor (the CLI behind an SSH tunnel) asks the host to mint a
8638
+ * ticket a local browser can spend. The origin must be plain loopback HTTP —
8639
+ * the tunnel's local port — because that is the only place the minted ticket
8640
+ * is meant to be spent.
8641
+ */
8642
+ var BrowserTicketRequestSchema = strictObject({ origin: string().regex(/^http:\/\/(127\.0\.0\.1|localhost):[1-9][0-9]{0,4}$/) });
8643
+ strictObject({
8644
+ ticket: string().min(16).max(512),
8645
+ /** Ready to open: the origin the ticket was minted for, with `?pair=`. */
8646
+ url: string().min(1)
8647
+ });
8065
8648
  strictObject({
8066
8649
  token: string().min(16).max(256),
8067
8650
  sessionId: string().min(1).max(128),
@@ -8227,106 +8810,1425 @@ function originsForAuthorities(authorities) {
8227
8810
  * One gate, three questions, in order: is the request even addressed to us
8228
8811
  * (Host), does a browser-presented Origin match the allowlist exactly, and is
8229
8812
  * an Origin-less browser fetch quietly declaring itself same-site?
8813
+ *
8814
+ * A top-level *navigation* is allowed through even when it is cross-site: the
8815
+ * response is a document the linking page cannot read, and refusing it means
8816
+ * opening the workbench from a chat message or a bookmark shows a JSON error
8817
+ * instead of the app. Subresource and API requests still need an Origin the
8818
+ * policy knows, so a hostile page cannot read anything.
8230
8819
  */
8231
8820
  function checkOrigin(input, policy) {
8232
8821
  if (input.hostHeader === null || !policy.authorities.includes(input.hostHeader)) return "refused-host";
8233
8822
  if (input.origin !== null) {
8234
8823
  if (!policy.allowedOrigins.includes(input.origin)) return "refused-origin";
8235
8824
  }
8236
- if (input.secFetchSite !== null && input.origin === null && input.secFetchSite === "cross-site") return "refused-cross-site";
8825
+ if (input.secFetchSite !== null && input.origin === null && input.secFetchSite === "cross-site" && input.secFetchMode !== "navigate") return "refused-cross-site";
8237
8826
  return "ok";
8238
8827
  }
8239
8828
  //#endregion
8240
- //#region ../../packages/host/src/app.ts
8241
- var EXCHANGE_RATE_LIMIT = 10;
8242
- var EXCHANGE_RATE_WINDOW_MS = 6e4;
8243
- function frame(event, id, data) {
8244
- return `retry: 3000\nevent: ${event}\nid: ${id}\ndata: ${JSON.stringify(data)}\n\n`;
8829
+ //#region ../../packages/host/src/volumes.ts
8830
+ function runDf(args, timeoutMs = 1e4) {
8831
+ return new Promise((resolve) => {
8832
+ execFile("df", [...args], {
8833
+ timeout: timeoutMs,
8834
+ windowsHide: true
8835
+ }, (error, stdout) => {
8836
+ resolve(error ? null : stdout);
8837
+ });
8838
+ });
8245
8839
  }
8246
- function jsonResponse(payload, status, extraHeaders) {
8247
- return new Response(JSON.stringify(payload), {
8248
- status,
8249
- headers: {
8250
- "content-type": "application/json; charset=utf-8",
8251
- ...extraHeaders
8252
- }
8840
+ /**
8841
+ * Capacity for every distinct path, keyed by the input path. One `df` call
8842
+ * covers all paths; anything `df` cannot report (missing path, Windows,
8843
+ * parse failure) is simply absent, and the UI renders "unknown".
8844
+ *
8845
+ * `run` is injectable so tests can feed canned `df` output without spawning.
8846
+ */
8847
+ async function volumeCapacities(paths, run = runDf) {
8848
+ const found = /* @__PURE__ */ new Map();
8849
+ if (paths.length === 0 || platform() === "win32") return found;
8850
+ const output = await run([
8851
+ "-k",
8852
+ "-P",
8853
+ "--",
8854
+ ...paths
8855
+ ]);
8856
+ if (output === null) return found;
8857
+ const lines = output.split("\n");
8858
+ const entries = [];
8859
+ for (let index = 1; index < lines.length; index += 1) {
8860
+ const fields = lines[index]?.trim().split(/\s+/) ?? [];
8861
+ if (fields.length < 6) continue;
8862
+ const totalKb = Number(fields[1]);
8863
+ const usedKb = Number(fields[2]);
8864
+ const mount = fields.slice(5).join(" ");
8865
+ if (!Number.isFinite(totalKb) || !Number.isFinite(usedKb) || totalKb <= 0) continue;
8866
+ entries.push({
8867
+ mount,
8868
+ totalBytes: totalKb * 1024,
8869
+ usedBytes: usedKb * 1024
8870
+ });
8871
+ }
8872
+ entries.sort((a, b) => b.mount.length - a.mount.length);
8873
+ for (const path of paths) {
8874
+ const root = entries.find((entry) => path === entry.mount || entry.mount !== "/" && path.startsWith(`${entry.mount.replace(/\/+$/, "")}/`)) ?? entries.find((entry) => entry.mount === "/");
8875
+ if (root) found.set(path, {
8876
+ totalBytes: root.totalBytes,
8877
+ usedBytes: root.usedBytes
8878
+ });
8879
+ }
8880
+ return found;
8881
+ }
8882
+ /**
8883
+ * Every mounted local filesystem with its capacity: the "all my drives"
8884
+ * list for the pre-scan picker. Parses one bare `df -k -P` (no path args).
8885
+ *
8886
+ * APFS presents one physical disk as several mounts (`/`, `/System/Volumes/Data`,
8887
+ * preboot/VM siblings). Only `/` and `/Volumes/*` carry user-facing data, so
8888
+ * everything else is dropped, and the Data volume's numbers back the
8889
+ * Macintosh HD entry — `df /` alone understates a disk whose user data lives
8890
+ * on the Data twin.
8891
+ *
8892
+ * Display-only: mount points are facts, not scan targets — the picker offers
8893
+ * a scan only for paths inside the host's configured roots.
8894
+ */
8895
+ async function mountedVolumes(run = runDf) {
8896
+ if (platform() === "win32") return [];
8897
+ const output = await run(["-k", "-P"]);
8898
+ if (output === null) return [];
8899
+ const parsed = [];
8900
+ const seen = /* @__PURE__ */ new Set();
8901
+ for (const line of output.split("\n").slice(1)) {
8902
+ const fields = line.trim().split(/\s+/);
8903
+ if (fields.length < 6) continue;
8904
+ const [device, totalKb, , availableKb] = fields;
8905
+ const mount = fields.slice(5).join(" ");
8906
+ const total = Number(totalKb);
8907
+ const available = Number(availableKb);
8908
+ if (!Number.isFinite(total) || !Number.isFinite(available) || total <= 0) continue;
8909
+ if (seen.has(mount)) continue;
8910
+ seen.add(mount);
8911
+ if (!mount.startsWith("/Volumes/") && mount !== "/") continue;
8912
+ if (/^\/Volumes\/(Recovery|Preboot|Home|VM|Boot)$/i.test(mount)) continue;
8913
+ parsed.push({
8914
+ path: mount,
8915
+ totalBytes: total * 1024,
8916
+ availableBytes: available * 1024,
8917
+ freeBytes: available * 1024,
8918
+ isLocal: true
8919
+ });
8920
+ }
8921
+ const data = parsed.find((volume) => volume.path === "/System/Volumes/Data");
8922
+ const root = parsed.find((volume) => volume.path === "/");
8923
+ if (root && data) root.availableBytes = data.availableBytes;
8924
+ const volumes = parsed.filter((volume) => volume.path !== "/" || !data);
8925
+ if (root && data) volumes.unshift({
8926
+ ...root,
8927
+ totalBytes: Math.max(root.totalBytes, data.totalBytes),
8928
+ availableBytes: data.availableBytes,
8929
+ freeBytes: data.freeBytes
8253
8930
  });
8931
+ volumes.sort((a, b) => a.path === "/" ? -1 : b.path === "/" ? 1 : a.path.localeCompare(b.path));
8932
+ return volumes;
8254
8933
  }
8255
- function buildApp(deps) {
8256
- const app = new Hono();
8257
- const { config, auth, scans, events, assets, health, capabilities, allowlist } = deps;
8258
- let policy = {
8259
- authorities: authoritiesFor(config.bind.address, config.port),
8260
- allowedOrigins: [...config.uiOrigins]
8261
- };
8262
- app.rebindGate = (port) => {
8263
- const authorities = authoritiesFor(config.bind.address, port);
8264
- policy = {
8265
- authorities,
8266
- allowedOrigins: [...originsForAuthorities(authorities), ...config.uiOrigins]
8934
+ //#endregion
8935
+ //#region ../../packages/host/src/scan-index.ts
8936
+ /** Wire ids stay `sha1(path)` truncated to 24 hex characters (12 bytes). */
8937
+ function nodeIdOf(path) {
8938
+ return createHash("sha1").update(path).digest("hex").slice(0, 24);
8939
+ }
8940
+ var DIGEST_BYTES = 12;
8941
+ var NONE = -1;
8942
+ var IGNORED = 1;
8943
+ var COLLAPSED = 2;
8944
+ var HAS_IS_DIRECTORY = 4;
8945
+ var IS_DIRECTORY = 8;
8946
+ var STATE_SHIFT = 4;
8947
+ var STATE_MASK = 48;
8948
+ var HAS_SKIP_REASON = 64;
8949
+ var HAS_LOGICAL_SIZE = 128;
8950
+ /** The stored name is the whole path (roots, or a path that is not parent + sep + name). */
8951
+ var ABSOLUTE_NAME = 256;
8952
+ /** Added by background discovery; never part of the original scan's children. */
8953
+ var DISCOVERED = 512;
8954
+ var HAS_FINGERPRINT = 1024;
8955
+ var HAS_CLEANUP = 2048;
8956
+ var CLEANUP_IGNORED = 4096;
8957
+ var STATES = [
8958
+ void 0,
8959
+ "complete",
8960
+ "partial",
8961
+ "skipped"
8962
+ ];
8963
+ function grow(array, capacity) {
8964
+ const next = new array.constructor(capacity);
8965
+ next.set(array);
8966
+ return next;
8967
+ }
8968
+ function trim(array, length) {
8969
+ return array.length === length ? array : array.slice(0, length);
8970
+ }
8971
+ /**
8972
+ * Columnar scan index: one row per node in typed arrays, names in a single
8973
+ * UTF-8 buffer, paths rebuilt from parent links, and an open-addressing table
8974
+ * from the 12-byte id digest to the row. A Map of per-node objects cost
8975
+ * ~550 B/node; this costs ~70 B/node plus the name bytes.
8976
+ *
8977
+ * Children are a prepend-only linked list per parent, so appending in
8978
+ * preorder needs no per-node tail pointer; reads reverse it back into
8979
+ * insertion order.
8980
+ */
8981
+ var ScanIndex = class {
8982
+ count = 0;
8983
+ roots = [];
8984
+ capacity;
8985
+ digests;
8986
+ parents;
8987
+ firstChild;
8988
+ nextSibling;
8989
+ childCounts;
8990
+ sizes;
8991
+ logicalSizes = null;
8992
+ flags;
8993
+ nameEnds;
8994
+ names;
8995
+ nameBytes = 0;
8996
+ /** Names that do not round-trip through UTF-8 (lone surrogates) stay as strings. */
8997
+ rawNames = /* @__PURE__ */ new Map();
8998
+ skipReasons = /* @__PURE__ */ new Map();
8999
+ fingerprints = null;
9000
+ cleanup = null;
9001
+ slots;
9002
+ slotMask;
9003
+ constructor(capacity = 1024) {
9004
+ this.capacity = Math.max(16, capacity);
9005
+ this.digests = Buffer.alloc(this.capacity * DIGEST_BYTES);
9006
+ this.parents = new Int32Array(this.capacity);
9007
+ this.firstChild = new Int32Array(this.capacity);
9008
+ this.nextSibling = new Int32Array(this.capacity);
9009
+ this.childCounts = new Uint32Array(this.capacity);
9010
+ this.sizes = new Float64Array(this.capacity);
9011
+ this.flags = new Uint16Array(this.capacity);
9012
+ this.nameEnds = new Uint32Array(this.capacity);
9013
+ this.names = Buffer.allocUnsafeSlow(this.capacity * 16);
9014
+ let slots = 16;
9015
+ while (slots < this.capacity * 2) slots *= 2;
9016
+ this.slots = new Int32Array(slots).fill(NONE);
9017
+ this.slotMask = slots - 1;
9018
+ }
9019
+ /**
9020
+ * Adds one node under `parent` (NONE for a root) and returns its row, or
9021
+ * NONE when its id is already present. `parentPath` must be the parent's
9022
+ * full path. Nodes must arrive parent-first.
9023
+ */
9024
+ append(input, parent, parentPath, discovered = false) {
9025
+ const digest = createHash("sha1").update(input.path).digest();
9026
+ if (this.findDigest(digest, 0) !== NONE) return NONE;
9027
+ if (this.count === this.capacity) this.reserve(this.capacity * 2);
9028
+ const row = this.count;
9029
+ this.count += 1;
9030
+ digest.copy(this.digests, row * DIGEST_BYTES, 0, DIGEST_BYTES);
9031
+ this.insertSlot(row);
9032
+ let flags = (input.ignored ? IGNORED : 0) | (input.collapsed ? COLLAPSED : 0) | (discovered ? DISCOVERED : 0);
9033
+ if (input.isDirectory !== void 0) flags |= HAS_IS_DIRECTORY | (input.isDirectory ? IS_DIRECTORY : 0);
9034
+ if (input.scanState !== void 0) flags |= STATES.indexOf(input.scanState) << STATE_SHIFT;
9035
+ if (input.skipReason !== void 0) {
9036
+ flags |= HAS_SKIP_REASON;
9037
+ if (input.skipReason !== null) this.skipReasons.set(row, input.skipReason);
9038
+ }
9039
+ if (input.logicalSize !== void 0) {
9040
+ flags |= HAS_LOGICAL_SIZE;
9041
+ this.logicalSizes ??= new Float64Array(this.capacity);
9042
+ this.logicalSizes[row] = input.logicalSize;
9043
+ }
9044
+ if (input.fingerprint !== void 0) {
9045
+ flags |= HAS_FINGERPRINT;
9046
+ this.fingerprints ??= new Float64Array(this.capacity * 2);
9047
+ this.fingerprints[row * 2] = input.fingerprint.size;
9048
+ this.fingerprints[row * 2 + 1] = input.fingerprint.mtimeMs;
9049
+ }
9050
+ let name = parentPath === null ? null : childName(input.path, parentPath);
9051
+ if (name === null) {
9052
+ flags |= ABSOLUTE_NAME;
9053
+ name = input.path;
9054
+ }
9055
+ this.writeName(row, name);
9056
+ this.flags[row] = flags;
9057
+ this.sizes[row] = input.size;
9058
+ this.parents[row] = parent;
9059
+ this.firstChild[row] = NONE;
9060
+ this.nextSibling[row] = NONE;
9061
+ if (parent === NONE) {
9062
+ if (!discovered) this.roots.push(row);
9063
+ } else if (!discovered || (this.flags[parent] & DISCOVERED) !== 0) {
9064
+ this.nextSibling[row] = this.firstChild[parent];
9065
+ this.firstChild[parent] = row;
9066
+ this.childCounts[parent] += 1;
9067
+ }
9068
+ return row;
9069
+ }
9070
+ /** Releases growth slack once the scan is complete. */
9071
+ seal() {
9072
+ if (this.capacity === this.count) return;
9073
+ const length = Math.max(1, this.count);
9074
+ this.capacity = length;
9075
+ this.digests = Buffer.from(this.digests.subarray(0, length * DIGEST_BYTES));
9076
+ this.parents = trim(this.parents, length);
9077
+ this.firstChild = trim(this.firstChild, length);
9078
+ this.nextSibling = trim(this.nextSibling, length);
9079
+ this.childCounts = trim(this.childCounts, length);
9080
+ this.sizes = trim(this.sizes, length);
9081
+ this.flags = trim(this.flags, length);
9082
+ this.nameEnds = trim(this.nameEnds, length);
9083
+ if (this.logicalSizes !== null) this.logicalSizes = trim(this.logicalSizes, length);
9084
+ if (this.fingerprints !== null) this.fingerprints = trim(this.fingerprints, length * 2);
9085
+ if (this.cleanup !== null) this.cleanup = trim(this.cleanup, length * 3);
9086
+ this.names = Buffer.from(this.names.subarray(0, this.nameBytes));
9087
+ }
9088
+ find(id) {
9089
+ if (id.length !== 24) return NONE;
9090
+ for (let index = 0; index < id.length; index += 1) {
9091
+ const code = id.charCodeAt(index);
9092
+ if (!(code >= 48 && code <= 57 || code >= 97 && code <= 102)) return NONE;
9093
+ }
9094
+ return this.findDigest(Buffer.from(id, "hex"), 0);
9095
+ }
9096
+ has(id) {
9097
+ return this.find(id) !== NONE;
9098
+ }
9099
+ idOf(row) {
9100
+ return this.digests.toString("hex", row * DIGEST_BYTES, (row + 1) * DIGEST_BYTES);
9101
+ }
9102
+ parentOf(row) {
9103
+ return this.parents[row];
9104
+ }
9105
+ sizeOf(row) {
9106
+ return this.sizes[row];
9107
+ }
9108
+ childCount(row) {
9109
+ return this.childCounts[row];
9110
+ }
9111
+ /** Children in the order the scan reported them. */
9112
+ childrenOf(row) {
9113
+ const children = [];
9114
+ for (let child = this.firstChild[row]; child !== NONE; child = this.nextSibling[child]) children.push(child);
9115
+ return children.reverse();
9116
+ }
9117
+ isIgnored(row) {
9118
+ return (this.flags[row] & IGNORED) !== 0;
9119
+ }
9120
+ /** `undefined` when the scanner did not report it. */
9121
+ isDirectory(row) {
9122
+ const flags = this.flags[row];
9123
+ return (flags & HAS_IS_DIRECTORY) === 0 ? void 0 : (flags & IS_DIRECTORY) !== 0;
9124
+ }
9125
+ scanStateOf(row) {
9126
+ return STATES[(this.flags[row] & STATE_MASK) >> STATE_SHIFT];
9127
+ }
9128
+ isDiscovered(row) {
9129
+ return (this.flags[row] & DISCOVERED) !== 0;
9130
+ }
9131
+ /** Distance from the node's root, counted along parent links. */
9132
+ depthOf(row) {
9133
+ let depth = 0;
9134
+ for (let cursor = this.parents[row]; cursor !== NONE; cursor = this.parents[cursor]) depth += 1;
9135
+ return depth;
9136
+ }
9137
+ /** The stored name segment: the basename, or the whole path for roots. */
9138
+ nameOf(row) {
9139
+ const raw = this.rawNames.get(row);
9140
+ if (raw !== void 0) return raw;
9141
+ return this.names.toString("utf8", row === 0 ? 0 : this.nameEnds[row - 1], this.nameEnds[row]);
9142
+ }
9143
+ baseNameOf(row) {
9144
+ const name = this.nameOf(row);
9145
+ return (this.flags[row] & ABSOLUTE_NAME) === 0 ? name : basename(name);
9146
+ }
9147
+ pathOf(row) {
9148
+ const segments = [];
9149
+ let cursor = row;
9150
+ while ((this.flags[cursor] & ABSOLUTE_NAME) === 0) {
9151
+ segments.push(this.nameOf(cursor));
9152
+ cursor = this.parents[cursor];
9153
+ }
9154
+ let path = this.nameOf(cursor);
9155
+ for (let index = segments.length - 1; index >= 0; index -= 1) path = joinChild(path, segments[index]);
9156
+ return path;
9157
+ }
9158
+ summarize(row) {
9159
+ const flags = this.flags[row];
9160
+ const childCount = this.childCounts[row];
9161
+ const state = STATES[(flags & STATE_MASK) >> STATE_SHIFT];
9162
+ return {
9163
+ id: this.idOf(row),
9164
+ name: this.baseNameOf(row),
9165
+ path: this.pathOf(row),
9166
+ size: this.sizes[row],
9167
+ depth: this.depthOf(row),
9168
+ ignored: (flags & IGNORED) !== 0,
9169
+ collapsed: (flags & COLLAPSED) !== 0,
9170
+ hasChildren: childCount > 0,
9171
+ childCount,
9172
+ ...(flags & HAS_LOGICAL_SIZE) === 0 ? {} : { logicalSize: this.logicalSizes[row] },
9173
+ ...(flags & HAS_IS_DIRECTORY) === 0 ? {} : { isDirectory: (flags & IS_DIRECTORY) !== 0 },
9174
+ ...state === void 0 ? {} : { scanState: state },
9175
+ ...(flags & HAS_SKIP_REASON) === 0 ? {} : { skipReason: this.skipReasons.get(row) ?? null }
8267
9176
  };
8268
- };
8269
- const remoteAddress = (c) => {
8270
- const forwarded = c.req.header("x-forwarded-for");
8271
- if (forwarded !== void 0 && config.trustProxy) {
8272
- const first = forwarded.split(",")[0]?.trim();
8273
- if (first) return first;
9177
+ }
9178
+ /** Discovery's own measurement of an indexed node, used only for cleanup planning. */
9179
+ setCleanup(row, size, ignored, fingerprint) {
9180
+ this.cleanup ??= new Float64Array(this.capacity * 3);
9181
+ this.cleanup[row * 3] = size;
9182
+ this.cleanup[row * 3 + 1] = fingerprint.size;
9183
+ this.cleanup[row * 3 + 2] = fingerprint.mtimeMs;
9184
+ this.flags[row] = this.flags[row] & -4097 | HAS_CLEANUP | (ignored ? CLEANUP_IGNORED : 0);
9185
+ }
9186
+ cleanupView(row) {
9187
+ const flags = this.flags[row];
9188
+ const path = this.pathOf(row);
9189
+ if ((flags & HAS_CLEANUP) !== 0) {
9190
+ const cleanup = this.cleanup;
9191
+ return {
9192
+ path,
9193
+ size: cleanup[row * 3],
9194
+ ignored: (flags & CLEANUP_IGNORED) !== 0,
9195
+ fingerprint: {
9196
+ size: cleanup[row * 3 + 1],
9197
+ mtimeMs: cleanup[row * 3 + 2]
9198
+ }
9199
+ };
8274
9200
  }
8275
- return c.env?.incoming?.socket?.remoteAddress ?? null;
8276
- };
8277
- const corsHeadersFor = (origin) => {
8278
- if (origin === null || !config.uiOrigins.includes(origin)) return {};
8279
9201
  return {
8280
- "access-control-allow-origin": origin,
8281
- "access-control-allow-methods": "GET, POST, OPTIONS",
8282
- "access-control-allow-headers": "Authorization, Content-Type",
8283
- vary: "Origin"
9202
+ path,
9203
+ size: this.sizes[row],
9204
+ ignored: (flags & IGNORED) !== 0,
9205
+ fingerprint: (flags & HAS_FINGERPRINT) === 0 ? void 0 : {
9206
+ size: this.fingerprints[row * 2],
9207
+ mtimeMs: this.fingerprints[row * 2 + 1]
9208
+ }
8284
9209
  };
8285
- };
8286
- app.use("*", async (c, next) => {
8287
- const origin = c.req.header("origin") ?? null;
8288
- for (const [name, value] of Object.entries(corsHeadersFor(origin))) c.header(name, value);
8289
- const remote = remoteAddress(c);
8290
- if (remote !== null && !allowlist.check(remote)) throw Problems.forbidden(`client address ${normalizeRemoteAddress(remote)} is not in the allowed networks`);
8291
- const verdict = checkOrigin({
8292
- hostHeader: c.req.header("host") ?? null,
8293
- origin,
8294
- secFetchSite: c.req.header("sec-fetch-site") ?? null
8295
- }, policy);
8296
- if (verdict !== "ok") {
8297
- if (verdict === "refused-host") throw new ProblemError({
8298
- code: "InvalidRequest",
8299
- message: "request is not addressed to this service (Host header refused)",
8300
- retryable: false
8301
- }, 400);
8302
- if (verdict === "refused-origin") throw Problems.forbidden("request origin is not allowed");
8303
- throw Problems.forbidden("cross-site requests without a matching origin are refused");
9210
+ }
9211
+ writeName(row, name) {
9212
+ const start = this.nameBytes;
9213
+ if (!name.isWellFormed()) this.rawNames.set(row, name);
9214
+ else {
9215
+ const needed = start + name.length * 3;
9216
+ if (needed > this.names.length) {
9217
+ let length = this.names.length * 2;
9218
+ while (length < needed) length *= 2;
9219
+ const names = Buffer.allocUnsafeSlow(length);
9220
+ this.names.copy(names, 0, 0, start);
9221
+ this.names = names;
9222
+ }
9223
+ this.nameBytes += this.names.write(name, start, "utf8");
9224
+ }
9225
+ this.nameEnds[row] = this.nameBytes;
9226
+ }
9227
+ reserve(capacity) {
9228
+ this.capacity = capacity;
9229
+ const digests = Buffer.alloc(capacity * DIGEST_BYTES);
9230
+ this.digests.copy(digests);
9231
+ this.digests = digests;
9232
+ this.parents = grow(this.parents, capacity);
9233
+ this.firstChild = grow(this.firstChild, capacity);
9234
+ this.nextSibling = grow(this.nextSibling, capacity);
9235
+ this.childCounts = grow(this.childCounts, capacity);
9236
+ this.sizes = grow(this.sizes, capacity);
9237
+ this.flags = grow(this.flags, capacity);
9238
+ this.nameEnds = grow(this.nameEnds, capacity);
9239
+ if (this.logicalSizes !== null) this.logicalSizes = grow(this.logicalSizes, capacity);
9240
+ if (this.fingerprints !== null) this.fingerprints = grow(this.fingerprints, capacity * 2);
9241
+ if (this.cleanup !== null) this.cleanup = grow(this.cleanup, capacity * 3);
9242
+ if (this.slots.length < capacity * 2) {
9243
+ let slots = this.slots.length;
9244
+ while (slots < capacity * 2) slots *= 2;
9245
+ this.slots = new Int32Array(slots).fill(NONE);
9246
+ this.slotMask = slots - 1;
9247
+ for (let row = 0; row < this.count; row += 1) this.insertSlot(row);
9248
+ }
9249
+ }
9250
+ insertSlot(row) {
9251
+ let slot = this.digests.readUInt32LE(row * DIGEST_BYTES) & this.slotMask;
9252
+ while (this.slots[slot] !== NONE) slot = slot + 1 & this.slotMask;
9253
+ this.slots[slot] = row;
9254
+ }
9255
+ findDigest(digest, offset) {
9256
+ let slot = (digest[offset] | digest[offset + 1] << 8 | digest[offset + 2] << 16 | digest[offset + 3] << 24) & this.slotMask;
9257
+ for (;;) {
9258
+ const row = this.slots[slot];
9259
+ if (row === NONE) return NONE;
9260
+ if (this.digests.compare(digest, offset, offset + DIGEST_BYTES, row * DIGEST_BYTES, (row + 1) * DIGEST_BYTES) === 0) return row;
9261
+ slot = slot + 1 & this.slotMask;
8304
9262
  }
8305
- await next();
8306
- });
8307
- app.get("/health", (c) => c.json(health));
8308
- const exchangeAttempts = /* @__PURE__ */ new Map();
8309
- app.post("/api/v1/session/exchange", async (c) => {
8310
- const origin = c.req.header("origin") ?? "";
8311
- const key = `${origin}|${remoteAddress(c) ?? ""}`;
8312
- const now = Date.now();
8313
- const bucket = exchangeAttempts.get(key);
8314
- if (bucket === void 0 || bucket.resetAt <= now) {
8315
- if (exchangeAttempts.size > 4096) exchangeAttempts.clear();
8316
- exchangeAttempts.set(key, {
8317
- count: 1,
8318
- resetAt: now + EXCHANGE_RATE_WINDOW_MS
8319
- });
8320
- } else {
8321
- bucket.count += 1;
8322
- if (bucket.count > EXCHANGE_RATE_LIMIT) throw Problems.limit("too many pairing attempts; wait a minute");
9263
+ }
9264
+ };
9265
+ function joinChild(parent, name) {
9266
+ return parent.endsWith(sep) ? parent + name : parent + sep + name;
9267
+ }
9268
+ /** The segment that rebuilds `path` from `parentPath`, or null when it does not. */
9269
+ function childName(path, parentPath) {
9270
+ const prefixLength = parentPath.endsWith(sep) ? parentPath.length : parentPath.length + 1;
9271
+ if (path.length <= prefixLength || !path.startsWith(parentPath)) return null;
9272
+ if (prefixLength > parentPath.length && path[parentPath.length] !== sep) return null;
9273
+ const name = path.slice(prefixLength);
9274
+ return name.includes(sep) || name.includes("/") ? null : name;
9275
+ }
9276
+ //#endregion
9277
+ //#region ../../packages/host/src/local-process.ts
9278
+ var LOCAL_SCAN_BIN_ENV = "SPACELENS_LOCAL_SCAN_BIN";
9279
+ var MAX_LINE_BYTES$1 = 536870912;
9280
+ var MAX_NODE_LINE_BYTES = 1048576;
9281
+ /** Only executable artifacts are probed here, never scan targets. */
9282
+ function resolveLocalScanBin(explicit) {
9283
+ const configured = explicit ?? process.env["SPACELENS_LOCAL_SCAN_BIN"];
9284
+ const valid = (candidate) => {
9285
+ try {
9286
+ accessSync(candidate, constants.X_OK);
9287
+ return true;
9288
+ } catch {
9289
+ return false;
8323
9290
  }
8324
- const raw = await c.req.json().catch(() => void 0);
8325
- const parsed = SessionExchangeRequestSchema.safeParse(raw);
8326
- if (!parsed.success) throw Problems.invalid("malformed pairing request");
8327
- const result = auth.exchange(parsed.data.ticket, {
8328
- origin: origin === "" ? null : origin,
8329
- password: parsed.data.password
9291
+ };
9292
+ if (configured !== void 0) {
9293
+ if (!isAbsolute(configured) || !valid(configured)) throw Problems.unavailable(`${LOCAL_SCAN_BIN_ENV} must name an existing absolute executable; protected scans never fall back`);
9294
+ return configured;
9295
+ }
9296
+ const candidates = /* @__PURE__ */ new Set();
9297
+ for (const origin of [
9298
+ process.cwd(),
9299
+ dirname(fileURLToPath(import.meta.url)),
9300
+ dirname(process.execPath)
9301
+ ]) {
9302
+ let cursor = resolve(origin);
9303
+ for (;;) {
9304
+ candidates.add(join(cursor, "target", "release", process.platform === "win32" ? "spacelens.exe" : "spacelens"));
9305
+ const parent = dirname(cursor);
9306
+ if (parent === cursor) break;
9307
+ cursor = parent;
9308
+ }
9309
+ }
9310
+ for (const candidate of candidates) if (valid(candidate)) return candidate;
9311
+ throw Problems.unavailable(`protected release scanner not found; build target/release/spacelens or set ${LOCAL_SCAN_BIN_ENV}; no legacy fallback`);
9312
+ }
9313
+ function spawnLocalScan(binary, paths, request, onProgress) {
9314
+ const args = [
9315
+ "scan",
9316
+ ...paths,
9317
+ "--local-only",
9318
+ "--json",
9319
+ "--progress-json",
9320
+ "--stream-nodes",
9321
+ "--respect-gitignore",
9322
+ String(request.respectGitignore),
9323
+ "--ignored-mode",
9324
+ request.ignoredMode,
9325
+ ...request.ignoreHidden ? ["--ignore-hidden"] : []
9326
+ ];
9327
+ const child = spawn(binary, args, {
9328
+ shell: false,
9329
+ stdio: [
9330
+ "pipe",
9331
+ "pipe",
9332
+ "pipe"
9333
+ ],
9334
+ windowsHide: true
9335
+ });
9336
+ child.stdin.end();
9337
+ let killTimer;
9338
+ let ignoreOutput = false;
9339
+ let discardPending = () => {};
9340
+ let discardTree = () => {};
9341
+ const terminate = () => {
9342
+ ignoreOutput = true;
9343
+ discardPending();
9344
+ discardTree();
9345
+ if (child.exitCode !== null || child.signalCode !== null) return;
9346
+ child.kill("SIGTERM");
9347
+ killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2e3);
9348
+ killTimer.unref();
9349
+ };
9350
+ return {
9351
+ child,
9352
+ done: new Promise((resolveDone, rejectDone) => {
9353
+ let parts = [];
9354
+ let pendingBytes = 0;
9355
+ let header = "";
9356
+ discardPending = () => {
9357
+ parts = [];
9358
+ pendingBytes = 0;
9359
+ header = "";
9360
+ };
9361
+ let stderr = Buffer.alloc(0);
9362
+ let report = null;
9363
+ let index = new ScanIndex(65536);
9364
+ const ancestors = [];
9365
+ let streamed = false;
9366
+ discardTree = () => {
9367
+ index = new ScanIndex();
9368
+ ancestors.length = 0;
9369
+ report = null;
9370
+ };
9371
+ let failure = null;
9372
+ const fail = (message) => {
9373
+ failure ??= new Error(message);
9374
+ terminate();
9375
+ };
9376
+ const attach = (node) => {
9377
+ if (!isAbsolute(node.path) || resolve(node.path) !== node.path) throw new Error("stream node path is non-absolute, unnormalized, or duplicated");
9378
+ const cloud = /\/Library\/(?:CloudStorage|Mobile Documents)(?=\/|$)|\/Volumes\/GoogleDrive(?=\/|$)/.exec(node.path);
9379
+ if (cloud !== null) {
9380
+ const cloudRoot = node.path.slice(0, cloud.index + cloud[0].length);
9381
+ if (node.path !== cloudRoot || node.scanState !== "skipped") throw new Error("stream cloud roots must be skipped and must not contain measured descendants");
9382
+ }
9383
+ let parent = null;
9384
+ if (node.depth === 0) {
9385
+ if (!paths.includes(node.path)) throw new Error("stream root was not explicitly requested");
9386
+ } else {
9387
+ parent = node.depth <= ancestors.length ? ancestors[node.depth - 1] : null;
9388
+ if (parent === null || parent.node.path !== dirname(node.path) || parent.node.depth + 1 !== node.depth || !parent.node.isDirectory || parent.node.scanState === "skipped") throw new Error("stream node has an absent, skipped, non-directory, or invalid preorder parent");
9389
+ }
9390
+ const row = index.append(node, parent?.row ?? -1, parent?.node.path ?? null);
9391
+ if (row === -1) throw new Error("stream node path is non-absolute, unnormalized, or duplicated");
9392
+ ancestors.length = node.depth + 1;
9393
+ ancestors[node.depth] = {
9394
+ node,
9395
+ row
9396
+ };
9397
+ streamed = true;
9398
+ };
9399
+ const line = (input) => {
9400
+ if (failure !== null || input.trim() === "") return;
9401
+ try {
9402
+ const decoded = JSON.parse(input);
9403
+ if (streamed && decoded?.type === "done" && Array.isArray(decoded.report?.nodes) && decoded.report.nodes.length !== 0) throw new Error("stream completion must not repeat the full tree");
9404
+ if (decoded?.type === "node" && Buffer.byteLength(input) > MAX_NODE_LINE_BYTES) throw new Error("stream node line exceeds 1 MiB protocol limit");
9405
+ const message = LocalScanMessageSchema.parse(decoded);
9406
+ if (report !== null) {
9407
+ fail("protected scanner emitted data after its final report");
9408
+ return;
9409
+ }
9410
+ if (message.type === "progress") onProgress(message.progress);
9411
+ else if (message.type === "node") attach(message.node);
9412
+ else {
9413
+ if (streamed && message.report.nodes.length !== 0) throw new Error("stream completion must not repeat the full tree");
9414
+ report = message.report;
9415
+ }
9416
+ } catch (error) {
9417
+ fail(`invalid protected scanner protocol: ${error instanceof Error ? error.message.slice(0, 1e3) : String(error)}`);
9418
+ }
9419
+ };
9420
+ child.stdout.setEncoding("utf8");
9421
+ child.stdout.on("data", (chunk) => {
9422
+ if (failure !== null || ignoreOutput) return;
9423
+ let cursor = 0;
9424
+ for (;;) {
9425
+ const newline = chunk.indexOf("\n", cursor);
9426
+ const piece = chunk.slice(cursor, newline === -1 ? void 0 : newline);
9427
+ pendingBytes += Buffer.byteLength(piece);
9428
+ if (piece !== "") parts.push(piece);
9429
+ if (header.length < 256) header += piece.slice(0, 256 - header.length);
9430
+ const nodeLine = /^\s*\{\s*"node"\s*:/.test(header) || /^\s*\{\s*"type"\s*:\s*"node"/.test(header);
9431
+ if (pendingBytes > (nodeLine ? MAX_NODE_LINE_BYTES : MAX_LINE_BYTES$1)) {
9432
+ fail(nodeLine ? "stream node line exceeds 1 MiB protocol limit" : "protected scanner report exceeds 512 MiB protocol limit");
9433
+ return;
9434
+ }
9435
+ if (newline === -1) break;
9436
+ const complete = parts.join("");
9437
+ discardPending();
9438
+ line(complete);
9439
+ if (failure !== null || ignoreOutput) return;
9440
+ cursor = newline + 1;
9441
+ }
9442
+ });
9443
+ child.stderr.on("data", (chunk) => {
9444
+ stderr = Buffer.concat([stderr, chunk]).subarray(-8192);
9445
+ });
9446
+ child.on("error", (error) => {
9447
+ failure ??= /* @__PURE__ */ new Error(`protected scanner could not start: ${error.message}`);
9448
+ });
9449
+ child.on("close", (code, signal) => {
9450
+ if (killTimer !== void 0) clearTimeout(killTimer);
9451
+ if (!ignoreOutput && parts.length > 0) line(parts.join(""));
9452
+ discardPending();
9453
+ ancestors.length = 0;
9454
+ if (failure !== null) {
9455
+ discardTree();
9456
+ rejectDone(failure);
9457
+ } else if (code !== 0 || signal !== null) {
9458
+ discardTree();
9459
+ rejectDone(/* @__PURE__ */ new Error(`protected scanner exited (${signal ?? code}): ${stderr.toString("utf8").trim()}`));
9460
+ } else if (report === null) {
9461
+ discardTree();
9462
+ rejectDone(/* @__PURE__ */ new Error("protected scanner exited without a final report"));
9463
+ } else {
9464
+ const accepted = {
9465
+ report,
9466
+ index: streamed ? index : null
9467
+ };
9468
+ if (streamed) index.seal();
9469
+ index = new ScanIndex();
9470
+ report = null;
9471
+ resolveDone(accepted);
9472
+ }
9473
+ });
9474
+ }),
9475
+ terminate
9476
+ };
9477
+ }
9478
+ //#endregion
9479
+ //#region ../../packages/host/src/app-audit.ts
9480
+ var MAX_STDOUT_BYTES$1 = 67108864;
9481
+ function appAuditArgs(request, homeOverride) {
9482
+ const args = [
9483
+ "app-audit",
9484
+ "--json",
9485
+ "--min-size",
9486
+ String(request.minSize),
9487
+ "--limit",
9488
+ String(request.limit),
9489
+ ...request.includeHeuristic ? ["--all"] : ["--no-heuristic"]
9490
+ ];
9491
+ if (homeOverride !== null) args.push("--home", homeOverride);
9492
+ return args;
9493
+ }
9494
+ function runCli$1(binary, args) {
9495
+ return new Promise((resolve, reject) => {
9496
+ const child = spawn(binary, args, {
9497
+ shell: false,
9498
+ stdio: [
9499
+ "ignore",
9500
+ "pipe",
9501
+ "pipe"
9502
+ ],
9503
+ windowsHide: true
9504
+ });
9505
+ let stdout = Buffer.alloc(0);
9506
+ let stderr = Buffer.alloc(0);
9507
+ let overflowed = false;
9508
+ child.stdout.on("data", (chunk) => {
9509
+ if (overflowed) return;
9510
+ stdout = Buffer.concat([stdout, chunk]);
9511
+ if (stdout.length > MAX_STDOUT_BYTES$1) {
9512
+ overflowed = true;
9513
+ child.kill("SIGKILL");
9514
+ }
9515
+ });
9516
+ child.stderr.on("data", (chunk) => {
9517
+ stderr = Buffer.concat([stderr, chunk]).subarray(-8192);
9518
+ });
9519
+ child.on("error", (error) => {
9520
+ reject(/* @__PURE__ */ new Error(`app CLI could not start: ${error.message}`));
9521
+ });
9522
+ child.on("close", (code, signal) => {
9523
+ if (overflowed) {
9524
+ reject(/* @__PURE__ */ new Error("app CLI output exceeds 64 MiB protocol limit"));
9525
+ return;
9526
+ }
9527
+ if (code !== 0 || signal !== null) {
9528
+ const detail = stderr.toString("utf8").trim();
9529
+ reject(new Error(detail === "" ? `app CLI exited (${signal ?? code})` : detail.slice(0, 1e3)));
9530
+ return;
9531
+ }
9532
+ resolve({
9533
+ stdout: stdout.toString("utf8"),
9534
+ stderr: stderr.toString("utf8")
9535
+ });
9536
+ });
9537
+ });
9538
+ }
9539
+ async function runAppAuditCli(spawnArgs) {
9540
+ const args = appAuditArgs(spawnArgs.request, spawnArgs.homeOverride);
9541
+ const { stdout } = await runCli$1(spawnArgs.binary, args);
9542
+ try {
9543
+ return JSON.parse(stdout);
9544
+ } catch (error) {
9545
+ throw new Error(`app CLI returned invalid JSON: ${error instanceof Error ? error.message.slice(0, 200) : String(error)}`);
9546
+ }
9547
+ }
9548
+ async function runAppIconCli(binary, appPath) {
9549
+ const { stdout } = await runCli$1(binary, [
9550
+ "app-icon",
9551
+ "--path",
9552
+ appPath
9553
+ ]);
9554
+ let parsed;
9555
+ try {
9556
+ parsed = JSON.parse(stdout);
9557
+ } catch (error) {
9558
+ throw new Error(`app CLI returned invalid JSON: ${error instanceof Error ? error.message.slice(0, 200) : String(error)}`);
9559
+ }
9560
+ const dataUrl = parsed?.dataUrl;
9561
+ if (typeof dataUrl !== "string" || dataUrl.length === 0) throw new Error("app CLI returned no dataUrl");
9562
+ return { dataUrl };
9563
+ }
9564
+ //#endregion
9565
+ //#region ../../packages/host/src/ai.ts
9566
+ /**
9567
+ * Server-side AI forwarding (task H of `docs/ai-advisor-plan.md`).
9568
+ *
9569
+ * A browser or DSH page served by this host has a CSP of `connect-src 'self'`
9570
+ * and therefore cannot reach a model endpoint itself. The host forwards the
9571
+ * one non-streaming chat completion the advisor loop needs, adding the
9572
+ * operator-configured model and — when present — the API key. The endpoint,
9573
+ * model and key are never client-settable: the only input is the conversation
9574
+ * and tool schemas.
9575
+ *
9576
+ * The rules mirror `apps/desktop/src-tauri/src/ai.rs` (`chat_endpoint`,
9577
+ * `chat_body`, the size caps and the redaction): https unless loopback, no
9578
+ * userinfo, one appended `/chat/completions`, and error messages that never
9579
+ * carry the key.
9580
+ */
9581
+ /** Long enough for a slow tool-calling completion, short enough to fail before a user gives up. */
9582
+ var CHAT_TIMEOUT_MS = 12e4;
9583
+ /** `docs/ai-advisor-plan.md` item 5: 1 MiB of request, 2 MiB of response. */
9584
+ var MAX_REQUEST_BODY_BYTES = 1048576;
9585
+ var MAX_RESPONSE_BODY_BYTES = 2097152;
9586
+ /** A streamed reply is forwarded, not buffered, but still has a hard ceiling. */
9587
+ var MAX_STREAM_BODY_BYTES = 4194304;
9588
+ var CHAT_COMPLETIONS_PATH = "/chat/completions";
9589
+ /**
9590
+ * Where one chat completion goes. Pure and total — the only place a base URL
9591
+ * becomes a request target, so the transport rule cannot be bypassed by a
9592
+ * later caller. Also used by `resolveServeConfig` to validate the operator's
9593
+ * base URL at startup (wrapped into a `ConfigError` there).
9594
+ *
9595
+ * `https` is required, except for loopback (`localhost`, `127.0.0.1`, `::1`)
9596
+ * where plaintext never leaves the machine — that is what makes a local
9597
+ * llama.cpp/ollama endpoint usable without weakening remote calls. Userinfo is
9598
+ * rejected so credentials cannot hide inside the URL, and the path is appended
9599
+ * after trimming trailing slashes so `…/v1/` and `…/v1` produce the same
9600
+ * endpoint.
9601
+ */
9602
+ function chatEndpoint(baseUrl) {
9603
+ const base = baseUrl.trim().replace(/\/+$/, "");
9604
+ if (base === "") throw new Error("AI base URL is not set");
9605
+ let parsed;
9606
+ try {
9607
+ parsed = new URL(base);
9608
+ } catch {
9609
+ throw new Error("AI base URL is not a valid URL");
9610
+ }
9611
+ if (parsed.username !== "" || parsed.password !== "") throw new Error("AI base URL must not contain credentials");
9612
+ const scheme = parsed.protocol.replace(/:$/, "");
9613
+ if (scheme === "https") {} else if (scheme === "http" && isLoopbackHost(parsed.hostname)) {} else if (scheme === "http") throw new Error("AI base URL must use https unless the host is localhost");
9614
+ else throw new Error(`AI base URL scheme is not supported: ${scheme}`);
9615
+ if (base.endsWith("/chat/completions")) return base;
9616
+ return `${base}${CHAT_COMPLETIONS_PATH}`;
9617
+ }
9618
+ function isLoopbackHost(hostname) {
9619
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
9620
+ }
9621
+ /**
9622
+ * `temperature` is deliberately absent: OpenAI-compatible servers disagree on
9623
+ * its default and the agent loop wants the model's own default. `tools` is
9624
+ * omitted rather than sent as `[]` — several compatible servers reject an
9625
+ * empty array outright.
9626
+ */
9627
+ function buildChatBody(input) {
9628
+ const body = {
9629
+ model: input.model,
9630
+ messages: input.messages
9631
+ };
9632
+ if (input.disableThinking) body.thinking = { type: "disabled" };
9633
+ if (input.tools !== void 0 && input.tools.length > 0) body.tools = input.tools;
9634
+ return body;
9635
+ }
9636
+ /** The one cap predicate, shared by both directions so the two limits cannot drift. */
9637
+ function ensureWithinCap(label, length, cap) {
9638
+ if (length > cap) throw new Error(`${label} is too large (${length} bytes; the limit is ${cap} bytes)`);
9639
+ }
9640
+ var encoder = new TextEncoder();
9641
+ /**
9642
+ * Serializes one request body and enforces the 1 MiB cap before anything is
9643
+ * sent. The returned bytes are exactly what goes on the wire, so the checked
9644
+ * size and the sent size cannot disagree.
9645
+ */
9646
+ function encodeChatBody(body) {
9647
+ const bytes = encoder.encode(JSON.stringify(body));
9648
+ ensureWithinCap("AI request body", bytes.length, MAX_REQUEST_BODY_BYTES);
9649
+ return bytes;
9650
+ }
9651
+ /**
9652
+ * Appends one chunk under a hard cap. A chunk that would cross the cap is
9653
+ * refused *before* it is buffered, so an oversized body costs one chunk of
9654
+ * memory instead of the whole body.
9655
+ */
9656
+ function appendCapped(buffer, chunk, cap) {
9657
+ ensureWithinCap("AI response body", buffer.length + chunk.length, cap);
9658
+ const merged = new Uint8Array(buffer.length + chunk.length);
9659
+ merged.set(buffer, 0);
9660
+ merged.set(chunk, buffer.length);
9661
+ return merged;
9662
+ }
9663
+ /**
9664
+ * Reads the body chunk by chunk under the cap. Returning early drops (cancels)
9665
+ * the response — which aborts the connection — so the body is never buffered
9666
+ * unbounded.
9667
+ */
9668
+ async function readCappedBody(response, cap) {
9669
+ const reader = response.body?.getReader();
9670
+ if (reader === void 0) return /* @__PURE__ */ new Uint8Array();
9671
+ let buffer = /* @__PURE__ */ new Uint8Array();
9672
+ try {
9673
+ for (;;) {
9674
+ const { done, value } = await reader.read();
9675
+ if (done) break;
9676
+ if (value !== void 0) buffer = appendCapped(buffer, value, cap);
9677
+ }
9678
+ } catch (error) {
9679
+ await reader.cancel().catch(() => void 0);
9680
+ throw error;
9681
+ }
9682
+ return buffer;
9683
+ }
9684
+ /** Every error message crosses this: an API key must never appear in a string that reaches a client or a log. */
9685
+ function redact(message, key) {
9686
+ if (key === null || key === void 0 || key === "") return message;
9687
+ return message.replaceAll(key, "[redacted]");
9688
+ }
9689
+ function truncate(text, maxChars) {
9690
+ const chars = Array.from(text);
9691
+ if (chars.length <= maxChars) return text;
9692
+ return `${chars.slice(0, maxChars).join("")}…`;
9693
+ }
9694
+ function errorMessage(error) {
9695
+ return error instanceof Error ? error.message : String(error);
9696
+ }
9697
+ function isTimeout(error) {
9698
+ return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
9699
+ }
9700
+ /**
9701
+ * Forwards one non-streaming chat completion and returns the parsed JSON body.
9702
+ * The client sends the whole conversation (and tool schemas); the host adds the
9703
+ * model, the key, and the endpoint.
9704
+ */
9705
+ async function forwardChatCompletion(input) {
9706
+ const doFetch = input.fetchImpl ?? fetch;
9707
+ let body;
9708
+ try {
9709
+ body = encodeChatBody(buildChatBody({
9710
+ model: input.model,
9711
+ messages: input.messages,
9712
+ tools: input.tools,
9713
+ disableThinking: input.disableThinking
9714
+ }));
9715
+ } catch (error) {
9716
+ throw Problems.invalid(errorMessage(error));
9717
+ }
9718
+ const headers = { "content-type": "application/json" };
9719
+ if (input.apiKey !== null) headers.authorization = `Bearer ${input.apiKey}`;
9720
+ let response;
9721
+ try {
9722
+ response = await doFetch(input.endpoint, {
9723
+ method: "POST",
9724
+ headers,
9725
+ body,
9726
+ redirect: "error",
9727
+ signal: AbortSignal.timeout(CHAT_TIMEOUT_MS)
9728
+ });
9729
+ } catch (error) {
9730
+ if (isTimeout(error)) throw Problems.timeout("AI request timed out after 120s");
9731
+ throw Problems.unavailable(redact(`AI request failed: ${errorMessage(error)}`, input.apiKey));
9732
+ }
9733
+ let text;
9734
+ try {
9735
+ text = new TextDecoder().decode(await readCappedBody(response, MAX_RESPONSE_BODY_BYTES));
9736
+ } catch (error) {
9737
+ if (error instanceof ProblemError) throw error;
9738
+ throw Problems.unavailable(redact(errorMessage(error), input.apiKey));
9739
+ }
9740
+ if (!response.ok) throw Problems.unavailable(redact(`AI request failed with ${response.status} at ${input.endpoint}: ${truncate(text, 300)}`, input.apiKey));
9741
+ try {
9742
+ return JSON.parse(text);
9743
+ } catch (error) {
9744
+ throw Problems.unavailable(redact(`AI response was not JSON (${errorMessage(error)}): ${truncate(text, 300)}`, input.apiKey));
9745
+ }
9746
+ }
9747
+ /**
9748
+ * Forwards one streaming chat completion. The request carries `stream: true`
9749
+ * and the upstream response body is passed through as raw text chunks — never
9750
+ * parsed here. A shared parser in `@space-lens/ai-advisor` assembles the deltas.
9751
+ *
9752
+ * The 1 MiB request cap is the same as the non-streaming call and is checked
9753
+ * before the key is attached. A non-2xx upstream reads the (capped) body and
9754
+ * throws the same redacted `Problems.unavailable`, so the route can still answer
9755
+ * a problem JSON before any byte is sent. The forwarded bytes are capped at
9756
+ * 4 MiB: the crossing chunk is refused, the upstream reader is cancelled, and
9757
+ * the returned stream errors. Cancelling the returned stream (or aborting the
9758
+ * caller's signal) cancels the upstream request.
9759
+ */
9760
+ async function forwardChatStream(input) {
9761
+ const doFetch = input.fetchImpl ?? fetch;
9762
+ let body;
9763
+ try {
9764
+ body = encodeChatBody({
9765
+ ...buildChatBody({
9766
+ model: input.model,
9767
+ messages: input.messages,
9768
+ tools: input.tools,
9769
+ disableThinking: input.disableThinking
9770
+ }),
9771
+ stream: true
9772
+ });
9773
+ } catch (error) {
9774
+ throw Problems.invalid(errorMessage(error));
9775
+ }
9776
+ const headers = { "content-type": "application/json" };
9777
+ if (input.apiKey !== null) headers.authorization = `Bearer ${input.apiKey}`;
9778
+ const timeout = AbortSignal.timeout(CHAT_TIMEOUT_MS);
9779
+ const signal = input.signal === void 0 ? timeout : AbortSignal.any([timeout, input.signal]);
9780
+ let response;
9781
+ try {
9782
+ response = await doFetch(input.endpoint, {
9783
+ method: "POST",
9784
+ headers,
9785
+ body,
9786
+ redirect: "error",
9787
+ signal
9788
+ });
9789
+ } catch (error) {
9790
+ if (isTimeout(error)) throw Problems.timeout("AI request timed out after 120s");
9791
+ throw Problems.unavailable(redact(`AI request failed: ${errorMessage(error)}`, input.apiKey));
9792
+ }
9793
+ if (!response.ok) {
9794
+ let text;
9795
+ try {
9796
+ text = new TextDecoder().decode(await readCappedBody(response, MAX_RESPONSE_BODY_BYTES));
9797
+ } catch (error) {
9798
+ if (error instanceof ProblemError) throw error;
9799
+ throw Problems.unavailable(redact(errorMessage(error), input.apiKey));
9800
+ }
9801
+ throw Problems.unavailable(redact(`AI request failed with ${response.status} at ${input.endpoint}: ${truncate(text, 300)}`, input.apiKey));
9802
+ }
9803
+ const upstream = response.body?.getReader();
9804
+ if (upstream === void 0) return new ReadableStream({ start: (controller) => controller.close() });
9805
+ let forwarded = 0;
9806
+ return new ReadableStream({
9807
+ async pull(controller) {
9808
+ let read;
9809
+ try {
9810
+ read = await upstream.read();
9811
+ } catch (error) {
9812
+ try {
9813
+ controller.error(error);
9814
+ } catch {}
9815
+ return;
9816
+ }
9817
+ if (read.done) {
9818
+ try {
9819
+ controller.close();
9820
+ } catch {}
9821
+ return;
9822
+ }
9823
+ const chunk = read.value;
9824
+ if (chunk === void 0) return;
9825
+ if (forwarded + chunk.length > 4194304) {
9826
+ await upstream.cancel().catch(() => void 0);
9827
+ try {
9828
+ controller.error(Problems.unavailable(redact(`AI response body is too large (${forwarded + chunk.length} bytes; the limit is ${MAX_STREAM_BODY_BYTES} bytes)`, input.apiKey)));
9829
+ } catch {}
9830
+ return;
9831
+ }
9832
+ forwarded += chunk.length;
9833
+ try {
9834
+ controller.enqueue(chunk);
9835
+ } catch {}
9836
+ },
9837
+ async cancel(reason) {
9838
+ await upstream.cancel(reason).catch(() => void 0);
9839
+ }
9840
+ });
9841
+ }
9842
+ //#endregion
9843
+ //#region ../../packages/host/src/reveal.ts
9844
+ /** The host's own operating system — for the HTTP host that is the server. */
9845
+ function hostPlatform() {
9846
+ if (process.platform === "darwin") return "macos";
9847
+ if (process.platform === "win32") return "windows";
9848
+ if (process.platform === "linux") return "linux";
9849
+ return "unknown";
9850
+ }
9851
+ /** Component-aware containment: `/a/bc` does not live inside `/a/b`. */
9852
+ function within$2(path, root) {
9853
+ const base = root.endsWith(sep) ? root.slice(0, -1) : root;
9854
+ if (base === "") return path.startsWith(sep);
9855
+ return path === base || path.startsWith(`${base}${sep}`);
9856
+ }
9857
+ /** Both the lexical path and its canonical form, against both root forms. */
9858
+ function isServedPath(path, roots) {
9859
+ const candidates = /* @__PURE__ */ new Set([path]);
9860
+ try {
9861
+ candidates.add(realpathSync(path));
9862
+ } catch {}
9863
+ for (const root of roots) {
9864
+ const rootForms = /* @__PURE__ */ new Set([root]);
9865
+ try {
9866
+ rootForms.add(realpathSync(root));
9867
+ } catch {}
9868
+ for (const candidate of candidates) for (const rootForm of rootForms) if (within$2(candidate, rootForm)) return true;
9869
+ }
9870
+ return false;
9871
+ }
9872
+ /**
9873
+ * The platform's "show me this" launcher.
9874
+ *
9875
+ * `reveal` shows the item in its parent folder and selects it where the
9876
+ * platform can select; `open` opens a folder in the file manager itself.
9877
+ */
9878
+ function fileManagerTarget(platform, path, isDirectory, action = "reveal") {
9879
+ if (action === "open" && !isDirectory) throw new Error("only a folder can be opened in the file manager");
9880
+ switch (platform) {
9881
+ case "macos": return action === "open" ? {
9882
+ command: "open",
9883
+ args: [path]
9884
+ } : {
9885
+ command: "open",
9886
+ args: ["-R", path]
9887
+ };
9888
+ case "windows": return action === "open" ? {
9889
+ command: "explorer.exe",
9890
+ args: [path]
9891
+ } : {
9892
+ command: "explorer.exe",
9893
+ args: [`/select,${path}`]
9894
+ };
9895
+ case "linux": return action === "open" ? {
9896
+ command: "xdg-open",
9897
+ args: [path]
9898
+ } : {
9899
+ command: "xdg-open",
9900
+ args: [dirname(path)]
9901
+ };
9902
+ default: throw new Error("this platform has no file manager launcher");
9903
+ }
9904
+ }
9905
+ /**
9906
+ * The platform launcher: spawn the file manager and wait only until the
9907
+ * process exists. A missing `open`/`explorer`/`xdg-open` is reported to the
9908
+ * caller instead of being swallowed.
9909
+ */
9910
+ var spawnFileManager = async (target) => {
9911
+ await new Promise((resolve, reject) => {
9912
+ const child = spawn(target.command, target.args, {
9913
+ shell: false,
9914
+ stdio: "ignore",
9915
+ detached: true
9916
+ });
9917
+ child.once("spawn", () => {
9918
+ child.unref();
9919
+ resolve();
9920
+ });
9921
+ child.once("error", reject);
9922
+ });
9923
+ };
9924
+ /**
9925
+ * Open `path` in the host's file manager.
9926
+ *
9927
+ * `roots` are the paths this host is allowed to serve; a path outside them is
9928
+ * refused (`forbidden`), never opened. `launch` is injectable so tests never
9929
+ * spawn a real file manager.
9930
+ */
9931
+ async function revealPath(path, roots, options = {}) {
9932
+ if (path.trim() === "") return {
9933
+ ok: false,
9934
+ reason: "invalid",
9935
+ message: "a path is required"
9936
+ };
9937
+ if (!isAbsolute(path)) return {
9938
+ ok: false,
9939
+ reason: "invalid",
9940
+ message: "the path must be absolute"
9941
+ };
9942
+ const absolute = resolve(path);
9943
+ if (!isServedPath(absolute, roots)) return {
9944
+ ok: false,
9945
+ reason: "forbidden",
9946
+ message: "this path is outside the roots this host serves"
9947
+ };
9948
+ let isDirectory;
9949
+ try {
9950
+ isDirectory = lstatSync(absolute).isDirectory();
9951
+ } catch {
9952
+ return {
9953
+ ok: false,
9954
+ reason: "notFound",
9955
+ message: `no such path: ${absolute}`
9956
+ };
9957
+ }
9958
+ const platform = options.platform ?? hostPlatform();
9959
+ const action = options.action ?? "reveal";
9960
+ if (action === "open" && !isDirectory) return {
9961
+ ok: false,
9962
+ reason: "invalid",
9963
+ message: "only a folder can be opened in the file manager"
9964
+ };
9965
+ let target;
9966
+ try {
9967
+ target = fileManagerTarget(platform, absolute, isDirectory, action);
9968
+ } catch (error) {
9969
+ return {
9970
+ ok: false,
9971
+ reason: "unavailable",
9972
+ message: error instanceof Error ? error.message : "this platform cannot open a file manager"
9973
+ };
9974
+ }
9975
+ try {
9976
+ await (options.launch ?? spawnFileManager)(target);
9977
+ } catch (error) {
9978
+ return {
9979
+ ok: false,
9980
+ reason: "unavailable",
9981
+ message: error instanceof Error ? error.message : "the file manager could not be started"
9982
+ };
9983
+ }
9984
+ return { ok: true };
9985
+ }
9986
+ //#endregion
9987
+ //#region ../../packages/host/src/fs-list.ts
9988
+ /** How many entries a picker shows before it must narrow the filter. */
9989
+ var DEFAULT_LIMIT = 1e3;
9990
+ var MAX_LIMIT = 5e3;
9991
+ /**
9992
+ * Above this many entries the folder is listed without per-entry sizes: a
9993
+ * picker must stay responsive on directories like a browser cache, and the
9994
+ * size of each entry is a nicety, not the point of choosing a folder.
9995
+ */
9996
+ var STAT_BUDGET = 2e4;
9997
+ /** Concurrent `stat` calls; enough to hide latency without a fd storm. */
9998
+ var STAT_CONCURRENCY = 64;
9999
+ function within$1(path, root) {
10000
+ return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
10001
+ }
10002
+ /** `~` means the host's home, as it does everywhere else in this host. */
10003
+ function expandHome(path) {
10004
+ if (path === "~") return homedir();
10005
+ if (path.startsWith("~/") || path.startsWith("~\\")) return `${homedir()}${path.slice(1)}`;
10006
+ return path;
10007
+ }
10008
+ /**
10009
+ * Refuses a path outside the served roots. Containment is checked on the
10010
+ * real path, so a symlink inside a root cannot reach outside it — the same
10011
+ * rule scans apply, which keeps the picker from offering a folder the scan
10012
+ * would then reject. Returns the resolved path and the root that contains
10013
+ * it, so the caller can decide where the breadcrumb stops.
10014
+ */
10015
+ async function containInRoots(path, roots, realRoots) {
10016
+ let resolved;
10017
+ try {
10018
+ resolved = await realpath(path);
10019
+ } catch {
10020
+ throw Problems.notFound(`folder does not exist: ${path}`);
10021
+ }
10022
+ for (const [index, realRoot] of realRoots.entries()) if (within$1(resolved, realRoot)) return {
10023
+ resolved,
10024
+ root: roots[index]
10025
+ };
10026
+ throw Problems.forbidden(`that folder is outside the locations this host serves (${roots.join(", ")})`);
10027
+ }
10028
+ async function entryFor(folder, name, kind, size) {
10029
+ return {
10030
+ name,
10031
+ path: join(folder, name),
10032
+ kind: kind === "dir" || kind === "file" ? kind : "other",
10033
+ size
10034
+ };
10035
+ }
10036
+ /** `stat` a batch in parallel; a failed stat never fails the listing. */
10037
+ async function measured(folder, entries) {
10038
+ const output = new Array(entries.length);
10039
+ let cursor = 0;
10040
+ const worker = async () => {
10041
+ for (;;) {
10042
+ const index = cursor++;
10043
+ if (index >= entries.length) return;
10044
+ const entry = entries[index];
10045
+ const full = join(folder, entry.name);
10046
+ try {
10047
+ const info = await stat(full);
10048
+ const kind = info.isDirectory() ? "dir" : info.isFile() ? "file" : "other";
10049
+ output[index] = await entryFor(folder, entry.name, kind, info.size);
10050
+ } catch {
10051
+ output[index] = await entryFor(folder, entry.name, "other", null);
10052
+ }
10053
+ }
10054
+ };
10055
+ await Promise.all(Array.from({ length: Math.min(STAT_CONCURRENCY, entries.length) }, worker));
10056
+ return output;
10057
+ }
10058
+ /**
10059
+ * Lists one folder inside the served roots for the scan picker.
10060
+ *
10061
+ * Paths in the response stay *logical* (the path the caller asked for plus
10062
+ * the entry name) rather than canonical: on macOS a canonical `/Users/alice`
10063
+ * is `/System/Volumes/Data/Users/alice`, which is not what anyone wants to
10064
+ * read in a breadcrumb. Containment is still decided on the real path, so a
10065
+ * symlink entry that points outside the roots can be seen but not entered —
10066
+ * the next request refuses it.
10067
+ */
10068
+ async function listFolder(request, configuredRoots) {
10069
+ if (configuredRoots.length === 0) throw Problems.unavailable("this host serves no roots");
10070
+ const roots = configuredRoots.map((root) => resolve(root));
10071
+ const realRoots = await Promise.all(roots.map(async (root) => {
10072
+ try {
10073
+ return await realpath(root);
10074
+ } catch {
10075
+ return root;
10076
+ }
10077
+ }));
10078
+ const limit = Math.min(request.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
10079
+ const requested = expandHome(request.path ?? roots[0]);
10080
+ if (!isAbsolute(requested)) throw Problems.invalid("folder paths must be absolute");
10081
+ const folder = resolve(requested);
10082
+ const { resolved, root } = await containInRoots(folder, roots, realRoots);
10083
+ let dirents;
10084
+ try {
10085
+ dirents = await readdir(folder, { withFileTypes: true });
10086
+ } catch (error) {
10087
+ const code = error.code;
10088
+ if (code === "ENOTDIR") throw Problems.invalid("that path is a file, not a folder");
10089
+ if (code === "EACCES" || code === "EPERM") throw Problems.forbidden("permission denied while reading that folder");
10090
+ throw Problems.invalid(`cannot read that folder: ${code ?? "unknown error"}`);
10091
+ }
10092
+ const listed = dirents.map((dirent) => ({
10093
+ name: dirent.name,
10094
+ type: dirent.isDirectory() ? "dir" : dirent.isFile() ? "file" : dirent.isSymbolicLink() ? "link" : "unknown"
10095
+ }));
10096
+ const withSize = listed.length <= STAT_BUDGET;
10097
+ let entries;
10098
+ if (withSize) entries = await measured(folder, listed);
10099
+ else entries = await Promise.all(listed.map(async (entry) => {
10100
+ if (entry.type !== "link") return entryFor(folder, entry.name, entry.type, null);
10101
+ try {
10102
+ const info = await stat(join(folder, entry.name));
10103
+ return entryFor(folder, entry.name, info.isDirectory() ? "dir" : info.isFile() ? "file" : "other", info.size);
10104
+ } catch {
10105
+ return entryFor(folder, entry.name, "other", null);
10106
+ }
10107
+ }));
10108
+ entries.sort((left, right) => {
10109
+ if (left.kind !== right.kind) {
10110
+ if (left.kind === "dir") return -1;
10111
+ if (right.kind === "dir") return 1;
10112
+ }
10113
+ return left.name.localeCompare(right.name, void 0, {
10114
+ numeric: true,
10115
+ sensitivity: "base"
10116
+ });
10117
+ });
10118
+ const logicalParent = dirname(folder);
10119
+ return {
10120
+ path: folder,
10121
+ parent: resolved === realRoots[roots.indexOf(root)] || folder === root || logicalParent === folder ? null : logicalParent,
10122
+ roots,
10123
+ entries: entries.slice(0, limit),
10124
+ truncated: entries.length > limit
10125
+ };
10126
+ }
10127
+ //#endregion
10128
+ //#region ../../packages/host/src/app.ts
10129
+ var EXCHANGE_RATE_LIMIT = 10;
10130
+ var EXCHANGE_RATE_WINDOW_MS = 6e4;
10131
+ function frame(event, id, data) {
10132
+ return `retry: 3000\nevent: ${event}\nid: ${id}\ndata: ${JSON.stringify(data)}\n\n`;
10133
+ }
10134
+ function jsonResponse(payload, status, extraHeaders) {
10135
+ return new Response(JSON.stringify(payload), {
10136
+ status,
10137
+ headers: {
10138
+ "content-type": "application/json; charset=utf-8",
10139
+ ...extraHeaders
10140
+ }
10141
+ });
10142
+ }
10143
+ function buildApp(deps) {
10144
+ const app = new Hono();
10145
+ const { config, auth, scans, events, assets, health, capabilities, allowlist, localScanBin, memory } = deps;
10146
+ let activeAppAudits = 0;
10147
+ const MAX_CONCURRENT_APP_AUDITS = 2;
10148
+ let policy = {
10149
+ authorities: authoritiesFor(config.bind.address, config.port),
10150
+ allowedOrigins: [...config.uiOrigins]
10151
+ };
10152
+ app.rebindGate = (port) => {
10153
+ const authorities = authoritiesFor(config.bind.address, port);
10154
+ policy = {
10155
+ authorities,
10156
+ allowedOrigins: [...originsForAuthorities(authorities), ...config.uiOrigins]
10157
+ };
10158
+ };
10159
+ app.admitPairingOrigin = (origin) => {
10160
+ const authority = origin.replace(/^http:\/\//, "");
10161
+ if (!policy.authorities.includes(authority)) policy = {
10162
+ ...policy,
10163
+ authorities: [...policy.authorities, authority]
10164
+ };
10165
+ if (!policy.allowedOrigins.includes(origin)) policy = {
10166
+ ...policy,
10167
+ allowedOrigins: [...policy.allowedOrigins, origin]
10168
+ };
10169
+ };
10170
+ const remoteAddress = (c) => {
10171
+ const forwarded = c.req.header("x-forwarded-for");
10172
+ if (forwarded !== void 0 && config.trustProxy) {
10173
+ const first = forwarded.split(",")[0]?.trim();
10174
+ if (first) return first;
10175
+ }
10176
+ return c.env?.incoming?.socket?.remoteAddress ?? null;
10177
+ };
10178
+ const corsHeadersFor = (origin) => {
10179
+ if (origin === null || !config.uiOrigins.includes(origin)) return {};
10180
+ return {
10181
+ "access-control-allow-origin": origin,
10182
+ "access-control-allow-methods": "GET, POST, OPTIONS",
10183
+ "access-control-allow-headers": "Authorization, Content-Type",
10184
+ vary: "Origin"
10185
+ };
10186
+ };
10187
+ app.use("*", async (c, next) => {
10188
+ const origin = c.req.header("origin") ?? null;
10189
+ for (const [name, value] of Object.entries(corsHeadersFor(origin))) c.header(name, value);
10190
+ const remote = remoteAddress(c);
10191
+ if (remote !== null && !allowlist.check(remote)) throw Problems.forbidden(`client address ${normalizeRemoteAddress(remote)} is not in the allowed networks`);
10192
+ const verdict = checkOrigin({
10193
+ hostHeader: c.req.header("host") ?? null,
10194
+ origin,
10195
+ secFetchSite: c.req.header("sec-fetch-site") ?? null,
10196
+ secFetchMode: c.req.header("sec-fetch-mode") ?? null
10197
+ }, policy);
10198
+ if (verdict !== "ok") {
10199
+ if (verdict === "refused-host") throw new ProblemError({
10200
+ code: "InvalidRequest",
10201
+ message: "request is not addressed to this service (Host header refused)",
10202
+ retryable: false
10203
+ }, 400);
10204
+ if (verdict === "refused-origin") throw Problems.forbidden("request origin is not allowed");
10205
+ throw Problems.forbidden("cross-site requests without a matching origin are refused");
10206
+ }
10207
+ await next();
10208
+ });
10209
+ app.get("/health", (c) => c.json(health));
10210
+ const exchangeAttempts = /* @__PURE__ */ new Map();
10211
+ app.post("/api/v1/session/exchange", async (c) => {
10212
+ const origin = c.req.header("origin") ?? "";
10213
+ const key = `${origin}|${remoteAddress(c) ?? ""}`;
10214
+ const now = Date.now();
10215
+ const bucket = exchangeAttempts.get(key);
10216
+ if (bucket === void 0 || bucket.resetAt <= now) {
10217
+ if (exchangeAttempts.size > 4096) exchangeAttempts.clear();
10218
+ exchangeAttempts.set(key, {
10219
+ count: 1,
10220
+ resetAt: now + EXCHANGE_RATE_WINDOW_MS
10221
+ });
10222
+ } else {
10223
+ bucket.count += 1;
10224
+ if (bucket.count > EXCHANGE_RATE_LIMIT) throw Problems.limit("too many pairing attempts; wait a minute");
10225
+ }
10226
+ const raw = await c.req.json().catch(() => void 0);
10227
+ const parsed = SessionExchangeRequestSchema.safeParse(raw);
10228
+ if (!parsed.success) throw Problems.invalid("malformed pairing request");
10229
+ const result = auth.exchange(parsed.data.ticket, {
10230
+ origin: origin === "" ? null : origin,
10231
+ password: parsed.data.password
8330
10232
  });
8331
10233
  if (!result.ok) throw Problems.unauthenticated("ticket rejected (unknown, expired, origin-bound, or wrong password)");
8332
10234
  const session = {
@@ -8341,6 +10243,21 @@ function buildApp(deps) {
8341
10243
  });
8342
10244
  return c.json(session);
8343
10245
  });
10246
+ app.post("/api/v1/session/dev", (c) => {
10247
+ if (!config.devOpenSession) throw Problems.unavailable("dev sessions are off; pair with the ticket printed by spacelens serve");
10248
+ const minted = auth.mintSession();
10249
+ const session = {
10250
+ token: minted.token,
10251
+ sessionId: minted.sessionId,
10252
+ expiresAt: new Date(minted.expiresAtMs).toISOString(),
10253
+ scopes: [...minted.scopes]
10254
+ };
10255
+ events.publish({
10256
+ kind: "session",
10257
+ expiresAt: session.expiresAt
10258
+ });
10259
+ return c.json(session);
10260
+ });
8344
10261
  app.use("/api/*", async (c, next) => {
8345
10262
  const session = auth.authorize(c.req.header("authorization"));
8346
10263
  if (session === null) throw Problems.unauthenticated("a valid bearer token is required");
@@ -8360,23 +10277,62 @@ function buildApp(deps) {
8360
10277
  if (!ScanIdSchema.safeParse(value).success) throw Problems.invalid(`invalid ${what}`);
8361
10278
  return value;
8362
10279
  };
10280
+ app.post("/api/v1/session/ticket", async (c) => {
10281
+ const request = await parseBody(c, BrowserTicketRequestSchema);
10282
+ app.admitPairingOrigin(request.origin);
10283
+ const ticket = auth.mintTicket(request.origin, config.hostedPassword !== null);
10284
+ return c.json({
10285
+ ticket,
10286
+ url: `${request.origin}/?pair=${ticket}`
10287
+ });
10288
+ });
8363
10289
  app.get("/api/v1/capabilities", (c) => {
8364
10290
  ensureScope(c.get("session"), "scan:read");
8365
10291
  return c.json(capabilities);
8366
10292
  });
8367
- /** Preset scan targets: exactly the roots this host was configured with. */
8368
- app.get("/api/v1/roots", (c) => {
10293
+ /**
10294
+ * Preset scan targets: exactly the roots this host was configured with.
10295
+ * Capacity comes from one `df` call so the picker can show used/free
10296
+ * before any scan runs; roots `df` cannot report keep size 0 and no
10297
+ * `used`, which the UI renders as "unknown".
10298
+ */
10299
+ app.get("/api/v1/roots", async (c) => {
10300
+ ensureScope(c.get("session"), "scan:read");
10301
+ const capacities = await volumeCapacities(config.roots);
10302
+ return c.json({ roots: config.roots.map((rootPath, index) => {
10303
+ const capacity = capacities.get(rootPath);
10304
+ return {
10305
+ id: `root_${index}`,
10306
+ label: basename(rootPath) || rootPath,
10307
+ path: rootPath,
10308
+ kind: "folder",
10309
+ description: "",
10310
+ size: capacity?.totalBytes ?? 0,
10311
+ ...capacity ? { used: capacity.usedBytes } : {},
10312
+ source: "preset",
10313
+ removable: false
10314
+ };
10315
+ }) });
10316
+ });
10317
+ /**
10318
+ * Mounted volumes with capacity, for the pre-scan "all my drives" list.
10319
+ * Display-only: mount points are facts, not scan targets — the picker
10320
+ * offers a scan only for paths inside the host's configured roots.
10321
+ */
10322
+ app.get("/api/v1/volumes", async (c) => {
8369
10323
  ensureScope(c.get("session"), "scan:read");
8370
- return c.json({ roots: config.roots.map((rootPath, index) => ({
8371
- id: `root_${index}`,
8372
- label: basename(rootPath) || rootPath,
8373
- path: rootPath,
8374
- kind: "folder",
8375
- description: "",
8376
- size: 0,
8377
- source: "preset",
8378
- removable: false
8379
- })) });
10324
+ return c.json({ volumes: await mountedVolumes() });
10325
+ });
10326
+ /**
10327
+ * One folder inside the served roots, for the scan picker's browse mode.
10328
+ * Read only and never recursive: the picker drills one level at a time so
10329
+ * a browser (or a remote workbench over SSH) can choose a folder it cannot
10330
+ * see, instead of typing an absolute path and hoping.
10331
+ */
10332
+ app.post("/api/v1/fs/list", async (c) => {
10333
+ ensureScope(c.get("session"), "scan:read");
10334
+ const request = await parseBody(c, FsListRequestSchema);
10335
+ return c.json(await listFolder(request, config.roots));
8380
10336
  });
8381
10337
  app.post("/api/v1/scans", async (c) => {
8382
10338
  ensureScope(c.get("session"), "scan:start");
@@ -8421,6 +10377,162 @@ function buildApp(deps) {
8421
10377
  const request = await parseBody(c, CleanupExecuteRequestSchema);
8422
10378
  return c.json(await scans.execute(request.planId));
8423
10379
  });
10380
+ app.post("/api/v1/apps/audit", async (c) => {
10381
+ ensureScope(c.get("session"), "scan:read");
10382
+ if (activeAppAudits >= MAX_CONCURRENT_APP_AUDITS) throw Problems.limit("app audit is busy; try again shortly");
10383
+ const request = await parseBody(c, AppAuditRequestSchema);
10384
+ const binary = resolveLocalScanBin(localScanBin);
10385
+ activeAppAudits += 1;
10386
+ try {
10387
+ let raw;
10388
+ try {
10389
+ raw = await runAppAuditCli({
10390
+ binary,
10391
+ request,
10392
+ homeOverride: config.appAuditHome
10393
+ });
10394
+ } catch (error) {
10395
+ throw Problems.internal(`app audit failed: ${error instanceof Error ? error.message.slice(0, 500) : String(error)}`);
10396
+ }
10397
+ const parsed = AppAuditReportSchema.safeParse(raw);
10398
+ if (!parsed.success) throw Problems.internal("app audit returned an unexpected report shape");
10399
+ return c.json(parsed.data);
10400
+ } finally {
10401
+ activeAppAudits -= 1;
10402
+ }
10403
+ });
10404
+ app.post("/api/v1/apps/icon", async (c) => {
10405
+ ensureScope(c.get("session"), "scan:read");
10406
+ const body = await parseBody(c, AppIconRequestSchema);
10407
+ const binary = resolveLocalScanBin(localScanBin);
10408
+ try {
10409
+ return c.json(await runAppIconCli(binary, body.appPath));
10410
+ } catch (error) {
10411
+ if (error instanceof ProblemError) throw error;
10412
+ throw Problems.notFound("no icon available for this app");
10413
+ }
10414
+ });
10415
+ app.post("/api/v1/host/reveal", async (c) => {
10416
+ ensureScope(c.get("session"), "host:reveal");
10417
+ const request = await parseBody(c, RevealPathRequestSchema);
10418
+ const outcome = await revealPath(request.path, config.roots, {
10419
+ launch: deps.revealLauncher,
10420
+ action: request.action ?? "reveal"
10421
+ });
10422
+ if (!outcome.ok) {
10423
+ if (outcome.reason === "invalid") throw Problems.invalid(outcome.message);
10424
+ if (outcome.reason === "forbidden") throw Problems.forbidden(outcome.message);
10425
+ if (outcome.reason === "notFound") throw Problems.notFound(outcome.message);
10426
+ throw Problems.unavailable(outcome.message);
10427
+ }
10428
+ return c.json({ revealed: true });
10429
+ });
10430
+ const requireAi = () => {
10431
+ if (config.ai === null) throw Problems.unavailable("this host has no AI advisor configured (start it with --ai-base-url and --ai-model)", false);
10432
+ return config.ai;
10433
+ };
10434
+ app.get("/api/v1/ai/config", (c) => {
10435
+ const ai = requireAi();
10436
+ ensureScope(c.get("session"), "ai:chat");
10437
+ const view = {
10438
+ baseUrl: ai.baseUrl,
10439
+ model: ai.model,
10440
+ hasKey: ai.apiKey !== null,
10441
+ disableThinking: ai.disableThinking,
10442
+ managed: true
10443
+ };
10444
+ return c.json(view);
10445
+ });
10446
+ app.post("/api/v1/ai/chat", async (c) => {
10447
+ const ai = requireAi();
10448
+ ensureScope(c.get("session"), "ai:chat");
10449
+ const request = await parseBody(c, AiChatRequestSchema);
10450
+ const forwarded = {
10451
+ endpoint: ai.endpoint,
10452
+ model: ai.model,
10453
+ apiKey: ai.apiKey,
10454
+ disableThinking: ai.disableThinking,
10455
+ messages: request.messages,
10456
+ tools: request.tools
10457
+ };
10458
+ if (request.stream === true) {
10459
+ const stream = await forwardChatStream({
10460
+ ...forwarded,
10461
+ signal: c.req.raw.signal
10462
+ });
10463
+ return new Response(stream, {
10464
+ status: 200,
10465
+ headers: {
10466
+ "content-type": "text/event-stream",
10467
+ "cache-control": "no-store",
10468
+ "x-accel-buffering": "no"
10469
+ }
10470
+ });
10471
+ }
10472
+ return c.json(await forwardChatCompletion(forwarded));
10473
+ });
10474
+ const requireMemory = () => {
10475
+ if (memory === void 0) throw Problems.unavailable("this host does not have the memory view enabled (start it with --allow-memory)", false);
10476
+ return memory;
10477
+ };
10478
+ /** Feature gate first, then scope, so a disabled feature never leaks scope state. */
10479
+ const memoryGate = (session, scope) => {
10480
+ const bridge = requireMemory();
10481
+ ensureScope(session, scope);
10482
+ return bridge;
10483
+ };
10484
+ /** Re-validate one child reply; anything off-contract becomes InternalError. */
10485
+ const parseMemoryReply = (raw, schema) => {
10486
+ const parsed = schema.safeParse(raw);
10487
+ if (!parsed.success || parsed.data === void 0) throw Problems.internal("the memory process returned a reply that does not satisfy the contract");
10488
+ return parsed.data;
10489
+ };
10490
+ app.get("/api/v1/memory/snapshot", async (c) => {
10491
+ const session = c.get("session");
10492
+ const bridge = memoryGate(session, "memory:read");
10493
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, { method: "snapshot" }), MemorySnapshotSchema));
10494
+ });
10495
+ app.post("/api/v1/memory/history", async (c) => {
10496
+ const session = c.get("session");
10497
+ const bridge = memoryGate(session, "memory:read");
10498
+ const call = {
10499
+ method: "history",
10500
+ request: await parseBody(c, HistoryRequestSchema)
10501
+ };
10502
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, call), MemoryHistorySchema));
10503
+ });
10504
+ app.post("/api/v1/memory/candidates", async (c) => {
10505
+ const session = c.get("session");
10506
+ const bridge = memoryGate(session, "memory:read");
10507
+ const call = {
10508
+ method: "candidates",
10509
+ request: await parseBody(c, CandidatesRequestSchema)
10510
+ };
10511
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, call), FreeUpCandidatesSchema));
10512
+ });
10513
+ app.get("/api/v1/memory/audit", async (c) => {
10514
+ const session = c.get("session");
10515
+ const bridge = memoryGate(session, "memory:read");
10516
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, { method: "audit" }), AuditLogSchema));
10517
+ });
10518
+ app.post("/api/v1/memory/terminate/plan", async (c) => {
10519
+ const session = c.get("session");
10520
+ const bridge = memoryGate(session, "memory:terminate");
10521
+ const call = {
10522
+ method: "plan",
10523
+ request: await parseBody(c, TerminatePlanRequestSchema)
10524
+ };
10525
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, call), TerminatePlanSchema));
10526
+ });
10527
+ app.post("/api/v1/memory/terminate/execute", async (c) => {
10528
+ const session = c.get("session");
10529
+ const bridge = memoryGate(session, "memory:terminate");
10530
+ const call = {
10531
+ method: "execute",
10532
+ request: await parseBody(c, TerminateExecuteRequestSchema)
10533
+ };
10534
+ return c.json(parseMemoryReply(await bridge.call(session.sessionId, call), TerminateOutcomeSchema));
10535
+ });
8424
10536
  app.get("/api/v1/events", (c) => {
8425
10537
  ensureScope(c.get("session"), "scan:read");
8426
10538
  const since = Number.parseInt(c.req.query("since") ?? "0", 10);
@@ -8574,6 +10686,39 @@ function isLoopbackOrigin(origin) {
8574
10686
  return false;
8575
10687
  }
8576
10688
  }
10689
+ /**
10690
+ * Validates and resolves the operator AI advisor config. A malformed base URL
10691
+ * is a startup failure (`ConfigError`), not a request-time surprise: the same
10692
+ * guard the request path uses is applied here.
10693
+ *
10694
+ * The key is tri-state: `apiKey` string wins, `apiKey: null` means explicitly
10695
+ * none, and an omitted/empty `apiKey` falls back to {@link AI_API_KEY_ENV}.
10696
+ */
10697
+ function resolveAiConfig(options) {
10698
+ if (options === void 0) return null;
10699
+ const baseUrl = options.baseUrl.trim();
10700
+ let endpoint;
10701
+ try {
10702
+ endpoint = chatEndpoint(baseUrl);
10703
+ } catch (error) {
10704
+ throw new ConfigError(error instanceof Error ? error.message : String(error));
10705
+ }
10706
+ const model = options.model.trim();
10707
+ if (model === "") throw new ConfigError("the AI model must not be empty");
10708
+ const envKey = process.env["SPACLENS_AI_API_KEY"]?.trim() ?? "";
10709
+ const optionKey = options.apiKey?.trim() ?? "";
10710
+ let apiKey;
10711
+ if (options.apiKey === null) apiKey = null;
10712
+ else if (optionKey !== "") apiKey = optionKey;
10713
+ else apiKey = envKey !== "" ? envKey : null;
10714
+ return {
10715
+ endpoint,
10716
+ baseUrl,
10717
+ model,
10718
+ apiKey,
10719
+ disableThinking: options.disableThinking ?? false
10720
+ };
10721
+ }
8577
10722
  function parsePort(port) {
8578
10723
  if (port === void 0) return DEFAULT_PORT;
8579
10724
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new ConfigError(`--port must be an integer between 0 and 65535: ${port}`);
@@ -8605,7 +10750,13 @@ function resolveServeConfig(options) {
8605
10750
  if (!bind.loopback && allowCidr.length === 0 && !allowLan) throw new ConfigError(`binding ${bind.display} exposes the server beyond this machine; pass --allow-cidr <cidr> (repeatable) to name the allowed networks, or --allow-lan to accept any client explicitly`);
8606
10751
  const hostedPassword = (typeof options.hostedPassword === "string" ? options.hostedPassword.trim() : null) ?? (process.env["SPACLENS_HOSTED_PASSWORD"]?.trim() || null);
8607
10752
  if (uiOrigins.some((origin) => !isLoopbackOrigin(origin)) && hostedPassword === null) throw new ConfigError(`a non-loopback --ui-origin requires ${HOSTED_PASSWORD_ENV} in the environment; a ticket alone must never unlock a hosted UI`);
8608
- const roots = [...options.roots ?? [process.cwd()]].map((root) => root.startsWith("/") ? root : `${process.cwd()}/${root}`);
10753
+ const allowMemory = options.allowMemory ?? false;
10754
+ const allowProcessControl = options.allowProcessControl ?? false;
10755
+ if (allowProcessControl && !allowMemory) throw new ConfigError("--allow-process-control requires --allow-memory (there is no view to act from otherwise)");
10756
+ if (allowProcessControl && (!bind.loopback || uiOrigins.some((origin) => !isLoopbackOrigin(origin)))) throw new ConfigError("--allow-process-control requires a loopback bind and loopback-only --ui-origin values; quitting processes is never exposed to other machines");
10757
+ const devOpenSession = options.devOpenSession ?? false;
10758
+ if (devOpenSession && !bind.loopback) throw new ConfigError("--dev-open-session requires a loopback bind; a session without a pairing ticket must never be reachable from another machine");
10759
+ const roots = [...options.roots ?? [process.cwd()]].map((root) => isAbsolute(root) ? resolve(root) : resolve(process.cwd(), root));
8609
10760
  return {
8610
10761
  bind,
8611
10762
  port,
@@ -8613,6 +10764,9 @@ function resolveServeConfig(options) {
8613
10764
  allowCidr,
8614
10765
  allowLan,
8615
10766
  allowCleanup: options.allowCleanup ?? false,
10767
+ allowMemory,
10768
+ allowProcessControl,
10769
+ devOpenSession,
8616
10770
  uiOrigins,
8617
10771
  ticketTtlMs: (options.ticketTtlSeconds ?? 60) * 1e3,
8618
10772
  sessionTtlMs: (options.sessionTtlSeconds ?? 28800) * 1e3,
@@ -8625,7 +10779,9 @@ function resolveServeConfig(options) {
8625
10779
  trustProxy: options.trustProxy ?? false,
8626
10780
  maxConcurrentScans: options.maxConcurrentScans ?? 4,
8627
10781
  maxTotalScans: options.maxTotalScans ?? 8,
8628
- frameAncestors: [...options.frameAncestors ?? ["'none'"]]
10782
+ frameAncestors: [...options.frameAncestors ?? ["'none'"]],
10783
+ appAuditHome: options.appAuditHome ?? null,
10784
+ ai: resolveAiConfig(options.ai)
8629
10785
  };
8630
10786
  }
8631
10787
  //#endregion
@@ -8669,446 +10825,269 @@ var EventRing = class {
8669
10825
  if (oldest !== void 0) this.bytes -= JSON.stringify(oldest).length;
8670
10826
  }
8671
10827
  while (this.events.length > this.maxEvents) {
8672
- const oldest = this.events.shift();
8673
- if (oldest !== void 0) this.bytes -= JSON.stringify(oldest).length;
8674
- }
8675
- for (const listener of this.listeners) try {
8676
- listener(envelope);
8677
- } catch {}
8678
- return envelope;
8679
- }
8680
- replay(since) {
8681
- const events = this.events.filter((envelope) => envelope.sequence > since);
8682
- let gap = null;
8683
- if (since > 0 && this.events.length > 0) {
8684
- const oldest = this.events[0].sequence;
8685
- if (since < oldest - 1) gap = {
8686
- fromSequence: since + 1,
8687
- toSequence: oldest - 1
8688
- };
8689
- }
8690
- return {
8691
- events,
8692
- gap
8693
- };
8694
- }
8695
- subscribe(listener) {
8696
- this.listeners.add(listener);
8697
- return () => this.listeners.delete(listener);
8698
- }
8699
- get highWatermark() {
8700
- return this.sequence;
8701
- }
8702
- get droppedCount() {
8703
- return this.dropped;
8704
- }
8705
- };
8706
- //#endregion
8707
- //#region ../../packages/host/src/discovery.ts
8708
- /**
8709
- * Plain JavaScript source is embedded deliberately: serializing transpiled
8710
- * functions captures loader/bundler helpers (for example tsx keepNames), which
8711
- * are unavailable in an isolated worker. This also keeps bundled hosts free
8712
- * of a separate worker file that would need to be copied beside the bundle.
8713
- */
8714
- var DISCOVERY_BOOTSTRAP = `
8715
- /** Self-contained so its compiled function can run inside the scan worker. */
8716
- function inspectDiscovery(engine, fs, path, crypto, roots) {
8717
- const within = (candidate, root) =>
8718
- candidate === root || candidate.startsWith(root.endsWith(path.sep) ? root : \`\${root}\${path.sep}\`)
8719
- const idOf = (value) => crypto.createHash('sha1').update(value).digest('hex').slice(0, 24)
8720
- const safeStat = (value) => {
8721
- try {
8722
- const stats = fs.lstatSync(value)
8723
- if (stats.isSymbolicLink() || fs.realpathSync(value) !== value || !roots.some((root) => within(value, root)))
8724
- return null
8725
- return stats
8726
- } catch {
8727
- return null
8728
- }
8729
- }
8730
- const tree = engine.scanDirectory({
8731
- directories: roots,
8732
- fullPath: true,
8733
- ignoreHidden: false,
8734
- respectGitignore: false,
8735
- followSymlinks: false,
8736
- })
8737
- const ignoredTree = engine.scanDirectory({
8738
- directories: roots,
8739
- fullPath: true,
8740
- ignoreHidden: false,
8741
- respectGitignore: true,
8742
- ignoredMode: 'summarize',
8743
- followSymlinks: false,
8744
- })
8745
- const ignoredPaths = []
8746
- const collectIgnored = (node) => {
8747
- if (node.ignored) ignoredPaths.push(node.path)
8748
- else for (const child of node.children) collectIgnored(child)
8749
- }
8750
- for (const root of ignoredTree) collectIgnored(root)
8751
- const ignoredSet = new Set(ignoredPaths)
8752
- const isIgnored = (value) => {
8753
- let cursor = value
8754
- for (;;) {
8755
- if (ignoredSet.has(cursor)) return true
8756
- const parent = path.dirname(cursor)
8757
- if (parent === cursor) return false
8758
- cursor = parent
8759
- }
8760
- }
8761
- const entries = []
8762
- const byPath = new Map()
8763
- const directories = new Set()
8764
- const regularFiles = new Set()
8765
- const walk = (node, parent, depth) => {
8766
- const stats = safeStat(node.path)
8767
- if (stats === null) return null
8768
- const id = idOf(node.path)
8769
- const entry = {
8770
- id,
8771
- node: { ...node, children: [], ignored: isIgnored(node.path) },
8772
- parent,
8773
- depth,
8774
- childIds: [],
8775
- fingerprint: { size: stats.size, mtimeMs: stats.mtimeMs },
8776
- }
8777
- entries.push(entry)
8778
- byPath.set(node.path, entry)
8779
- if (stats.isDirectory()) directories.add(node.path)
8780
- if (stats.isFile()) regularFiles.add(node.path)
8781
- entry.childIds = node.children.map((child) => walk(child, id, depth + 1)).filter((id) => id !== null)
8782
- return id
8783
- }
8784
- for (const root of tree) walk(root, null, 0)
8785
- const summary = (entry) => ({
8786
- id: entry.id,
8787
- name: path.basename(entry.node.path),
8788
- path: entry.node.path,
8789
- size: entry.node.size,
8790
- depth: entry.depth,
8791
- ignored: entry.node.ignored,
8792
- collapsed: false,
8793
- hasChildren: entry.childIds.length > 0,
8794
- childCount: entry.childIds.length,
8795
- })
8796
- const item = (entry, category) => ({
8797
- node: summary(entry),
8798
- parentId: entry.parent,
8799
- category,
8800
- isDirectory: directories.has(entry.node.path),
8801
- })
8802
- const hasFile = (directory, name) => safeStat(path.join(directory, name))?.isFile() === true
8803
- const pythonEnvironment = (value) => {
8804
- let cursor = path.dirname(value)
8805
- for (;;) {
8806
- if (['.venv', 'venv', 'env'].includes(path.basename(cursor)) || hasFile(cursor, 'pyvenv.cfg')) return true
8807
- if (roots.includes(cursor)) return false
8808
- const parent = path.dirname(cursor)
8809
- if (parent === cursor) return false
8810
- cursor = parent
8811
- }
8812
- }
8813
- const pythonCategories = new Map([
8814
- ['__pycache__', 'Python bytecode'],
8815
- ['.pytest_cache', 'pytest cache'],
8816
- ['.mypy_cache', 'mypy cache'],
8817
- ['.ruff_cache', 'Ruff cache'],
8818
- ])
8819
- const jsNames = new Set(['.next', '.nuxt', '.turbo', '.parcel-cache', '.svelte-kit'])
8820
- const cacheCategory = (entry) => {
8821
- const value = entry.node.path
8822
- if (!directories.has(value) || entry.parent === null) return null
8823
- const name = path.basename(value)
8824
- if (name !== 'node_modules' && name !== 'target' && !pythonCategories.has(name) && !jsNames.has(name)) return null
8825
- if (pythonEnvironment(value)) return null
8826
- const parent = path.dirname(value)
8827
- if (name === 'node_modules' && hasFile(parent, 'package.json')) return 'Node dependencies'
8828
- if (name === 'target' && hasFile(parent, 'Cargo.toml')) return 'Rust build output'
8829
- if (pythonCategories.has(name)) return pythonCategories.get(name)
8830
- if (jsNames.has(name) && hasFile(parent, 'package.json')) return 'JavaScript build cache'
8831
- return null
8832
- }
8833
- const prune = (items) => {
8834
- const sorted = items.sort(
8835
- (a, b) => a.node.path.length - b.node.path.length || a.node.path.localeCompare(b.node.path),
8836
- )
8837
- const kept = []
8838
- const keptPaths = new Set()
8839
- const keptDirectories = new Set()
8840
- for (const candidate of sorted) {
8841
- if (keptPaths.has(candidate.node.path)) continue
8842
- let cursor = path.dirname(candidate.node.path)
8843
- let nested = false
8844
- for (;;) {
8845
- if (keptDirectories.has(cursor)) {
8846
- nested = true
8847
- break
8848
- }
8849
- const parent = path.dirname(cursor)
8850
- if (parent === cursor) break
8851
- cursor = parent
8852
- }
8853
- if (nested) continue
8854
- kept.push(candidate)
8855
- keptPaths.add(candidate.node.path)
8856
- if (candidate.isDirectory) keptDirectories.add(candidate.node.path)
8857
- }
8858
- return kept
8859
- }
8860
- const caches = []
8861
- const files = []
8862
- for (const entry of entries) {
8863
- if (regularFiles.has(entry.node.path)) files.push(item(entry, 'Large file'))
8864
- const category = cacheCategory(entry)
8865
- if (category !== null) caches.push(item(entry, category))
8866
- }
8867
- const ignored = ignoredPaths
8868
- .map((value) => byPath.get(value))
8869
- .filter((entry) => entry !== undefined)
8870
- .filter((entry) => entry.parent !== null)
8871
- .map((entry) => item(entry, 'Gitignored'))
8872
- const items = { 'large-files': files, caches: prune(caches), gitignored: prune(ignored) }
8873
- const cumulativeSizes = {}
8874
- for (const kind of Object.keys(items)) {
8875
- items[kind].sort((a, b) => b.node.size - a.node.size || a.node.path.localeCompare(b.node.path))
8876
- const sums = [0]
8877
- for (const candidate of items[kind]) sums.push(sums[sums.length - 1] + candidate.node.size)
8878
- cumulativeSizes[kind] = sums
8879
- }
8880
- return { entries, items, cumulativeSizes }
8881
- }
8882
-
8883
- ;(async () => {
8884
- const { parentPort, workerData } = await import('node:worker_threads')
8885
- try {
8886
- const loaded = await import(workerData.enginePath)
8887
- const result = inspectDiscovery(
8888
- loaded.default ?? loaded,
8889
- await import('node:fs'),
8890
- await import('node:path'),
8891
- await import('node:crypto'),
8892
- workerData.roots,
8893
- )
8894
- parentPort.postMessage({ type: 'done', result })
8895
- } catch (error) {
8896
- parentPort.postMessage({ type: 'error', message: String(error && error.message ? error.message : error) })
8897
- }
8898
- })()
8899
- `;
8900
- //#endregion
8901
- //#region ../../packages/host/src/local-process.ts
8902
- var LOCAL_SCAN_BIN_ENV = "SPACLENS_LOCAL_SCAN_BIN";
8903
- var MAX_LINE_BYTES = 536870912;
8904
- var MAX_NODE_LINE_BYTES = 1048576;
8905
- /** Only executable artifacts are probed here, never scan targets. */
8906
- function resolveLocalScanBin(explicit) {
8907
- const configured = explicit ?? process.env["SPACLENS_LOCAL_SCAN_BIN"];
8908
- const valid = (candidate) => {
8909
- try {
8910
- accessSync(candidate, constants.X_OK);
8911
- return true;
8912
- } catch {
8913
- return false;
8914
- }
8915
- };
8916
- if (configured !== void 0) {
8917
- if (!isAbsolute(configured) || !valid(configured)) throw Problems.unavailable(`${LOCAL_SCAN_BIN_ENV} must name an existing absolute executable; protected scans never fall back`);
8918
- return configured;
10828
+ const oldest = this.events.shift();
10829
+ if (oldest !== void 0) this.bytes -= JSON.stringify(oldest).length;
10830
+ }
10831
+ for (const listener of this.listeners) try {
10832
+ listener(envelope);
10833
+ } catch {}
10834
+ return envelope;
8919
10835
  }
8920
- const candidates = /* @__PURE__ */ new Set();
8921
- for (const origin of [
8922
- process.cwd(),
8923
- dirname(fileURLToPath(import.meta.url)),
8924
- dirname(process.execPath)
8925
- ]) {
8926
- let cursor = resolve(origin);
8927
- for (;;) {
8928
- candidates.add(join(cursor, "target", "release", process.platform === "win32" ? "spacelens.exe" : "spacelens"));
8929
- const parent = dirname(cursor);
8930
- if (parent === cursor) break;
8931
- cursor = parent;
10836
+ replay(since) {
10837
+ const events = this.events.filter((envelope) => envelope.sequence > since);
10838
+ let gap = null;
10839
+ if (since > 0 && this.events.length > 0) {
10840
+ const oldest = this.events[0].sequence;
10841
+ if (since < oldest - 1) gap = {
10842
+ fromSequence: since + 1,
10843
+ toSequence: oldest - 1
10844
+ };
8932
10845
  }
10846
+ return {
10847
+ events,
10848
+ gap
10849
+ };
8933
10850
  }
8934
- for (const candidate of candidates) if (valid(candidate)) return candidate;
8935
- throw Problems.unavailable(`protected release scanner not found; build target/release/spacelens or set ${LOCAL_SCAN_BIN_ENV}; no legacy fallback`);
8936
- }
8937
- function spawnLocalScan(binary, paths, request, onProgress) {
8938
- const args = [
8939
- "scan",
8940
- ...paths,
8941
- "--local-only",
8942
- "--json",
8943
- "--progress-json",
8944
- "--stream-nodes",
8945
- "--respect-gitignore",
8946
- String(request.respectGitignore),
8947
- "--ignored-mode",
8948
- request.ignoredMode,
8949
- ...request.ignoreHidden ? ["--ignore-hidden"] : []
8950
- ];
8951
- const child = spawn(binary, args, {
8952
- shell: false,
8953
- stdio: [
8954
- "pipe",
8955
- "pipe",
8956
- "pipe"
8957
- ],
8958
- windowsHide: true
8959
- });
8960
- child.stdin.end();
8961
- let killTimer;
8962
- let ignoreOutput = false;
8963
- let discardPending = () => {};
8964
- let discardTree = () => {};
8965
- const terminate = () => {
8966
- ignoreOutput = true;
8967
- discardPending();
8968
- discardTree();
8969
- if (child.exitCode !== null || child.signalCode !== null) return;
8970
- child.kill("SIGTERM");
8971
- killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2e3);
8972
- killTimer.unref();
8973
- };
10851
+ subscribe(listener) {
10852
+ this.listeners.add(listener);
10853
+ return () => this.listeners.delete(listener);
10854
+ }
10855
+ get highWatermark() {
10856
+ return this.sequence;
10857
+ }
10858
+ get droppedCount() {
10859
+ return this.dropped;
10860
+ }
10861
+ };
10862
+ //#endregion
10863
+ //#region ../../packages/host/src/discovery.ts
10864
+ function snapshotView(snapshot) {
8974
10865
  return {
8975
- child,
8976
- done: new Promise((resolveDone, rejectDone) => {
8977
- let parts = [];
8978
- let pendingBytes = 0;
8979
- let header = "";
8980
- discardPending = () => {
8981
- parts = [];
8982
- pendingBytes = 0;
8983
- header = "";
8984
- };
8985
- let stderr = Buffer.alloc(0);
8986
- let report = null;
8987
- let roots = [];
8988
- const seenPaths = /* @__PURE__ */ new Set();
8989
- const parents = /* @__PURE__ */ new Map();
8990
- const ancestors = [];
8991
- let streamed = false;
8992
- discardTree = () => {
8993
- roots = [];
8994
- seenPaths.clear();
8995
- parents.clear();
8996
- ancestors.length = 0;
8997
- report = null;
8998
- };
8999
- let failure = null;
9000
- const fail = (message) => {
9001
- failure ??= new Error(message);
9002
- terminate();
9003
- };
9004
- const attach = (node) => {
9005
- if (!isAbsolute(node.path) || resolve(node.path) !== node.path || seenPaths.has(node.path)) throw new Error("stream node path is non-absolute, unnormalized, or duplicated");
9006
- const cloud = /\/Library\/(?:CloudStorage|Mobile Documents)(?=\/|$)|\/Volumes\/GoogleDrive(?=\/|$)/.exec(node.path);
9007
- if (cloud !== null) {
9008
- const cloudRoot = node.path.slice(0, cloud.index + cloud[0].length);
9009
- if (node.path !== cloudRoot || node.scanState !== "skipped") throw new Error("stream cloud roots must be skipped and must not contain measured descendants");
9010
- }
9011
- if (node.depth === 0) {
9012
- if (!paths.includes(node.path)) throw new Error("stream root was not explicitly requested");
9013
- } else {
9014
- const parent = parents.get(dirname(node.path));
9015
- if (parent === void 0 || parent.depth + 1 !== node.depth || ancestors[node.depth - 1] !== parent || !parent.isDirectory || parent.scanState === "skipped") throw new Error("stream node has an absent, skipped, non-directory, or invalid preorder parent");
9016
- parent.children.push(node);
9017
- }
9018
- for (let depth = ancestors.length - 1; depth >= node.depth; depth -= 1) parents.delete(ancestors[depth].path);
9019
- ancestors.length = node.depth + 1;
9020
- ancestors[node.depth] = node;
9021
- if (node.isDirectory && node.scanState !== "skipped") parents.set(node.path, node);
9022
- if (node.depth === 0) roots.push(node);
9023
- seenPaths.add(node.path);
9024
- streamed = true;
9025
- };
9026
- const line = (input) => {
9027
- if (failure !== null || input.trim() === "") return;
9028
- try {
9029
- const decoded = JSON.parse(input);
9030
- if (streamed && decoded?.type === "done" && Array.isArray(decoded.report?.nodes) && decoded.report.nodes.length !== 0) throw new Error("stream completion must not repeat the full tree");
9031
- if (decoded?.type === "node" && Buffer.byteLength(input) > MAX_NODE_LINE_BYTES) throw new Error("stream node line exceeds 1 MiB protocol limit");
9032
- const message = LocalScanMessageSchema.parse(decoded);
9033
- if (report !== null) {
9034
- fail("protected scanner emitted data after its final report");
9035
- return;
9036
- }
9037
- if (message.type === "progress") onProgress(message.progress);
9038
- else if (message.type === "node") attach(message.node);
9039
- else {
9040
- if (streamed && message.report.nodes.length !== 0) throw new Error("stream completion must not repeat the full tree");
9041
- report = streamed ? {
9042
- ...message.report,
9043
- nodes: roots
9044
- } : message.report;
9045
- }
9046
- } catch (error) {
9047
- fail(`invalid protected scanner protocol: ${error instanceof Error ? error.message.slice(0, 1e3) : String(error)}`);
9048
- }
9049
- };
9050
- child.stdout.setEncoding("utf8");
9051
- child.stdout.on("data", (chunk) => {
9052
- if (failure !== null || ignoreOutput) return;
9053
- let cursor = 0;
9054
- for (;;) {
9055
- const newline = chunk.indexOf("\n", cursor);
9056
- const piece = chunk.slice(cursor, newline === -1 ? void 0 : newline);
9057
- pendingBytes += Buffer.byteLength(piece);
9058
- if (piece !== "") parts.push(piece);
9059
- if (header.length < 256) header += piece.slice(0, 256 - header.length);
9060
- const nodeLine = /^\s*\{\s*"node"\s*:/.test(header) || /^\s*\{\s*"type"\s*:\s*"node"/.test(header);
9061
- if (pendingBytes > (nodeLine ? MAX_NODE_LINE_BYTES : MAX_LINE_BYTES)) {
9062
- fail(nodeLine ? "stream node line exceeds 1 MiB protocol limit" : "protected scanner report exceeds 512 MiB protocol limit");
9063
- return;
9064
- }
9065
- if (newline === -1) break;
9066
- const complete = parts.join("");
9067
- discardPending();
9068
- line(complete);
9069
- if (failure !== null || ignoreOutput) return;
9070
- cursor = newline + 1;
9071
- }
9072
- });
9073
- child.stderr.on("data", (chunk) => {
9074
- stderr = Buffer.concat([stderr, chunk]).subarray(-8192);
9075
- });
9076
- child.on("error", (error) => {
9077
- failure ??= /* @__PURE__ */ new Error(`protected scanner could not start: ${error.message}`);
9078
- });
9079
- child.on("close", (code, signal) => {
9080
- if (killTimer !== void 0) clearTimeout(killTimer);
9081
- if (!ignoreOutput && parts.length > 0) line(parts.join(""));
9082
- discardPending();
9083
- seenPaths.clear();
9084
- parents.clear();
9085
- ancestors.length = 0;
9086
- if (failure !== null) {
9087
- discardTree();
9088
- rejectDone(failure);
9089
- } else if (code !== 0 || signal !== null) {
9090
- discardTree();
9091
- rejectDone(/* @__PURE__ */ new Error(`protected scanner exited (${signal ?? code}): ${stderr.toString("utf8").trim()}`));
9092
- } else if (report === null) {
9093
- discardTree();
9094
- rejectDone(/* @__PURE__ */ new Error("protected scanner exited without a final report"));
9095
- } else {
9096
- const accepted = report;
9097
- roots = [];
9098
- report = null;
9099
- resolveDone(accepted);
9100
- }
9101
- });
9102
- }),
9103
- terminate
10866
+ count: (kind) => snapshot.items[kind].length,
10867
+ sizeAt: (kind, position) => snapshot.items[kind][position].node.size,
10868
+ itemAt: (kind, position) => snapshot.items[kind][position],
10869
+ cumulativeSize: (kind, count) => snapshot.cumulativeSizes[kind][count]
9104
10870
  };
9105
10871
  }
10872
+ /**
10873
+ * Plain JavaScript source is embedded deliberately: serializing transpiled
10874
+ * functions captures loader/bundler helpers (for example tsx keepNames), which
10875
+ * are unavailable in an isolated worker. This also keeps bundled hosts free
10876
+ * of a separate worker file that would need to be copied beside the bundle.
10877
+ */
10878
+ var DISCOVERY_BOOTSTRAP = `
10879
+ /** Self-contained so its compiled function can run inside the scan worker. */
10880
+ function inspectDiscovery(engine, fs, path, crypto, roots) {
10881
+ const within = (candidate, root) =>
10882
+ candidate === root || candidate.startsWith(root.endsWith(path.sep) ? root : \`\${root}\${path.sep}\`)
10883
+ const idOf = (value) => crypto.createHash('sha1').update(value).digest('hex').slice(0, 24)
10884
+ const safeStat = (value) => {
10885
+ try {
10886
+ const stats = fs.lstatSync(value)
10887
+ if (stats.isSymbolicLink() || fs.realpathSync(value) !== value || !roots.some((root) => within(value, root)))
10888
+ return null
10889
+ return stats
10890
+ } catch {
10891
+ return null
10892
+ }
10893
+ }
10894
+ const tree = engine.scanDirectory({
10895
+ directories: roots,
10896
+ fullPath: true,
10897
+ ignoreHidden: false,
10898
+ respectGitignore: false,
10899
+ followSymlinks: false,
10900
+ })
10901
+ const ignoredTree = engine.scanDirectory({
10902
+ directories: roots,
10903
+ fullPath: true,
10904
+ ignoreHidden: false,
10905
+ respectGitignore: true,
10906
+ ignoredMode: 'summarize',
10907
+ followSymlinks: false,
10908
+ })
10909
+ const ignoredPaths = []
10910
+ const collectIgnored = (node) => {
10911
+ if (node.ignored) ignoredPaths.push(node.path)
10912
+ else for (const child of node.children) collectIgnored(child)
10913
+ }
10914
+ for (const root of ignoredTree) collectIgnored(root)
10915
+ const ignoredSet = new Set(ignoredPaths)
10916
+ const isIgnored = (value) => {
10917
+ let cursor = value
10918
+ for (;;) {
10919
+ if (ignoredSet.has(cursor)) return true
10920
+ const parent = path.dirname(cursor)
10921
+ if (parent === cursor) return false
10922
+ cursor = parent
10923
+ }
10924
+ }
10925
+ const entries = []
10926
+ const byPath = new Map()
10927
+ const directories = new Set()
10928
+ const regularFiles = new Set()
10929
+ const walk = (node, parent, depth) => {
10930
+ const stats = safeStat(node.path)
10931
+ if (stats === null) return null
10932
+ const id = idOf(node.path)
10933
+ const entry = {
10934
+ id,
10935
+ node: { ...node, children: [], ignored: isIgnored(node.path) },
10936
+ parent,
10937
+ depth,
10938
+ childIds: [],
10939
+ fingerprint: { size: stats.size, mtimeMs: stats.mtimeMs },
10940
+ }
10941
+ entries.push(entry)
10942
+ byPath.set(node.path, entry)
10943
+ if (stats.isDirectory()) directories.add(node.path)
10944
+ if (stats.isFile()) regularFiles.add(node.path)
10945
+ entry.childIds = node.children.map((child) => walk(child, id, depth + 1)).filter((id) => id !== null)
10946
+ return id
10947
+ }
10948
+ for (const root of tree) walk(root, null, 0)
10949
+ const summary = (entry) => ({
10950
+ id: entry.id,
10951
+ name: path.basename(entry.node.path),
10952
+ path: entry.node.path,
10953
+ size: entry.node.size,
10954
+ depth: entry.depth,
10955
+ ignored: entry.node.ignored,
10956
+ collapsed: false,
10957
+ hasChildren: entry.childIds.length > 0,
10958
+ childCount: entry.childIds.length,
10959
+ })
10960
+ const item = (entry, category) => ({
10961
+ node: summary(entry),
10962
+ parentId: entry.parent,
10963
+ category,
10964
+ isDirectory: directories.has(entry.node.path),
10965
+ })
10966
+ const hasFile = (directory, name) => safeStat(path.join(directory, name))?.isFile() === true
10967
+ const pythonEnvironment = (value) => {
10968
+ let cursor = path.dirname(value)
10969
+ for (;;) {
10970
+ if (['.venv', 'venv', 'env'].includes(path.basename(cursor)) || hasFile(cursor, 'pyvenv.cfg')) return true
10971
+ if (roots.includes(cursor)) return false
10972
+ const parent = path.dirname(cursor)
10973
+ if (parent === cursor) return false
10974
+ cursor = parent
10975
+ }
10976
+ }
10977
+ const pythonCategories = new Map([
10978
+ ['__pycache__', 'Python bytecode'],
10979
+ ['.pytest_cache', 'pytest cache'],
10980
+ ['.mypy_cache', 'mypy cache'],
10981
+ ['.ruff_cache', 'Ruff cache'],
10982
+ ])
10983
+ const jsNames = new Set(['.next', '.nuxt', '.turbo', '.parcel-cache', '.svelte-kit'])
10984
+ const cacheCategory = (entry) => {
10985
+ const value = entry.node.path
10986
+ if (!directories.has(value) || entry.parent === null) return null
10987
+ const name = path.basename(value)
10988
+ if (name !== 'node_modules' && name !== 'target' && !pythonCategories.has(name) && !jsNames.has(name)) return null
10989
+ if (pythonEnvironment(value)) return null
10990
+ const parent = path.dirname(value)
10991
+ if (name === 'node_modules' && hasFile(parent, 'package.json')) return 'Node dependencies'
10992
+ if (name === 'target' && hasFile(parent, 'Cargo.toml')) return 'Rust build output'
10993
+ if (pythonCategories.has(name)) return pythonCategories.get(name)
10994
+ if (jsNames.has(name) && hasFile(parent, 'package.json')) return 'JavaScript build cache'
10995
+ return null
10996
+ }
10997
+ const prune = (items) => {
10998
+ const sorted = items.sort(
10999
+ (a, b) => a.node.path.length - b.node.path.length || a.node.path.localeCompare(b.node.path),
11000
+ )
11001
+ const kept = []
11002
+ const keptPaths = new Set()
11003
+ const keptDirectories = new Set()
11004
+ for (const candidate of sorted) {
11005
+ if (keptPaths.has(candidate.node.path)) continue
11006
+ let cursor = path.dirname(candidate.node.path)
11007
+ let nested = false
11008
+ for (;;) {
11009
+ if (keptDirectories.has(cursor)) {
11010
+ nested = true
11011
+ break
11012
+ }
11013
+ const parent = path.dirname(cursor)
11014
+ if (parent === cursor) break
11015
+ cursor = parent
11016
+ }
11017
+ if (nested) continue
11018
+ kept.push(candidate)
11019
+ keptPaths.add(candidate.node.path)
11020
+ if (candidate.isDirectory) keptDirectories.add(candidate.node.path)
11021
+ }
11022
+ return kept
11023
+ }
11024
+ const caches = []
11025
+ const files = []
11026
+ for (const entry of entries) {
11027
+ if (regularFiles.has(entry.node.path)) files.push(item(entry, 'Large file'))
11028
+ const category = cacheCategory(entry)
11029
+ if (category !== null) caches.push(item(entry, category))
11030
+ }
11031
+ const ignored = ignoredPaths
11032
+ .map((value) => byPath.get(value))
11033
+ .filter((entry) => entry !== undefined)
11034
+ .filter((entry) => entry.parent !== null)
11035
+ .map((entry) => item(entry, 'Gitignored'))
11036
+ const items = { 'large-files': files, caches: prune(caches), gitignored: prune(ignored) }
11037
+ const cumulativeSizes = {}
11038
+ for (const kind of Object.keys(items)) {
11039
+ items[kind].sort((a, b) => b.node.size - a.node.size || a.node.path.localeCompare(b.node.path))
11040
+ const sums = [0]
11041
+ for (const candidate of items[kind]) sums.push(sums[sums.length - 1] + candidate.node.size)
11042
+ cumulativeSizes[kind] = sums
11043
+ }
11044
+ return { entries, items, cumulativeSizes }
11045
+ }
11046
+
11047
+ ;(async () => {
11048
+ const { parentPort, workerData } = await import('node:worker_threads')
11049
+ try {
11050
+ const loaded = await import(workerData.enginePath)
11051
+ const result = inspectDiscovery(
11052
+ loaded.default ?? loaded,
11053
+ await import('node:fs'),
11054
+ await import('node:path'),
11055
+ await import('node:crypto'),
11056
+ workerData.roots,
11057
+ )
11058
+ parentPort.postMessage({ type: 'done', result })
11059
+ } catch (error) {
11060
+ parentPort.postMessage({ type: 'error', message: String(error && error.message ? error.message : error) })
11061
+ }
11062
+ })()
11063
+ `;
9106
11064
  //#endregion
9107
11065
  //#region ../../packages/host/src/protected-discovery.ts
11066
+ /**
11067
+ * Size-descending, then path order. Paths are rebuilt only for rows whose
11068
+ * size ties, so large-file lists never hold one path string per file.
11069
+ */
11070
+ function sortRows(index, rows) {
11071
+ const order = Int32Array.from(rows);
11072
+ order.sort((a, b) => index.sizeOf(b) - index.sizeOf(a) || a - b);
11073
+ for (let start = 0; start < order.length;) {
11074
+ const size = index.sizeOf(order[start]);
11075
+ let end = start + 1;
11076
+ while (end < order.length && index.sizeOf(order[end]) === size) end += 1;
11077
+ if (end - start > 1) {
11078
+ const run = Array.from(order.subarray(start, end), (row) => ({
11079
+ row,
11080
+ path: index.pathOf(row)
11081
+ }));
11082
+ run.sort((a, b) => a.path.localeCompare(b.path) || a.row - b.row);
11083
+ for (let offset = 0; offset < run.length; offset += 1) order[start + offset] = run[offset].row;
11084
+ }
11085
+ start = end;
11086
+ }
11087
+ return order;
11088
+ }
9108
11089
  /** Classify already protected report metadata; no filesystem probes or rescans. */
9109
- async function protectedDiscovery(entries, summarize) {
9110
- const all = [...entries];
9111
- const byPath = new Map(all.map((entry) => [entry.node.path, entry]));
11090
+ async function protectedDiscovery(index) {
9112
11091
  const python = /* @__PURE__ */ new Map([
9113
11092
  ["__pycache__", "Python bytecode"],
9114
11093
  [".pytest_cache", "pytest cache"],
@@ -9123,8 +11102,8 @@ async function protectedDiscovery(entries, summarize) {
9123
11102
  ".svelte-kit"
9124
11103
  ]);
9125
11104
  const isLocalFile = (path) => {
9126
- const node = byPath.get(path)?.node;
9127
- return node?.isDirectory === false && node.scanState === "complete";
11105
+ const row = index.find(nodeIdOf(path));
11106
+ return row !== -1 && index.isDirectory(row) === false && index.scanStateOf(row) === "complete";
9128
11107
  };
9129
11108
  const inEnvironment = (path) => {
9130
11109
  let cursor = dirname(path);
@@ -9139,59 +11118,121 @@ async function protectedDiscovery(entries, summarize) {
9139
11118
  cursor = parent;
9140
11119
  }
9141
11120
  };
9142
- const items = {
11121
+ const rows = {
9143
11122
  "large-files": [],
9144
11123
  caches: [],
9145
11124
  gitignored: []
9146
11125
  };
9147
- let count = 0;
9148
- for (const entry of all) {
9149
- if (++count % 1e3 === 0) await new Promise((yieldTurn) => setImmediate(yieldTurn));
9150
- if (entry.node.scanState === "skipped" || entry.parent === null) continue;
9151
- const item = (category) => ({
9152
- node: summarize(entry),
9153
- parentId: entry.parent,
9154
- category,
9155
- isDirectory: entry.node.isDirectory === true
9156
- });
9157
- if (entry.node.ignored) items.gitignored.push(item("Gitignored"));
9158
- if (entry.node.isDirectory === false) {
9159
- items["large-files"].push(item("Large file"));
11126
+ const cacheCategories = /* @__PURE__ */ new Map();
11127
+ for (let row = 0; row < index.count; row += 1) {
11128
+ if ((row + 1) % 1e3 === 0) await new Promise((yieldTurn) => setImmediate(yieldTurn));
11129
+ if (index.scanStateOf(row) === "skipped" || index.parentOf(row) === -1) continue;
11130
+ if (index.isIgnored(row)) rows.gitignored.push(row);
11131
+ if (index.isDirectory(row) === false) {
11132
+ rows["large-files"].push(row);
9160
11133
  continue;
9161
11134
  }
9162
- const name = basename(entry.node.path);
11135
+ const name = index.baseNameOf(row);
9163
11136
  let category = python.get(name);
9164
- if (name === "node_modules" && isLocalFile(join(dirname(entry.node.path), "package.json"))) category = "Node dependencies";
9165
- if (name === "target" && isLocalFile(join(dirname(entry.node.path), "Cargo.toml"))) category = "Rust build output";
9166
- if (js.has(name) && isLocalFile(join(dirname(entry.node.path), "package.json"))) category = "JavaScript build cache";
9167
- if (category !== void 0 && !inEnvironment(entry.node.path)) items.caches.push(item(category));
11137
+ if (category === void 0 && name !== "node_modules" && name !== "target" && !js.has(name)) continue;
11138
+ const path = index.pathOf(row);
11139
+ if (name === "node_modules" && isLocalFile(join(dirname(path), "package.json"))) category = "Node dependencies";
11140
+ if (name === "target" && isLocalFile(join(dirname(path), "Cargo.toml"))) category = "Rust build output";
11141
+ if (js.has(name) && isLocalFile(join(dirname(path), "package.json"))) category = "JavaScript build cache";
11142
+ if (category !== void 0 && !inEnvironment(path)) {
11143
+ rows.caches.push(row);
11144
+ cacheCategories.set(row, category);
11145
+ }
9168
11146
  }
9169
11147
  for (const kind of ["caches", "gitignored"]) {
9170
- const directories = new Set(items[kind].filter((item) => item.isDirectory).map((item) => item.node.path));
9171
- items[kind] = items[kind].filter((item) => {
9172
- let cursor = dirname(item.node.path);
11148
+ const selected = new Uint8Array(index.count);
11149
+ for (const row of rows[kind]) if (index.isDirectory(row) === true) selected[row] = 1;
11150
+ const rootNested = /* @__PURE__ */ new Map();
11151
+ const nestedAboveRoot = (root) => {
11152
+ let nested = rootNested.get(root);
11153
+ if (nested === void 0) {
11154
+ nested = false;
11155
+ let cursor = index.pathOf(root);
11156
+ for (let parent = dirname(cursor); parent !== cursor; cursor = parent, parent = dirname(cursor)) {
11157
+ const row = index.find(nodeIdOf(parent));
11158
+ if (row !== -1 && selected[row] === 1) {
11159
+ nested = true;
11160
+ break;
11161
+ }
11162
+ }
11163
+ rootNested.set(root, nested);
11164
+ }
11165
+ return nested;
11166
+ };
11167
+ rows[kind] = rows[kind].filter((row) => {
11168
+ let cursor = index.parentOf(row);
9173
11169
  for (;;) {
9174
- if (directories.has(cursor)) return false;
9175
- const parent = dirname(cursor);
9176
- if (parent === cursor) return true;
11170
+ if (selected[cursor] === 1) return false;
11171
+ const parent = index.parentOf(cursor);
11172
+ if (parent === -1) return !nestedAboveRoot(cursor);
9177
11173
  cursor = parent;
9178
11174
  }
9179
11175
  });
9180
11176
  }
9181
- const cumulativeSizes = {};
9182
- for (const kind of Object.keys(items)) {
9183
- items[kind].sort((a, b) => b.node.size - a.node.size || a.node.path.localeCompare(b.node.path));
9184
- const totals = [0];
9185
- for (const item of items[kind]) totals.push(totals[totals.length - 1] + item.node.size);
9186
- cumulativeSizes[kind] = totals;
11177
+ const order = {};
11178
+ const cumulative = {};
11179
+ for (const kind of Object.keys(rows)) {
11180
+ order[kind] = sortRows(index, rows[kind]);
11181
+ rows[kind] = [];
11182
+ const totals = new Float64Array(order[kind].length + 1);
11183
+ for (let position = 0; position < order[kind].length; position += 1) totals[position + 1] = totals[position] + index.sizeOf(order[kind][position]);
11184
+ cumulative[kind] = totals;
9187
11185
  }
11186
+ const categoryOf = (kind, row) => kind === "large-files" ? "Large file" : kind === "gitignored" ? "Gitignored" : cacheCategories.get(row);
9188
11187
  return {
9189
- entries: [],
9190
- items,
9191
- cumulativeSizes
11188
+ count: (kind) => order[kind].length,
11189
+ sizeAt: (kind, position) => index.sizeOf(order[kind][position]),
11190
+ itemAt: (kind, position) => {
11191
+ const row = order[kind][position];
11192
+ return {
11193
+ node: index.summarize(row),
11194
+ parentId: index.idOf(index.parentOf(row)),
11195
+ category: categoryOf(kind, row),
11196
+ isDirectory: index.isDirectory(row) === true
11197
+ };
11198
+ },
11199
+ cumulativeSize: (kind, count) => cumulative[kind][count]
9192
11200
  };
9193
11201
  }
9194
11202
  //#endregion
11203
+ //#region ../../packages/host/src/storage-usage.ts
11204
+ var TIMEOUT_MS = 15e3;
11205
+ var MAX_STDOUT_BYTES = 1048576;
11206
+ var runCli = (binary, args) => new Promise((resolve) => {
11207
+ execFile(binary, [...args], {
11208
+ timeout: TIMEOUT_MS,
11209
+ maxBuffer: MAX_STDOUT_BYTES,
11210
+ windowsHide: true
11211
+ }, (error, stdout) => resolve(error ? null : stdout));
11212
+ });
11213
+ function storageUsageArgs(roots) {
11214
+ return ["storage-usage", ...roots.flatMap((root) => [
11215
+ "--root",
11216
+ root.path,
11217
+ "--scanned-bytes",
11218
+ String(root.bytes)
11219
+ ])];
11220
+ }
11221
+ /** `undefined` off macOS, without roots, or when the CLI gives no valid breakdown. */
11222
+ async function readStorageUsage(binary, roots, run = runCli, platform = process.platform) {
11223
+ if (platform !== "darwin" || roots.length === 0) return void 0;
11224
+ const stdout = await run(binary, storageUsageArgs(roots));
11225
+ if (stdout === null) return void 0;
11226
+ let parsed;
11227
+ try {
11228
+ parsed = JSON.parse(stdout);
11229
+ } catch {
11230
+ return;
11231
+ }
11232
+ const result = StorageBreakdownSchema.safeParse(parsed);
11233
+ return result.success ? result.data : void 0;
11234
+ }
11235
+ //#endregion
9195
11236
  //#region ../../packages/host/src/scan-store.ts
9196
11237
  /**
9197
11238
  * The engine is loaded by path and handed to the worker explicitly: eval-mode
@@ -9200,7 +11241,7 @@ async function protectedDiscovery(entries, summarize) {
9200
11241
  * and in tests.
9201
11242
  */
9202
11243
  function resolveEnginePath() {
9203
- return createRequire(import.meta.url).resolve("space-lens");
11244
+ return pathToFileURL(createRequire(import.meta.url).resolve("space-lens")).href;
9204
11245
  }
9205
11246
  var WORKER_BOOTSTRAP = `
9206
11247
  ;(async () => {
@@ -9235,9 +11276,6 @@ function normalizeLocalScanPath(path) {
9235
11276
  }
9236
11277
  return normalized;
9237
11278
  }
9238
- function nodeIdOf(path) {
9239
- return createHash("sha1").update(path).digest("hex").slice(0, 24);
9240
- }
9241
11279
  function newId(prefix) {
9242
11280
  return `${prefix}${randomBytes(6).toString("hex")}`;
9243
11281
  }
@@ -9293,7 +11331,6 @@ var ScanManager = class {
9293
11331
  session,
9294
11332
  status,
9295
11333
  worker: null,
9296
- tree: null,
9297
11334
  index: null,
9298
11335
  done: new Promise((resolve) => {
9299
11336
  resolveDone = resolve;
@@ -9334,13 +11371,12 @@ var ScanManager = class {
9334
11371
  worker.on("message", (message) => {
9335
11372
  if (record.status.state !== "scanning") return;
9336
11373
  if (message.type === "done" && message.tree) {
9337
- record.tree = message.tree;
9338
11374
  record.index = this.buildIndex(message.tree);
9339
11375
  record.status = {
9340
11376
  ...record.status,
9341
11377
  state: "ready",
9342
11378
  bytesScanned: message.tree.reduce((total, root) => total + root.size, 0),
9343
- entriesScanned: this.countNodes(message.tree),
11379
+ entriesScanned: record.index.count,
9344
11380
  rootIds: message.tree.map((root) => nodeIdOf(root.path)),
9345
11381
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
9346
11382
  };
@@ -9406,23 +11442,17 @@ var ScanManager = class {
9406
11442
  }
9407
11443
  slice(scanId, nodeId, depth, maxChildrenPerNode) {
9408
11444
  const { index } = this.requireReady(scanId);
9409
- const entry = index.get(nodeId);
9410
- if (entry === void 0) throw Problems.notFound(`no node ${nodeId} in scan ${scanId}`);
11445
+ const row = index.find(nodeId);
11446
+ if (row === -1) throw Problems.notFound(`no node ${nodeId} in scan ${scanId}`);
9411
11447
  const ancestors = [];
9412
- let cursor = entry;
9413
- while (cursor.parent !== null) {
9414
- const parent = index.get(cursor.parent);
9415
- if (parent === void 0) break;
9416
- ancestors.unshift(this.summarize(parent));
9417
- cursor = parent;
9418
- }
9419
- const tree = this.buildSliceNode(index, entry, depth, maxChildrenPerNode);
11448
+ for (let parent = index.parentOf(row); parent !== -1; parent = index.parentOf(parent)) ancestors.unshift(index.summarize(parent));
11449
+ const tree = this.buildSliceNode(index, row, depth, maxChildrenPerNode);
9420
11450
  return {
9421
11451
  scanId,
9422
- focusNode: this.summarize(entry),
11452
+ focusNode: index.summarize(row),
9423
11453
  ancestors,
9424
11454
  tree,
9425
- totalSize: entry.node.size,
11455
+ totalSize: index.sizeOf(row),
9426
11456
  truncated: tree.truncated,
9427
11457
  omittedBytes: tree.omittedBytes,
9428
11458
  omittedCount: tree.omittedCount,
@@ -9431,9 +11461,9 @@ var ScanManager = class {
9431
11461
  }
9432
11462
  children(scanId, nodeId, offset, limit, sort) {
9433
11463
  const { index } = this.requireReady(scanId);
9434
- const entry = index.get(nodeId);
9435
- if (entry === void 0) throw Problems.notFound(`no node ${nodeId} in scan ${scanId}`);
9436
- const items = entry.childIds.map((childId) => this.summarize(index.get(childId))).sort((a, b) => {
11464
+ const row = index.find(nodeId);
11465
+ if (row === -1) throw Problems.notFound(`no node ${nodeId} in scan ${scanId}`);
11466
+ const items = index.childrenOf(row).map((child) => index.summarize(child)).sort((a, b) => {
9437
11467
  if (sort === "size") return b.size - a.size || a.name.localeCompare(b.name);
9438
11468
  if (sort === "name") return a.name.localeCompare(b.name);
9439
11469
  return a.path.localeCompare(b.path);
@@ -9452,30 +11482,31 @@ var ScanManager = class {
9452
11482
  if (this.closed) throw Problems.unavailable("the host is stopping");
9453
11483
  const { record, index } = this.requireReady(request.scanId);
9454
11484
  if (record.localOnly && !record.gitignoreClassified && request.kind === "gitignored") throw Problems.unsupported("this protected scan did not classify gitignored paths; scan with respectGitignore enabled");
9455
- record.discovery ??= record.localOnly ? protectedDiscovery(index.values(), (entry) => this.summarize(entry)) : this.startDiscovery(record, index);
11485
+ record.discovery ??= record.localOnly ? protectedDiscovery(index) : this.startDiscovery(record, index);
9456
11486
  const pending = record.discovery;
9457
- let snapshot;
11487
+ let view;
9458
11488
  try {
9459
- snapshot = await pending;
11489
+ view = await pending;
9460
11490
  } catch (error) {
9461
11491
  if (record.discovery === pending) record.discovery = null;
9462
11492
  throw error;
9463
11493
  }
9464
- const items = snapshot.items[request.kind];
9465
11494
  let low = 0;
9466
- let high = items.length;
11495
+ let high = view.count(request.kind);
9467
11496
  while (low < high) {
9468
11497
  const middle = Math.floor((low + high) / 2);
9469
- if (items[middle].node.size >= request.minSize) low = middle + 1;
11498
+ if (view.sizeAt(request.kind, middle) >= request.minSize) low = middle + 1;
9470
11499
  else high = middle;
9471
11500
  }
9472
11501
  const total = low;
11502
+ const items = [];
11503
+ for (let position = request.offset; position < Math.min(total, request.offset + request.limit); position += 1) items.push(view.itemAt(request.kind, position));
9473
11504
  return {
9474
11505
  scanId: request.scanId,
9475
11506
  kind: request.kind,
9476
- items: request.offset >= total ? [] : items.slice(request.offset, Math.min(total, request.offset + request.limit)),
11507
+ items,
9477
11508
  total,
9478
- totalSize: snapshot.cumulativeSizes[request.kind][total],
11509
+ totalSize: view.cumulativeSize(request.kind, total),
9479
11510
  offset: request.offset,
9480
11511
  limit: request.limit
9481
11512
  };
@@ -9536,12 +11567,23 @@ var ScanManager = class {
9536
11567
  reject(Problems.cancelled("discovery was stopped"));
9537
11568
  return;
9538
11569
  }
9539
- const original = index.get(entry.id);
9540
- if (original === void 0) index.set(entry.id, entry);
9541
- else original.cleanup = entry;
11570
+ const original = index.find(entry.id);
11571
+ if (original === -1) {
11572
+ const parent = entry.parent === null ? -1 : index.find(entry.parent);
11573
+ index.append({
11574
+ path: entry.node.path,
11575
+ size: entry.node.size,
11576
+ ignored: entry.node.ignored,
11577
+ collapsed: entry.node.collapsed,
11578
+ fingerprint: entry.fingerprint
11579
+ }, parent, parent === -1 ? null : index.pathOf(parent), true);
11580
+ } else index.setCleanup(original, entry.node.size, entry.node.ignored, entry.fingerprint);
9542
11581
  if (++registered % 1e3 === 0) await new Promise((yieldTurn) => setImmediate(yieldTurn));
9543
11582
  }
9544
- resolve(snapshot);
11583
+ resolve(snapshotView({
11584
+ items: snapshot.items,
11585
+ cumulativeSizes: snapshot.cumulativeSizes
11586
+ }));
9545
11587
  };
9546
11588
  worker.on("message", (message) => {
9547
11589
  if (message.type === "done" && message.result) finish(null, message.result);
@@ -9584,18 +11626,15 @@ var ScanManager = class {
9584
11626
  if (this.options.cleanupMode === "none") throw Problems.unsupported("this host was started without --allow-cleanup");
9585
11627
  const unknown = nodeIds.filter((nodeId) => !index.has(nodeId));
9586
11628
  if (unknown.length > 0) throw Problems.invalid(`plan references ${unknown.length} unknown node id(s)`, { example: unknown[0] });
9587
- const selections = [...new Set(nodeIds)].map((nodeId) => {
9588
- const entry = index.get(nodeId);
9589
- return entry.cleanup ?? entry;
9590
- });
11629
+ const selections = [...new Set(nodeIds)].map((nodeId) => index.cleanupView(index.find(nodeId)));
9591
11630
  for (const entry of selections) {
9592
- this.guardSelection(record, entry.node.path);
9593
- const current = this.fingerprintOf(entry.node.path);
9594
- if (entry.fingerprint === void 0 || current.size !== entry.fingerprint.size || current.mtimeMs !== entry.fingerprint.mtimeMs) throw Problems.staleSnapshot(`path changed since scanning: ${entry.node.path}; scan again`);
11631
+ this.guardSelection(record, entry.path);
11632
+ const current = this.fingerprintOf(entry.path);
11633
+ if (entry.fingerprint === void 0 || current.size !== entry.fingerprint.size || current.mtimeMs !== entry.fingerprint.mtimeMs) throw Problems.staleSnapshot(`path changed since scanning: ${entry.path}; scan again`);
9595
11634
  }
9596
- const selectedPaths = new Set(selections.map((entry) => entry.node.path));
11635
+ const selectedPaths = new Set(selections.map((entry) => entry.path));
9597
11636
  const entries = selections.filter((entry) => {
9598
- let parent = dirname(entry.node.path);
11637
+ let parent = dirname(entry.path);
9599
11638
  for (;;) {
9600
11639
  if (selectedPaths.has(parent)) return false;
9601
11640
  const next = dirname(parent);
@@ -9604,12 +11643,12 @@ var ScanManager = class {
9604
11643
  }
9605
11644
  }).map((entry) => {
9606
11645
  return {
9607
- path: entry.node.path,
9608
- size: entry.node.size,
9609
- reason: entry.node.ignored ? "ignored" : "staged",
11646
+ path: entry.path,
11647
+ size: entry.size,
11648
+ reason: entry.ignored ? "ignored" : "staged",
9610
11649
  preset: null,
9611
- ignored: entry.node.ignored,
9612
- fingerprint: this.fingerprintOf(entry.node.path)
11650
+ ignored: entry.ignored,
11651
+ fingerprint: this.fingerprintOf(entry.path)
9613
11652
  };
9614
11653
  });
9615
11654
  const now = Date.now();
@@ -9723,9 +11762,18 @@ var ScanManager = class {
9723
11762
  });
9724
11763
  record.process = process;
9725
11764
  this.activeLocalProcesses.add(process);
9726
- process.done.then((report) => {
11765
+ process.done.then(async (result) => {
11766
+ if (record.status.state !== "scanning" || this.closed) return;
11767
+ const storage = await readStorageUsage(binary, result.report.nodes.map((root) => ({
11768
+ path: root.path,
11769
+ bytes: root.size
11770
+ })));
9727
11771
  if (record.status.state !== "scanning" || this.closed) return;
9728
- this.acceptLocalReport(record, report);
11772
+ this.acceptLocalReport(record, result);
11773
+ if (storage !== void 0) record.status = {
11774
+ ...record.status,
11775
+ storage
11776
+ };
9729
11777
  }).catch((error) => {
9730
11778
  if (record.status.state !== "scanning") return;
9731
11779
  record.status = {
@@ -9741,27 +11789,33 @@ var ScanManager = class {
9741
11789
  this.finish(record);
9742
11790
  });
9743
11791
  }
9744
- acceptLocalReport(record, report) {
11792
+ acceptLocalReport(record, { report, index: streamed }) {
9745
11793
  if (process.platform === "darwin" && report.coverage.protection !== "macos-no-materialization") throw Problems.unavailable("protected scanner did not establish macOS no-materialization protection");
9746
11794
  const roots = new Set(record.roots);
9747
- if (report.nodes.length !== roots.size || report.nodes.some((node) => !roots.has(node.path))) throw Problems.invalid("protected scanner report does not cover the requested roots");
9748
- const seen = /* @__PURE__ */ new Set();
9749
- const validate = (node, parent) => {
9750
- if (!isAbsolute(node.path) || resolve(node.path) !== node.path || seen.has(node.path) || !record.roots.some((root) => within(node.path, root)) || parent !== null && dirname(node.path) !== parent.path || node.scanState === "skipped" && node.children.length > 0) throw Problems.invalid("protected scanner report contains unsafe or duplicate paths");
9751
- seen.add(node.path);
9752
- for (const child of node.children) validate(child, node);
9753
- };
9754
- for (const root of report.nodes) validate(root, null);
9755
- record.tree = report.nodes;
9756
- record.index = this.buildIndex(report.nodes, false);
11795
+ let index;
11796
+ if (streamed !== null) {
11797
+ if (streamed.roots.length !== roots.size || streamed.roots.some((root) => !roots.has(streamed.pathOf(root)))) throw Problems.invalid("protected scanner report does not cover the requested roots");
11798
+ index = streamed;
11799
+ } else {
11800
+ if (report.nodes.length !== roots.size || report.nodes.some((node) => !roots.has(node.path))) throw Problems.invalid("protected scanner report does not cover the requested roots");
11801
+ const seen = /* @__PURE__ */ new Set();
11802
+ const validate = (node, parent) => {
11803
+ if (!isAbsolute(node.path) || resolve(node.path) !== node.path || seen.has(node.path) || !record.roots.some((root) => within(node.path, root)) || parent !== null && dirname(node.path) !== parent.path || node.scanState === "skipped" && node.children.length > 0) throw Problems.invalid("protected scanner report contains unsafe or duplicate paths");
11804
+ seen.add(node.path);
11805
+ for (const child of node.children) validate(child, node);
11806
+ };
11807
+ for (const root of report.nodes) validate(root, null);
11808
+ index = this.buildIndex(report.nodes, false);
11809
+ }
11810
+ record.index = index;
9757
11811
  record.status = {
9758
11812
  ...record.status,
9759
11813
  state: "ready",
9760
11814
  message: "",
9761
11815
  currentPath: null,
9762
- bytesScanned: report.nodes.reduce((total, root) => total + root.size, 0),
11816
+ bytesScanned: index.roots.reduce((total, root) => total + index.sizeOf(root), 0),
9763
11817
  entriesScanned: report.coverage.files + report.coverage.directories,
9764
- rootIds: report.nodes.map((root) => nodeIdOf(root.path)),
11818
+ rootIds: index.roots.map((root) => index.idOf(root)),
9765
11819
  coverage: report.coverage,
9766
11820
  volumes: report.volumes,
9767
11821
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -9805,63 +11859,39 @@ var ScanManager = class {
9805
11859
  this.pumpDiscovery();
9806
11860
  }
9807
11861
  buildIndex(tree, fingerprintEnabled = true) {
9808
- const index = /* @__PURE__ */ new Map();
9809
- const walk = (node, parent, depth) => {
9810
- const id = nodeIdOf(node.path);
9811
- const childIds = (node.children ?? []).map((child) => walk(child, id, depth + 1));
11862
+ const index = new ScanIndex();
11863
+ const walk = (node, parent, parentPath) => {
9812
11864
  let fingerprint;
9813
11865
  try {
9814
11866
  if (fingerprintEnabled) fingerprint = this.fingerprintOf(node.path);
9815
11867
  } catch {}
9816
- index.set(id, {
9817
- id,
9818
- node,
9819
- parent,
9820
- childIds,
9821
- depth,
11868
+ const row = index.append({
11869
+ path: node.path,
11870
+ size: node.size,
11871
+ ignored: node.ignored,
11872
+ collapsed: node.collapsed,
11873
+ logicalSize: node.logicalSize,
11874
+ isDirectory: node.isDirectory,
11875
+ scanState: node.scanState,
11876
+ skipReason: node.skipReason,
9822
11877
  fingerprint
9823
- });
9824
- return id;
11878
+ }, parent, parentPath);
11879
+ if (row === -1) return;
11880
+ for (const child of node.children ?? []) walk(child, row, node.path);
9825
11881
  };
9826
- for (const root of tree) walk(root, null, 0);
11882
+ for (const root of tree) walk(root, -1, null);
11883
+ index.seal();
9827
11884
  return index;
9828
11885
  }
9829
- countNodes(tree) {
9830
- let count = 0;
9831
- const walk = (node) => {
9832
- count += 1;
9833
- for (const child of node.children ?? []) walk(child);
9834
- };
9835
- for (const root of tree) walk(root);
9836
- return count;
9837
- }
9838
- summarize(entry) {
9839
- const childCount = entry.childIds.length;
9840
- return {
9841
- id: entry.id,
9842
- name: basename(entry.node.path),
9843
- path: entry.node.path,
9844
- size: entry.node.size,
9845
- depth: entry.depth,
9846
- ignored: entry.node.ignored,
9847
- collapsed: entry.node.collapsed,
9848
- hasChildren: childCount > 0,
9849
- childCount,
9850
- ...entry.node.logicalSize === void 0 ? {} : { logicalSize: entry.node.logicalSize },
9851
- ...entry.node.isDirectory === void 0 ? {} : { isDirectory: entry.node.isDirectory },
9852
- ...entry.node.scanState === void 0 ? {} : { scanState: entry.node.scanState },
9853
- ...entry.node.skipReason === void 0 ? {} : { skipReason: entry.node.skipReason }
9854
- };
9855
- }
9856
- buildSliceNode(index, entry, remainingDepth, maxChildrenPerNode) {
9857
- const summary = this.summarize(entry);
9858
- const children = entry.childIds.map((childId) => index.get(childId)).sort((a, b) => b.node.size - a.node.size);
11886
+ buildSliceNode(index, row, remainingDepth, maxChildrenPerNode) {
11887
+ const summary = index.summarize(row);
11888
+ const children = index.childrenOf(row).sort((a, b) => index.sizeOf(b) - index.sizeOf(a));
9859
11889
  let omittedBytes = 0;
9860
11890
  let omittedCount = 0;
9861
11891
  const kept = children.slice(0, remainingDepth > 0 ? maxChildrenPerNode : 0);
9862
11892
  const dropped = children.slice(kept.length);
9863
11893
  for (const child of dropped) {
9864
- omittedBytes += child.node.size;
11894
+ omittedBytes += index.sizeOf(child);
9865
11895
  omittedCount += 1;
9866
11896
  }
9867
11897
  let truncated = dropped.length > 0;
@@ -9871,7 +11901,7 @@ var ScanManager = class {
9871
11901
  omittedCount += slice.omittedCount;
9872
11902
  truncated ||= slice.truncated;
9873
11903
  return {
9874
- ...this.summarize(child),
11904
+ ...index.summarize(child),
9875
11905
  children: slice.children,
9876
11906
  omittedBytes: slice.omittedBytes,
9877
11907
  omittedCount: slice.omittedCount
@@ -10411,6 +12441,254 @@ var serve = (options, listeningListener) => {
10411
12441
  return server;
10412
12442
  };
10413
12443
  //#endregion
12444
+ //#region ../../packages/host/src/memory.ts
12445
+ /**
12446
+ * The host's bridge to `spacelens memory stdio` (T13 of
12447
+ * docs/memory-cleaner-plan.md, §4.6). The HTTP host never re-implements a
12448
+ * memory rule: it spawns the release CLI as one long-lived child and forwards
12449
+ * each call over the line protocol, so plans, history and rate limits all live
12450
+ * in the Rust process.
12451
+ *
12452
+ * The bridge owns exactly one child, spawned lazily on the first call. Requests
12453
+ * are correlated by a monotonic id; replies either resolve their call or reject
12454
+ * it with the child's problem (the same closed code, status from the host's
12455
+ * `Problems` helpers). A reply line is capped at 4 MiB: a longer one kills the
12456
+ * child and rejects everything pending. A call that gets no reply within
12457
+ * `callTimeoutMs` becomes a `Timeout`; a child that exits rejects the pending
12458
+ * calls with `Unavailable` and is respawned on the next call.
12459
+ */
12460
+ /** The most bytes one reply line may take (§4.6). */
12461
+ var MAX_LINE_BYTES = 4194304;
12462
+ /** How long `stop` waits for the child to honour `shutdown` before it is killed. */
12463
+ var SHUTDOWN_GRACE_MS = 2e3;
12464
+ var PROBLEM_BY_CODE = {
12465
+ Unauthenticated: (message) => Problems.unauthenticated(message),
12466
+ Forbidden: (message) => Problems.forbidden(message),
12467
+ NotFound: (message) => Problems.notFound(message),
12468
+ InvalidRequest: (message) => Problems.invalid(message),
12469
+ UnsupportedOperation: (message) => Problems.unsupported(message),
12470
+ LimitExceeded: (message, retryable) => Problems.limit(message, retryable),
12471
+ StalePlan: (message) => Problems.stalePlan(message),
12472
+ StaleSnapshot: (message) => Problems.staleSnapshot(message),
12473
+ Conflict: (message) => Problems.conflict(message),
12474
+ Timeout: (message, retryable) => Problems.timeout(message, retryable),
12475
+ Cancelled: (message) => Problems.cancelled(message),
12476
+ Unavailable: (message, retryable) => Problems.unavailable(message, retryable),
12477
+ InternalError: (message) => Problems.internal(message)
12478
+ };
12479
+ /** True for a plain JSON object, never an array or null. */
12480
+ function isRecord(value) {
12481
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12482
+ }
12483
+ /** True when `value` is one of the wire platform literals. */
12484
+ function isPlatform(value) {
12485
+ return typeof value === "string" && MEMORY_PLATFORMS.some((platform) => platform === value);
12486
+ }
12487
+ /** True when `value` is one of the closed problem codes. */
12488
+ function isProblemCode(value) {
12489
+ return PROBLEM_CODES.some((code) => code === value);
12490
+ }
12491
+ /** Validate the `hello` payload; a malformed one is an `InternalError`. */
12492
+ function parseHello(raw) {
12493
+ if (!isRecord(raw)) return null;
12494
+ const { platform, terminate, gracefulAppQuit } = raw;
12495
+ if (!isPlatform(platform) || typeof terminate !== "boolean" || typeof gracefulAppQuit !== "boolean") return null;
12496
+ return {
12497
+ platform,
12498
+ terminate,
12499
+ gracefulAppQuit
12500
+ };
12501
+ }
12502
+ /** Rebuild the child's problem through the host helpers so the status matches its code. */
12503
+ function decodeProblem(raw) {
12504
+ if (isRecord(raw)) {
12505
+ const { code, message, retryable } = raw;
12506
+ if (typeof code === "string" && isProblemCode(code) && typeof message === "string" && message !== "") {
12507
+ const base = PROBLEM_BY_CODE[code](message, typeof retryable === "boolean" ? retryable : false);
12508
+ return new ProblemError(base.problem, base.status);
12509
+ }
12510
+ }
12511
+ return Problems.internal("The memory process sent a malformed problem reply.");
12512
+ }
12513
+ /**
12514
+ * Create the bridge. Nothing is spawned until the first `hello()` or `call()`,
12515
+ * so a host with the memory scopes disabled costs nothing.
12516
+ */
12517
+ function createMemoryBridge(options) {
12518
+ const args = options.args ?? [];
12519
+ const callTimeoutMs = options.callTimeoutMs ?? 15e3;
12520
+ const spawnImpl = options.spawnImpl ?? spawn;
12521
+ let state = null;
12522
+ let nextId = 1;
12523
+ const pending = /* @__PURE__ */ new Map();
12524
+ /** Reject every pending call with `error` and stop their timers. */
12525
+ const failPending = (error) => {
12526
+ for (const call of pending.values()) {
12527
+ clearTimeout(call.timer);
12528
+ call.reject(error);
12529
+ }
12530
+ pending.clear();
12531
+ };
12532
+ /** The child closed or failed to start; fail everything still waiting on it. */
12533
+ const handleExit = (child) => {
12534
+ if (child.exited) return;
12535
+ child.exited = true;
12536
+ if (state === child) state = null;
12537
+ child.rejectHello(Problems.unavailable("The memory process exited before its hello reply."));
12538
+ failPending(Problems.unavailable("The memory process exited before replying."));
12539
+ };
12540
+ /** A reply line broke the 4 MiB cap; kill the child and fail everything. */
12541
+ const handleOverflow = (child) => {
12542
+ if (child.exited) return;
12543
+ child.exited = true;
12544
+ if (state === child) state = null;
12545
+ child.proc.kill("SIGKILL");
12546
+ const detail = `The memory process sent a reply line over the ${MAX_LINE_BYTES} byte limit.`;
12547
+ child.rejectHello(Problems.internal(detail));
12548
+ failPending(Problems.internal(detail));
12549
+ };
12550
+ /** Dispatch one complete reply line. */
12551
+ const handleLine = (child, line) => {
12552
+ const text = line.trim();
12553
+ if (text === "") return;
12554
+ let decoded;
12555
+ try {
12556
+ decoded = JSON.parse(text);
12557
+ } catch {
12558
+ return;
12559
+ }
12560
+ if (!isRecord(decoded)) return;
12561
+ if ("hello" in decoded) {
12562
+ const hello = parseHello(decoded.hello);
12563
+ if (hello === null) child.rejectHello(Problems.internal("The memory process sent a malformed hello reply."));
12564
+ else child.resolveHello(hello);
12565
+ return;
12566
+ }
12567
+ const { id } = decoded;
12568
+ if (typeof id !== "number") return;
12569
+ const call = pending.get(id);
12570
+ if (call === void 0) return;
12571
+ pending.delete(id);
12572
+ clearTimeout(call.timer);
12573
+ if (decoded.ok === true) call.resolve(decoded.result);
12574
+ else call.reject(decodeProblem(decoded.problem));
12575
+ };
12576
+ /** Split stdout into lines, enforcing the cap before anything is buffered past it. */
12577
+ const onData = (child, chunk) => {
12578
+ if (child.exited) return;
12579
+ child.buffer = Buffer.concat([child.buffer, chunk]);
12580
+ for (;;) {
12581
+ const newline = child.buffer.indexOf(10);
12582
+ if (newline === -1) {
12583
+ if (child.buffer.length > 4194304) handleOverflow(child);
12584
+ return;
12585
+ }
12586
+ if (newline > 4194304) {
12587
+ handleOverflow(child);
12588
+ return;
12589
+ }
12590
+ const line = child.buffer.subarray(0, newline).toString("utf8");
12591
+ child.buffer = child.buffer.subarray(newline + 1);
12592
+ handleLine(child, line);
12593
+ if (child.exited) return;
12594
+ }
12595
+ };
12596
+ /** Spawn the child if needed and resolve with its `hello`. */
12597
+ const start = () => {
12598
+ if (state !== null) return state.hello;
12599
+ const proc = spawnImpl(options.binary, [
12600
+ ...args,
12601
+ "memory",
12602
+ "stdio"
12603
+ ], {
12604
+ shell: false,
12605
+ windowsHide: true
12606
+ });
12607
+ let resolveHello = () => {};
12608
+ let rejectHello = () => {};
12609
+ const hello = new Promise((resolve, reject) => {
12610
+ resolveHello = resolve;
12611
+ rejectHello = reject;
12612
+ });
12613
+ const child = {
12614
+ proc,
12615
+ hello,
12616
+ resolveHello,
12617
+ rejectHello,
12618
+ exited: false,
12619
+ buffer: Buffer.alloc(0)
12620
+ };
12621
+ state = child;
12622
+ proc.stdout.on("data", (chunk) => onData(child, chunk));
12623
+ proc.stderr.on("data", () => {});
12624
+ proc.stdin.on("error", () => {});
12625
+ proc.on("error", () => handleExit(child));
12626
+ proc.on("close", () => handleExit(child));
12627
+ return hello;
12628
+ };
12629
+ const call = async (sessionId, request) => {
12630
+ await start();
12631
+ if (state === null) throw Problems.unavailable("The memory process is not running.");
12632
+ const child = state;
12633
+ const id = nextId;
12634
+ nextId += 1;
12635
+ return await new Promise((resolve, reject) => {
12636
+ const timer = setTimeout(() => {
12637
+ pending.delete(id);
12638
+ reject(Problems.timeout(`The memory process did not reply within ${callTimeoutMs} ms.`));
12639
+ }, callTimeoutMs);
12640
+ timer.unref();
12641
+ pending.set(id, {
12642
+ resolve,
12643
+ reject,
12644
+ timer
12645
+ });
12646
+ child.proc.stdin.write(`${JSON.stringify({
12647
+ id,
12648
+ sessionId,
12649
+ call: request
12650
+ })}\n`);
12651
+ });
12652
+ };
12653
+ const stop = async () => {
12654
+ const child = state;
12655
+ if (child === null) return;
12656
+ state = null;
12657
+ child.exited = true;
12658
+ const stopped = Problems.unavailable("The memory bridge stopped.");
12659
+ child.rejectHello(stopped);
12660
+ failPending(stopped);
12661
+ try {
12662
+ child.proc.stdin.write(`${JSON.stringify({
12663
+ id: nextId,
12664
+ sessionId: "",
12665
+ call: { method: "shutdown" }
12666
+ })}\n`);
12667
+ child.proc.stdin.end();
12668
+ } catch {}
12669
+ await new Promise((resolve) => {
12670
+ if (child.proc.exitCode !== null || child.proc.signalCode !== null) {
12671
+ resolve();
12672
+ return;
12673
+ }
12674
+ const timer = setTimeout(() => {
12675
+ child.proc.kill("SIGKILL");
12676
+ resolve();
12677
+ }, SHUTDOWN_GRACE_MS);
12678
+ timer.unref();
12679
+ child.proc.once("close", () => {
12680
+ clearTimeout(timer);
12681
+ resolve();
12682
+ });
12683
+ });
12684
+ };
12685
+ return {
12686
+ hello: start,
12687
+ call,
12688
+ stop
12689
+ };
12690
+ }
12691
+ //#endregion
10414
12692
  //#region ../../packages/host/src/trash.ts
10415
12693
  function run(command, args, timeoutMs = 3e4) {
10416
12694
  return new Promise((resolve) => {
@@ -10458,15 +12736,78 @@ function linuxTrash() {
10458
12736
  return { async trash(paths) {
10459
12737
  const results = /* @__PURE__ */ new Map();
10460
12738
  if (paths.length === 0) return results;
10461
- const outcome = await run("gio", [
10462
- "trash",
10463
- "--",
10464
- ...paths
10465
- ]);
10466
- for (const path of paths) results.set(path, outcome.ok ? null : `gio trash failed: ${outcome.stderr.trim() || "unknown error"}`);
10467
- return results;
12739
+ if (await hasGio()) {
12740
+ const outcome = await run("gio", [
12741
+ "trash",
12742
+ "--",
12743
+ ...paths
12744
+ ]);
12745
+ for (const path of paths) results.set(path, outcome.ok ? null : `gio trash failed: ${outcome.stderr.trim() || "unknown error"}`);
12746
+ return results;
12747
+ }
12748
+ return freedesktopTrash(paths, homeTrashRoot());
10468
12749
  } };
10469
12750
  }
12751
+ var gioProbe = null;
12752
+ function hasGio() {
12753
+ gioProbe ??= run("gio", ["--version"]).then((outcome) => outcome.ok);
12754
+ return gioProbe;
12755
+ }
12756
+ /** `$XDG_DATA_HOME/Trash`, defaulting to `~/.local/share/Trash`. */
12757
+ function homeTrashRoot() {
12758
+ const dataHome = process.env.XDG_DATA_HOME;
12759
+ const base = dataHome && dataHome.startsWith("/") ? dataHome : join(homedir(), ".local", "share");
12760
+ return join(base, "Trash");
12761
+ }
12762
+ /**
12763
+ * Moves every path into a freedesktop trash directory: `files/<name>` plus the
12764
+ * matching `info/<name>.trashinfo`. Never deletes — a cross-device source is
12765
+ * copied and then removed only after the copy lands, mirroring gio.
12766
+ */
12767
+ async function freedesktopTrash(paths, root) {
12768
+ const results = /* @__PURE__ */ new Map();
12769
+ const files = join(root, "files");
12770
+ const info = join(root, "info");
12771
+ mkdirSync(files, { recursive: true });
12772
+ mkdirSync(info, { recursive: true });
12773
+ for (const path of paths) {
12774
+ let isDirectory = false;
12775
+ try {
12776
+ isDirectory = statSync(path).isDirectory();
12777
+ } catch {
12778
+ results.set(path, "path vanished before it could be trashed");
12779
+ continue;
12780
+ }
12781
+ try {
12782
+ const name = uniqueTrashedName(files, basename(path));
12783
+ const target = join(files, name);
12784
+ try {
12785
+ renameSync(path, target);
12786
+ } catch (error) {
12787
+ if (error?.code !== "EXDEV") throw error;
12788
+ if (isDirectory) cpSync(path, target, { recursive: true });
12789
+ else cpSync(path, target);
12790
+ rmSync(path, { recursive: true });
12791
+ }
12792
+ writeFileSync(join(info, `${name}.trashinfo`), trashInfo(path));
12793
+ results.set(path, null);
12794
+ } catch (error) {
12795
+ results.set(path, `freedesktop trash failed: ${error instanceof Error ? error.message : String(error)}`);
12796
+ }
12797
+ }
12798
+ return results;
12799
+ }
12800
+ function uniqueTrashedName(filesDir, name) {
12801
+ if (!existsSync(join(filesDir, name))) return name;
12802
+ for (let counter = 2;; counter += 1) {
12803
+ const candidate = `${name} ${counter}`;
12804
+ if (!existsSync(join(filesDir, candidate))) return candidate;
12805
+ }
12806
+ }
12807
+ /** `.trashinfo` body: the original location percent-encoded as a URI path. */
12808
+ function trashInfo(originalPath, deletedAt = /* @__PURE__ */ new Date()) {
12809
+ return `[Trash Info]\nPath=${encodeURIComponent(originalPath).replaceAll("%2F", "/")}\nDeletionDate=${deletedAt.toISOString().slice(0, 19)}\n`;
12810
+ }
10470
12811
  function windowsTrash() {
10471
12812
  return { async trash(paths) {
10472
12813
  const results = /* @__PURE__ */ new Map();
@@ -10523,12 +12864,15 @@ async function startServe(options) {
10523
12864
  const config = resolveServeConfig(options);
10524
12865
  const serviceInstanceId = `inst_${randomBytes(6).toString("hex")}`;
10525
12866
  const hostedPassword = config.hostedPassword === null ? null : hashHostedPassword(config.hostedPassword);
10526
- const scopes = config.allowCleanup ? [
12867
+ const scopes = [
10527
12868
  "scan:read",
10528
12869
  "scan:start",
10529
- "cleanup:plan",
10530
- "cleanup:execute"
10531
- ] : ["scan:read", "scan:start"];
12870
+ "host:reveal",
12871
+ ...config.allowCleanup ? ["cleanup:plan", "cleanup:execute"] : [],
12872
+ ...config.ai !== null ? ["ai:chat"] : [],
12873
+ ...config.allowMemory ? ["memory:read"] : [],
12874
+ ...config.allowProcessControl ? ["memory:terminate"] : []
12875
+ ];
10532
12876
  const auth = new AuthService({
10533
12877
  serviceInstanceId,
10534
12878
  ticketTtlMs: config.ticketTtlMs,
@@ -10546,6 +12890,30 @@ async function startServe(options) {
10546
12890
  maxTotal: config.maxTotalScans,
10547
12891
  localScanBin: options.localScanBin
10548
12892
  });
12893
+ let appAuditAvailable = false;
12894
+ try {
12895
+ resolveLocalScanBin(options.localScanBin);
12896
+ appAuditAvailable = true;
12897
+ } catch {
12898
+ appAuditAvailable = false;
12899
+ }
12900
+ let memory;
12901
+ let memoryCapability;
12902
+ if (config.allowMemory) try {
12903
+ memory = createMemoryBridge({ binary: resolveLocalScanBin(options.localScanBin) });
12904
+ const hello = await memory.hello();
12905
+ memoryCapability = {
12906
+ sample: true,
12907
+ terminate: config.allowProcessControl && hello.terminate,
12908
+ gracefulAppQuit: hello.gracefulAppQuit,
12909
+ reopen: false,
12910
+ platform: hello.platform
12911
+ };
12912
+ } catch {
12913
+ await memory?.stop();
12914
+ memory = void 0;
12915
+ memoryCapability = void 0;
12916
+ }
10549
12917
  const capabilities = {
10550
12918
  apiMajor: 1,
10551
12919
  contractVersion: CONTRACT_VERSION,
@@ -10553,6 +12921,7 @@ async function startServe(options) {
10553
12921
  start: true,
10554
12922
  cancel: true,
10555
12923
  discovery: true,
12924
+ appAudit: appAuditAvailable,
10556
12925
  maxConcurrent: config.maxConcurrentScans
10557
12926
  },
10558
12927
  cleanup: {
@@ -10560,8 +12929,15 @@ async function startServe(options) {
10560
12929
  execute: config.allowCleanup,
10561
12930
  mode: config.allowCleanup ? "trash" : "none"
10562
12931
  },
10563
- host: { folderPicker: false },
10564
- icloud: "unavailable"
12932
+ host: {
12933
+ folderPicker: false,
12934
+ pathReveal: true,
12935
+ pathList: true,
12936
+ platform: hostPlatform()
12937
+ },
12938
+ icloud: "unavailable",
12939
+ ai: config.ai !== null,
12940
+ ...memoryCapability === void 0 ? {} : { memory: memoryCapability }
10565
12941
  };
10566
12942
  const app = buildApp({
10567
12943
  config,
@@ -10571,7 +12947,9 @@ async function startServe(options) {
10571
12947
  assets: createAssetHandler(config.webRoot, config.frameAncestors),
10572
12948
  health: healthPayload(serviceInstanceId),
10573
12949
  capabilities,
10574
- allowlist: createClientAllowlist(config.allowCidr)
12950
+ allowlist: createClientAllowlist(config.allowCidr),
12951
+ localScanBin: options.localScanBin,
12952
+ ...memory === void 0 ? {} : { memory }
10575
12953
  });
10576
12954
  let server = null;
10577
12955
  let port = config.port;
@@ -10603,6 +12981,7 @@ async function startServe(options) {
10603
12981
  const stop = async () => {
10604
12982
  if (stopped) return;
10605
12983
  stopped = true;
12984
+ await memory?.stop();
10606
12985
  await scans.close();
10607
12986
  await new Promise((resolve) => {
10608
12987
  server?.close(() => resolve());
@@ -10643,10 +13022,16 @@ var FLAG_ALIASES = {
10643
13022
  "allow-cidr": "allowCidr",
10644
13023
  "allow-lan": "allowLan",
10645
13024
  "allow-cleanup": "allowCleanup",
13025
+ "allow-memory": "allowMemory",
13026
+ "allow-process-control": "allowProcessControl",
13027
+ "dev-open-session": "devOpenSession",
10646
13028
  "ui-origin": "uiOrigins",
10647
13029
  "ticket-ttl": "ticketTtlSeconds",
10648
13030
  root: "roots",
10649
13031
  "web-root": "webRoot",
13032
+ "ai-base-url": "aiBaseUrl",
13033
+ "ai-model": "aiModel",
13034
+ "ai-disable-thinking": "aiDisableThinking",
10650
13035
  json: "json",
10651
13036
  machine: "machine",
10652
13037
  "trust-proxy": "trustProxy",
@@ -10689,12 +13074,24 @@ function parseServeArgs(argv) {
10689
13074
  case "webRoot":
10690
13075
  parsed.webRoot = resolve(nextValue(raw));
10691
13076
  break;
13077
+ case "aiBaseUrl":
13078
+ parsed.aiBaseUrl = nextValue(raw);
13079
+ break;
13080
+ case "aiModel":
13081
+ parsed.aiModel = nextValue(raw);
13082
+ break;
13083
+ case "aiDisableThinking":
13084
+ parsed.aiDisableThinking = true;
13085
+ break;
10692
13086
  case "ticketTtlSeconds":
10693
13087
  parsed.ticketTtlSeconds = Number.parseInt(nextValue(raw), 10);
10694
13088
  if (!Number.isInteger(parsed.ticketTtlSeconds)) throw new ServeUsageError("--ticket-ttl must be an integer");
10695
13089
  break;
10696
13090
  case "allowLan":
10697
13091
  case "allowCleanup":
13092
+ case "allowMemory":
13093
+ case "allowProcessControl":
13094
+ case "devOpenSession":
10698
13095
  case "json":
10699
13096
  case "machine":
10700
13097
  case "trustProxy":
@@ -10709,6 +13106,23 @@ function parseServeArgs(argv) {
10709
13106
  }
10710
13107
  return parsed;
10711
13108
  }
13109
+ /**
13110
+ * Assembles the operator AI config from the AI flags. The base URL and model
13111
+ * are the on/off switch and must be given together; the API key is read only
13112
+ * from `SPACLENS_AI_API_KEY` (by the host resolver), never from a flag and
13113
+ * never printed.
13114
+ */
13115
+ function aiOptionsFromArgs(args) {
13116
+ if (!(args.aiBaseUrl !== void 0 || args.aiModel !== void 0 || args.aiDisableThinking === true)) return void 0;
13117
+ const baseUrl = args.aiBaseUrl?.trim() ?? "";
13118
+ const model = args.aiModel?.trim() ?? "";
13119
+ if (baseUrl === "" || model === "") throw new ServeUsageError("--ai-base-url and --ai-model are required together to enable the AI advisor");
13120
+ return {
13121
+ baseUrl,
13122
+ model,
13123
+ ...args.aiDisableThinking === true ? { disableThinking: true } : {}
13124
+ };
13125
+ }
10712
13126
  var HELP = `spacelens serve — serve the Space Lens web workbench over HTTP
10713
13127
 
10714
13128
  Usage: spacelens serve [flags]
@@ -10724,6 +13138,22 @@ Capabilities:
10724
13138
  --allow-cleanup grant paired sessions cleanup powers (trash-only, never permanent delete)
10725
13139
  --root <dir> directories scans may target (repeatable; default: current directory)
10726
13140
 
13141
+ Memory view (optional):
13142
+ --allow-memory grant the read-only memory view (live snapshot, history, candidates, audit)
13143
+ --allow-process-control
13144
+ allow quitting processes from a loopback UI; requires --allow-memory and a
13145
+ loopback bind with loopback-only --ui-origin values
13146
+
13147
+ Development:
13148
+ --dev-open-session let a loopback client open a session without the pairing ticket
13149
+ (POST /api/v1/session/dev); loopback bind only, never for a shared host
13150
+
13151
+ AI advisor (optional):
13152
+ --ai-base-url <url> OpenAI-compatible base URL (https; http only for loopback). Enables the advisor.
13153
+ --ai-model <name> model to request (required together with --ai-base-url)
13154
+ --ai-disable-thinking send thinking:{type:"disabled"} (faster on reasoning models; off by default)
13155
+ The API key is read only from SPACLENS_AI_API_KEY in the environment — never a flag, never printed.
13156
+
10727
13157
  Web UI:
10728
13158
  --ui-origin <url> exact origins allowed to call this API cross-origin (repeatable)
10729
13159
  --open open the pairing URL in a browser
@@ -10769,6 +13199,8 @@ async function runServe(argv) {
10769
13199
  `);
10770
13200
  if (existsSync(`${candidate}/200.html`)) args.webRoot = candidate;
10771
13201
  }
13202
+ const ai = aiOptionsFromArgs(args);
13203
+ if (ai !== void 0) args.ai = ai;
10772
13204
  const server = await startServe(args);
10773
13205
  const pairingUrl = server.mintPairingUrl();
10774
13206
  const reprintPairing = () => {
@@ -10788,6 +13220,9 @@ async function runServe(argv) {
10788
13220
  `pairing URL (single use): ${pairingUrl}`,
10789
13221
  `scan roots: ${server.config.roots.join(", ")}`,
10790
13222
  `cleanup: ${server.config.allowCleanup ? "enabled (trash only)" : "disabled (read-only)"}`,
13223
+ `memory: ${server.config.allowProcessControl ? "read + process control" : server.config.allowMemory ? "read-only" : "disabled"}`,
13224
+ server.config.devOpenSession ? "dev sessions: open (loopback clients need no pairing ticket)" : "",
13225
+ args.ai ? `ai advisor: ${args.ai.model} at ${args.ai.baseUrl}` : "",
10791
13226
  args.uiOrigins?.length ? `cross-origin UIs: ${args.uiOrigins.join(", ")}` : "",
10792
13227
  `press p + Enter to reprint the pairing URL, Ctrl+C to stop`,
10793
13228
  ""